From ef8f0e3831c3b888c390e0734fde4c31ee8e386d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 5 Sep 2019 10:50:09 -0700 Subject: [PATCH 001/283] Deterministic example for atomics. Fixes #265 --- examples/atomic-counters/atomic-counters.go | 39 +++++----- examples/atomic-counters/atomic-counters.hash | 4 +- examples/atomic-counters/atomic-counters.sh | 10 ++- public/atomic-counters | 71 ++++++++++--------- 4 files changed, 63 insertions(+), 61 deletions(-) diff --git a/examples/atomic-counters/atomic-counters.go b/examples/atomic-counters/atomic-counters.go index 9df327686..2a0901b6b 100644 --- a/examples/atomic-counters/atomic-counters.go +++ b/examples/atomic-counters/atomic-counters.go @@ -7,9 +7,11 @@ package main -import "fmt" -import "time" -import "sync/atomic" +import ( + "fmt" + "sync" + "sync/atomic" +) func main() { @@ -17,33 +19,28 @@ func main() { // (always-positive) counter. var ops uint64 - // To simulate concurrent updates, we'll start 50 - // goroutines that each increment the counter about - // once a millisecond. + // A WaitGroup will help us wait for all goroutines + // to finish their work. + var wg sync.WaitGroup + + // We'll start 50 goroutines that each increment the + // counter exactly 1000 times. for i := 0; i < 50; i++ { + wg.Add(1) + go func() { - for { + for c := 0; c < 1000; c++ { // To atomically increment the counter we // use `AddUint64`, giving it the memory // address of our `ops` counter with the // `&` syntax. atomic.AddUint64(&ops, 1) - - // Wait a bit between increments. - time.Sleep(time.Millisecond) } + wg.Done() }() } - // Wait a second to allow some ops to accumulate. - time.Sleep(time.Second) - - // In order to safely use the counter while it's still - // being updated by other goroutines, we extract a - // copy of the current value into `opsFinal` via - // `LoadUint64`. As above we need to give this - // function the memory address `&ops` from which to - // fetch the value. - opsFinal := atomic.LoadUint64(&ops) - fmt.Println("ops:", opsFinal) + // Wait until all the goroutines are done. + wg.Wait() + fmt.Println("ops:", ops) } diff --git a/examples/atomic-counters/atomic-counters.hash b/examples/atomic-counters/atomic-counters.hash index c1b531a0c..e35f8f246 100644 --- a/examples/atomic-counters/atomic-counters.hash +++ b/examples/atomic-counters/atomic-counters.hash @@ -1,2 +1,2 @@ -a4190094ea0405b5f2733101beb97939a1d43aee -KDr9EMMPMgi +103c9b7d036e3a5c14dc481755b78b10dc9f894e +GRkVf6J1--B diff --git a/examples/atomic-counters/atomic-counters.sh b/examples/atomic-counters/atomic-counters.sh index e4523f907..1680a100c 100644 --- a/examples/atomic-counters/atomic-counters.sh +++ b/examples/atomic-counters/atomic-counters.sh @@ -1,7 +1,11 @@ -# Running the program shows that we executed about -# 40,000 operations. +# We expect to get exactly 50,000 operations. Had we +# used the non-atomic `ops++` to increment the counter, +# we'd likely get a different number, changing between +# runs, because the goroutines would interfere with +# each other. Moreover, we'd get data race failures +# when running with the `-race` flag. $ go run atomic-counters.go -ops: 41419 +ops: 50000 # Next we'll look at mutexes, another tool for managing # state. diff --git a/public/atomic-counters b/public/atomic-counters index b2e006e0c..6c9d94cbf 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -46,7 +46,7 @@ counters accessed by multiple goroutines.

- +
package main
 
@@ -59,9 +59,11 @@ counters accessed by multiple goroutines.

-
import "fmt"
-import "time"
-import "sync/atomic"
+          
import (
+    "fmt"
+    "sync"
+    "sync/atomic"
+)
 
@@ -95,16 +97,13 @@ counters accessed by multiple goroutines.

-

To simulate concurrent updates, we’ll start 50 -goroutines that each increment the counter about -once a millisecond.

+

A WaitGroup will help us wait for all goroutines +to finish their work.

-
    for i := 0; i < 50; i++ {
-        go func() {
-            for {
+          
    var wg sync.WaitGroup
 
@@ -112,15 +111,14 @@ once a millisecond.

-

To atomically increment the counter we -use AddUint64, giving it the memory -address of our ops counter with the -& syntax.

+

We’ll start 50 goroutines that each increment the +counter exactly 1000 times.

-
                atomic.AddUint64(&ops, 1)
+          
    for i := 0; i < 50; i++ {
+        wg.Add(1)
 
@@ -128,15 +126,16 @@ address of our ops counter with the -

Wait a bit between increments.

+

To atomically increment the counter we +use AddUint64, giving it the memory +address of our ops counter with the +& syntax.

-
                time.Sleep(time.Millisecond)
-            }
-        }()
-    }
+          
        go func() {
+            for c := 0; c < 1000; c++ {
 
@@ -144,12 +143,15 @@ address of our ops counter with the -

Wait a second to allow some ops to accumulate.

- + -
    time.Sleep(time.Second)
+          
                atomic.AddUint64(&ops, 1)
+            }
+            wg.Done()
+        }()
+    }
 
@@ -157,18 +159,13 @@ address of our ops counter with the -

In order to safely use the counter while it’s still -being updated by other goroutines, we extract a -copy of the current value into opsFinal via -LoadUint64. As above we need to give this -function the memory address &ops from which to -fetch the value.

+

Wait until all the goroutines are done.

-
    opsFinal := atomic.LoadUint64(&ops)
-    fmt.Println("ops:", opsFinal)
+          
    wg.Wait()
+    fmt.Println("ops:", ops)
 }
 
@@ -181,14 +178,18 @@ fetch the value.

-

Running the program shows that we executed about -40,000 operations.

+

We expect to get exactly 50,000 operations. Had we +used the non-atomic ops++ to increment the counter, +we’d likely get a different number, changing between +runs, because the goroutines would interfere with +each other. Moreover, we’d get data race failures +when running with the -race flag.

$ go run atomic-counters.go
-ops: 41419
+ops: 50000
 
@@ -219,7 +220,7 @@ state.

From b70c15adaa0983b3d07312f425b8c6d4df71457f Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 5 Sep 2019 13:26:08 -0700 Subject: [PATCH 002/283] Clarify reading op non-atomically --- examples/atomic-counters/atomic-counters.go | 6 +++++ examples/atomic-counters/atomic-counters.hash | 4 ++-- public/atomic-counters | 24 +++++++++++++++---- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/examples/atomic-counters/atomic-counters.go b/examples/atomic-counters/atomic-counters.go index 2a0901b6b..046a347f3 100644 --- a/examples/atomic-counters/atomic-counters.go +++ b/examples/atomic-counters/atomic-counters.go @@ -42,5 +42,11 @@ func main() { // Wait until all the goroutines are done. wg.Wait() + + // It's safe to access `ops` now because we know + // no other goroutine is writing to it. Reading + // atomics safely while they are being updated is + // also possible, using functions like + // `atomic.LoadUint64`. fmt.Println("ops:", ops) } diff --git a/examples/atomic-counters/atomic-counters.hash b/examples/atomic-counters/atomic-counters.hash index e35f8f246..989ed197c 100644 --- a/examples/atomic-counters/atomic-counters.hash +++ b/examples/atomic-counters/atomic-counters.hash @@ -1,2 +1,2 @@ -103c9b7d036e3a5c14dc481755b78b10dc9f894e -GRkVf6J1--B +8ebec0be3b167021c96b8b497d0e8c0a2ea99385 +F2pJfduyQiA diff --git a/public/atomic-counters b/public/atomic-counters index 6c9d94cbf..9627c9703 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -46,7 +46,7 @@ counters accessed by multiple goroutines.

- +
package main
 
@@ -162,10 +162,26 @@ address of our ops counter with the

Wait until all the goroutines are done.

- +
    wg.Wait()
-    fmt.Println("ops:", ops)
+
+ + + + + + +

It’s safe to access ops now because we know +no other goroutine is writing to it. Reading +atomics safely while they are being updated is +also possible, using functions like +atomic.LoadUint64.

+ + + + +
    fmt.Println("ops:", ops)
 }
 
@@ -220,7 +236,7 @@ state.

From a34c967eaf2e1bda05eadc5c1af59fe8060ca0dc Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 5 Sep 2019 13:30:16 -0700 Subject: [PATCH 003/283] Clarify use of buffered channel in the timeouts example. The buffered channel prevents goroutine leaks in case the channel doesn't end up being read (as indeed happens to c1). Updates #207 --- examples/timeouts/timeouts.go | 5 ++++- examples/timeouts/timeouts.hash | 4 ++-- public/timeouts | 7 +++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/examples/timeouts/timeouts.go b/examples/timeouts/timeouts.go index ccc9ecbc9..ce1d1cd06 100644 --- a/examples/timeouts/timeouts.go +++ b/examples/timeouts/timeouts.go @@ -12,7 +12,10 @@ func main() { // For our example, suppose we're executing an external // call that returns its result on a channel `c1` - // after 2s. + // after 2s. Note that the channel is buffered, so the + // send in the goroutine is nonblocking. This is a + // common pattern to prevent goroutine leaks in case the + // channel is never read. c1 := make(chan string, 1) go func() { time.Sleep(2 * time.Second) diff --git a/examples/timeouts/timeouts.hash b/examples/timeouts/timeouts.hash index 64d1c5ad7..f510bfa0b 100644 --- a/examples/timeouts/timeouts.hash +++ b/examples/timeouts/timeouts.hash @@ -1,2 +1,2 @@ -93343e1aacb14f818c87732914c29ba57afab245 -MgcfA-xpJO9 +b1e8d0efbabd0c52271a85fad5ad58dcd1c7c476 +gyY_qDsRVUe diff --git a/public/timeouts b/public/timeouts index c00732d59..532dbc02b 100644 --- a/public/timeouts +++ b/public/timeouts @@ -44,7 +44,7 @@ elegant thanks to channels and select.

- +
package main
 
@@ -80,7 +80,10 @@ elegant thanks to channels and select.

For our example, suppose we’re executing an external call that returns its result on a channel c1 -after 2s.

+after 2s. Note that the channel is buffered, so the +send in the goroutine is nonblocking. This is a +common pattern to prevent goroutine leaks in case the +channel is never read.

From 9889d7f702a06b0d0b58d37279aa2976c0ca3993 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 6 Sep 2019 07:37:49 -0700 Subject: [PATCH 004/283] This transition paragraph no longer makes sense --- examples/timeouts/timeouts.sh | 6 ------ public/timeouts | 19 ++----------------- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/examples/timeouts/timeouts.sh b/examples/timeouts/timeouts.sh index 8a9dfb4b9..3c4344fe5 100644 --- a/examples/timeouts/timeouts.sh +++ b/examples/timeouts/timeouts.sh @@ -3,9 +3,3 @@ $ go run timeouts.go timeout 1 result 2 - -# Using this `select` timeout pattern requires -# communicating results over channels. This is a good -# idea in general because other important Go features are -# based on channels and `select`. We'll look at two -# examples of this next: timers and tickers. diff --git a/public/timeouts b/public/timeouts index 532dbc02b..814298529 100644 --- a/public/timeouts +++ b/public/timeouts @@ -156,7 +156,7 @@ from c2 will succeed and we’ll print the result.

out and the second succeeding.

- +
$ go run timeouts.go 
 timeout 1
@@ -166,21 +166,6 @@ out and the second succeeding.

- - -

Using this select timeout pattern requires -communicating results over channels. This is a good -idea in general because other important Go features are -based on channels and select. We’ll look at two -examples of this next: timers and tickers.

- - - - - - - - @@ -194,7 +179,7 @@ examples of this next: timers and tickers.

From c2735885215bf405b22c1ae606b6c58de6b746c5 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 6 Sep 2019 15:20:22 -0700 Subject: [PATCH 005/283] Make multiple imports consistent with import ( ... ) style Fixes #272 --- examples/base64-encoding/base64-encoding.go | 6 ++++-- examples/base64-encoding/base64-encoding.hash | 4 ++-- .../channel-synchronization.go | 6 ++++-- .../channel-synchronization.hash | 4 ++-- .../collection-functions/collection-functions.go | 6 ++++-- .../collection-functions/collection-functions.hash | 4 ++-- .../command-line-arguments.go | 6 ++++-- .../command-line-arguments.hash | 4 ++-- examples/command-line-flags/command-line-flags.go | 6 ++++-- .../command-line-flags/command-line-flags.hash | 4 ++-- examples/constants/constants.go | 6 ++++-- examples/constants/constants.hash | 4 ++-- examples/defer/defer.go | 6 ++++-- examples/defer/defer.hash | 4 ++-- .../environment-variables/environment-variables.go | 8 +++++--- .../environment-variables.hash | 4 ++-- examples/epoch/epoch.go | 6 ++++-- examples/epoch/epoch.hash | 4 ++-- examples/errors/errors.go | 6 ++++-- examples/errors/errors.hash | 4 ++-- examples/execing-processes/execing-processes.go | 8 +++++--- examples/execing-processes/execing-processes.hash | 4 ++-- examples/exit/exit.go | 6 ++++-- examples/exit/exit.hash | 4 ++-- examples/interfaces/interfaces.go | 6 ++++-- examples/interfaces/interfaces.hash | 4 ++-- examples/json/json.go | 8 +++++--- examples/json/json.hash | 4 ++-- examples/number-parsing/number-parsing.go | 6 ++++-- examples/number-parsing/number-parsing.hash | 4 ++-- examples/random-numbers/random-numbers.go | 8 +++++--- examples/random-numbers/random-numbers.hash | 4 ++-- examples/rate-limiting/rate-limiting.go | 6 ++++-- examples/rate-limiting/rate-limiting.hash | 4 ++-- .../regular-expressions/regular-expressions.go | 8 +++++--- .../regular-expressions/regular-expressions.hash | 4 ++-- examples/select/select.go | 6 ++++-- examples/select/select.hash | 4 ++-- examples/sha1-hashes/sha1-hashes.go | 6 ++++-- examples/sha1-hashes/sha1-hashes.hash | 4 ++-- examples/signals/signals.go | 10 ++++++---- examples/signals/signals.hash | 4 ++-- .../sorting-by-functions/sorting-by-functions.go | 6 ++++-- .../sorting-by-functions/sorting-by-functions.hash | 4 ++-- examples/sorting/sorting.go | 6 ++++-- examples/sorting/sorting.hash | 4 ++-- examples/spawning-processes/spawning-processes.go | 8 +++++--- .../spawning-processes/spawning-processes.hash | 4 ++-- examples/string-formatting/string-formatting.go | 6 ++++-- examples/string-formatting/string-formatting.hash | 4 ++-- examples/string-functions/string-functions.go | 6 ++++-- examples/string-functions/string-functions.hash | 4 ++-- examples/switch/switch.go | 6 ++++-- examples/switch/switch.hash | 4 ++-- examples/tickers/tickers.go | 6 ++++-- examples/tickers/tickers.hash | 4 ++-- .../time-formatting-parsing.go | 6 ++++-- .../time-formatting-parsing.hash | 4 ++-- examples/time/time.go | 6 ++++-- examples/time/time.hash | 4 ++-- examples/timeouts/timeouts.go | 6 ++++-- examples/timeouts/timeouts.hash | 4 ++-- examples/timers/timers.go | 6 ++++-- examples/timers/timers.hash | 4 ++-- examples/url-parsing/url-parsing.go | 8 +++++--- examples/url-parsing/url-parsing.hash | 4 ++-- examples/worker-pools/worker-pools.go | 6 ++++-- examples/worker-pools/worker-pools.hash | 4 ++-- public/base64-encoding | 10 ++++++---- public/channel-synchronization | 10 ++++++---- public/collection-functions | 10 ++++++---- public/command-line-arguments | 10 ++++++---- public/command-line-flags | 10 ++++++---- public/constants | 10 ++++++---- public/defer | 10 ++++++---- public/environment-variables | 12 +++++++----- public/epoch | 10 ++++++---- public/errors | 10 ++++++---- public/execing-processes | 12 +++++++----- public/exit | 10 ++++++---- public/interfaces | 10 ++++++---- public/json | 12 +++++++----- public/number-parsing | 10 ++++++---- public/random-numbers | 12 +++++++----- public/rate-limiting | 10 ++++++---- public/regular-expressions | 12 +++++++----- public/select | 10 ++++++---- public/sha1-hashes | 10 ++++++---- public/signals | 14 ++++++++------ public/sorting | 10 ++++++---- public/sorting-by-functions | 10 ++++++---- public/spawning-processes | 12 +++++++----- public/string-formatting | 10 ++++++---- public/string-functions | 10 ++++++---- public/switch | 10 ++++++---- public/tickers | 10 ++++++---- public/time | 10 ++++++---- public/time-formatting-parsing | 10 ++++++---- public/timeouts | 10 ++++++---- public/timers | 10 ++++++---- public/url-parsing | 12 +++++++----- public/worker-pools | 10 ++++++---- 102 files changed, 426 insertions(+), 290 deletions(-) diff --git a/examples/base64-encoding/base64-encoding.go b/examples/base64-encoding/base64-encoding.go index 4bdeaf1dd..09e94fd28 100644 --- a/examples/base64-encoding/base64-encoding.go +++ b/examples/base64-encoding/base64-encoding.go @@ -6,8 +6,10 @@ package main // This syntax imports the `encoding/base64` package with // the `b64` name instead of the default `base64`. It'll // save us some space below. -import b64 "encoding/base64" -import "fmt" +import ( + b64 "encoding/base64" + "fmt" +) func main() { diff --git a/examples/base64-encoding/base64-encoding.hash b/examples/base64-encoding/base64-encoding.hash index 1cb409a41..717ff3f66 100644 --- a/examples/base64-encoding/base64-encoding.hash +++ b/examples/base64-encoding/base64-encoding.hash @@ -1,2 +1,2 @@ -c20da14820b656c867790f2e99bc37140babca8c -y_QTcqdkvZh +e0148b9b4acb01e849b8f678cba03f549d250c44 +V3oV1bvh94k diff --git a/examples/channel-synchronization/channel-synchronization.go b/examples/channel-synchronization/channel-synchronization.go index 79ceafeb3..889b97bb8 100644 --- a/examples/channel-synchronization/channel-synchronization.go +++ b/examples/channel-synchronization/channel-synchronization.go @@ -6,8 +6,10 @@ package main -import "fmt" -import "time" +import ( + "fmt" + "time" +) // This is the function we'll run in a goroutine. The // `done` channel will be used to notify another diff --git a/examples/channel-synchronization/channel-synchronization.hash b/examples/channel-synchronization/channel-synchronization.hash index e90612315..9dea9a004 100644 --- a/examples/channel-synchronization/channel-synchronization.hash +++ b/examples/channel-synchronization/channel-synchronization.hash @@ -1,2 +1,2 @@ -eb022977181884c2ab0f2b69e50311769e67a509 -8lmP8beav0p +0d5a9de912e2a4a18943e082e2f8107cb75d0ce4 +fe9If6OhYMk diff --git a/examples/collection-functions/collection-functions.go b/examples/collection-functions/collection-functions.go index b6ff547f9..730644c57 100644 --- a/examples/collection-functions/collection-functions.go +++ b/examples/collection-functions/collection-functions.go @@ -18,8 +18,10 @@ package main -import "strings" -import "fmt" +import ( + "fmt" + "strings" +) // Index returns the first index of the target string `t`, or // -1 if no match is found. diff --git a/examples/collection-functions/collection-functions.hash b/examples/collection-functions/collection-functions.hash index 4c459526a..abbd3d524 100644 --- a/examples/collection-functions/collection-functions.hash +++ b/examples/collection-functions/collection-functions.hash @@ -1,2 +1,2 @@ -d961fc0e0074aed46cfd1516efdadea78781af56 -BJB_npWH516 +28456737ea996664bdaeb8e1e821d95697d00646 +8hI6oPNEfyh diff --git a/examples/command-line-arguments/command-line-arguments.go b/examples/command-line-arguments/command-line-arguments.go index e000e1381..110411329 100644 --- a/examples/command-line-arguments/command-line-arguments.go +++ b/examples/command-line-arguments/command-line-arguments.go @@ -5,8 +5,10 @@ package main -import "os" -import "fmt" +import ( + "fmt" + "os" +) func main() { diff --git a/examples/command-line-arguments/command-line-arguments.hash b/examples/command-line-arguments/command-line-arguments.hash index 5bf53c77f..ad22b5916 100644 --- a/examples/command-line-arguments/command-line-arguments.hash +++ b/examples/command-line-arguments/command-line-arguments.hash @@ -1,2 +1,2 @@ -41c970a1ef29ad2a05307e6c783ff52ab80eaccd -6pFdjf800jj +9c80d495201148bbeb0fd0a5a2ce1735aeb34b60 +myJy_-H8Fo_Q diff --git a/examples/command-line-flags/command-line-flags.go b/examples/command-line-flags/command-line-flags.go index ab9c1b717..96647f5ff 100644 --- a/examples/command-line-flags/command-line-flags.go +++ b/examples/command-line-flags/command-line-flags.go @@ -8,8 +8,10 @@ package main // Go provides a `flag` package supporting basic // command-line flag parsing. We'll use this package to // implement our example command-line program. -import "flag" -import "fmt" +import ( + "flag" + "fmt" +) func main() { diff --git a/examples/command-line-flags/command-line-flags.hash b/examples/command-line-flags/command-line-flags.hash index 1b8f3ac52..abee236af 100644 --- a/examples/command-line-flags/command-line-flags.hash +++ b/examples/command-line-flags/command-line-flags.hash @@ -1,2 +1,2 @@ -e2ba0461c090789168c712cc7ed0f66aab09a8c8 -klFR5DitrCy +ab08bf890dcd87b807956b5bee441d59efe458e3 +lPaZodnG9TF diff --git a/examples/constants/constants.go b/examples/constants/constants.go index 50ce8f22b..e7af86001 100644 --- a/examples/constants/constants.go +++ b/examples/constants/constants.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "math" +import ( + "fmt" + "math" +) // `const` declares a constant value. const s string = "constant" diff --git a/examples/constants/constants.hash b/examples/constants/constants.hash index 1e282aa59..93d42caac 100644 --- a/examples/constants/constants.hash +++ b/examples/constants/constants.hash @@ -1,2 +1,2 @@ -2f2ec3a5ff4eef280199da1908eed261346fb40e -VhP0f8moZd3 +7cc09460e8dc6fffd0ba811679f92a85eb51e927 +gmjHSglwLic diff --git a/examples/defer/defer.go b/examples/defer/defer.go index 724e698c2..b4077c7b8 100644 --- a/examples/defer/defer.go +++ b/examples/defer/defer.go @@ -5,8 +5,10 @@ package main -import "fmt" -import "os" +import ( + "fmt" + "os" +) // Suppose we wanted to create a file, write to it, // and then close when we're done. Here's how we could diff --git a/examples/defer/defer.hash b/examples/defer/defer.hash index 78d3e3557..d45bfd754 100644 --- a/examples/defer/defer.hash +++ b/examples/defer/defer.hash @@ -1,2 +1,2 @@ -fadbe9c05bb42db672316ba19adf3c2189c7b3f5 -OrCaBiCrTKq +4fc23579a9bd5d8512884902394f4dce51eb7d60 +QJJ2R6kv6K5 diff --git a/examples/environment-variables/environment-variables.go b/examples/environment-variables/environment-variables.go index beca4e715..b316b8afc 100644 --- a/examples/environment-variables/environment-variables.go +++ b/examples/environment-variables/environment-variables.go @@ -5,9 +5,11 @@ package main -import "os" -import "strings" -import "fmt" +import ( + "fmt" + "os" + "strings" +) func main() { diff --git a/examples/environment-variables/environment-variables.hash b/examples/environment-variables/environment-variables.hash index 81632ac9b..b2458517f 100644 --- a/examples/environment-variables/environment-variables.hash +++ b/examples/environment-variables/environment-variables.hash @@ -1,2 +1,2 @@ -4d0832c5a1ddd4e95474791e8802c15452358214 -CZJ4R_uu6Uu +db2e203da519a22943753295e9cc27d89e4347b0 +bKuCOOD16KH diff --git a/examples/epoch/epoch.go b/examples/epoch/epoch.go index 63cffbb80..ed7f442f7 100644 --- a/examples/epoch/epoch.go +++ b/examples/epoch/epoch.go @@ -5,8 +5,10 @@ package main -import "fmt" -import "time" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/epoch/epoch.hash b/examples/epoch/epoch.hash index 3899c7ff8..d37c230ff 100644 --- a/examples/epoch/epoch.hash +++ b/examples/epoch/epoch.hash @@ -1,2 +1,2 @@ -61a498229c8878a97d729cfdd215e5f3960f87ac -eN1Qv2ATB-C +184c8f3e94dd28176be81956115ac417e33513a6 +3uYNHHRplmQ diff --git a/examples/errors/errors.go b/examples/errors/errors.go index 0b69badff..b8501392d 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -9,8 +9,10 @@ package main -import "errors" -import "fmt" +import ( + "errors" + "fmt" +) // By convention, errors are the last return value and // have type `error`, a built-in interface. diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index d0b2112b4..b650d2559 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -210ba0f8196006c0380acaec01655816848ef168 -mP_ZR1qjUvA +ed58ad3162d93c723d3efe72529a61ce7041fe13 +vrwN32gxaYx diff --git a/examples/execing-processes/execing-processes.go b/examples/execing-processes/execing-processes.go index b9caed104..18eb283ec 100644 --- a/examples/execing-processes/execing-processes.go +++ b/examples/execing-processes/execing-processes.go @@ -10,9 +10,11 @@ package main -import "syscall" -import "os" -import "os/exec" +import ( + "os" + "os/exec" + "syscall" +) func main() { diff --git a/examples/execing-processes/execing-processes.hash b/examples/execing-processes/execing-processes.hash index 4701404c6..020f78e5d 100644 --- a/examples/execing-processes/execing-processes.hash +++ b/examples/execing-processes/execing-processes.hash @@ -1,2 +1,2 @@ -b527bbb76a42dd4bae541b73a7377b7e83e79905 -bf11ADw-2Ho +e6b4830d4264f307506b54726ec79b25a0363874 +ahZjpJaZz44 diff --git a/examples/exit/exit.go b/examples/exit/exit.go index d1e3646fa..578e553e7 100644 --- a/examples/exit/exit.go +++ b/examples/exit/exit.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "os" +import ( + "fmt" + "os" +) func main() { diff --git a/examples/exit/exit.hash b/examples/exit/exit.hash index 988b8f323..234717b79 100644 --- a/examples/exit/exit.hash +++ b/examples/exit/exit.hash @@ -1,2 +1,2 @@ -dc0bb3eaafa045d6aa05e88aff39322a1ccf822e -vDaM0-MGJ_k +2316e6c8e364e2066c6bd350dc9b0b2af85b63fe +OX997ykuOGx diff --git a/examples/interfaces/interfaces.go b/examples/interfaces/interfaces.go index 2ac30bd5c..806ffa7d4 100644 --- a/examples/interfaces/interfaces.go +++ b/examples/interfaces/interfaces.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "math" +import ( + "fmt" + "math" +) // Here's a basic interface for geometric shapes. type geometry interface { diff --git a/examples/interfaces/interfaces.hash b/examples/interfaces/interfaces.hash index d9daecea5..b6fa98378 100644 --- a/examples/interfaces/interfaces.hash +++ b/examples/interfaces/interfaces.hash @@ -1,2 +1,2 @@ -3547b935d1e0322c0fb696726c27cae53a275e0a -0EwsqIn3TTi +aac1328f5a04568272b82753ff0762b9eacff4fc +hXTlbUAGcvn diff --git a/examples/json/json.go b/examples/json/json.go index 8d443bd05..259478632 100644 --- a/examples/json/json.go +++ b/examples/json/json.go @@ -4,9 +4,11 @@ package main -import "encoding/json" -import "fmt" -import "os" +import ( + "encoding/json" + "fmt" + "os" +) // We'll use these two structs to demonstrate encoding and // decoding of custom types below. diff --git a/examples/json/json.hash b/examples/json/json.hash index 0c3c3a1b4..8c217d64c 100644 --- a/examples/json/json.hash +++ b/examples/json/json.hash @@ -1,2 +1,2 @@ -6b92694b7be60cdec3e7a04e9fdbf49d5c84adb1 -63PdbTHxKJA +c751bc7223b8bc615f82fe7643ab98ce2b80240f +ROikmz5tRhZ diff --git a/examples/number-parsing/number-parsing.go b/examples/number-parsing/number-parsing.go index 15a03bfbf..63716370a 100644 --- a/examples/number-parsing/number-parsing.go +++ b/examples/number-parsing/number-parsing.go @@ -5,8 +5,10 @@ package main // The built-in package `strconv` provides the number // parsing. -import "strconv" -import "fmt" +import ( + "fmt" + "strconv" +) func main() { diff --git a/examples/number-parsing/number-parsing.hash b/examples/number-parsing/number-parsing.hash index 324990391..eeaf3cd16 100644 --- a/examples/number-parsing/number-parsing.hash +++ b/examples/number-parsing/number-parsing.hash @@ -1,2 +1,2 @@ -0d2155e9863a73c098d44637e92403d7f5e8e965 -NZh4LjhguvN +0191c7e43706640207c403ba92dd2272d66fc868 +t2q4KnWWTAw diff --git a/examples/random-numbers/random-numbers.go b/examples/random-numbers/random-numbers.go index b27c20049..ebb6a8ccd 100644 --- a/examples/random-numbers/random-numbers.go +++ b/examples/random-numbers/random-numbers.go @@ -4,9 +4,11 @@ package main -import "time" -import "fmt" -import "math/rand" +import ( + "fmt" + "math/rand" + "time" +) func main() { diff --git a/examples/random-numbers/random-numbers.hash b/examples/random-numbers/random-numbers.hash index 87959ee1a..3ebbc4aca 100644 --- a/examples/random-numbers/random-numbers.hash +++ b/examples/random-numbers/random-numbers.hash @@ -1,2 +1,2 @@ -8e97de760147b061dd09939db294c892211b6b80 -jiJaIjxL2sP +9374869a809d28ea784a9e1181b4aa1988018776 +DVHO7SjJZnp diff --git a/examples/rate-limiting/rate-limiting.go b/examples/rate-limiting/rate-limiting.go index 175bbcc96..c32483d3d 100644 --- a/examples/rate-limiting/rate-limiting.go +++ b/examples/rate-limiting/rate-limiting.go @@ -6,8 +6,10 @@ package main -import "time" -import "fmt" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/rate-limiting/rate-limiting.hash b/examples/rate-limiting/rate-limiting.hash index ccbbc4922..be48802c6 100644 --- a/examples/rate-limiting/rate-limiting.hash +++ b/examples/rate-limiting/rate-limiting.hash @@ -1,2 +1,2 @@ -edad78bf3b36ddc9bec30b344b8a72be4de90f3b -l4uDE-RCDpa +357d83df3e48675eb1e135188cb9f07448c1f146 +AJ-MJephNib diff --git a/examples/regular-expressions/regular-expressions.go b/examples/regular-expressions/regular-expressions.go index 5d5ee8c5d..52ec06d3e 100644 --- a/examples/regular-expressions/regular-expressions.go +++ b/examples/regular-expressions/regular-expressions.go @@ -4,9 +4,11 @@ package main -import "bytes" -import "fmt" -import "regexp" +import ( + "bytes" + "fmt" + "regexp" +) func main() { diff --git a/examples/regular-expressions/regular-expressions.hash b/examples/regular-expressions/regular-expressions.hash index abc14cd49..236706c0a 100644 --- a/examples/regular-expressions/regular-expressions.hash +++ b/examples/regular-expressions/regular-expressions.hash @@ -1,2 +1,2 @@ -7cde6b9af5cf6c47606001dd54eee468a6c61dbb -qR5gn2l0AGa +de24265897edf1d3913e3b87f70757284a66ecea +urHlUNDVenk diff --git a/examples/select/select.go b/examples/select/select.go index c05aacbc7..d2ce16e5a 100644 --- a/examples/select/select.go +++ b/examples/select/select.go @@ -4,8 +4,10 @@ package main -import "time" -import "fmt" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/select/select.hash b/examples/select/select.hash index 50376689d..ea97b26d1 100644 --- a/examples/select/select.hash +++ b/examples/select/select.hash @@ -1,2 +1,2 @@ -8d743edffd7de6bf7bccdf4437f45672b6adc75e -ZdSOPe1Gj13 +6e1125087bc036ebd905452300575f160d683918 +yF-xgN7Xf9P diff --git a/examples/sha1-hashes/sha1-hashes.go b/examples/sha1-hashes/sha1-hashes.go index db8bb394a..24e59210b 100644 --- a/examples/sha1-hashes/sha1-hashes.go +++ b/examples/sha1-hashes/sha1-hashes.go @@ -9,8 +9,10 @@ package main // Go implements several hash functions in various // `crypto/*` packages. -import "crypto/sha1" -import "fmt" +import ( + "crypto/sha1" + "fmt" +) func main() { s := "sha1 this string" diff --git a/examples/sha1-hashes/sha1-hashes.hash b/examples/sha1-hashes/sha1-hashes.hash index e56a0143b..5af2939b1 100644 --- a/examples/sha1-hashes/sha1-hashes.hash +++ b/examples/sha1-hashes/sha1-hashes.hash @@ -1,2 +1,2 @@ -6a896270e34f2696b881a8fa7e68bfff57dee51f -1oT-5GBUkLr +4cda643ba233014fe6b30966c37d4d0fcd4edbe8 +oqcrTfY4Ykd diff --git a/examples/signals/signals.go b/examples/signals/signals.go index 38e17ad6f..4cd373b2f 100644 --- a/examples/signals/signals.go +++ b/examples/signals/signals.go @@ -7,10 +7,12 @@ package main -import "fmt" -import "os" -import "os/signal" -import "syscall" +import ( + "fmt" + "os" + "os/signal" + "syscall" +) func main() { diff --git a/examples/signals/signals.hash b/examples/signals/signals.hash index 94e8edb4d..82345ca02 100644 --- a/examples/signals/signals.hash +++ b/examples/signals/signals.hash @@ -1,2 +1,2 @@ -9720d747e3ab2893df508a70cbb341c90fdd7ca1 -9koJAW1raI5 +1e43c6f63f1d57e1a52c89f52d35b68757e9676b +_6oj-T3Gko2 diff --git a/examples/sorting-by-functions/sorting-by-functions.go b/examples/sorting-by-functions/sorting-by-functions.go index b880564c4..8524f668a 100644 --- a/examples/sorting-by-functions/sorting-by-functions.go +++ b/examples/sorting-by-functions/sorting-by-functions.go @@ -6,8 +6,10 @@ package main -import "sort" -import "fmt" +import ( + "fmt" + "sort" +) // In order to sort by a custom function in Go, we need a // corresponding type. Here we've created a `byLength` diff --git a/examples/sorting-by-functions/sorting-by-functions.hash b/examples/sorting-by-functions/sorting-by-functions.hash index 776dde838..d62f035bc 100644 --- a/examples/sorting-by-functions/sorting-by-functions.hash +++ b/examples/sorting-by-functions/sorting-by-functions.hash @@ -1,2 +1,2 @@ -6a04058b564d5741815e523f97f240ee6563cb15 -y3kuCwIFRYK +f7d0b7840dd12601fb86946f9dc4c38fb1c0501f +Jtxf94x94Hx diff --git a/examples/sorting/sorting.go b/examples/sorting/sorting.go index b6317ed20..acc67d8d7 100644 --- a/examples/sorting/sorting.go +++ b/examples/sorting/sorting.go @@ -4,8 +4,10 @@ package main -import "fmt" -import "sort" +import ( + "fmt" + "sort" +) func main() { diff --git a/examples/sorting/sorting.hash b/examples/sorting/sorting.hash index ae5e44944..d72396f6a 100644 --- a/examples/sorting/sorting.hash +++ b/examples/sorting/sorting.hash @@ -1,2 +1,2 @@ -4e576421f2bdbd11847c367d223bd30d0e301990 -e6hp3Rn-oH6 +e11e944d34b21e75ce4f7c91026d4200ce592dc5 +tAWAkRlBJNX diff --git a/examples/spawning-processes/spawning-processes.go b/examples/spawning-processes/spawning-processes.go index 98e0f6599..58fdae8e0 100644 --- a/examples/spawning-processes/spawning-processes.go +++ b/examples/spawning-processes/spawning-processes.go @@ -7,9 +7,11 @@ package main -import "fmt" -import "io/ioutil" -import "os/exec" +import ( + "fmt" + "io/ioutil" + "os/exec" +) func main() { diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index dd1b74922..bcde70779 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -0b676b93e41ac5434003c194bc038d5f3ce76bc8 -6HRWVK5gPYU +cc68e4290f10209ad2fa8db74fdfaea7fdb44d5c +QS_Nkoe8VLG diff --git a/examples/string-formatting/string-formatting.go b/examples/string-formatting/string-formatting.go index de7c28531..958cb64d1 100644 --- a/examples/string-formatting/string-formatting.go +++ b/examples/string-formatting/string-formatting.go @@ -4,8 +4,10 @@ package main -import "fmt" -import "os" +import ( + "fmt" + "os" +) type point struct { x, y int diff --git a/examples/string-formatting/string-formatting.hash b/examples/string-formatting/string-formatting.hash index ba1b3965c..c339d9bbf 100644 --- a/examples/string-formatting/string-formatting.hash +++ b/examples/string-formatting/string-formatting.hash @@ -1,2 +1,2 @@ -5f39ae6d8f26d59a688a9a9d7d13a5c1d0f7a08b -CkBQ3CFpHQ9 +12b245c576b43537c092a5b84995ebca8ce78a57 +vmYSdxfUcRh diff --git a/examples/string-functions/string-functions.go b/examples/string-functions/string-functions.go index c8f2b5403..676e904e5 100644 --- a/examples/string-functions/string-functions.go +++ b/examples/string-functions/string-functions.go @@ -4,8 +4,10 @@ package main -import s "strings" -import "fmt" +import ( + "fmt" + s "strings" +) // We alias `fmt.Println` to a shorter name as we'll use // it a lot below. diff --git a/examples/string-functions/string-functions.hash b/examples/string-functions/string-functions.hash index 068746c11..568c7c6db 100644 --- a/examples/string-functions/string-functions.hash +++ b/examples/string-functions/string-functions.hash @@ -1,2 +1,2 @@ -17aa523bbd606fa0b624fae44b89812d46330755 -Vn4D3y4_711 +bf39c7540bd78eba38eb5a9047a9d0ffc7235f85 +xoRUhG86wsF diff --git a/examples/switch/switch.go b/examples/switch/switch.go index 8d72bee26..2d2ec2e2b 100644 --- a/examples/switch/switch.go +++ b/examples/switch/switch.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "time" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/switch/switch.hash b/examples/switch/switch.hash index 5559e1ac4..54d2e9f43 100644 --- a/examples/switch/switch.hash +++ b/examples/switch/switch.hash @@ -1,2 +1,2 @@ -b47004b3e3b6d787ea98642dc5b955df57cd2bcd -TJ4Az0KuLfL +2486fc553301cdeac9a26f3d0b3aed4143d9f4f0 +ZcDzdx3nYQn diff --git a/examples/tickers/tickers.go b/examples/tickers/tickers.go index 1d2a8e515..c23dd5cde 100644 --- a/examples/tickers/tickers.go +++ b/examples/tickers/tickers.go @@ -6,8 +6,10 @@ package main -import "time" -import "fmt" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/tickers/tickers.hash b/examples/tickers/tickers.hash index 28a173e1d..e724ec153 100644 --- a/examples/tickers/tickers.hash +++ b/examples/tickers/tickers.hash @@ -1,2 +1,2 @@ -c83f34821c69d156713919a42c73ec9f58560f72 -IUmkvvXL5Ok +4a42333d14f902e890902343c7bd9b9c735fd8ad +n1q1sSGEvmv diff --git a/examples/time-formatting-parsing/time-formatting-parsing.go b/examples/time-formatting-parsing/time-formatting-parsing.go index a213bafff..2968c3c68 100644 --- a/examples/time-formatting-parsing/time-formatting-parsing.go +++ b/examples/time-formatting-parsing/time-formatting-parsing.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "time" +import ( + "fmt" + "time" +) func main() { p := fmt.Println diff --git a/examples/time-formatting-parsing/time-formatting-parsing.hash b/examples/time-formatting-parsing/time-formatting-parsing.hash index 0d05bde9f..eee6d65fd 100644 --- a/examples/time-formatting-parsing/time-formatting-parsing.hash +++ b/examples/time-formatting-parsing/time-formatting-parsing.hash @@ -1,2 +1,2 @@ -1f9962260f5c92efe57db0b96099b3dd06c90333 -nHAisH6amZG +9e3f17061fef280191e3e8518365e231e17a5d5a +1410R7Fcyx0 diff --git a/examples/time/time.go b/examples/time/time.go index 1d01432ae..db96527f4 100644 --- a/examples/time/time.go +++ b/examples/time/time.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "time" +import ( + "fmt" + "time" +) func main() { p := fmt.Println diff --git a/examples/time/time.hash b/examples/time/time.hash index 9542207c3..2c9d41588 100644 --- a/examples/time/time.hash +++ b/examples/time/time.hash @@ -1,2 +1,2 @@ -b6308f1fea7665e89a28f54aac6cb49b95685eb5 -PZMCzzaJURJ +c47d853fa7527a652ce78b0285e452c6cd740050 +u-7i_p8BHVt diff --git a/examples/timeouts/timeouts.go b/examples/timeouts/timeouts.go index ce1d1cd06..3f25aec86 100644 --- a/examples/timeouts/timeouts.go +++ b/examples/timeouts/timeouts.go @@ -5,8 +5,10 @@ package main -import "time" -import "fmt" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/timeouts/timeouts.hash b/examples/timeouts/timeouts.hash index f510bfa0b..f622aeb5f 100644 --- a/examples/timeouts/timeouts.hash +++ b/examples/timeouts/timeouts.hash @@ -1,2 +1,2 @@ -b1e8d0efbabd0c52271a85fad5ad58dcd1c7c476 -gyY_qDsRVUe +b8d3e745539b24d3530ca21efcdc924f08769edb +TYJgoFjlTd6 diff --git a/examples/timers/timers.go b/examples/timers/timers.go index 939cf119b..d0256e672 100644 --- a/examples/timers/timers.go +++ b/examples/timers/timers.go @@ -6,8 +6,10 @@ package main -import "time" -import "fmt" +import ( + "fmt" + "time" +) func main() { diff --git a/examples/timers/timers.hash b/examples/timers/timers.hash index f51b1f0c4..8c0f2c427 100644 --- a/examples/timers/timers.hash +++ b/examples/timers/timers.hash @@ -1,2 +1,2 @@ -e10c601ab3b702dfcea728c1edb31673561484b5 -pybl9hRvJq2 +e8e501d6083bea786629ca5e485e8b18caab4815 +pLnKEIesooU diff --git a/examples/url-parsing/url-parsing.go b/examples/url-parsing/url-parsing.go index b4e0050b8..f7590f135 100644 --- a/examples/url-parsing/url-parsing.go +++ b/examples/url-parsing/url-parsing.go @@ -3,9 +3,11 @@ package main -import "fmt" -import "net" -import "net/url" +import ( + "fmt" + "net" + "net/url" +) func main() { diff --git a/examples/url-parsing/url-parsing.hash b/examples/url-parsing/url-parsing.hash index 019a1a66c..77021f1a0 100644 --- a/examples/url-parsing/url-parsing.hash +++ b/examples/url-parsing/url-parsing.hash @@ -1,2 +1,2 @@ -b7a0813e9413bfcc956cc58b850f655dd129ebb7 -AL79Lv-9CWo +babc12f5066652f4cb0151231c06f1037298ff28 +M218D9Tldlr diff --git a/examples/worker-pools/worker-pools.go b/examples/worker-pools/worker-pools.go index 84c8bf109..1584d5950 100644 --- a/examples/worker-pools/worker-pools.go +++ b/examples/worker-pools/worker-pools.go @@ -3,8 +3,10 @@ package main -import "fmt" -import "time" +import ( + "fmt" + "time" +) // Here's the worker, of which we'll run several // concurrent instances. These workers will receive diff --git a/examples/worker-pools/worker-pools.hash b/examples/worker-pools/worker-pools.hash index 9f101b7aa..dbfeb88ff 100644 --- a/examples/worker-pools/worker-pools.hash +++ b/examples/worker-pools/worker-pools.hash @@ -1,2 +1,2 @@ -bc69c6602d438413dcb9ceac112299ee253e4575 -yuHsGf712D1 +9b30cdfc3f46d634c3b8671a7ae1551c133fb6e2 +IiKZ-nj-nKY diff --git a/public/base64-encoding b/public/base64-encoding index d60fe9dce..7bf8d2887 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -42,7 +42,7 @@ encoding/decoding.

- +
package main
 
@@ -58,8 +58,10 @@ save us some space below.

-
import b64 "encoding/base64"
-import "fmt"
+          
import (
+    b64 "encoding/base64"
+    "fmt"
+)
 
@@ -189,7 +191,7 @@ but they both decode to the original string as desired.

diff --git a/public/channel-synchronization b/public/channel-synchronization index 16de09231..7a0d3a384 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -45,7 +45,7 @@ you may prefer to use a WaitGroup.

- +
package main
 
@@ -58,8 +58,10 @@ you may prefer to use a WaitGroup.

-
import "fmt"
-import "time"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -182,7 +184,7 @@ started.

diff --git a/public/collection-functions b/public/collection-functions index 2acb092b7..569c4b3b9 100644 --- a/public/collection-functions +++ b/public/collection-functions @@ -75,7 +75,7 @@ helper function.

- +
package main
 
@@ -88,8 +88,10 @@ helper function.

-
import "strings"
-import "fmt"
+          
import (
+    "fmt"
+    "strings"
+)
 
@@ -369,7 +371,7 @@ type.

diff --git a/public/command-line-arguments b/public/command-line-arguments index 1cb6ffd04..a2aa9ff3a 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -44,7 +44,7 @@ For example, go run hello.go uses run and - +
package main
 
@@ -57,8 +57,10 @@ For example, go run hello.go uses run and -
import "os"
-import "fmt"
+          
import (
+    "fmt"
+    "os"
+)
 
@@ -168,7 +170,7 @@ with flags.

diff --git a/public/command-line-flags b/public/command-line-flags index b2230fa86..76e2bfc9f 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -44,7 +44,7 @@ command-line flag.

- +
package main
 
@@ -60,8 +60,10 @@ implement our example command-line program.

-
import "flag"
-import "fmt"
+          
import (
+    "flag"
+    "fmt"
+)
 
@@ -308,7 +310,7 @@ and show the help text again.

diff --git a/public/constants b/public/constants index 17379bfa9..31e2c7b22 100644 --- a/public/constants +++ b/public/constants @@ -42,7 +42,7 @@ and numeric values.

- +
package main
 
@@ -55,8 +55,10 @@ and numeric values.

-
import "fmt"
-import "math"
+          
import (
+    "fmt"
+    "math"
+)
 
@@ -181,7 +183,7 @@ assignment or function call. For example, here
diff --git a/public/defer b/public/defer index 6c62c6433..f99d59d8f 100644 --- a/public/defer +++ b/public/defer @@ -44,7 +44,7 @@ purposes of cleanup. defer is often used where e.g. - +
package main
 
@@ -57,8 +57,10 @@ purposes of cleanup. defer is often used where e.g. -
import "fmt"
-import "os"
+          
import (
+    "fmt"
+    "os"
+)
 
@@ -210,7 +212,7 @@ after being written.

diff --git a/public/environment-variables b/public/environment-variables index c452feb27..25504ae69 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -44,7 +44,7 @@ Let’s look at how to set, get, and list environment variables.

- +
package main
 
@@ -57,9 +57,11 @@ Let’s look at how to set, get, and list environment variables.

-
import "os"
-import "strings"
-import "fmt"
+          
import (
+    "fmt"
+    "os"
+    "strings"
+)
 
@@ -184,7 +186,7 @@ program picks that value up.

diff --git a/public/epoch b/public/epoch index 644ef794a..76a9b201f 100644 --- a/public/epoch +++ b/public/epoch @@ -44,7 +44,7 @@ Here’s how to do it in Go.

- +
package main
 
@@ -57,8 +57,10 @@ Here’s how to do it in Go.

-
import "fmt"
-import "time"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -175,7 +177,7 @@ parsing and formatting.

diff --git a/public/errors b/public/errors index b0ea98e5b..351cb86df 100644 --- a/public/errors +++ b/public/errors @@ -48,7 +48,7 @@ non-error tasks.

- +
package main
 
@@ -61,8 +61,10 @@ non-error tasks.

-
import "errors"
-import "fmt"
+          
import (
+    "errors"
+    "fmt"
+)
 
@@ -297,7 +299,7 @@ on the Go blog for more on error handling.

diff --git a/public/execing-processes b/public/execing-processes index 500d807a7..98ce62a78 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -49,7 +49,7 @@ function.

- +
package main
 
@@ -62,9 +62,11 @@ function.

-
import "syscall"
-import "os"
-import "os/exec"
+          
import (
+    "os"
+    "os/exec"
+    "syscall"
+)
 
@@ -201,7 +203,7 @@ processes covers most use cases for fork.

diff --git a/public/exit b/public/exit index b8c38a6d2..5929eb645 100644 --- a/public/exit +++ b/public/exit @@ -38,7 +38,7 @@ status.

- +
package main
 
@@ -51,8 +51,10 @@ status.

-
import "fmt"
-import "os"
+          
import (
+    "fmt"
+    "os"
+)
 
@@ -168,7 +170,7 @@ the status in the terminal.

diff --git a/public/interfaces b/public/interfaces index eddb06677..fad0ed06c 100644 --- a/public/interfaces +++ b/public/interfaces @@ -42,7 +42,7 @@ signatures.

- +
package main
 
@@ -55,8 +55,10 @@ signatures.

-
import "fmt"
-import "math"
+          
import (
+    "fmt"
+    "math"
+)
 
@@ -234,7 +236,7 @@ these structs as arguments to measure.

diff --git a/public/json b/public/json index a0d639536..e2327ec0d 100644 --- a/public/json +++ b/public/json @@ -43,7 +43,7 @@ data types.

- +
package main
 
@@ -56,9 +56,11 @@ data types.

-
import "encoding/json"
-import "fmt"
-import "os"
+          
import (
+    "encoding/json"
+    "fmt"
+    "os"
+)
 
@@ -414,7 +416,7 @@ for more.

diff --git a/public/number-parsing b/public/number-parsing index db31e0d18..269da8526 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -42,7 +42,7 @@ in many programs; here’s how to do it in Go.

- +
package main
 
@@ -57,8 +57,10 @@ parsing.

-
import "strconv"
-import "fmt"
+          
import (
+    "fmt"
+    "strconv"
+)
 
@@ -211,7 +213,7 @@ bits.

diff --git a/public/random-numbers b/public/random-numbers index ffafb2975..d3685c5ee 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -43,7 +43,7 @@ generation.

- +
package main
 
@@ -56,9 +56,11 @@ generation.

-
import "time"
-import "fmt"
-import "math/rand"
+          
import (
+    "fmt"
+    "math/rand"
+    "time"
+)
 
@@ -227,7 +229,7 @@ that Go can provide.

diff --git a/public/rate-limiting b/public/rate-limiting index 897642b50..33dd25132 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -45,7 +45,7 @@ channels, and tickers.

- +
package main
 
@@ -58,8 +58,10 @@ channels, and tickers.

-
import "time"
-import "fmt"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -259,7 +261,7 @@ then serve the remaining 2 with ~200ms delays each.

diff --git a/public/regular-expressions b/public/regular-expressions index d63163e8c..76529e33c 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -43,7 +43,7 @@ in Go.

- +
package main
 
@@ -56,9 +56,11 @@ in Go.

-
import "bytes"
-import "fmt"
-import "regexp"
+          
import (
+    "bytes"
+    "fmt"
+    "regexp"
+)
 
@@ -340,7 +342,7 @@ the regexp package docs
diff --git a/public/select b/public/select index 8be3cf48d..116ac3bac 100644 --- a/public/select +++ b/public/select @@ -43,7 +43,7 @@ select is a powerful feature of Go.

- +
package main
 
@@ -56,8 +56,10 @@ select is a powerful feature of Go.

-
import "time"
-import "fmt"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -181,7 +183,7 @@ concurrently.

diff --git a/public/sha1-hashes b/public/sha1-hashes index b072bf7df..4db037545 100644 --- a/public/sha1-hashes +++ b/public/sha1-hashes @@ -46,7 +46,7 @@ compute SHA1 hashes in Go.

- +
package main
 
@@ -61,8 +61,10 @@ compute SHA1 hashes in Go.

-
import "crypto/sha1"
-import "fmt"
+          
import (
+    "crypto/sha1"
+    "fmt"
+)
 
@@ -201,7 +203,7 @@ you should carefully research
diff --git a/public/signals b/public/signals index 28c2b5a3b..b0109b583 100644 --- a/public/signals +++ b/public/signals @@ -46,7 +46,7 @@ Here’s how to handle signals in Go with channels.

- +
package main
 
@@ -59,10 +59,12 @@ Here’s how to handle signals in Go with channels.

-
import "fmt"
-import "os"
-import "os/signal"
-import "syscall"
+          
import (
+    "fmt"
+    "os"
+    "os/signal"
+    "syscall"
+)
 
@@ -186,7 +188,7 @@ causing the program to print interrupt and then exit.

diff --git a/public/sorting b/public/sorting index b52d37587..ded8f4816 100644 --- a/public/sorting +++ b/public/sorting @@ -43,7 +43,7 @@ builtins first.

- +
package main
 
@@ -56,8 +56,10 @@ builtins first.

-
import "fmt"
-import "sort"
+          
import (
+    "fmt"
+    "sort"
+)
 
@@ -158,7 +160,7 @@ slices and true as the result of our AreSorted test. diff --git a/public/sorting-by-functions b/public/sorting-by-functions index 904dbf5ef..f86a18849 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -45,7 +45,7 @@ in Go.

- +
package main
 
@@ -58,8 +58,10 @@ in Go.

-
import "sort"
-import "fmt"
+          
import (
+    "fmt"
+    "sort"
+)
 
@@ -175,7 +177,7 @@ functions.

diff --git a/public/spawning-processes b/public/spawning-processes index 634bd6910..da8dfc5ce 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -46,7 +46,7 @@ of spawning processes from Go.

- +
package main
 
@@ -59,9 +59,11 @@ of spawning processes from Go.

-
import "fmt"
-import "io/ioutil"
-import "os/exec"
+          
import (
+    "fmt"
+    "io/ioutil"
+    "os/exec"
+)
 
@@ -257,7 +259,7 @@ as if we had run them directly from the command-line.

diff --git a/public/string-formatting b/public/string-formatting index 438e9a5d4..6616ed040 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -43,7 +43,7 @@ common string formatting tasks.

- +
package main
 
@@ -56,8 +56,10 @@ common string formatting tasks.

-
import "fmt"
-import "os"
+          
import (
+    "fmt"
+    "os"
+)
 
@@ -455,7 +457,7 @@ and returns a string without printing it anywhere.

diff --git a/public/string-functions b/public/string-functions index 05a6e1ce6..093c467b3 100644 --- a/public/string-functions +++ b/public/string-functions @@ -43,7 +43,7 @@ to give you a sense of the package.

- +
package main
 
@@ -56,8 +56,10 @@ to give you a sense of the package.

-
import s "strings"
-import "fmt"
+          
import (
+    "fmt"
+    s "strings"
+)
 
@@ -207,7 +209,7 @@ for more information.

diff --git a/public/switch b/public/switch index a93cff824..f0eff96db 100644 --- a/public/switch +++ b/public/switch @@ -42,7 +42,7 @@ branches.

- +
package main
 
@@ -55,8 +55,10 @@ branches.

-
import "fmt"
-import "time"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -201,7 +203,7 @@ type corresponding to its clause.

diff --git a/public/tickers b/public/tickers index 8bb9280bb..dd2bb2871 100644 --- a/public/tickers +++ b/public/tickers @@ -45,7 +45,7 @@ periodically until we stop it.

- +
package main
 
@@ -58,8 +58,10 @@ periodically until we stop it.

-
import "time"
-import "fmt"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -169,7 +171,7 @@ before we stop it.

diff --git a/public/time b/public/time index 49421deaa..12137d802 100644 --- a/public/time +++ b/public/time @@ -42,7 +42,7 @@ here are some examples.

- +
package main
 
@@ -55,8 +55,10 @@ here are some examples.

-
import "fmt"
-import "time"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -268,7 +270,7 @@ the Unix epoch.

diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index cd8a62a71..5c8f26644 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -42,7 +42,7 @@ pattern-based layouts.

- +
package main
 
@@ -55,8 +55,10 @@ pattern-based layouts.

-
import "fmt"
-import "time"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -202,7 +204,7 @@ explaining the parsing problem.

diff --git a/public/timeouts b/public/timeouts index 814298529..39238ed5e 100644 --- a/public/timeouts +++ b/public/timeouts @@ -44,7 +44,7 @@ elegant thanks to channels and select.

- +
package main
 
@@ -57,8 +57,10 @@ elegant thanks to channels and select.

-
import "time"
-import "fmt"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -179,7 +181,7 @@ out and the second succeeding.

diff --git a/public/timers b/public/timers index 1cff00171..977afef0c 100644 --- a/public/timers +++ b/public/timers @@ -45,7 +45,7 @@ at tickers.

- +
package main
 
@@ -58,8 +58,10 @@ at tickers.

-
import "time"
-import "fmt"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -168,7 +170,7 @@ a chance to expire.

diff --git a/public/url-parsing b/public/url-parsing index 668af2f73..0cd07f42b 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -42,7 +42,7 @@ Here’s how to parse URLs in Go.

- +
package main
 
@@ -55,9 +55,11 @@ Here’s how to parse URLs in Go.

-
import "fmt"
-import "net"
-import "net/url"
+          
import (
+    "fmt"
+    "net"
+    "net/url"
+)
 
@@ -233,7 +235,7 @@ pieces that we extracted.

diff --git a/public/worker-pools b/public/worker-pools index 0ddf1b3fb..70a6a0b09 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -42,7 +42,7 @@ a worker pool using goroutines and channels.

- +
package main
 
@@ -55,8 +55,10 @@ a worker pool using goroutines and channels.

-
import "fmt"
-import "time"
+          
import (
+    "fmt"
+    "time"
+)
 
@@ -221,7 +223,7 @@ there are 3 workers operating concurrently.

From 8d0a0e06d2d95bf2d37184a0133edc5f0900b10a Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Tue, 10 Sep 2019 14:50:34 -0400 Subject: [PATCH 006/283] Add Czech translation, closes #275 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 21686c48b..6d839900c 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ The Go Gopher is copyright [Renée French](http://reneefrench.blogspot.com/) and Contributor translations of the Go by Example site are available in: * [Chinese](https://gobyexample.xgwang.me/) by [xg-wang](https://github.com/xg-wang/gobyexample) +* [Czech](http://gobyexamples.sweb.cz/) by [martinkunc](https://github.com/martinkunc/gobyexample-cz) * [French](http://le-go-par-l-exemple.keiruaprod.fr) by [keirua](https://github.com/keirua/gobyexample) * [Italian](http://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) From e5af060488a94b44fca5ec174557d5c6f000c8eb Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 12 Sep 2019 09:29:38 -0700 Subject: [PATCH 007/283] Add basic test in main_test and check it passes with 'go test' --- examples/testing/main_test.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 examples/testing/main_test.go diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go new file mode 100644 index 000000000..e119fa007 --- /dev/null +++ b/examples/testing/main_test.go @@ -0,0 +1,20 @@ +package main + +import ( + "testing" +) + +func IntMin(a, b int) int { + if a < b { + return a + } else { + return b + } +} + +func TestIntMinBasic(t *testing.T) { + result := IntMin(2, -2) + if result != -2 { + t.Errorf("IntMin(2, -2) = %d; want -2", result) + } +} From 507f2b6145a1f3852c6c027f33c1f881522e95fb Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 12 Sep 2019 11:23:01 -0700 Subject: [PATCH 008/283] Added table-driven tests and comments --- examples/testing/main_test.go | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index e119fa007..2fc5eccb4 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -1,9 +1,23 @@ +// Unit testing is an important part of writing +// principled Go programs. The `testing` package +// provides the tools we need to write unit tests +// and the `go test` command runs tests. + +// For the same of demonstration, this code is in package +// `main`, but it could be any package. Testing code +// typically lives in the same package as the code it tests. package main import ( + "fmt" "testing" ) +// We'll be testing this simple implementation of an +// integer minimum. Typically, the code we're testing +// would be in a source file named something like +// `intutils.go`, and the test file for it would then +// be named `intutils_test.go`. func IntMin(a, b int) int { if a < b { return a @@ -12,9 +26,43 @@ func IntMin(a, b int) int { } } +// A test is created by writing a function with a name +// beginning with `Test`. func TestIntMinBasic(t *testing.T) { result := IntMin(2, -2) if result != -2 { + // `t.Error*` will report test failures but continue + // executing the test. `t.Fail*` will report test + // failures and stop the test immediately. t.Errorf("IntMin(2, -2) = %d; want -2", result) } } + +// Writing tests can be repetitive, so it's idiomatic to +// use a *table-driven style*, where test inputs and +// expected outputs are listed in a table and a single loop +// walks over them and performs the test logic. +func TestIntMinTableDriven(t *testing.T) { + var tests = []struct { + a, b int + expected int + }{ + {0, 1, 0}, + {1, 0, 0}, + {2, -2, -2}, + {0, -1, -1}, + {-1, 0, -1}, + } + + for _, tt := range tests { + // t.Run enables running "subtests", one for each + // table entry. These will be reported separately + // when executing `go test -v`. + t.Run(fmt.Sprintf("%d,%d", tt.a, tt.b), func(t *testing.T) { + result := IntMin(tt.a, tt.b) + if result != tt.expected { + t.Errorf("got %d, want %d", result, tt.expected) + } + }) + } +} From be9b84288c3ceabe6d00a73ae6c01e7896b5976d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 12 Sep 2019 11:30:07 -0700 Subject: [PATCH 009/283] Add a new example: testing --- examples.txt | 1 + examples/testing/main_test.go | 23 +-- examples/testing/main_test.sh | 18 ++ examples/testing/testing.hash | 2 + public/command-line-arguments | 2 +- public/index.html | 2 + public/temporary-files-and-directories | 4 +- public/testing | 239 +++++++++++++++++++++++++ 8 files changed, 277 insertions(+), 14 deletions(-) create mode 100644 examples/testing/main_test.sh create mode 100644 examples/testing/testing.hash create mode 100644 public/testing diff --git a/examples.txt b/examples.txt index 880802faf..dd3c1579b 100644 --- a/examples.txt +++ b/examples.txt @@ -61,6 +61,7 @@ Line Filters File Paths Directories Temporary Files and Directories +Testing Command-Line Arguments Command-Line Flags Command-Line Subcommands diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index 2fc5eccb4..3bcdd6ec0 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -3,7 +3,7 @@ // provides the tools we need to write unit tests // and the `go test` command runs tests. -// For the same of demonstration, this code is in package +// For the sake of demonstration, this code is in package // `main`, but it could be any package. Testing code // typically lives in the same package as the code it tests. package main @@ -29,12 +29,12 @@ func IntMin(a, b int) int { // A test is created by writing a function with a name // beginning with `Test`. func TestIntMinBasic(t *testing.T) { - result := IntMin(2, -2) - if result != -2 { + ans := IntMin(2, -2) + if ans != -2 { // `t.Error*` will report test failures but continue // executing the test. `t.Fail*` will report test // failures and stop the test immediately. - t.Errorf("IntMin(2, -2) = %d; want -2", result) + t.Errorf("IntMin(2, -2) = %d; want -2", ans) } } @@ -44,8 +44,8 @@ func TestIntMinBasic(t *testing.T) { // walks over them and performs the test logic. func TestIntMinTableDriven(t *testing.T) { var tests = []struct { - a, b int - expected int + a, b int + want int }{ {0, 1, 0}, {1, 0, 0}, @@ -56,12 +56,13 @@ func TestIntMinTableDriven(t *testing.T) { for _, tt := range tests { // t.Run enables running "subtests", one for each - // table entry. These will be reported separately + // table entry. These are shown separately // when executing `go test -v`. - t.Run(fmt.Sprintf("%d,%d", tt.a, tt.b), func(t *testing.T) { - result := IntMin(tt.a, tt.b) - if result != tt.expected { - t.Errorf("got %d, want %d", result, tt.expected) + testname := fmt.Sprintf("%d,%d", tt.a, tt.b) + t.Run(testname, func(t *testing.T) { + ans := IntMin(tt.a, tt.b) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) } }) } diff --git a/examples/testing/main_test.sh b/examples/testing/main_test.sh new file mode 100644 index 000000000..58e0615e5 --- /dev/null +++ b/examples/testing/main_test.sh @@ -0,0 +1,18 @@ +# Run all tests in the current project in verbose mode. +$ go test -v +== RUN TestIntMinBasic +--- PASS: TestIntMinBasic (0.00s) +=== RUN TestIntMinTableDriven +=== RUN TestIntMinTableDriven/0,1 +=== RUN TestIntMinTableDriven/1,0 +=== RUN TestIntMinTableDriven/2,-2 +=== RUN TestIntMinTableDriven/0,-1 +=== RUN TestIntMinTableDriven/-1,0 +--- PASS: TestIntMinTableDriven (0.00s) + --- PASS: TestIntMinTableDriven/0,1 (0.00s) + --- PASS: TestIntMinTableDriven/1,0 (0.00s) + --- PASS: TestIntMinTableDriven/2,-2 (0.00s) + --- PASS: TestIntMinTableDriven/0,-1 (0.00s) + --- PASS: TestIntMinTableDriven/-1,0 (0.00s) +PASS +ok examples/testing 0.023s diff --git a/examples/testing/testing.hash b/examples/testing/testing.hash new file mode 100644 index 000000000..317487fad --- /dev/null +++ b/examples/testing/testing.hash @@ -0,0 +1,2 @@ +8f00c5178a33be2e92a853f14bfc3fbf0919cd97 +fyy7h1adGWr diff --git a/public/command-line-arguments b/public/command-line-arguments index a2aa9ff3a..593e93f91 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'temporary-files-and-directories'; + window.location.href = 'testing'; } diff --git a/public/index.html b/public/index.html index 74ff2610b..94549ee2d 100644 --- a/public/index.html +++ b/public/index.html @@ -149,6 +149,8 @@

Go by Example

  • Temporary Files and Directories
  • +
  • Testing
  • +
  • Command-Line Arguments
  • Command-Line Flags
  • diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 37d783167..93bd965b8 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'command-line-arguments'; + window.location.href = 'testing'; } } @@ -232,7 +232,7 @@ prefixing them with our temporary directory.

    - Next example: Command-Line Arguments. + Next example: Testing.

    +

    Go by Example: Testing

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Unit testing is an important part of writing +principled Go programs. The testing package +provides the tools we need to write unit tests +and the go test command runs tests.

    + +
    + + +
    +

    For the sake of demonstration, this code is in package +main, but it could be any package. Testing code +typically lives in the same package as the code it tests.

    + +
    + +
    package main
    +
    + +
    + + + +
    import (
    +    "fmt"
    +    "testing"
    +)
    +
    + +
    +

    We’ll be testing this simple implementation of an +integer minimum. Typically, the code we’re testing +would be in a source file named something like +intutils.go, and the test file for it would then +be named intutils_test.go.

    + +
    + +
    func IntMin(a, b int) int {
    +    if a < b {
    +        return a
    +    } else {
    +        return b
    +    }
    +}
    +
    + +
    +

    A test is created by writing a function with a name +beginning with Test.

    + +
    + +
    func TestIntMinBasic(t *testing.T) {
    +    ans := IntMin(2, -2)
    +    if ans != -2 {
    +
    + +
    +

    t.Error* will report test failures but continue +executing the test. t.Fail* will report test +failures and stop the test immediately.

    + +
    + +
            t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    +    }
    +}
    +
    + +
    +

    Writing tests can be repetitive, so it’s idiomatic to +use a table-driven style, where test inputs and +expected outputs are listed in a table and a single loop +walks over them and performs the test logic.

    + +
    + +
    func TestIntMinTableDriven(t *testing.T) {
    +    var tests = []struct {
    +        a, b int
    +        want int
    +    }{
    +        {0, 1, 0},
    +        {1, 0, 0},
    +        {2, -2, -2},
    +        {0, -1, -1},
    +        {-1, 0, -1},
    +    }
    +
    + +
    +

    t.Run enables running “subtests”, one for each +table entry. These are shown separately +when executing go test -v.

    + +
    + +
        for _, tt := range tests {
    +
    + +
    + + + +
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
    +        t.Run(testname, func(t *testing.T) {
    +            ans := IntMin(tt.a, tt.b)
    +            if ans != tt.want {
    +                t.Errorf("got %d, want %d", ans, tt.want)
    +            }
    +        })
    +    }
    +}
    +
    + +
    + + + + + + + + +
    +

    Run all tests in the current project in verbose mode.

    + +
    + +
    $ go test -v
    +== RUN   TestIntMinBasic
    +--- PASS: TestIntMinBasic (0.00s)
    +=== RUN   TestIntMinTableDriven
    +=== RUN   TestIntMinTableDriven/0,1
    +=== RUN   TestIntMinTableDriven/1,0
    +=== RUN   TestIntMinTableDriven/2,-2
    +=== RUN   TestIntMinTableDriven/0,-1
    +=== RUN   TestIntMinTableDriven/-1,0
    +--- PASS: TestIntMinTableDriven (0.00s)
    +    --- PASS: TestIntMinTableDriven/0,1 (0.00s)
    +    --- PASS: TestIntMinTableDriven/1,0 (0.00s)
    +    --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
    +    --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
    +    --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
    +PASS
    +ok      examples/testing    0.023s
    +
    + +
    + + +

    + Next example: Command-Line Arguments. +

    + + +
    + + + + From 1c4e40df3f7903fa0e7a968dfaaa7932dd82879c Mon Sep 17 00:00:00 2001 From: danitello Date: Sun, 15 Sep 2019 12:46:45 -0700 Subject: [PATCH 010/283] Structs - fix example output --- examples/structs/structs.sh | 4 ++-- public/structs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/structs/structs.sh b/examples/structs/structs.sh index f0d6025b6..039fd000b 100644 --- a/examples/structs/structs.sh +++ b/examples/structs/structs.sh @@ -3,7 +3,7 @@ $ go run structs.go {Alice 30} {Fred 0} &{Ann 40} +&{Jon 42} Sean 50 -51 -&{Jon 42} \ No newline at end of file +51 \ No newline at end of file diff --git a/public/structs b/public/structs index 672b2144f..0bb814c55 100644 --- a/public/structs +++ b/public/structs @@ -244,10 +244,10 @@ pointers are automatically dereferenced.

    {Alice 30} {Fred 0} &{Ann 40} +&{Jon 42} Sean 50 51 -&{Jon 42}
    From 61e8dde1c18f31aa40efedcf8d282a1976cbbc68 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 20 Sep 2019 14:55:41 -0700 Subject: [PATCH 011/283] Use time.Sleep instead of fmt.Scanln to wait for goroutines The Scanln doesn't work on the Go playground Fixes #279 --- examples/goroutines/goroutines.go | 12 +++++++----- examples/goroutines/goroutines.hash | 4 ++-- examples/goroutines/goroutines.sh | 1 - public/goroutines | 17 +++++++++-------- 4 files changed, 18 insertions(+), 16 deletions(-) diff --git a/examples/goroutines/goroutines.go b/examples/goroutines/goroutines.go index c2bdde87a..4943ec93f 100644 --- a/examples/goroutines/goroutines.go +++ b/examples/goroutines/goroutines.go @@ -2,7 +2,10 @@ package main -import "fmt" +import ( + "fmt" + "time" +) func f(from string) { for i := 0; i < 3; i++ { @@ -29,9 +32,8 @@ func main() { }("going") // Our two function calls are running asynchronously in - // separate goroutines now, so execution falls through - // to here. This `Scanln` requires we press a key - // before the program exits. - fmt.Scanln() + // separate goroutines now. Wait for them to finish + // (for a more robust approach, use a [WaitGroup](waitgroups)). + time.Sleep(time.Second) fmt.Println("done") } diff --git a/examples/goroutines/goroutines.hash b/examples/goroutines/goroutines.hash index e86550b81..a83b7b83b 100644 --- a/examples/goroutines/goroutines.hash +++ b/examples/goroutines/goroutines.hash @@ -1,2 +1,2 @@ -bfdaa0c8104c1257e6fea102fd26d476a3e8c14e -6Y8t3Yxd1LD +3737e7b5129b649d202e75225a1ac732eda116d0 +rovAFf9-n78 diff --git a/examples/goroutines/goroutines.sh b/examples/goroutines/goroutines.sh index 2dcf3bb37..1d42ee279 100644 --- a/examples/goroutines/goroutines.sh +++ b/examples/goroutines/goroutines.sh @@ -10,7 +10,6 @@ goroutine : 0 going goroutine : 1 goroutine : 2 - done # Next we'll look at a complement to goroutines in diff --git a/public/goroutines b/public/goroutines index a7a4222c1..6b87012d6 100644 --- a/public/goroutines +++ b/public/goroutines @@ -41,7 +41,7 @@ - +
    package main
     
    @@ -54,7 +54,10 @@ -
    import "fmt"
    +          
    import (
    +    "fmt"
    +    "time"
    +)
     
    @@ -137,14 +140,13 @@ function call.

    Our two function calls are running asynchronously in -separate goroutines now, so execution falls through -to here. This Scanln requires we press a key -before the program exits.

    +separate goroutines now. Wait for them to finish +(for a more robust approach, use a WaitGroup).

    -
        fmt.Scanln()
    +          
        time.Sleep(time.Second)
         fmt.Println("done")
     }
     
    @@ -174,7 +176,6 @@ goroutines being run concurrently by the Go runtime.

    going goroutine : 1 goroutine : 2 -<enter> done
    @@ -206,7 +207,7 @@ concurrent Go programs: channels.

    From 4076ee15e5df11ad68018094ce8cbc7dc2556cf3 Mon Sep 17 00:00:00 2001 From: Jerry Kotas Date: Thu, 10 Oct 2019 15:38:15 -0400 Subject: [PATCH 012/283] Fixed comment in tickers.go --- examples/tickers/tickers.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/tickers/tickers.go b/examples/tickers/tickers.go index c23dd5cde..d9615d317 100644 --- a/examples/tickers/tickers.go +++ b/examples/tickers/tickers.go @@ -15,8 +15,8 @@ func main() { // Tickers use a similar mechanism to timers: a // channel that is sent values. Here we'll use the - // `range` builtin on the channel to iterate over - // the values as they arrive every 500ms. + // `select` builtin on the channel to await the + // values as they arrive every 500ms. ticker := time.NewTicker(500 * time.Millisecond) done := make(chan bool) From c06d8a62c5f32b4c0a724785a213a06234f35372 Mon Sep 17 00:00:00 2001 From: Scott Moser Date: Wed, 9 Oct 2019 16:02:33 -0400 Subject: [PATCH 013/283] Use SplitN rather than Split on os.Environ return value. Environment variables can contain a '=' in their value KEY=BAR=1 sh -c 'echo KEY VALUE is "$KEY"' If you just use Split() then you may not actually get a 'pair' but rather a slice with length >= 3. --- examples/environment-variables/environment-variables.go | 2 +- examples/environment-variables/environment-variables.hash | 4 ++-- public/environment-variables | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/environment-variables/environment-variables.go b/examples/environment-variables/environment-variables.go index b316b8afc..d1754a1d8 100644 --- a/examples/environment-variables/environment-variables.go +++ b/examples/environment-variables/environment-variables.go @@ -27,7 +27,7 @@ func main() { // get the key and value. Here we print all the keys. fmt.Println() for _, e := range os.Environ() { - pair := strings.Split(e, "=") + pair := strings.SplitN(e, "=", 2) fmt.Println(pair[0]) } } diff --git a/examples/environment-variables/environment-variables.hash b/examples/environment-variables/environment-variables.hash index b2458517f..e41003837 100644 --- a/examples/environment-variables/environment-variables.hash +++ b/examples/environment-variables/environment-variables.hash @@ -1,2 +1,2 @@ -db2e203da519a22943753295e9cc27d89e4347b0 -bKuCOOD16KH +b651bc17e4d2880cba0885c52f476ab2a86e39ae +MTbfmZYa4vP diff --git a/public/environment-variables b/public/environment-variables index 25504ae69..9920efd2a 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -44,7 +44,7 @@ Let’s look at how to set, get, and list environment variables.

    - +
    package main
     
    @@ -109,7 +109,7 @@ get the key and value. Here we print all the keys.

        fmt.Println()
         for _, e := range os.Environ() {
    -        pair := strings.Split(e, "=")
    +        pair := strings.SplitN(e, "=", 2)
             fmt.Println(pair[0])
         }
     }
    @@ -186,7 +186,7 @@ program picks that value up.

    From 2c7063ec2fee3e0fdebacec9a218136d9fdac351 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 13 Oct 2019 18:28:25 -0700 Subject: [PATCH 014/283] Rebuild --- examples/tickers/tickers.hash | 4 ++-- public/tickers | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/tickers/tickers.hash b/examples/tickers/tickers.hash index e724ec153..cd2eaf3df 100644 --- a/examples/tickers/tickers.hash +++ b/examples/tickers/tickers.hash @@ -1,2 +1,2 @@ -4a42333d14f902e890902343c7bd9b9c735fd8ad -n1q1sSGEvmv +05a1e62b5d363b67df0f9bac5c8f75dc19ca2c54 +E1ro_QHJD9L diff --git a/public/tickers b/public/tickers index dd2bb2871..82648e0a1 100644 --- a/public/tickers +++ b/public/tickers @@ -45,7 +45,7 @@ periodically until we stop it.

    - +
    package main
     
    @@ -83,8 +83,8 @@ periodically until we stop it.

    Tickers use a similar mechanism to timers: a channel that is sent values. Here we’ll use the -range builtin on the channel to iterate over -the values as they arrive every 500ms.

    +select builtin on the channel to await the +values as they arrive every 500ms.

    From 43825687bb7a06f763e6ece279103f3de276e042 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 13 Oct 2019 18:29:40 -0700 Subject: [PATCH 015/283] Rebuild for environment-variables --- examples/environment-variables/environment-variables.go | 2 +- examples/environment-variables/environment-variables.hash | 4 ++-- public/environment-variables | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/environment-variables/environment-variables.go b/examples/environment-variables/environment-variables.go index d1754a1d8..e3e42a5de 100644 --- a/examples/environment-variables/environment-variables.go +++ b/examples/environment-variables/environment-variables.go @@ -23,7 +23,7 @@ func main() { // Use `os.Environ` to list all key/value pairs in the // environment. This returns a slice of strings in the - // form `KEY=value`. You can `strings.Split` them to + // form `KEY=value`. You can `strings.SplitN` them to // get the key and value. Here we print all the keys. fmt.Println() for _, e := range os.Environ() { diff --git a/examples/environment-variables/environment-variables.hash b/examples/environment-variables/environment-variables.hash index e41003837..e12d01d1b 100644 --- a/examples/environment-variables/environment-variables.hash +++ b/examples/environment-variables/environment-variables.hash @@ -1,2 +1,2 @@ -b651bc17e4d2880cba0885c52f476ab2a86e39ae -MTbfmZYa4vP +69d6a768ac84c873ae03b2169ac5cc4cfbc601a6 +gSTxKWLOHRb diff --git a/public/environment-variables b/public/environment-variables index 9920efd2a..ecaef7e02 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -44,7 +44,7 @@ Let’s look at how to set, get, and list environment variables.

    - +
    package main
     
    @@ -101,7 +101,7 @@ environment.

    Use os.Environ to list all key/value pairs in the environment. This returns a slice of strings in the -form KEY=value. You can strings.Split them to +form KEY=value. You can strings.SplitN them to get the key and value. Here we print all the keys.

    From 50f8ce8382184c653f460d2366f4e1da3ad901bf Mon Sep 17 00:00:00 2001 From: Oleg Butuzov Date: Tue, 22 Oct 2019 13:48:43 +0300 Subject: [PATCH 016/283] Ukrainian Translation URL changes As gobyexample.com.ua going to be dropped soon, translation moving to github pages hosting. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d839900c..c208ec733 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Contributor translations of the Go by Example site are available in: * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) -* [Ukrainian](http://gobyexample.com.ua/) by [butuzov](https://github.com/butuzov/gobyexample) +* [Ukrainian](http://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) ### Thanks From 646c8b39da6a59649a2575575f6a7d174ec78422 Mon Sep 17 00:00:00 2001 From: Oleg Butuzov Date: Tue, 22 Oct 2019 14:27:02 +0300 Subject: [PATCH 017/283] bugfix (mmcgrana/gobyexample#294) sha1 sum calculator This bugfix implements correct way to calculate source sha1 hash, before it will changed, by propagation of unchanged sources. This commit will also include regenerated static files and *.hash files. --- examples/arrays/arrays.hash | 4 ++-- examples/atomic-counters/atomic-counters.hash | 4 ++-- examples/base64-encoding/base64-encoding.hash | 4 ++-- examples/channel-buffering/channel-buffering.hash | 4 ++-- examples/channel-directions/channel-directions.hash | 4 ++-- .../channel-synchronization/channel-synchronization.hash | 4 ++-- examples/channels/channels.hash | 4 ++-- examples/closing-channels/closing-channels.hash | 4 ++-- examples/closures/closures.hash | 4 ++-- examples/collection-functions/collection-functions.hash | 4 ++-- .../command-line-arguments/command-line-arguments.hash | 4 ++-- examples/command-line-flags/command-line-flags.hash | 4 ++-- .../command-line-subcommands.hash | 4 ++-- examples/constants/constants.hash | 4 ++-- examples/defer/defer.hash | 4 ++-- examples/directories/directories.hash | 4 ++-- examples/environment-variables/environment-variables.hash | 4 ++-- examples/epoch/epoch.hash | 4 ++-- examples/errors/errors.hash | 4 ++-- examples/execing-processes/execing-processes.hash | 4 ++-- examples/exit/exit.hash | 4 ++-- examples/file-paths/file-paths.hash | 4 ++-- examples/for/for.hash | 4 ++-- examples/functions/functions.hash | 4 ++-- examples/goroutines/goroutines.hash | 4 ++-- examples/hello-world/hello-world.hash | 4 ++-- examples/http-clients/http-clients.hash | 4 ++-- examples/http-servers/http-servers.hash | 4 ++-- examples/if-else/if-else.hash | 4 ++-- examples/interfaces/interfaces.hash | 4 ++-- examples/json/json.hash | 4 ++-- examples/line-filters/line-filters.hash | 4 ++-- examples/maps/maps.hash | 4 ++-- examples/methods/methods.hash | 4 ++-- .../multiple-return-values/multiple-return-values.hash | 4 ++-- examples/mutexes/mutexes.hash | 4 ++-- .../non-blocking-channel-operations.hash | 4 ++-- examples/number-parsing/number-parsing.hash | 4 ++-- examples/panic/panic.hash | 4 ++-- examples/pointers/pointers.hash | 4 ++-- examples/random-numbers/random-numbers.hash | 4 ++-- examples/range-over-channels/range-over-channels.hash | 4 ++-- examples/range/range.hash | 4 ++-- examples/rate-limiting/rate-limiting.hash | 4 ++-- examples/reading-files/reading-files.hash | 4 ++-- examples/recursion/recursion.hash | 4 ++-- examples/regular-expressions/regular-expressions.hash | 4 ++-- examples/select/select.hash | 4 ++-- examples/sha1-hashes/sha1-hashes.hash | 4 ++-- examples/signals/signals.hash | 4 ++-- examples/slices/slices.hash | 4 ++-- examples/sorting-by-functions/sorting-by-functions.hash | 4 ++-- examples/sorting/sorting.hash | 4 ++-- examples/spawning-processes/spawning-processes.hash | 4 ++-- examples/stateful-goroutines/stateful-goroutines.hash | 4 ++-- examples/string-formatting/string-formatting.hash | 4 ++-- examples/string-functions/string-functions.hash | 4 ++-- examples/structs/structs.hash | 4 ++-- examples/switch/switch.hash | 4 ++-- .../temporary-files-and-directories.hash | 4 ++-- examples/testing/testing.hash | 4 ++-- examples/tickers/tickers.hash | 4 ++-- .../time-formatting-parsing/time-formatting-parsing.hash | 4 ++-- examples/time/time.hash | 4 ++-- examples/timeouts/timeouts.hash | 4 ++-- examples/timers/timers.hash | 4 ++-- examples/url-parsing/url-parsing.hash | 4 ++-- examples/values/values.hash | 4 ++-- examples/variables/variables.hash | 4 ++-- examples/variadic-functions/variadic-functions.hash | 4 ++-- examples/waitgroups/waitgroups.hash | 4 ++-- examples/worker-pools/worker-pools.hash | 4 ++-- examples/writing-files/writing-files.hash | 4 ++-- examples/xml/xml.hash | 4 ++-- public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 2 +- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 2 +- public/collection-functions | 2 +- public/command-line-arguments | 2 +- public/command-line-flags | 2 +- public/command-line-subcommands | 2 +- public/constants | 2 +- public/defer | 2 +- public/directories | 2 +- public/environment-variables | 2 +- public/epoch | 2 +- public/errors | 2 +- public/execing-processes | 2 +- public/exit | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/goroutines | 2 +- public/hello-world | 2 +- public/http-clients | 2 +- public/http-servers | 2 +- public/if-else | 2 +- public/interfaces | 2 +- public/json | 2 +- public/line-filters | 2 +- public/maps | 2 +- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 2 +- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 2 +- public/random-numbers | 2 +- public/range | 2 +- public/range-over-channels | 2 +- public/rate-limiting | 2 +- public/reading-files | 2 +- public/recursion | 2 +- public/regular-expressions | 2 +- public/select | 2 +- public/sha1-hashes | 2 +- public/signals | 2 +- public/slices | 2 +- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 2 +- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- tools/generate.go | 8 ++++++-- 149 files changed, 228 insertions(+), 224 deletions(-) diff --git a/examples/arrays/arrays.hash b/examples/arrays/arrays.hash index cae0e0dc2..c04751e96 100644 --- a/examples/arrays/arrays.hash +++ b/examples/arrays/arrays.hash @@ -1,2 +1,2 @@ -305975d13d24223181d13f042b290906d86c1a0e -W7NwfDq8Vdw +e71f2d3763eb2950727faa39b90cf1bc037d85fa +TaahifSGSwU diff --git a/examples/atomic-counters/atomic-counters.hash b/examples/atomic-counters/atomic-counters.hash index 989ed197c..f4c10e6d5 100644 --- a/examples/atomic-counters/atomic-counters.hash +++ b/examples/atomic-counters/atomic-counters.hash @@ -1,2 +1,2 @@ -8ebec0be3b167021c96b8b497d0e8c0a2ea99385 -F2pJfduyQiA +7b491b40d56a77b01d8e2bd08366de081a4e8d99 +j-14agntvEO diff --git a/examples/base64-encoding/base64-encoding.hash b/examples/base64-encoding/base64-encoding.hash index 717ff3f66..09e2b2a41 100644 --- a/examples/base64-encoding/base64-encoding.hash +++ b/examples/base64-encoding/base64-encoding.hash @@ -1,2 +1,2 @@ -e0148b9b4acb01e849b8f678cba03f549d250c44 -V3oV1bvh94k +cd00d89ad0a31e48d6a2e2adc2e8d65b0f70dc73 +S7ff3UgzNlG diff --git a/examples/channel-buffering/channel-buffering.hash b/examples/channel-buffering/channel-buffering.hash index 6956e0360..74e0a9be0 100644 --- a/examples/channel-buffering/channel-buffering.hash +++ b/examples/channel-buffering/channel-buffering.hash @@ -1,2 +1,2 @@ -122140f7ad1bc5cff4fcd7a9e7245b87aaca3ec5 -mPoF-Xi-rip +558f4f1140a52e1804636f5720a10de0b37ebddb +3BRCdRnRszb diff --git a/examples/channel-directions/channel-directions.hash b/examples/channel-directions/channel-directions.hash index fb68662c8..b84878195 100644 --- a/examples/channel-directions/channel-directions.hash +++ b/examples/channel-directions/channel-directions.hash @@ -1,2 +1,2 @@ -635cc13dfe33123ac188e01e3002d3aa935d765f -Jnn9_9hC48c +d1b1580f72c3c101ea46480e6c2361f4f96b049a +mjNJDHwUH4R diff --git a/examples/channel-synchronization/channel-synchronization.hash b/examples/channel-synchronization/channel-synchronization.hash index 9dea9a004..4c3c3a41b 100644 --- a/examples/channel-synchronization/channel-synchronization.hash +++ b/examples/channel-synchronization/channel-synchronization.hash @@ -1,2 +1,2 @@ -0d5a9de912e2a4a18943e082e2f8107cb75d0ce4 -fe9If6OhYMk +aa83d53fdee417727ec9a7cd90172d34c15a28c2 +Nw-1DzIGk5f diff --git a/examples/channels/channels.hash b/examples/channels/channels.hash index 92301ce86..480ea9d80 100644 --- a/examples/channels/channels.hash +++ b/examples/channels/channels.hash @@ -1,2 +1,2 @@ -926212c784ab820648906c96f6ab21afbc161526 -bRGMAqinovA +4fa3a8956f7f1ded57e8dc72827329aef8497e18 +MaLY7AiAkHM diff --git a/examples/closing-channels/closing-channels.hash b/examples/closing-channels/closing-channels.hash index 007751fde..3e33a0715 100644 --- a/examples/closing-channels/closing-channels.hash +++ b/examples/closing-channels/closing-channels.hash @@ -1,2 +1,2 @@ -5205898a520533e46ea24c849848d19ebc2d08a9 -mkz69rVMHs6 +8f26c901e0f14df2ca40329a354c3ac86a5c3a07 +vCvRjcMq7p3 diff --git a/examples/closures/closures.hash b/examples/closures/closures.hash index fa66f0ff9..df8a22b03 100644 --- a/examples/closures/closures.hash +++ b/examples/closures/closures.hash @@ -1,2 +1,2 @@ -e304df67e760dda93ffe434aca58aea4a6c94f19 -zb93qzV6iN3 +6713bdbb6de0d7d484422517dd77316c8b9f0a7a +66Lgw9iIIch diff --git a/examples/collection-functions/collection-functions.hash b/examples/collection-functions/collection-functions.hash index abbd3d524..27465b8db 100644 --- a/examples/collection-functions/collection-functions.hash +++ b/examples/collection-functions/collection-functions.hash @@ -1,2 +1,2 @@ -28456737ea996664bdaeb8e1e821d95697d00646 -8hI6oPNEfyh +002b2ee17f1111c7607a7b7742753af1b5a3c8c1 +uKnePZM91WV diff --git a/examples/command-line-arguments/command-line-arguments.hash b/examples/command-line-arguments/command-line-arguments.hash index ad22b5916..658742928 100644 --- a/examples/command-line-arguments/command-line-arguments.hash +++ b/examples/command-line-arguments/command-line-arguments.hash @@ -1,2 +1,2 @@ -9c80d495201148bbeb0fd0a5a2ce1735aeb34b60 -myJy_-H8Fo_Q +d60d1c9cb5dbbb748cf3b692334076951cea7d59 +oSxtj7v_v1K diff --git a/examples/command-line-flags/command-line-flags.hash b/examples/command-line-flags/command-line-flags.hash index abee236af..f59c45a7e 100644 --- a/examples/command-line-flags/command-line-flags.hash +++ b/examples/command-line-flags/command-line-flags.hash @@ -1,2 +1,2 @@ -ab08bf890dcd87b807956b5bee441d59efe458e3 -lPaZodnG9TF +e86d2c60cee18fa926ce1eea60bd082837bd950b +fD0SmjD4GdZ diff --git a/examples/command-line-subcommands/command-line-subcommands.hash b/examples/command-line-subcommands/command-line-subcommands.hash index f22bcc812..ae70db7d1 100644 --- a/examples/command-line-subcommands/command-line-subcommands.hash +++ b/examples/command-line-subcommands/command-line-subcommands.hash @@ -1,2 +1,2 @@ -5a0ec258e4992e9b93b11d48f2f249092ff3db66 -gtgSAg76N4I +eed015f91ba8a8d5a667dfc4dde745e341fded6e +DkvdHKK-XCv diff --git a/examples/constants/constants.hash b/examples/constants/constants.hash index 93d42caac..3f409497f 100644 --- a/examples/constants/constants.hash +++ b/examples/constants/constants.hash @@ -1,2 +1,2 @@ -7cc09460e8dc6fffd0ba811679f92a85eb51e927 -gmjHSglwLic +9f776516953ae57a76544444c72802d3fad63da3 +Vw-pXSfo9_b diff --git a/examples/defer/defer.hash b/examples/defer/defer.hash index d45bfd754..de9f4dad0 100644 --- a/examples/defer/defer.hash +++ b/examples/defer/defer.hash @@ -1,2 +1,2 @@ -4fc23579a9bd5d8512884902394f4dce51eb7d60 -QJJ2R6kv6K5 +f0eb978a0cdbacc5e4d709bccce6cea6b71be39f +5SDVfc_jxbg diff --git a/examples/directories/directories.hash b/examples/directories/directories.hash index cebae5692..7dae4aa15 100644 --- a/examples/directories/directories.hash +++ b/examples/directories/directories.hash @@ -1,2 +1,2 @@ -83f67db91816b4544072d0a4d099111a21c60723 --7kWq0PmATF +fa3655fa8f4fa28e971cbe853dffb02773afce83 +UaeLMS5VQVR diff --git a/examples/environment-variables/environment-variables.hash b/examples/environment-variables/environment-variables.hash index e12d01d1b..bf640457e 100644 --- a/examples/environment-variables/environment-variables.hash +++ b/examples/environment-variables/environment-variables.hash @@ -1,2 +1,2 @@ -69d6a768ac84c873ae03b2169ac5cc4cfbc601a6 -gSTxKWLOHRb +bee983e7820d64dec5331dc706c08f6135b5c632 +KuD8tDyB4lQ diff --git a/examples/epoch/epoch.hash b/examples/epoch/epoch.hash index d37c230ff..ad0a47164 100644 --- a/examples/epoch/epoch.hash +++ b/examples/epoch/epoch.hash @@ -1,2 +1,2 @@ -184c8f3e94dd28176be81956115ac417e33513a6 -3uYNHHRplmQ +3b1fc502f41a978f1c8150335801aa9096db8954 +0ooeler0RfR diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index b650d2559..a1f74a51c 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -ed58ad3162d93c723d3efe72529a61ce7041fe13 -vrwN32gxaYx +00affa44cc98f14c2b10934a4187c9445fac0fe6 +NiJOpCPO3L0 diff --git a/examples/execing-processes/execing-processes.hash b/examples/execing-processes/execing-processes.hash index 020f78e5d..90da7c400 100644 --- a/examples/execing-processes/execing-processes.hash +++ b/examples/execing-processes/execing-processes.hash @@ -1,2 +1,2 @@ -e6b4830d4264f307506b54726ec79b25a0363874 -ahZjpJaZz44 +7a8185c4b55c20a678f1e51698f0f4b6e25d4536 +T3da5euHejy diff --git a/examples/exit/exit.hash b/examples/exit/exit.hash index 234717b79..6be0f6336 100644 --- a/examples/exit/exit.hash +++ b/examples/exit/exit.hash @@ -1,2 +1,2 @@ -2316e6c8e364e2066c6bd350dc9b0b2af85b63fe -OX997ykuOGx +16f2c50f58d9d113f2cdd5367ddd95a220d89b19 +b9aYzlENkb__R diff --git a/examples/file-paths/file-paths.hash b/examples/file-paths/file-paths.hash index f1610a14c..872cc7b50 100644 --- a/examples/file-paths/file-paths.hash +++ b/examples/file-paths/file-paths.hash @@ -1,2 +1,2 @@ -1215302b9e59ee9dee21dcd3c47d5f6c672fb058 -QIitbMNiFRx +10823f6a3f4daea097a91374efa88c4361932488 +5h3lUytvmyO diff --git a/examples/for/for.hash b/examples/for/for.hash index 7852dec97..2b9b9907d 100644 --- a/examples/for/for.hash +++ b/examples/for/for.hash @@ -1,2 +1,2 @@ -33056d6b36f9894fb6359c9cf2ef8725bbdafa19 -lGYfUJwiGfi +50eb0c667de576107da5f814f5780754b724346a +jPI-IwqVC1c diff --git a/examples/functions/functions.hash b/examples/functions/functions.hash index 85d4e8fe2..c1efad973 100644 --- a/examples/functions/functions.hash +++ b/examples/functions/functions.hash @@ -1,2 +1,2 @@ -ae669923c20e5ebf4a7b4b11b8fdf2972accf9e2 -hzGUvK6iJNm +94ade6d23721234a9612c9f77431106308b84953 +-o49-dQfGbK diff --git a/examples/goroutines/goroutines.hash b/examples/goroutines/goroutines.hash index a83b7b83b..63a8b2c4a 100644 --- a/examples/goroutines/goroutines.hash +++ b/examples/goroutines/goroutines.hash @@ -1,2 +1,2 @@ -3737e7b5129b649d202e75225a1ac732eda116d0 -rovAFf9-n78 +08aa2b9e426724e07ec83162eb6892648ccc7fd5 +I7scqRijEJt diff --git a/examples/hello-world/hello-world.hash b/examples/hello-world/hello-world.hash index df7b0e0cd..658e0743e 100644 --- a/examples/hello-world/hello-world.hash +++ b/examples/hello-world/hello-world.hash @@ -1,2 +1,2 @@ -c98395a44701add5bf84e2f3a63e300fc1bc4bfe -mp1ENMU6ZYu +3eb6e21f5f89b9a4bf64f267972a24211f0032e7 +NeviD0awXjt diff --git a/examples/http-clients/http-clients.hash b/examples/http-clients/http-clients.hash index e550dd504..b36a4b2da 100644 --- a/examples/http-clients/http-clients.hash +++ b/examples/http-clients/http-clients.hash @@ -1,2 +1,2 @@ -ec8fd69aa19e54a7ea05d2a911f09d3a98f0396c -VxYIifr_UuH +fbc80f8cfcd34e9daa3c52c23f6720f6ef7019dc +kHCcVLoz7nd diff --git a/examples/http-servers/http-servers.hash b/examples/http-servers/http-servers.hash index a491ac180..f4f7581f4 100644 --- a/examples/http-servers/http-servers.hash +++ b/examples/http-servers/http-servers.hash @@ -1,2 +1,2 @@ -a4e8d30b7a6f3a6abd96b916d81ce5930bad94f9 -lNuS9ysZmxH +7694e4f5c3907e999331bbab9ead9743b6e9c6b7 +s3xMMt9Ytry diff --git a/examples/if-else/if-else.hash b/examples/if-else/if-else.hash index 844700f19..8f1ebb5de 100644 --- a/examples/if-else/if-else.hash +++ b/examples/if-else/if-else.hash @@ -1,2 +1,2 @@ -89b78f3378e1a574ddfd0260a0404a962852eff8 -p6-WKTqEks4 +ae7f289ac1b2b1f152cd1952b93769209eed8e1d +QlMkcwHvmns diff --git a/examples/interfaces/interfaces.hash b/examples/interfaces/interfaces.hash index b6fa98378..b228f689a 100644 --- a/examples/interfaces/interfaces.hash +++ b/examples/interfaces/interfaces.hash @@ -1,2 +1,2 @@ -aac1328f5a04568272b82753ff0762b9eacff4fc -hXTlbUAGcvn +d4ea9541521cfee94107ba9331d0dabb1f9f16c1 +XJASG4MxBQr diff --git a/examples/json/json.hash b/examples/json/json.hash index 8c217d64c..60f6c01bd 100644 --- a/examples/json/json.hash +++ b/examples/json/json.hash @@ -1,2 +1,2 @@ -c751bc7223b8bc615f82fe7643ab98ce2b80240f -ROikmz5tRhZ +35295476f817fe575619b6168273a29eddd7f545 +JOQpRGJWAxR diff --git a/examples/line-filters/line-filters.hash b/examples/line-filters/line-filters.hash index d62fbff77..81f5db45d 100644 --- a/examples/line-filters/line-filters.hash +++ b/examples/line-filters/line-filters.hash @@ -1,2 +1,2 @@ -87f4a67edf741979f8ff6da85947aa177547f9ef -hnaOIaQAjKF +42fd593180c40f71839f05447cc0a70d7cd213d1 +kNcupWRsYPP diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index 57c1a724e..79caf58c9 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -3e39d07e3f80ecbac558c6fb8baee2a5f914cf97 -U67R66Oab8r +9e0e4535c99668b460c7175f8ff2edc2ccf58bec +agK2Ro2i-Lu diff --git a/examples/methods/methods.hash b/examples/methods/methods.hash index 00c7c28b7..b8b20fde8 100644 --- a/examples/methods/methods.hash +++ b/examples/methods/methods.hash @@ -1,2 +1,2 @@ -24cfb9ad45e43c2d49163149bc55925a4e1b3c7a -ffMb0txGnYB +8c5af60ad04b3e9baa62a85924f829711abe94d4 +4wmDCAydC1e diff --git a/examples/multiple-return-values/multiple-return-values.hash b/examples/multiple-return-values/multiple-return-values.hash index 73f9fa8f8..4d4b70596 100644 --- a/examples/multiple-return-values/multiple-return-values.hash +++ b/examples/multiple-return-values/multiple-return-values.hash @@ -1,2 +1,2 @@ -5063ce3d3c70c6bd70f4b709de24bb93d0f24e0c -FZoIB5LXQGZ +c6e4f5dd9c55b5d2aaeb7e939c216ec76f042501 +vZdUvLB1WbK diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index aea2025e5..95b8135f1 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -ca257d9594a6219d5803193132e999a32dc8c856 -IRewFKz2OPN +7cb6349117087c78ddb71c240e988ec8281c8952 +0WEmOOjoCjp diff --git a/examples/non-blocking-channel-operations/non-blocking-channel-operations.hash b/examples/non-blocking-channel-operations/non-blocking-channel-operations.hash index a9f03de66..3537e4e24 100644 --- a/examples/non-blocking-channel-operations/non-blocking-channel-operations.hash +++ b/examples/non-blocking-channel-operations/non-blocking-channel-operations.hash @@ -1,2 +1,2 @@ -a6e0a8bb87153c7ed0de4996172f7ad5d89c6814 -n5ttmOsMrrJ +40588abf859a0280d8c71b79732e869eb2da9291 +TFv6-7OVNVq diff --git a/examples/number-parsing/number-parsing.hash b/examples/number-parsing/number-parsing.hash index eeaf3cd16..32193a2cf 100644 --- a/examples/number-parsing/number-parsing.hash +++ b/examples/number-parsing/number-parsing.hash @@ -1,2 +1,2 @@ -0191c7e43706640207c403ba92dd2272d66fc868 -t2q4KnWWTAw +146b42780ac43135d97f094c6d30db364882ea17 +ZAMEid6Fpmu diff --git a/examples/panic/panic.hash b/examples/panic/panic.hash index bd32ff3ef..8223707dd 100644 --- a/examples/panic/panic.hash +++ b/examples/panic/panic.hash @@ -1,2 +1,2 @@ -91639bbcfcc6ed088295a9ee6b1c36ab35ae402a -91HXbZZZopt +d1d154be95ba37739e3598a9195b6ae0a427bc80 +9-2vCvRuhmE diff --git a/examples/pointers/pointers.hash b/examples/pointers/pointers.hash index a0c5985f7..455774fb3 100644 --- a/examples/pointers/pointers.hash +++ b/examples/pointers/pointers.hash @@ -1,2 +1,2 @@ -85cff3345d2f22b65a5d54eb8f7aa8f508f27887 -fnQkHp4hriG +c727916063ddc3e99199cd24bfbde37ff301c0b4 +oimmXypnAcs diff --git a/examples/random-numbers/random-numbers.hash b/examples/random-numbers/random-numbers.hash index 3ebbc4aca..907e93b44 100644 --- a/examples/random-numbers/random-numbers.hash +++ b/examples/random-numbers/random-numbers.hash @@ -1,2 +1,2 @@ -9374869a809d28ea784a9e1181b4aa1988018776 -DVHO7SjJZnp +102041ca421268afbd4b4e7687386bb65a8c7965 +PGklfJzErTN diff --git a/examples/range-over-channels/range-over-channels.hash b/examples/range-over-channels/range-over-channels.hash index f0ffe629b..b3b135cfe 100644 --- a/examples/range-over-channels/range-over-channels.hash +++ b/examples/range-over-channels/range-over-channels.hash @@ -1,2 +1,2 @@ -8b5d8a77e84c34771c5b14af014ecef3f88b2a6c -QnARPm-ddFB +1812ab409c07ea4209106ee4c0d2eb597fccd717 +yQMclmwOYs9 diff --git a/examples/range/range.hash b/examples/range/range.hash index 2f8d0dade..f6e5a86ab 100644 --- a/examples/range/range.hash +++ b/examples/range/range.hash @@ -1,2 +1,2 @@ -ebe328a57f3d34708709ca99d3304af1733592d9 -JTY1VAUjfBw +c7d9ae9ed081fb4bbf27ef45242fbb39bbae3d4c +pdZOtv4g-7J diff --git a/examples/rate-limiting/rate-limiting.hash b/examples/rate-limiting/rate-limiting.hash index be48802c6..813cbef2a 100644 --- a/examples/rate-limiting/rate-limiting.hash +++ b/examples/rate-limiting/rate-limiting.hash @@ -1,2 +1,2 @@ -357d83df3e48675eb1e135188cb9f07448c1f146 -AJ-MJephNib +c2d4dd4c2121e61395db186e3f15ce8cb3acf643 +20c_m1AtOEI diff --git a/examples/reading-files/reading-files.hash b/examples/reading-files/reading-files.hash index 8cf5bf666..2933d50c9 100644 --- a/examples/reading-files/reading-files.hash +++ b/examples/reading-files/reading-files.hash @@ -1,2 +1,2 @@ -463a6f2999a023887af6b23c8f79f24978eb8115 -cocJ6kBH_iZ +3420958bafd67fd997481d1ada288566666343c7 +kF0cDC0drsX diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index 2ebf561c2..ac2db783c 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -5d1ba6b03a50ccae2a0f46865eb72c587e11857c -4yUp5wLVyiG +9bfb2f870007082835a3c0efaac9aa1c3bc2c15c +smWim1q9ofu diff --git a/examples/regular-expressions/regular-expressions.hash b/examples/regular-expressions/regular-expressions.hash index 236706c0a..a1d564485 100644 --- a/examples/regular-expressions/regular-expressions.hash +++ b/examples/regular-expressions/regular-expressions.hash @@ -1,2 +1,2 @@ -de24265897edf1d3913e3b87f70757284a66ecea -urHlUNDVenk +3db643ab821ee2a5b70e05fbadbde1a7f7ba1591 +944r7pT2YIl diff --git a/examples/select/select.hash b/examples/select/select.hash index ea97b26d1..e18682219 100644 --- a/examples/select/select.hash +++ b/examples/select/select.hash @@ -1,2 +1,2 @@ -6e1125087bc036ebd905452300575f160d683918 -yF-xgN7Xf9P +33fe111b666efb3243c9cbd0ba12b2e795d90fab +FzONhs4-tae diff --git a/examples/sha1-hashes/sha1-hashes.hash b/examples/sha1-hashes/sha1-hashes.hash index 5af2939b1..6313184a6 100644 --- a/examples/sha1-hashes/sha1-hashes.hash +++ b/examples/sha1-hashes/sha1-hashes.hash @@ -1,2 +1,2 @@ -4cda643ba233014fe6b30966c37d4d0fcd4edbe8 -oqcrTfY4Ykd +fc2de63b58865a6761749490ee217a94b4e343d1 +XLftf8Gvj4y diff --git a/examples/signals/signals.hash b/examples/signals/signals.hash index 82345ca02..205ac6905 100644 --- a/examples/signals/signals.hash +++ b/examples/signals/signals.hash @@ -1,2 +1,2 @@ -1e43c6f63f1d57e1a52c89f52d35b68757e9676b -_6oj-T3Gko2 +ccee3fe41771b7cf56d64de38b12588022458154 +YRV64KEXJW1 diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index 8b501cb36..24199a58e 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -c6fa1627841f199dbf901f88580cb97eb92c5530 -Z3_U32sn8RF +02c5330eb3ef32a88ca22a5adbded9bd356f89f3 +iLnoIEIxeQ1 diff --git a/examples/sorting-by-functions/sorting-by-functions.hash b/examples/sorting-by-functions/sorting-by-functions.hash index d62f035bc..ff61f8111 100644 --- a/examples/sorting-by-functions/sorting-by-functions.hash +++ b/examples/sorting-by-functions/sorting-by-functions.hash @@ -1,2 +1,2 @@ -f7d0b7840dd12601fb86946f9dc4c38fb1c0501f -Jtxf94x94Hx +e5a6006366e05ee7785eebac8ba588e4b937a197 +h4g4vaLBtkw diff --git a/examples/sorting/sorting.hash b/examples/sorting/sorting.hash index d72396f6a..e845bdf24 100644 --- a/examples/sorting/sorting.hash +++ b/examples/sorting/sorting.hash @@ -1,2 +1,2 @@ -e11e944d34b21e75ce4f7c91026d4200ce592dc5 -tAWAkRlBJNX +c39a7498686fe1d74f729fd6b21a70bf063abf14 +_gY0tANzJ4l diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index bcde70779..f36a1cc12 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -cc68e4290f10209ad2fa8db74fdfaea7fdb44d5c -QS_Nkoe8VLG +64e8937dacf6d81f39a3b66584fb70f46dd2126b +jUpRr-RcUKf diff --git a/examples/stateful-goroutines/stateful-goroutines.hash b/examples/stateful-goroutines/stateful-goroutines.hash index 1f3eb4800..a5b475c08 100644 --- a/examples/stateful-goroutines/stateful-goroutines.hash +++ b/examples/stateful-goroutines/stateful-goroutines.hash @@ -1,2 +1,2 @@ -956afe7524b492b2e85f8320c70f180c448a764a -saQTLpdIgp2 +9c73569ad2e16252b04fe171618db4c5fd09efb7 +5mf_P9xqBzk diff --git a/examples/string-formatting/string-formatting.hash b/examples/string-formatting/string-formatting.hash index c339d9bbf..a8cc20984 100644 --- a/examples/string-formatting/string-formatting.hash +++ b/examples/string-formatting/string-formatting.hash @@ -1,2 +1,2 @@ -12b245c576b43537c092a5b84995ebca8ce78a57 -vmYSdxfUcRh +99fb572787ffa93dad9c491aec5ce5c7a7516081 +L6BkGeaN_p4 diff --git a/examples/string-functions/string-functions.hash b/examples/string-functions/string-functions.hash index 568c7c6db..68fb9a490 100644 --- a/examples/string-functions/string-functions.hash +++ b/examples/string-functions/string-functions.hash @@ -1,2 +1,2 @@ -bf39c7540bd78eba38eb5a9047a9d0ffc7235f85 -xoRUhG86wsF +33b15b8c999ba65564b965b96cbfeadac0d1637d +fZ_FqN5WlSz diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index 15fcdc062..ca7cc8523 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -c5caaf1eefaf084d688afb70d2ee5884a4983182 -00Yiw6xuICq +e630f9890f89e157aa88f5d774dbed0c0c04224e +qHz9gNnAtyw diff --git a/examples/switch/switch.hash b/examples/switch/switch.hash index 54d2e9f43..1bd1eaac2 100644 --- a/examples/switch/switch.hash +++ b/examples/switch/switch.hash @@ -1,2 +1,2 @@ -2486fc553301cdeac9a26f3d0b3aed4143d9f4f0 -ZcDzdx3nYQn +28a8909ee7963cb315f14a3be1607def1d91f3a3 +qVDqWoUQ6AI diff --git a/examples/temporary-files-and-directories/temporary-files-and-directories.hash b/examples/temporary-files-and-directories/temporary-files-and-directories.hash index f52300281..ebe1eeb36 100644 --- a/examples/temporary-files-and-directories/temporary-files-and-directories.hash +++ b/examples/temporary-files-and-directories/temporary-files-and-directories.hash @@ -1,2 +1,2 @@ -5f7d0c43988d7dce235adb06ec02f4d2026b7f83 -pxE20wGTFjv +371689e72c46daa43eefbd9b9f4eaa3c490e7fd2 +yKWE4QTsYQr diff --git a/examples/testing/testing.hash b/examples/testing/testing.hash index 317487fad..e3a25164d 100644 --- a/examples/testing/testing.hash +++ b/examples/testing/testing.hash @@ -1,2 +1,2 @@ -8f00c5178a33be2e92a853f14bfc3fbf0919cd97 -fyy7h1adGWr +017c9d7ba927cdfbcef1643e86f9b8022f13fc31 +jCRgtgRwie3 diff --git a/examples/tickers/tickers.hash b/examples/tickers/tickers.hash index cd2eaf3df..86e4cddf1 100644 --- a/examples/tickers/tickers.hash +++ b/examples/tickers/tickers.hash @@ -1,2 +1,2 @@ -05a1e62b5d363b67df0f9bac5c8f75dc19ca2c54 -E1ro_QHJD9L +432b3be0884cead3f01b9cce0868ac6146e7864e +gs6zoJP-Pl9 diff --git a/examples/time-formatting-parsing/time-formatting-parsing.hash b/examples/time-formatting-parsing/time-formatting-parsing.hash index eee6d65fd..fffa49e01 100644 --- a/examples/time-formatting-parsing/time-formatting-parsing.hash +++ b/examples/time-formatting-parsing/time-formatting-parsing.hash @@ -1,2 +1,2 @@ -9e3f17061fef280191e3e8518365e231e17a5d5a -1410R7Fcyx0 +9136a09d33b7a812de3ba0129b9aa6953bca0fbe +BoZYtr_2j66 diff --git a/examples/time/time.hash b/examples/time/time.hash index 2c9d41588..236413765 100644 --- a/examples/time/time.hash +++ b/examples/time/time.hash @@ -1,2 +1,2 @@ -c47d853fa7527a652ce78b0285e452c6cd740050 -u-7i_p8BHVt +24eefcc82ee0c70a4678a4952fe2b8c558c7419c +YAM3s1KPc8c diff --git a/examples/timeouts/timeouts.hash b/examples/timeouts/timeouts.hash index f622aeb5f..8fbb39d99 100644 --- a/examples/timeouts/timeouts.hash +++ b/examples/timeouts/timeouts.hash @@ -1,2 +1,2 @@ -b8d3e745539b24d3530ca21efcdc924f08769edb -TYJgoFjlTd6 +fb913ae361c41095a39bb3fa0c5e9dcd54ec840e +4oOz0j29MJ6 diff --git a/examples/timers/timers.hash b/examples/timers/timers.hash index 8c0f2c427..aa71908b7 100644 --- a/examples/timers/timers.hash +++ b/examples/timers/timers.hash @@ -1,2 +1,2 @@ -e8e501d6083bea786629ca5e485e8b18caab4815 -pLnKEIesooU +fb413c9b1152a30107c53bf0a739a22c0056976b +_cLT2ewHYO8 diff --git a/examples/url-parsing/url-parsing.hash b/examples/url-parsing/url-parsing.hash index 77021f1a0..8468d1fa5 100644 --- a/examples/url-parsing/url-parsing.hash +++ b/examples/url-parsing/url-parsing.hash @@ -1,2 +1,2 @@ -babc12f5066652f4cb0151231c06f1037298ff28 -M218D9Tldlr +7e77917c98bd88187b4fed2b8c988afdd0b0df7d +fHTQn9X7l1B diff --git a/examples/values/values.hash b/examples/values/values.hash index b10176b05..4c64e23c1 100644 --- a/examples/values/values.hash +++ b/examples/values/values.hash @@ -1,2 +1,2 @@ -c5a53c75cc57dc15ac4458285c9b139bf85c67bf -aGiVohrYqYC +476982956a689418d548148af5f17145de16f063 +YnVS3LZr8pk diff --git a/examples/variables/variables.hash b/examples/variables/variables.hash index 316281a75..040888bcc 100644 --- a/examples/variables/variables.hash +++ b/examples/variables/variables.hash @@ -1,2 +1,2 @@ -636a63e1bf810cb9d0620cc5160330f6d3d8679d -kwm2xuWnlKq +736ce4018f275bb8d12e5232349bae93611506b2 +iYyAIilyBRf diff --git a/examples/variadic-functions/variadic-functions.hash b/examples/variadic-functions/variadic-functions.hash index 3c44a2b27..850311a8d 100644 --- a/examples/variadic-functions/variadic-functions.hash +++ b/examples/variadic-functions/variadic-functions.hash @@ -1,2 +1,2 @@ -34ba16069a5d972a837cc5c0172ab30873535220 -7f0JlVhToDD +560aaef6ce8867710f3ef609b1bb2317377a71bf +Ua6kZOMabBp diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index 71ecfc871..f944ca9bd 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -499c7ee59b2ae06d2d3171768d9cf11762121a87 -gLLmgcR7YkP +39bbc00ecd87888761d480666e95d8b2c2a2a589 +oBOGrV0n2Y2 diff --git a/examples/worker-pools/worker-pools.hash b/examples/worker-pools/worker-pools.hash index dbfeb88ff..97b94fde8 100644 --- a/examples/worker-pools/worker-pools.hash +++ b/examples/worker-pools/worker-pools.hash @@ -1,2 +1,2 @@ -9b30cdfc3f46d634c3b8671a7ae1551c133fb6e2 -IiKZ-nj-nKY +dbe5adf9aad6828387231e477e22c5f0cd550b74 +WXYS5_KpNvq diff --git a/examples/writing-files/writing-files.hash b/examples/writing-files/writing-files.hash index 360897a02..3d09d103c 100644 --- a/examples/writing-files/writing-files.hash +++ b/examples/writing-files/writing-files.hash @@ -1,2 +1,2 @@ -0853ca57176872e9b34b501855ceb8bf5fbdbf46 -gyJn9PcndtP +d4f19bc0168674b17551bbf55bab7af989452d0e +8kx-qYUXBpA diff --git a/examples/xml/xml.hash b/examples/xml/xml.hash index 104125d65..aef8f3597 100644 --- a/examples/xml/xml.hash +++ b/examples/xml/xml.hash @@ -1,2 +1,2 @@ -18ada773098bca38778a58b438d6af70529f18b0 -qd9Ii_3AW0s +f42dec8593a45931145f0a55f104f2ca34b2d112 +wlkywJsuWqL diff --git a/public/arrays b/public/arrays index d8273e023..352a0108b 100644 --- a/public/arrays +++ b/public/arrays @@ -42,7 +42,7 @@ specific length.

    - +
    package main
     
    diff --git a/public/atomic-counters b/public/atomic-counters index 9627c9703..2d5252981 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -46,7 +46,7 @@ counters accessed by multiple goroutines.

    - +
    package main
     
    diff --git a/public/base64-encoding b/public/base64-encoding index 7bf8d2887..13baf617c 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -42,7 +42,7 @@ encoding/decoding.

    - +
    package main
     
    diff --git a/public/channel-buffering b/public/channel-buffering index eab9a6e15..5f2d1f532 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -46,7 +46,7 @@ those values.

    - +
    package main
     
    diff --git a/public/channel-directions b/public/channel-directions index fbbe7b58a..f79750a4c 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -44,7 +44,7 @@ the program.

    - +
    package main
     
    diff --git a/public/channel-synchronization b/public/channel-synchronization index 7a0d3a384..71fec1264 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -45,7 +45,7 @@ you may prefer to use a WaitGroup.

    - +
    package main
     
    diff --git a/public/channels b/public/channels index 704c9f44e..6ae7ade6f 100644 --- a/public/channels +++ b/public/channels @@ -44,7 +44,7 @@ goroutine.

    - +
    package main
     
    diff --git a/public/closing-channels b/public/closing-channels index 8566518b9..5271faab0 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -43,7 +43,7 @@ completion to the channel’s receivers.

    - +
    package main
     
    diff --git a/public/closures b/public/closures index 36d6dc43d..e31c87a21 100644 --- a/public/closures +++ b/public/closures @@ -44,7 +44,7 @@ a function inline without having to name it.

    - +
    package main
     
    diff --git a/public/collection-functions b/public/collection-functions index 569c4b3b9..33c38fdcc 100644 --- a/public/collection-functions +++ b/public/collection-functions @@ -75,7 +75,7 @@ helper function.

    - +
    package main
     
    diff --git a/public/command-line-arguments b/public/command-line-arguments index 593e93f91..687aefd3f 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -44,7 +44,7 @@ For example, go run hello.go uses run and - +
    package main
     
    diff --git a/public/command-line-flags b/public/command-line-flags index 76e2bfc9f..024349f26 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -44,7 +44,7 @@ command-line flag.

    - +
    package main
     
    diff --git a/public/command-line-subcommands b/public/command-line-subcommands index f5add9363..6bee74c6d 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -46,7 +46,7 @@ subcommands that have their own flags.

    - +
    package main
     
    diff --git a/public/constants b/public/constants index 31e2c7b22..b1cf8801f 100644 --- a/public/constants +++ b/public/constants @@ -42,7 +42,7 @@ and numeric values.

    - +
    package main
     
    diff --git a/public/defer b/public/defer index f99d59d8f..54bb2d7e3 100644 --- a/public/defer +++ b/public/defer @@ -44,7 +44,7 @@ purposes of cleanup. defer is often used where e.g. - +
    package main
     
    diff --git a/public/directories b/public/directories index 5cfc5b013..c88a76c06 100644 --- a/public/directories +++ b/public/directories @@ -42,7 +42,7 @@ - +
    package main
     
    diff --git a/public/environment-variables b/public/environment-variables index ecaef7e02..e68934d4b 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -44,7 +44,7 @@ Let’s look at how to set, get, and list environment variables.

    - +
    package main
     
    diff --git a/public/epoch b/public/epoch index 76a9b201f..02bfc7ea8 100644 --- a/public/epoch +++ b/public/epoch @@ -44,7 +44,7 @@ Here’s how to do it in Go.

    - +
    package main
     
    diff --git a/public/errors b/public/errors index 351cb86df..3103a2efa 100644 --- a/public/errors +++ b/public/errors @@ -48,7 +48,7 @@ non-error tasks.

    - +
    package main
     
    diff --git a/public/execing-processes b/public/execing-processes index 98ce62a78..585a266cb 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -49,7 +49,7 @@ function.

    - +
    package main
     
    diff --git a/public/exit b/public/exit index 5929eb645..179e1618f 100644 --- a/public/exit +++ b/public/exit @@ -38,7 +38,7 @@ status.

    - +
    package main
     
    diff --git a/public/file-paths b/public/file-paths index 235195455..3219a93c2 100644 --- a/public/file-paths +++ b/public/file-paths @@ -34,7 +34,7 @@ between operating systems; dir/file on Linux vs. - +
    package main
     
    diff --git a/public/for b/public/for index 81b98d950..fea862c33 100644 --- a/public/for +++ b/public/for @@ -42,7 +42,7 @@ three basic types of for loops.

    - +
    package main
     
    diff --git a/public/functions b/public/functions index 8880847c9..b4b80b384 100644 --- a/public/functions +++ b/public/functions @@ -42,7 +42,7 @@ functions with a few different examples.

    - +
    package main
     
    diff --git a/public/goroutines b/public/goroutines index 6b87012d6..105d9bdb3 100644 --- a/public/goroutines +++ b/public/goroutines @@ -41,7 +41,7 @@ - +
    package main
     
    diff --git a/public/hello-world b/public/hello-world index 4c2373ab6..4b7c360c1 100644 --- a/public/hello-world +++ b/public/hello-world @@ -28,7 +28,7 @@ message. Here’s the full source code.

    - +
    package main
     
    diff --git a/public/http-clients b/public/http-clients index 7bdaa06f7..09080b5eb 100644 --- a/public/http-clients +++ b/public/http-clients @@ -34,7 +34,7 @@ HTTP requests.

    - +
    package main
     
    diff --git a/public/http-servers b/public/http-servers index aa2802dbe..f3f9638aa 100644 --- a/public/http-servers +++ b/public/http-servers @@ -32,7 +32,7 @@ - +
    package main
     
    diff --git a/public/if-else b/public/if-else index f00d6b5a3..ed87d6a1d 100644 --- a/public/if-else +++ b/public/if-else @@ -42,7 +42,7 @@ straight-forward.

    - +
    package main
     
    diff --git a/public/interfaces b/public/interfaces index fad0ed06c..737c5180e 100644 --- a/public/interfaces +++ b/public/interfaces @@ -42,7 +42,7 @@ signatures.

    - +
    package main
     
    diff --git a/public/json b/public/json index e2327ec0d..4a648d1b1 100644 --- a/public/json +++ b/public/json @@ -43,7 +43,7 @@ data types.

    - +
    package main
     
    diff --git a/public/line-filters b/public/line-filters index f7796d0e9..ec8491568 100644 --- a/public/line-filters +++ b/public/line-filters @@ -47,7 +47,7 @@ pattern to write your own Go line filters.

    - +
    package main
     
    diff --git a/public/maps b/public/maps index 443efd7fd..f0c7c0f03 100644 --- a/public/maps +++ b/public/maps @@ -42,7 +42,7 @@ - +
    package main
     
    diff --git a/public/methods b/public/methods index ca0589af1..a053c8599 100644 --- a/public/methods +++ b/public/methods @@ -41,7 +41,7 @@ - +
    package main
     
    diff --git a/public/multiple-return-values b/public/multiple-return-values index bd16bd1db..ec3ebcb5c 100644 --- a/public/multiple-return-values +++ b/public/multiple-return-values @@ -43,7 +43,7 @@ to return both result and error values from a function.

    - +
    package main
     
    diff --git a/public/mutexes b/public/mutexes index 14d81373b..fb406ee34 100644 --- a/public/mutexes +++ b/public/mutexes @@ -44,7 +44,7 @@ to safely access data across multiple goroutines.

    - +
    package main
     
    diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations index bbe6d5528..6a529c8bf 100644 --- a/public/non-blocking-channel-operations +++ b/public/non-blocking-channel-operations @@ -44,7 +44,7 @@ non-blocking multi-way selects.

    - +
    package main
     
    diff --git a/public/number-parsing b/public/number-parsing index 269da8526..6b063ee98 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -42,7 +42,7 @@ in many programs; here’s how to do it in Go.

    - +
    package main
     
    diff --git a/public/panic b/public/panic index 6a9b83452..f078c0304 100644 --- a/public/panic +++ b/public/panic @@ -44,7 +44,7 @@ aren’t prepared to handle gracefully.

    - +
    package main
     
    diff --git a/public/pointers b/public/pointers index 4d105270c..53d075a4c 100644 --- a/public/pointers +++ b/public/pointers @@ -43,7 +43,7 @@ within your program.

    - +
    package main
     
    diff --git a/public/random-numbers b/public/random-numbers index d3685c5ee..7d14d7961 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -43,7 +43,7 @@ generation.

    - +
    package main
     
    diff --git a/public/range b/public/range index f09b0c7f6..947af8601 100644 --- a/public/range +++ b/public/range @@ -43,7 +43,7 @@ of the data structures we’ve already learned.

    - +
    package main
     
    diff --git a/public/range-over-channels b/public/range-over-channels index 1b7354ce3..cc279fbd4 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -44,7 +44,7 @@ values received from a channel.

    - +
    package main
     
    diff --git a/public/rate-limiting b/public/rate-limiting index 33dd25132..49e16b918 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -45,7 +45,7 @@ channels, and tickers.

    - +
    package main
     
    diff --git a/public/reading-files b/public/reading-files index 5f87bee0e..62e692cfe 100644 --- a/public/reading-files +++ b/public/reading-files @@ -43,7 +43,7 @@ reading files.

    - +
    package main
     
    diff --git a/public/recursion b/public/recursion index 215d30d3c..12b7ffacd 100644 --- a/public/recursion +++ b/public/recursion @@ -43,7 +43,7 @@ Here’s a classic factorial example.

    - +
    package main
     
    diff --git a/public/regular-expressions b/public/regular-expressions index 76529e33c..20d4fbd00 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -43,7 +43,7 @@ in Go.

    - +
    package main
     
    diff --git a/public/select b/public/select index 116ac3bac..fc1eda7c9 100644 --- a/public/select +++ b/public/select @@ -43,7 +43,7 @@ select is a powerful feature of Go.

    - +
    package main
     
    diff --git a/public/sha1-hashes b/public/sha1-hashes index 4db037545..9bbcddf77 100644 --- a/public/sha1-hashes +++ b/public/sha1-hashes @@ -46,7 +46,7 @@ compute SHA1 hashes in Go.

    - +
    package main
     
    diff --git a/public/signals b/public/signals index b0109b583..786fb5a69 100644 --- a/public/signals +++ b/public/signals @@ -46,7 +46,7 @@ Here’s how to handle signals in Go with channels.

    - +
    package main
     
    diff --git a/public/slices b/public/slices index ee57572ff..c61dcb758 100644 --- a/public/slices +++ b/public/slices @@ -42,7 +42,7 @@ powerful interface to sequences than arrays.

    - +
    package main
     
    diff --git a/public/sorting b/public/sorting index ded8f4816..18f89fbdf 100644 --- a/public/sorting +++ b/public/sorting @@ -43,7 +43,7 @@ builtins first.

    - +
    package main
     
    diff --git a/public/sorting-by-functions b/public/sorting-by-functions index f86a18849..0d2b44217 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -45,7 +45,7 @@ in Go.

    - +
    package main
     
    diff --git a/public/spawning-processes b/public/spawning-processes index da8dfc5ce..26f65620a 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -46,7 +46,7 @@ of spawning processes from Go.

    - +
    package main
     
    diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 80ad0ba75..25b8f59b4 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -48,7 +48,7 @@ by exactly 1 goroutine.

    - +
    package main
     
    diff --git a/public/string-formatting b/public/string-formatting index 6616ed040..6ec05687a 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -43,7 +43,7 @@ common string formatting tasks.

    - +
    package main
     
    diff --git a/public/string-functions b/public/string-functions index 093c467b3..3c0ddfabe 100644 --- a/public/string-functions +++ b/public/string-functions @@ -43,7 +43,7 @@ to give you a sense of the package.

    - +
    package main
     
    diff --git a/public/structs b/public/structs index 0bb814c55..e941fefd2 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.

    - +
    package main
     
    diff --git a/public/switch b/public/switch index f0eff96db..ead4de41d 100644 --- a/public/switch +++ b/public/switch @@ -42,7 +42,7 @@ branches.

    - +
    package main
     
    diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 93bd965b8..3919f3635 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -45,7 +45,7 @@ time.

    - +
    package main
     
    diff --git a/public/testing b/public/testing index dc0c51791..e8a3bc291 100644 --- a/public/testing +++ b/public/testing @@ -47,7 +47,7 @@ typically lives in the same package as the code it tests.

    - +
    package main
     
    diff --git a/public/tickers b/public/tickers index 82648e0a1..6b219ab42 100644 --- a/public/tickers +++ b/public/tickers @@ -45,7 +45,7 @@ periodically until we stop it.

    - +
    package main
     
    diff --git a/public/time b/public/time index 12137d802..ae8046955 100644 --- a/public/time +++ b/public/time @@ -42,7 +42,7 @@ here are some examples.

    - +
    package main
     
    diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index 5c8f26644..e6b54d831 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -42,7 +42,7 @@ pattern-based layouts.

    - +
    package main
     
    diff --git a/public/timeouts b/public/timeouts index 39238ed5e..36abd5467 100644 --- a/public/timeouts +++ b/public/timeouts @@ -44,7 +44,7 @@ elegant thanks to channels and select.

    - +
    package main
     
    diff --git a/public/timers b/public/timers index 977afef0c..082fb4033 100644 --- a/public/timers +++ b/public/timers @@ -45,7 +45,7 @@ at tickers.

    - +
    package main
     
    diff --git a/public/url-parsing b/public/url-parsing index 0cd07f42b..4fd0fb873 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -42,7 +42,7 @@ Here’s how to parse URLs in Go.

    - +
    package main
     
    diff --git a/public/values b/public/values index eef6bfba9..807830bd0 100644 --- a/public/values +++ b/public/values @@ -43,7 +43,7 @@ basic examples.

    - +
    package main
     
    diff --git a/public/variables b/public/variables index 8ce28a3dc..b10cded1c 100644 --- a/public/variables +++ b/public/variables @@ -43,7 +43,7 @@ calls.

    - +
    package main
     
    diff --git a/public/variadic-functions b/public/variadic-functions index 536970bf2..d36665815 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -44,7 +44,7 @@ function.

    - +
    package main
     
    diff --git a/public/waitgroups b/public/waitgroups index d8c3f1314..e9d39c70c 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    - +
    package main
     
    diff --git a/public/worker-pools b/public/worker-pools index 70a6a0b09..97ea215eb 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -42,7 +42,7 @@ a worker pool using goroutines and channels.

    - +
    package main
     
    diff --git a/public/writing-files b/public/writing-files index 2969c778e..49214e1f1 100644 --- a/public/writing-files +++ b/public/writing-files @@ -42,7 +42,7 @@ ones we saw earlier for reading.

    - +
    package main
     
    diff --git a/public/xml b/public/xml index e463b37e2..85a2d15db 100644 --- a/public/xml +++ b/public/xml @@ -42,7 +42,7 @@ formats with the encoding.xml package.

    - +
    package main
     
    diff --git a/tools/generate.go b/tools/generate.go index 7776380a8..04d2e920e 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -165,12 +165,16 @@ func resetURLHashFile(codehash, code, sourcePath string) string { } func parseSegs(sourcePath string) ([]*Seg, string) { - var lines []string + var ( + lines []string + source []string + ) // Convert tabs to spaces for uniform rendering. for _, line := range readLines(sourcePath) { lines = append(lines, strings.Replace(line, "\t", " ", -1)) + source = append(source, line) } - filecontent := strings.Join(lines, "\n") + filecontent := strings.Join(source, "\n") segs := []*Seg{} lastSeen := "" for _, line := range lines { From ff70f04795069bf4459ba86fb8055a1350ed0994 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 19 Nov 2019 06:39:53 -0800 Subject: [PATCH 018/283] Adding example of HTTP server using context.Context --- .../context-in-http-servers.go | 42 +++++++++++++++++++ .../context-in-http-servers.hash | 2 + .../context-in-http-servers.sh | 11 +++++ 3 files changed, 55 insertions(+) create mode 100644 examples/context-in-http-servers/context-in-http-servers.go create mode 100644 examples/context-in-http-servers/context-in-http-servers.hash create mode 100644 examples/context-in-http-servers/context-in-http-servers.sh diff --git a/examples/context-in-http-servers/context-in-http-servers.go b/examples/context-in-http-servers/context-in-http-servers.go new file mode 100644 index 000000000..09acd1961 --- /dev/null +++ b/examples/context-in-http-servers/context-in-http-servers.go @@ -0,0 +1,42 @@ +// In the previous example we looked at setting up a simple +// [HTTP server](http-servers). HTTP servers are useful for +// demonstrating the usage of `context.Context` for +// controlling cancellation. +package main + +import ( + "fmt" + "net/http" + "time" +) + +func hello(w http.ResponseWriter, req *http.Request) { + // A `context.Context` is created for each request by + // the `net/http` machinery, and is available with + // the `Context()` method. + ctx := req.Context() + fmt.Println("server: hello handler started") + defer fmt.Println("server: hello handler ended") + + // Wait for 3 seconds before sending a reply to the + // client. This could simulate some work the server is + // doing. While working, keep an eye on the context's + // `Done()` channel for a signal that we should cancel + // the work and return as soon as possible. + select { + case <-time.After(3 * time.Second): + fmt.Fprintf(w, "hello\n") + case <-ctx.Done(): + err := ctx.Err() + fmt.Println("server:", err) + internalError := http.StatusInternalServerError + http.Error(w, err.Error(), internalError) + } +} + +func main() { + // As before, we register our handler on the "/hello" + // route, and start serving. + http.HandleFunc("/hello", hello) + http.ListenAndServe(":8090", nil) +} diff --git a/examples/context-in-http-servers/context-in-http-servers.hash b/examples/context-in-http-servers/context-in-http-servers.hash new file mode 100644 index 000000000..6f5d37db4 --- /dev/null +++ b/examples/context-in-http-servers/context-in-http-servers.hash @@ -0,0 +1,2 @@ +4ec814bf1b01bf71fb95007cad39586ad87e3fb6 +k3vHfk-r3EE diff --git a/examples/context-in-http-servers/context-in-http-servers.sh b/examples/context-in-http-servers/context-in-http-servers.sh new file mode 100644 index 000000000..68d6f4db1 --- /dev/null +++ b/examples/context-in-http-servers/context-in-http-servers.sh @@ -0,0 +1,11 @@ +# Run the server in the background. +$ go run context-in-http-servers.go & + +# Simulate a client request to `/hello`, hitting +# Ctrl+C shortly after starting to signal +# cancellation. +$ curl localhost:8090/hello +server: hello handler started +^C +server: context canceled +server: hello handler ended From fa9179916437d5e32177f930753ab0230b07c652 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 19 Nov 2019 06:41:40 -0800 Subject: [PATCH 019/283] Reformat comoments to flow better with the code --- examples.txt | 1 + examples/context-in-http-servers/context-in-http-servers.go | 2 ++ examples/context-in-http-servers/context-in-http-servers.hash | 4 ++-- public/http-servers | 4 ++-- public/index.html | 2 ++ public/spawning-processes | 2 +- 6 files changed, 10 insertions(+), 5 deletions(-) diff --git a/examples.txt b/examples.txt index dd3c1579b..aa3ce317c 100644 --- a/examples.txt +++ b/examples.txt @@ -68,6 +68,7 @@ Command-Line Subcommands Environment Variables HTTP Clients HTTP Servers +Context in HTTP Servers Spawning Processes Exec'ing Processes Signals diff --git a/examples/context-in-http-servers/context-in-http-servers.go b/examples/context-in-http-servers/context-in-http-servers.go index 09acd1961..364d463e3 100644 --- a/examples/context-in-http-servers/context-in-http-servers.go +++ b/examples/context-in-http-servers/context-in-http-servers.go @@ -11,6 +11,7 @@ import ( ) func hello(w http.ResponseWriter, req *http.Request) { + // A `context.Context` is created for each request by // the `net/http` machinery, and is available with // the `Context()` method. @@ -35,6 +36,7 @@ func hello(w http.ResponseWriter, req *http.Request) { } func main() { + // As before, we register our handler on the "/hello" // route, and start serving. http.HandleFunc("/hello", hello) diff --git a/examples/context-in-http-servers/context-in-http-servers.hash b/examples/context-in-http-servers/context-in-http-servers.hash index 6f5d37db4..8e46d0016 100644 --- a/examples/context-in-http-servers/context-in-http-servers.hash +++ b/examples/context-in-http-servers/context-in-http-servers.hash @@ -1,2 +1,2 @@ -4ec814bf1b01bf71fb95007cad39586ad87e3fb6 -k3vHfk-r3EE +50f0c85266d1f8f546242ce8f8caf27732e99dff +h1gVSe70R00 diff --git a/public/http-servers b/public/http-servers index aa2802dbe..ee3c14632 100644 --- a/public/http-servers +++ b/public/http-servers @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'spawning-processes'; + window.location.href = 'context-in-http-servers'; } } @@ -201,7 +201,7 @@ router we’ve just set up.

    - Next example: Spawning Processes. + Next example: Context in HTTP Servers.

    Go by Example

  • HTTP Servers
  • +
  • Context in HTTP Servers
  • +
  • Spawning Processes
  • Exec'ing Processes
  • diff --git a/public/spawning-processes b/public/spawning-processes index da8dfc5ce..748398aa6 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'http-servers'; + window.location.href = 'context-in-http-servers'; } From 061f69cb98c557da66381a4489ea0daa4b294265 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 19 Nov 2019 06:42:43 -0800 Subject: [PATCH 020/283] Add generated HTML --- public/context-in-http-servers | 196 +++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 public/context-in-http-servers diff --git a/public/context-in-http-servers b/public/context-in-http-servers new file mode 100644 index 000000000..960de8d3c --- /dev/null +++ b/public/context-in-http-servers @@ -0,0 +1,196 @@ + + + + + Go by Example: Context in HTTP Servers + + + + +
    +

    Go by Example: Context in HTTP Servers

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    In the previous example we looked at setting up a simple +HTTP server. HTTP servers are useful for +demonstrating the usage of context.Context for +controlling cancellation.

    + +
    + +
    package main
    +
    + +
    + + + +
    import (
    +    "fmt"
    +    "net/http"
    +    "time"
    +)
    +
    + +
    + + + +
    func hello(w http.ResponseWriter, req *http.Request) {
    +
    + +
    +

    A context.Context is created for each request by +the net/http machinery, and is available with +the Context() method.

    + +
    + +
        ctx := req.Context()
    +    fmt.Println("server: hello handler started")
    +    defer fmt.Println("server: hello handler ended")
    +
    + +
    +

    Wait for 3 seconds before sending a reply to the +client. This could simulate some work the server is +doing. While working, keep an eye on the context’s +Done() channel for a signal that we should cancel +the work and return as soon as possible.

    + +
    + +
        select {
    +    case <-time.After(3 * time.Second):
    +        fmt.Fprintf(w, "hello\n")
    +    case <-ctx.Done():
    +        err := ctx.Err()
    +        fmt.Println("server:", err)
    +        internalError := http.StatusInternalServerError
    +        http.Error(w, err.Error(), internalError)
    +    }
    +}
    +
    + +
    + + + +
    func main() {
    +
    + +
    +

    As before, we register our handler on the “/hello” +route, and start serving.

    + +
    + +
        http.HandleFunc("/hello", hello)
    +    http.ListenAndServe(":8090", nil)
    +}
    +
    + +
    + + + + + + + + + + + + + +
    +

    Run the server in the background.

    + +
    + +
    $ go run context-in-http-servers.go &
    +
    + +
    +

    Simulate a client request to /hello, hitting +Ctrl+C shortly after starting to signal +cancellation.

    + +
    + +
    $ curl localhost:8090/hello
    +server: hello handler started
    +^C
    +server: context canceled
    +server: hello handler ended
    +
    + +
    + + +

    + Next example: Spawning Processes. +

    + + +
    + + + + From ed06d3779b6bd53d315b8dc8ee22782332613aef Mon Sep 17 00:00:00 2001 From: gorda Date: Thu, 12 Dec 2019 21:52:55 +0800 Subject: [PATCH 021/283] Change chinese translator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d839900c..040fdd273 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ The Go Gopher is copyright [Renée French](http://reneefrench.blogspot.com/) and Contributor translations of the Go by Example site are available in: -* [Chinese](https://gobyexample.xgwang.me/) by [xg-wang](https://github.com/xg-wang/gobyexample) +* [Chinese](https://gobyexample-cn.github.io/) by [gobyexample-cn](https://github.com/gobyexample-cn) * [Czech](http://gobyexamples.sweb.cz/) by [martinkunc](https://github.com/martinkunc/gobyexample-cz) * [French](http://le-go-par-l-exemple.keiruaprod.fr) by [keirua](https://github.com/keirua/gobyexample) * [Italian](http://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) From df99089b9f50215bd12671168b92c4d776c1e722 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sat, 4 Jan 2020 09:50:52 -0800 Subject: [PATCH 022/283] Rename to shorter context --- examples.txt | 2 +- .../context-in-http-servers.hash | 2 -- .../context.go} | 2 +- examples/context/context.hash | 2 ++ .../context.sh} | 0 public/{context-in-http-servers => context} | 14 +++++++------- public/http-servers | 4 ++-- public/index.html | 2 +- public/spawning-processes | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) delete mode 100644 examples/context-in-http-servers/context-in-http-servers.hash rename examples/{context-in-http-servers/context-in-http-servers.go => context/context.go} (96%) create mode 100644 examples/context/context.hash rename examples/{context-in-http-servers/context-in-http-servers.sh => context/context.sh} (100%) rename public/{context-in-http-servers => context} (87%) diff --git a/examples.txt b/examples.txt index aa3ce317c..27b9df570 100644 --- a/examples.txt +++ b/examples.txt @@ -68,7 +68,7 @@ Command-Line Subcommands Environment Variables HTTP Clients HTTP Servers -Context in HTTP Servers +Context Spawning Processes Exec'ing Processes Signals diff --git a/examples/context-in-http-servers/context-in-http-servers.hash b/examples/context-in-http-servers/context-in-http-servers.hash deleted file mode 100644 index 8e46d0016..000000000 --- a/examples/context-in-http-servers/context-in-http-servers.hash +++ /dev/null @@ -1,2 +0,0 @@ -50f0c85266d1f8f546242ce8f8caf27732e99dff -h1gVSe70R00 diff --git a/examples/context-in-http-servers/context-in-http-servers.go b/examples/context/context.go similarity index 96% rename from examples/context-in-http-servers/context-in-http-servers.go rename to examples/context/context.go index 364d463e3..0ad734cca 100644 --- a/examples/context-in-http-servers/context-in-http-servers.go +++ b/examples/context/context.go @@ -25,7 +25,7 @@ func hello(w http.ResponseWriter, req *http.Request) { // `Done()` channel for a signal that we should cancel // the work and return as soon as possible. select { - case <-time.After(3 * time.Second): + case <-time.After(10 * time.Second): fmt.Fprintf(w, "hello\n") case <-ctx.Done(): err := ctx.Err() diff --git a/examples/context/context.hash b/examples/context/context.hash new file mode 100644 index 000000000..311c608b4 --- /dev/null +++ b/examples/context/context.hash @@ -0,0 +1,2 @@ +a899a68d131b0f8cf3ae846ef728877d2407d219 +9fUzFC2uyFk diff --git a/examples/context-in-http-servers/context-in-http-servers.sh b/examples/context/context.sh similarity index 100% rename from examples/context-in-http-servers/context-in-http-servers.sh rename to examples/context/context.sh diff --git a/public/context-in-http-servers b/public/context similarity index 87% rename from public/context-in-http-servers rename to public/context index 960de8d3c..52712e4dd 100644 --- a/public/context-in-http-servers +++ b/public/context @@ -2,7 +2,7 @@ - Go by Example: Context in HTTP Servers + Go by Example: Context -
    -

    Go by Example: Context in HTTP Servers

    +
    +

    Go by Example: Context

    @@ -34,7 +34,7 @@ controlling cancellation.

    @@ -115,21 +115,35 @@ expired.

    - + + + + + @@ -140,7 +141,7 @@ channel to indicate that’s all the work we have.

    + + + + + @@ -83,13 +82,12 @@ pointer.

    @@ -97,12 +95,25 @@ pointer.

    + + + + + @@ -179,7 +179,7 @@ as a local variable will survive the scope of the function.

    @@ -266,7 +266,7 @@ pointers are automatically dereferenced.

    From 6fcca63e42a58f311e93209ad7389d753e9d6256 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 17:58:40 -0700 Subject: [PATCH 057/283] Add one more word --- examples/regular-expressions/regular-expressions.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/regular-expressions/regular-expressions.go b/examples/regular-expressions/regular-expressions.go index 95d425a6a..f05d26955 100644 --- a/examples/regular-expressions/regular-expressions.go +++ b/examples/regular-expressions/regular-expressions.go @@ -67,7 +67,7 @@ func main() { // When creating global variables with regular // expressions you can use the `MustCompile` variation // of `Compile`. `MustCompile` panics instead of - // returning error, which makes it safer to use for + // returning an error, which makes it safer to use for // global variables. r = regexp.MustCompile("p([a-z]+)ch") fmt.Println(r) From b08d1e88d1ee98519d423ee34d62551c70247289 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 17:58:50 -0700 Subject: [PATCH 058/283] Regenerate --- examples/regular-expressions/regular-expressions.hash | 4 ++-- public/regular-expressions | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/examples/regular-expressions/regular-expressions.hash b/examples/regular-expressions/regular-expressions.hash index a1d564485..bffd78787 100644 --- a/examples/regular-expressions/regular-expressions.hash +++ b/examples/regular-expressions/regular-expressions.hash @@ -1,2 +1,2 @@ -3db643ab821ee2a5b70e05fbadbde1a7f7ba1591 -944r7pT2YIl +c0dd720036ac70269ce233bf47c5d6aefd43161f +LEKGY_d3Nu_P diff --git a/public/regular-expressions b/public/regular-expressions index 7a312eb74..ec3315778 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -43,7 +43,7 @@ in Go.

    From 9e216da9ef940a0e8c4b1f30219a8f6b57804a89 Mon Sep 17 00:00:00 2001 From: Hana Date: Mon, 15 Feb 2021 16:22:08 -0500 Subject: [PATCH 065/283] go.mod: add go.mod and move pygments to third_party After go1.16, go will use module mode by default, even when the repository is checked out under GOPATH or in a one-off directory. Add go.mod, go.sum to keep this repo buildable without opting out of the module mode. > go mod init github.com/mmcgrana/gobyexample > go mod tidy > go mod vendor In module mode, the 'vendor' directory is special and its contents will be actively maintained by the go command. pygments aren't the dependency the go will know about, so it will delete the contents from vendor directory. Move it to `third_party` directory now. And, vendor the blackfriday package. Note: the tutorial contents are not affected by the change in go1.16 because all the examples in this tutorial ask users to run the go command with the explicit list of files to be compiled (e.g. `go run hello-world.go` or `go build command-line-arguments.go`). When the source list is provided, the go command does not have to compute the build list and whether it's running in GOPATH mode or module mode becomes irrelevant. --- README.md | 2 +- go.mod | 5 + go.sum | 2 + public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 2 +- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 2 +- public/collection-functions | 2 +- public/command-line-arguments | 2 +- public/command-line-flags | 2 +- public/command-line-subcommands | 2 +- public/constants | 2 +- public/context | 2 +- public/defer | 2 +- public/directories | 2 +- public/environment-variables | 2 +- public/epoch | 2 +- public/errors | 2 +- public/execing-processes | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/goroutines | 2 +- public/http-clients | 2 +- public/http-servers | 2 +- public/if-else | 2 +- public/index.html | 4 + public/interfaces | 2 +- public/json | 2 +- public/line-filters | 2 +- public/maps | 2 +- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 2 +- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 2 +- public/random-numbers | 2 +- public/range | 2 +- public/range-over-channels | 2 +- public/rate-limiting | 2 +- public/reading-files | 2 +- public/recursion | 2 +- public/regular-expressions | 2 +- public/select | 2 +- public/sha1-hashes | 2 +- public/signals | 2 +- public/slices | 2 +- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 2 +- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- {vendor => third_party}/pygments/.hgignore | 0 {vendor => third_party}/pygments/.hgtags | 0 {vendor => third_party}/pygments/AUTHORS | 0 {vendor => third_party}/pygments/CHANGES | 0 {vendor => third_party}/pygments/LICENSE | 0 {vendor => third_party}/pygments/MANIFEST.in | 0 {vendor => third_party}/pygments/Makefile | 0 {vendor => third_party}/pygments/PKG-INFO | 0 .../pygments/Pygments.egg-info/PKG-INFO | 0 .../pygments/Pygments.egg-info/SOURCES.txt | 0 .../Pygments.egg-info/dependency_links.txt | 0 .../Pygments.egg-info/entry_points.txt | 0 .../pygments/Pygments.egg-info/not-zip-safe | 0 .../pygments/Pygments.egg-info/top_level.txt | 0 {vendor => third_party}/pygments/README.rst | 0 {vendor => third_party}/pygments/TODO | 0 {vendor => third_party}/pygments/doc/Makefile | 0 .../pygments/doc/_static/favicon.ico | Bin .../pygments/doc/_static/logo_new.png | Bin .../pygments/doc/_static/logo_only.png | Bin .../pygments/doc/_templates/docssidebar.html | 0 .../pygments/doc/_templates/indexsidebar.html | 0 .../doc/_themes/pygments14/layout.html | 0 .../doc/_themes/pygments14/static/bodybg.png | Bin .../doc/_themes/pygments14/static/docbg.png | Bin .../_themes/pygments14/static/listitem.png | Bin .../doc/_themes/pygments14/static/logo.png | Bin .../doc/_themes/pygments14/static/pocoo.png | Bin .../pygments14/static/pygments14.css_t | 0 .../doc/_themes/pygments14/theme.conf | 0 {vendor => third_party}/pygments/doc/conf.py | 0 .../pygments/doc/docs/api.rst | 0 .../pygments/doc/docs/authors.rst | 0 .../pygments/doc/docs/changelog.rst | 0 .../pygments/doc/docs/cmdline.rst | 0 .../pygments/doc/docs/filterdevelopment.rst | 0 .../pygments/doc/docs/filters.rst | 0 .../doc/docs/formatterdevelopment.rst | 0 .../pygments/doc/docs/formatters.rst | 0 .../pygments/doc/docs/index.rst | 0 .../pygments/doc/docs/integrate.rst | 0 .../pygments/doc/docs/java.rst | 0 .../pygments/doc/docs/lexerdevelopment.rst | 0 .../pygments/doc/docs/lexers.rst | 0 .../pygments/doc/docs/moinmoin.rst | 0 .../pygments/doc/docs/plugins.rst | 0 .../pygments/doc/docs/quickstart.rst | 0 .../pygments/doc/docs/rstdirective.rst | 0 .../pygments/doc/docs/styles.rst | 0 .../pygments/doc/docs/tokens.rst | 0 .../pygments/doc/docs/unicode.rst | 0 .../pygments/doc/download.rst | 0 {vendor => third_party}/pygments/doc/faq.rst | 0 .../pygments/doc/index.rst | 0 .../pygments/doc/languages.rst | 0 {vendor => third_party}/pygments/doc/make.bat | 0 .../pygments/doc/pygmentize.1 | 0 .../pygments/external/autopygmentize | 0 .../external/lasso-builtins-generator-9.lasso | 0 .../pygments/external/markdown-processor.py | 0 .../pygments/external/moin-parser.py | 0 .../pygments/external/pygments.bashcomp | 0 .../pygments/external/rst-directive.py | 0 {vendor => third_party}/pygments/ez_setup.py | 0 {vendor => third_party}/pygments/pygmentize | 0 .../pygments/pygments/__init__.py | 0 .../pygments/pygments/cmdline.py | 0 .../pygments/pygments/console.py | 0 .../pygments/pygments/filter.py | 0 .../pygments/pygments/filters/__init__.py | 0 .../pygments/pygments/formatter.py | 0 .../pygments/pygments/formatters/__init__.py | 0 .../pygments/pygments/formatters/_mapping.py | 0 .../pygments/pygments/formatters/bbcode.py | 0 .../pygments/pygments/formatters/html.py | 0 .../pygments/pygments/formatters/img.py | 0 .../pygments/pygments/formatters/irc.py | 0 .../pygments/pygments/formatters/latex.py | 0 .../pygments/pygments/formatters/other.py | 0 .../pygments/pygments/formatters/rtf.py | 0 .../pygments/pygments/formatters/svg.py | 0 .../pygments/pygments/formatters/terminal.py | 0 .../pygments/formatters/terminal256.py | 0 .../pygments/pygments/lexer.py | 0 .../pygments/pygments/lexers/__init__.py | 0 .../pygments/pygments/lexers/_asy_builtins.py | 0 .../pygments/pygments/lexers/_cl_builtins.py | 0 .../pygments/lexers/_cocoa_builtins.py | 0 .../pygments/lexers/_csound_builtins.py | 0 .../pygments/lexers/_lasso_builtins.py | 0 .../pygments/pygments/lexers/_lua_builtins.py | 0 .../pygments/pygments/lexers/_mapping.py | 0 .../pygments/pygments/lexers/_mql_builtins.py | 0 .../pygments/lexers/_openedge_builtins.py | 0 .../pygments/pygments/lexers/_php_builtins.py | 0 .../pygments/lexers/_postgres_builtins.py | 0 .../pygments/lexers/_scilab_builtins.py | 0 .../pygments/lexers/_sourcemod_builtins.py | 0 .../pygments/lexers/_stan_builtins.py | 0 .../pygments/pygments/lexers/_vim_builtins.py | 0 .../pygments/pygments/lexers/actionscript.py | 0 .../pygments/pygments/lexers/agile.py | 0 .../pygments/pygments/lexers/algebra.py | 0 .../pygments/pygments/lexers/ambient.py | 0 .../pygments/pygments/lexers/apl.py | 0 .../pygments/pygments/lexers/archetype.py | 0 .../pygments/pygments/lexers/asm.py | 0 .../pygments/pygments/lexers/automation.py | 0 .../pygments/pygments/lexers/basic.py | 0 .../pygments/pygments/lexers/business.py | 0 .../pygments/pygments/lexers/c_cpp.py | 0 .../pygments/pygments/lexers/c_like.py | 0 .../pygments/pygments/lexers/chapel.py | 0 .../pygments/pygments/lexers/compiled.py | 0 .../pygments/pygments/lexers/configs.py | 0 .../pygments/pygments/lexers/console.py | 0 .../pygments/pygments/lexers/csound.py | 0 .../pygments/pygments/lexers/css.py | 0 .../pygments/pygments/lexers/d.py | 0 .../pygments/pygments/lexers/dalvik.py | 0 .../pygments/pygments/lexers/data.py | 0 .../pygments/pygments/lexers/diff.py | 0 .../pygments/pygments/lexers/dotnet.py | 0 .../pygments/pygments/lexers/dsls.py | 0 .../pygments/pygments/lexers/dylan.py | 0 .../pygments/pygments/lexers/ecl.py | 0 .../pygments/pygments/lexers/eiffel.py | 0 .../pygments/pygments/lexers/elm.py | 0 .../pygments/pygments/lexers/erlang.py | 0 .../pygments/pygments/lexers/esoteric.py | 0 .../pygments/pygments/lexers/ezhil.py | 0 .../pygments/pygments/lexers/factor.py | 0 .../pygments/pygments/lexers/fantom.py | 0 .../pygments/pygments/lexers/felix.py | 0 .../pygments/pygments/lexers/fortran.py | 0 .../pygments/pygments/lexers/foxpro.py | 0 .../pygments/pygments/lexers/functional.py | 0 .../pygments/pygments/lexers/go.py | 0 .../pygments/lexers/grammar_notation.py | 0 .../pygments/pygments/lexers/graph.py | 0 .../pygments/pygments/lexers/graphics.py | 0 .../pygments/pygments/lexers/haskell.py | 0 .../pygments/pygments/lexers/haxe.py | 0 .../pygments/pygments/lexers/hdl.py | 0 .../pygments/pygments/lexers/hexdump.py | 0 .../pygments/pygments/lexers/html.py | 0 .../pygments/pygments/lexers/idl.py | 0 .../pygments/pygments/lexers/igor.py | 0 .../pygments/pygments/lexers/inferno.py | 0 .../pygments/pygments/lexers/installers.py | 0 .../pygments/pygments/lexers/int_fiction.py | 0 .../pygments/pygments/lexers/iolang.py | 0 .../pygments/pygments/lexers/j.py | 0 .../pygments/pygments/lexers/javascript.py | 0 .../pygments/pygments/lexers/julia.py | 0 .../pygments/pygments/lexers/jvm.py | 0 .../pygments/pygments/lexers/lisp.py | 0 .../pygments/pygments/lexers/make.py | 0 .../pygments/pygments/lexers/markup.py | 0 .../pygments/pygments/lexers/math.py | 0 .../pygments/pygments/lexers/matlab.py | 0 .../pygments/pygments/lexers/ml.py | 0 .../pygments/pygments/lexers/modeling.py | 0 .../pygments/pygments/lexers/modula2.py | 0 .../pygments/pygments/lexers/nimrod.py | 0 .../pygments/pygments/lexers/nit.py | 0 .../pygments/pygments/lexers/nix.py | 0 .../pygments/pygments/lexers/oberon.py | 0 .../pygments/pygments/lexers/objective.py | 0 .../pygments/pygments/lexers/ooc.py | 0 .../pygments/pygments/lexers/other.py | 0 .../pygments/pygments/lexers/parasail.py | 0 .../pygments/pygments/lexers/parsers.py | 0 .../pygments/pygments/lexers/pascal.py | 0 .../pygments/pygments/lexers/pawn.py | 0 .../pygments/pygments/lexers/perl.py | 0 .../pygments/pygments/lexers/php.py | 0 .../pygments/pygments/lexers/praat.py | 0 .../pygments/pygments/lexers/prolog.py | 0 .../pygments/pygments/lexers/python.py | 0 .../pygments/pygments/lexers/qvt.py | 0 .../pygments/pygments/lexers/r.py | 0 .../pygments/pygments/lexers/rdf.py | 0 .../pygments/pygments/lexers/rebol.py | 0 .../pygments/pygments/lexers/resource.py | 0 .../pygments/pygments/lexers/roboconf.py | 0 .../pygments/lexers/robotframework.py | 0 .../pygments/pygments/lexers/ruby.py | 0 .../pygments/pygments/lexers/rust.py | 0 .../pygments/pygments/lexers/scripting.py | 0 .../pygments/pygments/lexers/shell.py | 0 .../pygments/pygments/lexers/smalltalk.py | 0 .../pygments/pygments/lexers/snobol.py | 0 .../pygments/pygments/lexers/special.py | 0 .../pygments/pygments/lexers/sql.py | 0 .../pygments/pygments/lexers/supercollider.py | 0 .../pygments/pygments/lexers/tcl.py | 0 .../pygments/pygments/lexers/templates.py | 0 .../pygments/pygments/lexers/testing.py | 0 .../pygments/pygments/lexers/text.py | 0 .../pygments/pygments/lexers/textedit.py | 0 .../pygments/pygments/lexers/textfmts.py | 0 .../pygments/pygments/lexers/theorem.py | 0 .../pygments/pygments/lexers/trafficscript.py | 0 .../pygments/pygments/lexers/urbi.py | 0 .../pygments/pygments/lexers/web.py | 0 .../pygments/pygments/lexers/webmisc.py | 0 .../pygments/pygments/lexers/x10.py | 0 .../pygments/pygments/modeline.py | 0 .../pygments/pygments/plugin.py | 0 .../pygments/pygments/regexopt.py | 0 .../pygments/pygments/scanner.py | 0 .../pygments/pygments/sphinxext.py | 0 .../pygments/pygments/style.py | 0 .../pygments/pygments/styles/__init__.py | 0 .../pygments/pygments/styles/algol.py | 0 .../pygments/pygments/styles/algol_nu.py | 0 .../pygments/pygments/styles/arduino.py | 0 .../pygments/pygments/styles/autumn.py | 0 .../pygments/pygments/styles/borland.py | 0 .../pygments/pygments/styles/bw.py | 0 .../pygments/pygments/styles/colorful.py | 0 .../pygments/pygments/styles/default.py | 0 .../pygments/pygments/styles/emacs.py | 0 .../pygments/pygments/styles/friendly.py | 0 .../pygments/pygments/styles/fruity.py | 0 .../pygments/pygments/styles/igor.py | 0 .../pygments/pygments/styles/lovelace.py | 0 .../pygments/pygments/styles/manni.py | 0 .../pygments/pygments/styles/monokai.py | 0 .../pygments/pygments/styles/murphy.py | 0 .../pygments/pygments/styles/native.py | 0 .../pygments/pygments/styles/paraiso_dark.py | 0 .../pygments/pygments/styles/paraiso_light.py | 0 .../pygments/pygments/styles/pastie.py | 0 .../pygments/pygments/styles/perldoc.py | 0 .../pygments/pygments/styles/rrt.py | 0 .../pygments/pygments/styles/tango.py | 0 .../pygments/pygments/styles/trac.py | 0 .../pygments/pygments/styles/vim.py | 0 .../pygments/pygments/styles/vs.py | 0 .../pygments/pygments/styles/xcode.py | 0 .../pygments/pygments/token.py | 0 .../pygments/pygments/unistring.py | 0 .../pygments/pygments/util.py | 0 .../pygments/requirements.txt | 0 .../pygments/scripts/check_sources.py | 0 .../pygments/scripts/debug_lexer.py | 0 .../scripts/detect_missing_analyse_text.py | 0 .../pygments/scripts/epydoc.css | 0 .../pygments/scripts/find_error.py | 0 .../pygments/scripts/get_vimkw.py | 0 .../pygments/scripts/pylintrc | 0 .../pygments/scripts/vim2pygments.py | 0 {vendor => third_party}/pygments/setup.cfg | 0 {vendor => third_party}/pygments/setup.py | 0 .../pygments/tests/.coverage | Bin .../pygments/tests/cover/coverage_html.js | 0 .../pygments/tests/cover/jquery.hotkeys.js | 0 .../pygments/tests/cover/jquery.isonscreen.js | 0 .../pygments/tests/cover/jquery.min.js | 0 .../tests/cover/jquery.tablesorter.min.js | 0 .../pygments/tests/cover/keybd_closed.png | Bin .../pygments/tests/cover/keybd_open.png | Bin .../pygments/tests/cover/status.dat | 0 .../pygments/tests/cover/style.css | 0 .../pygments/tests/dtds/HTML4-f.dtd | 0 .../pygments/tests/dtds/HTML4-s.dtd | 0 .../pygments/tests/dtds/HTML4.dcl | 0 .../pygments/tests/dtds/HTML4.dtd | 0 .../pygments/tests/dtds/HTML4.soc | 0 .../pygments/tests/dtds/HTMLlat1.ent | 0 .../pygments/tests/dtds/HTMLspec.ent | 0 .../pygments/tests/dtds/HTMLsym.ent | 0 .../examplefiles/99_bottles_of_beer.chpl | 0 .../tests/examplefiles/AcidStateAdvanced.hs | 0 .../tests/examplefiles/AlternatingGroup.mu | 0 .../pygments/tests/examplefiles/BOM.js | 0 .../pygments/tests/examplefiles/Blink.ino | 0 .../tests/examplefiles/CPDictionary.j | 0 .../tests/examplefiles/Config.in.cache | 0 .../pygments/tests/examplefiles/Constants.mo | 0 .../tests/examplefiles/DancingSudoku.lhs | 0 .../pygments/tests/examplefiles/Deflate.fs | 0 .../pygments/tests/examplefiles/Error.pmod | 0 .../pygments/tests/examplefiles/Errors.scala | 0 .../pygments/tests/examplefiles/FakeFile.pike | 0 .../Get-CommandDefinitionHtml.ps1 | 0 .../tests/examplefiles/IPDispatchC.nc | 0 .../tests/examplefiles/IPDispatchP.nc | 0 .../pygments/tests/examplefiles/Intro.java | 0 .../pygments/tests/examplefiles/Makefile | 0 .../pygments/tests/examplefiles/Object.st | 0 .../pygments/tests/examplefiles/OrderedMap.hx | 0 .../pygments/tests/examplefiles/RoleQ.pm6 | 0 .../pygments/tests/examplefiles/SmallCheck.hs | 0 .../pygments/tests/examplefiles/Sorting.mod | 0 .../pygments/tests/examplefiles/Sudoku.lhs | 0 .../tests/examplefiles/abnf_example1.abnf | 0 .../tests/examplefiles/abnf_example2.abnf | 0 .../tests/examplefiles/addressbook.proto | 0 .../pygments/tests/examplefiles/ahcon.f | 0 .../pygments/tests/examplefiles/all.nit | 0 .../tests/examplefiles/antlr_ANTLRv3.g | 0 .../pygments/tests/examplefiles/antlr_throws | 0 .../pygments/tests/examplefiles/apache2.conf | 0 .../pygments/tests/examplefiles/as3_test.as | 0 .../pygments/tests/examplefiles/as3_test2.as | 0 .../pygments/tests/examplefiles/as3_test3.as | 0 .../tests/examplefiles/aspx-cs_example | 0 .../tests/examplefiles/autoit_submit.au3 | 0 .../pygments/tests/examplefiles/automake.mk | 0 .../pygments/tests/examplefiles/badcase.java | 0 .../pygments/tests/examplefiles/bigtest.nsi | 0 .../tests/examplefiles/bnf_example1.bnf | 0 .../pygments/tests/examplefiles/boot-9.scm | 0 .../pygments/tests/examplefiles/ca65_example | 0 .../tests/examplefiles/cbmbas_example | 0 .../pygments/tests/examplefiles/cells.ps | Bin .../pygments/tests/examplefiles/ceval.c | 0 .../pygments/tests/examplefiles/char.scala | 0 .../tests/examplefiles/cheetah_example.html | 0 .../pygments/tests/examplefiles/classes.dylan | 0 .../examplefiles/clojure-weird-keywords.clj | 0 .../tests/examplefiles/condensed_ruby.rb | 0 .../tests/examplefiles/coq_RelationClasses | 0 .../pygments/tests/examplefiles/core.cljs | 0 .../pygments/tests/examplefiles/database.pytb | 0 .../tests/examplefiles/de.MoinMoin.po | 0 .../pygments/tests/examplefiles/demo.ahk | 0 .../pygments/tests/examplefiles/demo.cfm | 0 .../pygments/tests/examplefiles/demo.css.in | 0 .../pygments/tests/examplefiles/demo.hbs | 0 .../pygments/tests/examplefiles/demo.js.in | 0 .../pygments/tests/examplefiles/demo.thrift | 0 .../pygments/tests/examplefiles/demo.xul.in | 0 .../examplefiles/django_sample.html+django | 0 .../pygments/tests/examplefiles/docker.docker | 0 .../pygments/tests/examplefiles/dwarf.cw | 0 .../tests/examplefiles/eg_example1.eg | 0 .../tests/examplefiles/ember.handlebars | 0 .../pygments/tests/examplefiles/erl_session | 0 .../pygments/tests/examplefiles/es6.js | 0 .../tests/examplefiles/escape_semicolon.clj | 0 .../pygments/tests/examplefiles/eval.rs | 0 .../pygments/tests/examplefiles/evil_regex.js | 0 .../pygments/tests/examplefiles/example.Rd | 0 .../pygments/tests/examplefiles/example.als | 0 .../pygments/tests/examplefiles/example.bat | 0 .../pygments/tests/examplefiles/example.bc | 0 .../pygments/tests/examplefiles/example.bug | 0 .../pygments/tests/examplefiles/example.c | 0 .../tests/examplefiles/example.ceylon | 0 .../pygments/tests/examplefiles/example.chai | 0 .../pygments/tests/examplefiles/example.clay | 0 .../pygments/tests/examplefiles/example.cls | 0 .../pygments/tests/examplefiles/example.cob | 0 .../tests/examplefiles/example.coffee | 0 .../pygments/tests/examplefiles/example.cpp | 0 .../pygments/tests/examplefiles/example.e | 0 .../pygments/tests/examplefiles/example.elm | 0 .../pygments/tests/examplefiles/example.ezt | 0 .../pygments/tests/examplefiles/example.f90 | 0 .../tests/examplefiles/example.feature | 0 .../pygments/tests/examplefiles/example.fish | 0 .../pygments/tests/examplefiles/example.gd | 0 .../pygments/tests/examplefiles/example.gi | 0 .../pygments/tests/examplefiles/example.golo | 0 .../tests/examplefiles/example.groovy | 0 .../pygments/tests/examplefiles/example.gs | 0 .../pygments/tests/examplefiles/example.gst | 0 .../pygments/tests/examplefiles/example.hs | 0 .../pygments/tests/examplefiles/example.hx | 0 .../pygments/tests/examplefiles/example.i6t | 0 .../pygments/tests/examplefiles/example.i7x | 0 .../pygments/tests/examplefiles/example.j | 0 .../pygments/tests/examplefiles/example.jag | 0 .../pygments/tests/examplefiles/example.java | 0 .../pygments/tests/examplefiles/example.jcl | 0 .../tests/examplefiles/example.jsonld | 0 .../pygments/tests/examplefiles/example.kal | 0 .../pygments/tests/examplefiles/example.kt | 0 .../pygments/tests/examplefiles/example.lagda | 0 .../tests/examplefiles/example.liquid | 0 .../pygments/tests/examplefiles/example.lua | 0 .../pygments/tests/examplefiles/example.ma | 0 .../pygments/tests/examplefiles/example.mac | 0 .../tests/examplefiles/example.monkey | 0 .../pygments/tests/examplefiles/example.moo | 0 .../pygments/tests/examplefiles/example.moon | 0 .../pygments/tests/examplefiles/example.mq4 | 0 .../pygments/tests/examplefiles/example.mqh | 0 .../pygments/tests/examplefiles/example.msc | 0 .../pygments/tests/examplefiles/example.ni | 0 .../pygments/tests/examplefiles/example.nim | 0 .../pygments/tests/examplefiles/example.nix | 0 .../pygments/tests/examplefiles/example.ns2 | 0 .../pygments/tests/examplefiles/example.pas | 0 .../pygments/tests/examplefiles/example.pcmk | 0 .../pygments/tests/examplefiles/example.pp | 0 .../pygments/tests/examplefiles/example.praat | 0 .../pygments/tests/examplefiles/example.prg | 0 .../pygments/tests/examplefiles/example.rb | 0 .../pygments/tests/examplefiles/example.red | 0 .../pygments/tests/examplefiles/example.reds | 0 .../pygments/tests/examplefiles/example.reg | 0 .../pygments/tests/examplefiles/example.rexx | 0 .../pygments/tests/examplefiles/example.rhtml | 0 .../pygments/tests/examplefiles/example.rkt | 0 .../pygments/tests/examplefiles/example.rpf | 0 .../pygments/tests/examplefiles/example.rts | 0 .../pygments/tests/examplefiles/example.scd | 0 .../pygments/tests/examplefiles/example.sh | 0 .../tests/examplefiles/example.sh-session | 0 .../tests/examplefiles/example.shell-session | 0 .../pygments/tests/examplefiles/example.slim | 0 .../pygments/tests/examplefiles/example.sls | 0 .../pygments/tests/examplefiles/example.sml | 0 .../tests/examplefiles/example.snobol | 0 .../pygments/tests/examplefiles/example.stan | 0 .../pygments/tests/examplefiles/example.tap | 0 .../pygments/tests/examplefiles/example.tea | 0 .../pygments/tests/examplefiles/example.tf | 0 .../pygments/tests/examplefiles/example.thy | 0 .../tests/examplefiles/example.todotxt | 0 .../pygments/tests/examplefiles/example.ts | 0 .../pygments/tests/examplefiles/example.ttl | 0 .../pygments/tests/examplefiles/example.u | 0 .../tests/examplefiles/example.weechatlog | 0 .../pygments/tests/examplefiles/example.x10 | 0 .../pygments/tests/examplefiles/example.xhtml | 0 .../pygments/tests/examplefiles/example.xtend | 0 .../pygments/tests/examplefiles/example.yaml | 0 .../pygments/tests/examplefiles/example1.cadl | 0 .../pygments/tests/examplefiles/example2.aspx | 0 .../pygments/tests/examplefiles/example2.msc | 0 .../tests/examplefiles/exampleScript.cfc | 0 .../tests/examplefiles/exampleTag.cfc | 0 .../pygments/tests/examplefiles/example_coq.v | 0 .../tests/examplefiles/example_elixir.ex | 0 .../tests/examplefiles/example_file.fy | 0 .../tests/examplefiles/ezhil_primefactors.n | 0 .../pygments/tests/examplefiles/firefox.mak | 0 .../pygments/tests/examplefiles/flipflop.sv | 0 .../pygments/tests/examplefiles/foo.sce | 0 .../pygments/tests/examplefiles/format.ml | 0 .../pygments/tests/examplefiles/fucked_up.rb | 0 .../pygments/tests/examplefiles/function.mu | 0 .../tests/examplefiles/functional.rst | 0 .../tests/examplefiles/garcia-wachs.kk | 0 .../pygments/tests/examplefiles/genclass.clj | 0 .../examplefiles/genshi_example.xml+genshi | 0 .../genshitext_example.genshitext | 0 .../pygments/tests/examplefiles/glsl.frag | 0 .../pygments/tests/examplefiles/glsl.vert | 0 .../tests/examplefiles/grammar-test.p6 | 0 .../tests/examplefiles/hash_syntax.rb | 0 .../pygments/tests/examplefiles/hello.at | 0 .../pygments/tests/examplefiles/hello.golo | 0 .../pygments/tests/examplefiles/hello.lsl | 0 .../pygments/tests/examplefiles/hello.smali | 0 .../pygments/tests/examplefiles/hello.sp | 0 .../tests/examplefiles/hexdump_debugexe | 0 .../pygments/tests/examplefiles/hexdump_hd | 0 .../tests/examplefiles/hexdump_hexcat | 0 .../tests/examplefiles/hexdump_hexdump | 0 .../pygments/tests/examplefiles/hexdump_od | 0 .../pygments/tests/examplefiles/hexdump_xxd | 0 .../tests/examplefiles/html+php_faulty.php | 0 .../tests/examplefiles/http_request_example | 0 .../tests/examplefiles/http_response_example | 0 .../tests/examplefiles/hybris_File.hy | 0 .../tests/examplefiles/idl_sample.pro | 0 .../pygments/tests/examplefiles/iex_example | 0 .../pygments/tests/examplefiles/inet_pton6.dg | 0 .../tests/examplefiles/inform6_example | 0 .../pygments/tests/examplefiles/interp.scala | 0 .../pygments/tests/examplefiles/intro.ik | 0 .../pygments/tests/examplefiles/ints.php | 0 .../pygments/tests/examplefiles/intsyn.fun | 0 .../pygments/tests/examplefiles/intsyn.sig | 0 .../pygments/tests/examplefiles/irb_heredoc | 0 .../pygments/tests/examplefiles/irc.lsp | 0 .../tests/examplefiles/java.properties | 0 .../tests/examplefiles/jbst_example1.jbst | 0 .../tests/examplefiles/jbst_example2.jbst | 0 .../tests/examplefiles/jinjadesignerdoc.rst | 0 .../pygments/tests/examplefiles/json.lasso | 0 .../pygments/tests/examplefiles/json.lasso9 | 0 .../pygments/tests/examplefiles/language.hy | 0 .../tests/examplefiles/lighttpd_config.conf | 0 .../pygments/tests/examplefiles/limbo.b | 0 .../tests/examplefiles/linecontinuation.py | 0 .../tests/examplefiles/livescript-demo.ls | 0 .../tests/examplefiles/logos_example.xm | 0 .../pygments/tests/examplefiles/ltmain.sh | 0 .../pygments/tests/examplefiles/main.cmake | 0 .../pygments/tests/examplefiles/markdown.lsp | 0 .../tests/examplefiles/matlab_noreturn | 0 .../pygments/tests/examplefiles/matlab_sample | 0 .../examplefiles/matlabsession_sample.txt | 0 .../tests/examplefiles/metagrammar.treetop | 0 .../pygments/tests/examplefiles/minehunt.qml | 0 .../pygments/tests/examplefiles/minimal.ns2 | 0 .../tests/examplefiles/modula2_test_cases.def | 0 .../examplefiles/moin_SyntaxReference.txt | 0 .../tests/examplefiles/multiline_regexes.rb | 0 .../pygments/tests/examplefiles/nanomsg.intr | 0 .../tests/examplefiles/nasm_aoutso.asm | 0 .../tests/examplefiles/nasm_objexe.asm | 0 .../tests/examplefiles/nemerle_sample.n | 0 .../tests/examplefiles/nginx_nginx.conf | 0 .../pygments/tests/examplefiles/noexcept.cpp | 0 .../pygments/tests/examplefiles/numbers.c | 0 .../tests/examplefiles/objc_example.m | 0 .../tests/examplefiles/openedge_example | 0 .../pygments/tests/examplefiles/pacman.conf | 0 .../pygments/tests/examplefiles/pacman.ijs | 0 .../pygments/tests/examplefiles/pawn_example | 0 .../pygments/tests/examplefiles/perl_misc | 0 .../pygments/tests/examplefiles/perl_perl5db | 0 .../tests/examplefiles/perl_regex-delims | 0 .../pygments/tests/examplefiles/perlfunc.1 | 0 .../tests/examplefiles/phpMyAdmin.spec | 0 .../tests/examplefiles/phpcomplete.vim | 0 .../tests/examplefiles/pkgconfig_example.pc | 0 .../pygments/tests/examplefiles/pleac.in.rb | 0 .../tests/examplefiles/postgresql_test.txt | 0 .../tests/examplefiles/pppoe.applescript | 0 .../tests/examplefiles/psql_session.txt | 0 .../pygments/tests/examplefiles/py3_test.txt | 0 .../tests/examplefiles/py3tb_test.py3tb | 0 .../tests/examplefiles/pycon_ctrlc_traceback | 0 .../tests/examplefiles/pycon_test.pycon | 0 .../tests/examplefiles/pytb_test2.pytb | 0 .../tests/examplefiles/pytb_test3.pytb | 0 .../tests/examplefiles/python25-bsd.mak | 0 .../tests/examplefiles/qbasic_example | 0 .../pygments/tests/examplefiles/qsort.prolog | 0 .../examplefiles/r-console-transcript.Rout | 0 .../tests/examplefiles/r6rs-comments.scm | 0 .../tests/examplefiles/ragel-cpp_rlscan | 0 .../tests/examplefiles/ragel-cpp_snippet | 0 .../pygments/tests/examplefiles/regex.js | 0 .../tests/examplefiles/resourcebundle_demo | 0 .../pygments/tests/examplefiles/reversi.lsp | 0 .../tests/examplefiles/roboconf.graph | 0 .../tests/examplefiles/roboconf.instances | 0 .../examplefiles/robotframework_test.txt | 0 .../tests/examplefiles/rql-queries.rql | 0 .../tests/examplefiles/ruby_func_def.rb | 0 .../pygments/tests/examplefiles/sample.qvto | 0 .../pygments/tests/examplefiles/scilab.sci | 0 .../pygments/tests/examplefiles/scope.cirru | 0 .../tests/examplefiles/session.dylan-console | 0 .../tests/examplefiles/sibling.prolog | 0 .../pygments/tests/examplefiles/simple.camkes | 0 .../pygments/tests/examplefiles/simple.croc | 0 .../tests/examplefiles/smarty_example.html | 0 .../pygments/tests/examplefiles/source.lgt | 0 .../pygments/tests/examplefiles/sources.list | 0 .../pygments/tests/examplefiles/sparql.rq | 0 .../pygments/tests/examplefiles/sphere.pov | 0 .../examplefiles/sqlite3.sqlite3-console | 0 .../pygments/tests/examplefiles/squid.conf | 0 .../pygments/tests/examplefiles/string.jl | 0 .../tests/examplefiles/string_delimiters.d | 0 .../tests/examplefiles/stripheredoc.sh | 0 .../pygments/tests/examplefiles/subr.el | 0 .../pygments/tests/examplefiles/swig_java.swg | 0 .../tests/examplefiles/swig_std_vector.i | 0 .../tests/examplefiles/tads3_example.t | 0 .../pygments/tests/examplefiles/termcap | 0 .../pygments/tests/examplefiles/terminfo | 0 .../pygments/tests/examplefiles/test-3.0.xq | 0 .../tests/examplefiles/test-exist-update.xq | 0 .../pygments/tests/examplefiles/test.R | 0 .../pygments/tests/examplefiles/test.adb | 0 .../pygments/tests/examplefiles/test.adls | 0 .../pygments/tests/examplefiles/test.agda | 0 .../pygments/tests/examplefiles/test.apl | 0 .../pygments/tests/examplefiles/test.asy | 0 .../pygments/tests/examplefiles/test.awk | 0 .../pygments/tests/examplefiles/test.bb | 0 .../pygments/tests/examplefiles/test.bmx | 0 .../pygments/tests/examplefiles/test.boo | 0 .../pygments/tests/examplefiles/test.bpl | 0 .../pygments/tests/examplefiles/test.bro | 0 .../pygments/tests/examplefiles/test.cadl | 0 .../pygments/tests/examplefiles/test.cs | 0 .../pygments/tests/examplefiles/test.csd | 0 .../pygments/tests/examplefiles/test.css | 0 .../pygments/tests/examplefiles/test.cu | 0 .../pygments/tests/examplefiles/test.cyp | 0 .../pygments/tests/examplefiles/test.d | 0 .../pygments/tests/examplefiles/test.dart | 0 .../pygments/tests/examplefiles/test.dtd | 0 .../pygments/tests/examplefiles/test.ebnf | 0 .../pygments/tests/examplefiles/test.ec | 0 .../pygments/tests/examplefiles/test.eh | 0 .../pygments/tests/examplefiles/test.erl | 0 .../pygments/tests/examplefiles/test.evoque | 0 .../pygments/tests/examplefiles/test.fan | 0 .../pygments/tests/examplefiles/test.flx | 0 .../pygments/tests/examplefiles/test.gdc | 0 .../pygments/tests/examplefiles/test.gradle | 0 .../pygments/tests/examplefiles/test.groovy | 0 .../pygments/tests/examplefiles/test.html | 0 .../pygments/tests/examplefiles/test.idr | 0 .../pygments/tests/examplefiles/test.ini | 0 .../pygments/tests/examplefiles/test.java | 0 .../pygments/tests/examplefiles/test.jsp | 0 .../pygments/tests/examplefiles/test.lean | 0 .../pygments/tests/examplefiles/test.maql | 0 .../pygments/tests/examplefiles/test.mask | 0 .../pygments/tests/examplefiles/test.mod | 0 .../pygments/tests/examplefiles/test.moo | 0 .../pygments/tests/examplefiles/test.myt | 0 .../pygments/tests/examplefiles/test.nim | 0 .../pygments/tests/examplefiles/test.odin | 0 .../pygments/tests/examplefiles/test.opa | 0 .../pygments/tests/examplefiles/test.orc | 0 .../pygments/tests/examplefiles/test.p6 | 0 .../pygments/tests/examplefiles/test.pan | 0 .../pygments/tests/examplefiles/test.pas | 0 .../pygments/tests/examplefiles/test.php | 0 .../pygments/tests/examplefiles/test.pig | 0 .../pygments/tests/examplefiles/test.plot | 0 .../pygments/tests/examplefiles/test.ps1 | 0 .../pygments/tests/examplefiles/test.psl | 0 .../pygments/tests/examplefiles/test.pwn | 0 .../pygments/tests/examplefiles/test.pypylog | 0 .../pygments/tests/examplefiles/test.r3 | 0 .../pygments/tests/examplefiles/test.rb | 0 .../pygments/tests/examplefiles/test.rhtml | 0 .../pygments/tests/examplefiles/test.rsl | 0 .../pygments/tests/examplefiles/test.scaml | 0 .../pygments/tests/examplefiles/test.sco | 0 .../pygments/tests/examplefiles/test.shen | 0 .../pygments/tests/examplefiles/test.ssp | 0 .../pygments/tests/examplefiles/test.swift | 0 .../pygments/tests/examplefiles/test.tcsh | 0 .../pygments/tests/examplefiles/test.vb | 0 .../pygments/tests/examplefiles/test.vhdl | 0 .../pygments/tests/examplefiles/test.xqy | 0 .../pygments/tests/examplefiles/test.xsl | 0 .../pygments/tests/examplefiles/test.zep | 0 .../pygments/tests/examplefiles/test2.odin | 0 .../pygments/tests/examplefiles/test2.pypylog | 0 .../tests/examplefiles/test_basic.adls | 0 .../tests/examplefiles/truncated.pytb | 0 .../pygments/tests/examplefiles/twig_test | 0 .../pygments/tests/examplefiles/type.lisp | 0 .../tests/examplefiles/underscore.coffee | 0 .../tests/examplefiles/unicode.applescript | 0 .../pygments/tests/examplefiles/unicode.go | 0 .../pygments/tests/examplefiles/unicode.js | 0 .../pygments/tests/examplefiles/unicodedoc.py | 0 .../pygments/tests/examplefiles/unix-io.lid | 0 .../tests/examplefiles/vbnet_test.bas | 0 .../tests/examplefiles/vctreestatus_hg | 0 .../pygments/tests/examplefiles/vimrc | 0 .../pygments/tests/examplefiles/vpath.mk | 0 .../tests/examplefiles/webkit-transition.css | 0 .../pygments/tests/examplefiles/while.pov | 0 .../pygments/tests/examplefiles/wiki.factor | 0 .../pygments/tests/examplefiles/xml_example | 0 .../pygments/tests/examplefiles/yahalom.cpsa | 0 .../pygments/tests/examplefiles/zmlrpc.f90 | 0 {vendor => third_party}/pygments/tests/run.py | 0 .../pygments/tests/string_asserts.py | 0 .../pygments/tests/support.py | 0 .../pygments/tests/support/tags | 0 .../pygments/tests/test_basic_api.py | 0 .../pygments/tests/test_cfm.py | 0 .../pygments/tests/test_clexer.py | 0 .../pygments/tests/test_cmdline.py | 0 .../pygments/tests/test_examplefiles.py | 0 .../pygments/tests/test_ezhil.py | 0 .../pygments/tests/test_html_formatter.py | 0 .../pygments/tests/test_inherit.py | 0 .../pygments/tests/test_irc_formatter.py | 0 .../pygments/tests/test_java.py | 0 .../pygments/tests/test_latex_formatter.py | 0 .../pygments/tests/test_lexers_other.py | 0 .../pygments/tests/test_objectiveclexer.py | 0 .../pygments/tests/test_perllexer.py | 0 .../pygments/tests/test_qbasiclexer.py | 0 .../pygments/tests/test_regexlexer.py | 0 .../pygments/tests/test_regexopt.py | 0 .../pygments/tests/test_rtf_formatter.py | 0 .../pygments/tests/test_ruby.py | 0 .../pygments/tests/test_shell.py | 0 .../pygments/tests/test_smarty.py | 0 .../pygments/tests/test_string_asserts.py | 0 .../pygments/tests/test_terminal_formatter.py | 0 .../pygments/tests/test_textfmts.py | 0 .../pygments/tests/test_token.py | 0 .../pygments/tests/test_unistring.py | 0 .../pygments/tests/test_using_api.py | 0 .../pygments/tests/test_util.py | 0 {vendor => third_party}/pygments/tox.ini | 0 tools/generate.go | 2 +- .../russross/blackfriday/.gitignore | 8 + .../russross/blackfriday/.travis.yml | 18 + .../russross/blackfriday/LICENSE.txt | 28 + .../github.com/russross/blackfriday/README.md | 364 ++++ .../github.com/russross/blackfriday/block.go | 1480 +++++++++++++++++ vendor/github.com/russross/blackfriday/doc.go | 32 + vendor/github.com/russross/blackfriday/go.mod | 3 + .../github.com/russross/blackfriday/html.go | 945 +++++++++++ .../github.com/russross/blackfriday/inline.go | 1154 +++++++++++++ .../github.com/russross/blackfriday/latex.go | 334 ++++ .../russross/blackfriday/markdown.go | 943 +++++++++++ .../russross/blackfriday/smartypants.go | 430 +++++ vendor/modules.txt | 3 + 793 files changed, 5828 insertions(+), 75 deletions(-) create mode 100644 go.mod create mode 100644 go.sum rename {vendor => third_party}/pygments/.hgignore (100%) rename {vendor => third_party}/pygments/.hgtags (100%) rename {vendor => third_party}/pygments/AUTHORS (100%) rename {vendor => third_party}/pygments/CHANGES (100%) rename {vendor => third_party}/pygments/LICENSE (100%) rename {vendor => third_party}/pygments/MANIFEST.in (100%) rename {vendor => third_party}/pygments/Makefile (100%) rename {vendor => third_party}/pygments/PKG-INFO (100%) rename {vendor => third_party}/pygments/Pygments.egg-info/PKG-INFO (100%) rename {vendor => third_party}/pygments/Pygments.egg-info/SOURCES.txt (100%) rename {vendor => third_party}/pygments/Pygments.egg-info/dependency_links.txt (100%) rename {vendor => third_party}/pygments/Pygments.egg-info/entry_points.txt (100%) rename {vendor => third_party}/pygments/Pygments.egg-info/not-zip-safe (100%) rename {vendor => third_party}/pygments/Pygments.egg-info/top_level.txt (100%) rename {vendor => third_party}/pygments/README.rst (100%) rename {vendor => third_party}/pygments/TODO (100%) rename {vendor => third_party}/pygments/doc/Makefile (100%) rename {vendor => third_party}/pygments/doc/_static/favicon.ico (100%) rename {vendor => third_party}/pygments/doc/_static/logo_new.png (100%) rename {vendor => third_party}/pygments/doc/_static/logo_only.png (100%) rename {vendor => third_party}/pygments/doc/_templates/docssidebar.html (100%) rename {vendor => third_party}/pygments/doc/_templates/indexsidebar.html (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/layout.html (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/static/bodybg.png (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/static/docbg.png (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/static/listitem.png (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/static/logo.png (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/static/pocoo.png (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/static/pygments14.css_t (100%) rename {vendor => third_party}/pygments/doc/_themes/pygments14/theme.conf (100%) rename {vendor => third_party}/pygments/doc/conf.py (100%) rename {vendor => third_party}/pygments/doc/docs/api.rst (100%) rename {vendor => third_party}/pygments/doc/docs/authors.rst (100%) rename {vendor => third_party}/pygments/doc/docs/changelog.rst (100%) rename {vendor => third_party}/pygments/doc/docs/cmdline.rst (100%) rename {vendor => third_party}/pygments/doc/docs/filterdevelopment.rst (100%) rename {vendor => third_party}/pygments/doc/docs/filters.rst (100%) rename {vendor => third_party}/pygments/doc/docs/formatterdevelopment.rst (100%) rename {vendor => third_party}/pygments/doc/docs/formatters.rst (100%) rename {vendor => third_party}/pygments/doc/docs/index.rst (100%) rename {vendor => third_party}/pygments/doc/docs/integrate.rst (100%) rename {vendor => third_party}/pygments/doc/docs/java.rst (100%) rename {vendor => third_party}/pygments/doc/docs/lexerdevelopment.rst (100%) rename {vendor => third_party}/pygments/doc/docs/lexers.rst (100%) rename {vendor => third_party}/pygments/doc/docs/moinmoin.rst (100%) rename {vendor => third_party}/pygments/doc/docs/plugins.rst (100%) rename {vendor => third_party}/pygments/doc/docs/quickstart.rst (100%) rename {vendor => third_party}/pygments/doc/docs/rstdirective.rst (100%) rename {vendor => third_party}/pygments/doc/docs/styles.rst (100%) rename {vendor => third_party}/pygments/doc/docs/tokens.rst (100%) rename {vendor => third_party}/pygments/doc/docs/unicode.rst (100%) rename {vendor => third_party}/pygments/doc/download.rst (100%) rename {vendor => third_party}/pygments/doc/faq.rst (100%) rename {vendor => third_party}/pygments/doc/index.rst (100%) rename {vendor => third_party}/pygments/doc/languages.rst (100%) rename {vendor => third_party}/pygments/doc/make.bat (100%) rename {vendor => third_party}/pygments/doc/pygmentize.1 (100%) rename {vendor => third_party}/pygments/external/autopygmentize (100%) rename {vendor => third_party}/pygments/external/lasso-builtins-generator-9.lasso (100%) rename {vendor => third_party}/pygments/external/markdown-processor.py (100%) rename {vendor => third_party}/pygments/external/moin-parser.py (100%) rename {vendor => third_party}/pygments/external/pygments.bashcomp (100%) rename {vendor => third_party}/pygments/external/rst-directive.py (100%) rename {vendor => third_party}/pygments/ez_setup.py (100%) rename {vendor => third_party}/pygments/pygmentize (100%) rename {vendor => third_party}/pygments/pygments/__init__.py (100%) rename {vendor => third_party}/pygments/pygments/cmdline.py (100%) rename {vendor => third_party}/pygments/pygments/console.py (100%) rename {vendor => third_party}/pygments/pygments/filter.py (100%) rename {vendor => third_party}/pygments/pygments/filters/__init__.py (100%) rename {vendor => third_party}/pygments/pygments/formatter.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/__init__.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/_mapping.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/bbcode.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/html.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/img.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/irc.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/latex.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/other.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/rtf.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/svg.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/terminal.py (100%) rename {vendor => third_party}/pygments/pygments/formatters/terminal256.py (100%) rename {vendor => third_party}/pygments/pygments/lexer.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/__init__.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_asy_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_cl_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_cocoa_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_csound_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_lasso_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_lua_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_mapping.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_mql_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_openedge_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_php_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_postgres_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_scilab_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_sourcemod_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_stan_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/_vim_builtins.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/actionscript.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/agile.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/algebra.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/ambient.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/apl.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/archetype.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/asm.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/automation.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/basic.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/business.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/c_cpp.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/c_like.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/chapel.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/compiled.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/configs.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/console.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/csound.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/css.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/d.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/dalvik.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/data.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/diff.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/dotnet.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/dsls.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/dylan.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/ecl.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/eiffel.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/elm.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/erlang.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/esoteric.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/ezhil.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/factor.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/fantom.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/felix.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/fortran.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/foxpro.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/functional.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/go.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/grammar_notation.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/graph.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/graphics.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/haskell.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/haxe.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/hdl.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/hexdump.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/html.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/idl.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/igor.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/inferno.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/installers.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/int_fiction.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/iolang.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/j.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/javascript.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/julia.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/jvm.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/lisp.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/make.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/markup.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/math.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/matlab.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/ml.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/modeling.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/modula2.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/nimrod.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/nit.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/nix.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/oberon.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/objective.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/ooc.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/other.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/parasail.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/parsers.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/pascal.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/pawn.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/perl.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/php.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/praat.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/prolog.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/python.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/qvt.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/r.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/rdf.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/rebol.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/resource.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/roboconf.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/robotframework.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/ruby.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/rust.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/scripting.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/shell.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/smalltalk.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/snobol.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/special.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/sql.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/supercollider.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/tcl.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/templates.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/testing.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/text.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/textedit.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/textfmts.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/theorem.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/trafficscript.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/urbi.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/web.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/webmisc.py (100%) rename {vendor => third_party}/pygments/pygments/lexers/x10.py (100%) rename {vendor => third_party}/pygments/pygments/modeline.py (100%) rename {vendor => third_party}/pygments/pygments/plugin.py (100%) rename {vendor => third_party}/pygments/pygments/regexopt.py (100%) rename {vendor => third_party}/pygments/pygments/scanner.py (100%) rename {vendor => third_party}/pygments/pygments/sphinxext.py (100%) rename {vendor => third_party}/pygments/pygments/style.py (100%) rename {vendor => third_party}/pygments/pygments/styles/__init__.py (100%) rename {vendor => third_party}/pygments/pygments/styles/algol.py (100%) rename {vendor => third_party}/pygments/pygments/styles/algol_nu.py (100%) rename {vendor => third_party}/pygments/pygments/styles/arduino.py (100%) rename {vendor => third_party}/pygments/pygments/styles/autumn.py (100%) rename {vendor => third_party}/pygments/pygments/styles/borland.py (100%) rename {vendor => third_party}/pygments/pygments/styles/bw.py (100%) rename {vendor => third_party}/pygments/pygments/styles/colorful.py (100%) rename {vendor => third_party}/pygments/pygments/styles/default.py (100%) rename {vendor => third_party}/pygments/pygments/styles/emacs.py (100%) rename {vendor => third_party}/pygments/pygments/styles/friendly.py (100%) rename {vendor => third_party}/pygments/pygments/styles/fruity.py (100%) rename {vendor => third_party}/pygments/pygments/styles/igor.py (100%) rename {vendor => third_party}/pygments/pygments/styles/lovelace.py (100%) rename {vendor => third_party}/pygments/pygments/styles/manni.py (100%) rename {vendor => third_party}/pygments/pygments/styles/monokai.py (100%) rename {vendor => third_party}/pygments/pygments/styles/murphy.py (100%) rename {vendor => third_party}/pygments/pygments/styles/native.py (100%) rename {vendor => third_party}/pygments/pygments/styles/paraiso_dark.py (100%) rename {vendor => third_party}/pygments/pygments/styles/paraiso_light.py (100%) rename {vendor => third_party}/pygments/pygments/styles/pastie.py (100%) rename {vendor => third_party}/pygments/pygments/styles/perldoc.py (100%) rename {vendor => third_party}/pygments/pygments/styles/rrt.py (100%) rename {vendor => third_party}/pygments/pygments/styles/tango.py (100%) rename {vendor => third_party}/pygments/pygments/styles/trac.py (100%) rename {vendor => third_party}/pygments/pygments/styles/vim.py (100%) rename {vendor => third_party}/pygments/pygments/styles/vs.py (100%) rename {vendor => third_party}/pygments/pygments/styles/xcode.py (100%) rename {vendor => third_party}/pygments/pygments/token.py (100%) rename {vendor => third_party}/pygments/pygments/unistring.py (100%) rename {vendor => third_party}/pygments/pygments/util.py (100%) rename {vendor => third_party}/pygments/requirements.txt (100%) rename {vendor => third_party}/pygments/scripts/check_sources.py (100%) rename {vendor => third_party}/pygments/scripts/debug_lexer.py (100%) rename {vendor => third_party}/pygments/scripts/detect_missing_analyse_text.py (100%) rename {vendor => third_party}/pygments/scripts/epydoc.css (100%) rename {vendor => third_party}/pygments/scripts/find_error.py (100%) rename {vendor => third_party}/pygments/scripts/get_vimkw.py (100%) rename {vendor => third_party}/pygments/scripts/pylintrc (100%) rename {vendor => third_party}/pygments/scripts/vim2pygments.py (100%) rename {vendor => third_party}/pygments/setup.cfg (100%) rename {vendor => third_party}/pygments/setup.py (100%) rename {vendor => third_party}/pygments/tests/.coverage (100%) rename {vendor => third_party}/pygments/tests/cover/coverage_html.js (100%) rename {vendor => third_party}/pygments/tests/cover/jquery.hotkeys.js (100%) rename {vendor => third_party}/pygments/tests/cover/jquery.isonscreen.js (100%) rename {vendor => third_party}/pygments/tests/cover/jquery.min.js (100%) rename {vendor => third_party}/pygments/tests/cover/jquery.tablesorter.min.js (100%) rename {vendor => third_party}/pygments/tests/cover/keybd_closed.png (100%) rename {vendor => third_party}/pygments/tests/cover/keybd_open.png (100%) rename {vendor => third_party}/pygments/tests/cover/status.dat (100%) rename {vendor => third_party}/pygments/tests/cover/style.css (100%) rename {vendor => third_party}/pygments/tests/dtds/HTML4-f.dtd (100%) rename {vendor => third_party}/pygments/tests/dtds/HTML4-s.dtd (100%) rename {vendor => third_party}/pygments/tests/dtds/HTML4.dcl (100%) rename {vendor => third_party}/pygments/tests/dtds/HTML4.dtd (100%) rename {vendor => third_party}/pygments/tests/dtds/HTML4.soc (100%) rename {vendor => third_party}/pygments/tests/dtds/HTMLlat1.ent (100%) rename {vendor => third_party}/pygments/tests/dtds/HTMLspec.ent (100%) rename {vendor => third_party}/pygments/tests/dtds/HTMLsym.ent (100%) rename {vendor => third_party}/pygments/tests/examplefiles/99_bottles_of_beer.chpl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/AcidStateAdvanced.hs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/AlternatingGroup.mu (100%) rename {vendor => third_party}/pygments/tests/examplefiles/BOM.js (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Blink.ino (100%) rename {vendor => third_party}/pygments/tests/examplefiles/CPDictionary.j (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Config.in.cache (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Constants.mo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/DancingSudoku.lhs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Deflate.fs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Error.pmod (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Errors.scala (100%) rename {vendor => third_party}/pygments/tests/examplefiles/FakeFile.pike (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Get-CommandDefinitionHtml.ps1 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/IPDispatchC.nc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/IPDispatchP.nc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Intro.java (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Makefile (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Object.st (100%) rename {vendor => third_party}/pygments/tests/examplefiles/OrderedMap.hx (100%) rename {vendor => third_party}/pygments/tests/examplefiles/RoleQ.pm6 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/SmallCheck.hs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Sorting.mod (100%) rename {vendor => third_party}/pygments/tests/examplefiles/Sudoku.lhs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/abnf_example1.abnf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/abnf_example2.abnf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/addressbook.proto (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ahcon.f (100%) rename {vendor => third_party}/pygments/tests/examplefiles/all.nit (100%) rename {vendor => third_party}/pygments/tests/examplefiles/antlr_ANTLRv3.g (100%) rename {vendor => third_party}/pygments/tests/examplefiles/antlr_throws (100%) rename {vendor => third_party}/pygments/tests/examplefiles/apache2.conf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/as3_test.as (100%) rename {vendor => third_party}/pygments/tests/examplefiles/as3_test2.as (100%) rename {vendor => third_party}/pygments/tests/examplefiles/as3_test3.as (100%) rename {vendor => third_party}/pygments/tests/examplefiles/aspx-cs_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/autoit_submit.au3 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/automake.mk (100%) rename {vendor => third_party}/pygments/tests/examplefiles/badcase.java (100%) rename {vendor => third_party}/pygments/tests/examplefiles/bigtest.nsi (100%) rename {vendor => third_party}/pygments/tests/examplefiles/bnf_example1.bnf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/boot-9.scm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ca65_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/cbmbas_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/cells.ps (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ceval.c (100%) rename {vendor => third_party}/pygments/tests/examplefiles/char.scala (100%) rename {vendor => third_party}/pygments/tests/examplefiles/cheetah_example.html (100%) rename {vendor => third_party}/pygments/tests/examplefiles/classes.dylan (100%) rename {vendor => third_party}/pygments/tests/examplefiles/clojure-weird-keywords.clj (100%) rename {vendor => third_party}/pygments/tests/examplefiles/condensed_ruby.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/coq_RelationClasses (100%) rename {vendor => third_party}/pygments/tests/examplefiles/core.cljs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/database.pytb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/de.MoinMoin.po (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.ahk (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.cfm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.css.in (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.hbs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.js.in (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.thrift (100%) rename {vendor => third_party}/pygments/tests/examplefiles/demo.xul.in (100%) rename {vendor => third_party}/pygments/tests/examplefiles/django_sample.html+django (100%) rename {vendor => third_party}/pygments/tests/examplefiles/docker.docker (100%) rename {vendor => third_party}/pygments/tests/examplefiles/dwarf.cw (100%) rename {vendor => third_party}/pygments/tests/examplefiles/eg_example1.eg (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ember.handlebars (100%) rename {vendor => third_party}/pygments/tests/examplefiles/erl_session (100%) rename {vendor => third_party}/pygments/tests/examplefiles/es6.js (100%) rename {vendor => third_party}/pygments/tests/examplefiles/escape_semicolon.clj (100%) rename {vendor => third_party}/pygments/tests/examplefiles/eval.rs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/evil_regex.js (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.Rd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.als (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.bat (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.bc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.bug (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.c (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ceylon (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.chai (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.clay (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.cls (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.cob (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.coffee (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.cpp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.e (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.elm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ezt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.f90 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.feature (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.fish (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.gd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.gi (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.golo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.groovy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.gs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.gst (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.hs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.hx (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.i6t (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.i7x (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.j (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.jag (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.java (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.jcl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.jsonld (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.kal (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.kt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.lagda (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.liquid (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.lua (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ma (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.mac (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.monkey (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.moo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.moon (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.mq4 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.mqh (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.msc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ni (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.nim (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.nix (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ns2 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.pas (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.pcmk (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.pp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.praat (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.prg (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.red (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.reds (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.reg (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.rexx (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.rhtml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.rkt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.rpf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.rts (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.scd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.sh (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.sh-session (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.shell-session (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.slim (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.sls (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.sml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.snobol (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.stan (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.tap (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.tea (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.tf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.thy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.todotxt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ts (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.ttl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.u (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.weechatlog (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.x10 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.xhtml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.xtend (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example.yaml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example1.cadl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example2.aspx (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example2.msc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/exampleScript.cfc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/exampleTag.cfc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example_coq.v (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example_elixir.ex (100%) rename {vendor => third_party}/pygments/tests/examplefiles/example_file.fy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ezhil_primefactors.n (100%) rename {vendor => third_party}/pygments/tests/examplefiles/firefox.mak (100%) rename {vendor => third_party}/pygments/tests/examplefiles/flipflop.sv (100%) rename {vendor => third_party}/pygments/tests/examplefiles/foo.sce (100%) rename {vendor => third_party}/pygments/tests/examplefiles/format.ml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/fucked_up.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/function.mu (100%) rename {vendor => third_party}/pygments/tests/examplefiles/functional.rst (100%) rename {vendor => third_party}/pygments/tests/examplefiles/garcia-wachs.kk (100%) rename {vendor => third_party}/pygments/tests/examplefiles/genclass.clj (100%) rename {vendor => third_party}/pygments/tests/examplefiles/genshi_example.xml+genshi (100%) rename {vendor => third_party}/pygments/tests/examplefiles/genshitext_example.genshitext (100%) rename {vendor => third_party}/pygments/tests/examplefiles/glsl.frag (100%) rename {vendor => third_party}/pygments/tests/examplefiles/glsl.vert (100%) rename {vendor => third_party}/pygments/tests/examplefiles/grammar-test.p6 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hash_syntax.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hello.at (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hello.golo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hello.lsl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hello.smali (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hello.sp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hexdump_debugexe (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hexdump_hd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hexdump_hexcat (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hexdump_hexdump (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hexdump_od (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hexdump_xxd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/html+php_faulty.php (100%) rename {vendor => third_party}/pygments/tests/examplefiles/http_request_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/http_response_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/hybris_File.hy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/idl_sample.pro (100%) rename {vendor => third_party}/pygments/tests/examplefiles/iex_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/inet_pton6.dg (100%) rename {vendor => third_party}/pygments/tests/examplefiles/inform6_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/interp.scala (100%) rename {vendor => third_party}/pygments/tests/examplefiles/intro.ik (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ints.php (100%) rename {vendor => third_party}/pygments/tests/examplefiles/intsyn.fun (100%) rename {vendor => third_party}/pygments/tests/examplefiles/intsyn.sig (100%) rename {vendor => third_party}/pygments/tests/examplefiles/irb_heredoc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/irc.lsp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/java.properties (100%) rename {vendor => third_party}/pygments/tests/examplefiles/jbst_example1.jbst (100%) rename {vendor => third_party}/pygments/tests/examplefiles/jbst_example2.jbst (100%) rename {vendor => third_party}/pygments/tests/examplefiles/jinjadesignerdoc.rst (100%) rename {vendor => third_party}/pygments/tests/examplefiles/json.lasso (100%) rename {vendor => third_party}/pygments/tests/examplefiles/json.lasso9 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/language.hy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/lighttpd_config.conf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/limbo.b (100%) rename {vendor => third_party}/pygments/tests/examplefiles/linecontinuation.py (100%) rename {vendor => third_party}/pygments/tests/examplefiles/livescript-demo.ls (100%) rename {vendor => third_party}/pygments/tests/examplefiles/logos_example.xm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ltmain.sh (100%) rename {vendor => third_party}/pygments/tests/examplefiles/main.cmake (100%) rename {vendor => third_party}/pygments/tests/examplefiles/markdown.lsp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/matlab_noreturn (100%) rename {vendor => third_party}/pygments/tests/examplefiles/matlab_sample (100%) rename {vendor => third_party}/pygments/tests/examplefiles/matlabsession_sample.txt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/metagrammar.treetop (100%) rename {vendor => third_party}/pygments/tests/examplefiles/minehunt.qml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/minimal.ns2 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/modula2_test_cases.def (100%) rename {vendor => third_party}/pygments/tests/examplefiles/moin_SyntaxReference.txt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/multiline_regexes.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/nanomsg.intr (100%) rename {vendor => third_party}/pygments/tests/examplefiles/nasm_aoutso.asm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/nasm_objexe.asm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/nemerle_sample.n (100%) rename {vendor => third_party}/pygments/tests/examplefiles/nginx_nginx.conf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/noexcept.cpp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/numbers.c (100%) rename {vendor => third_party}/pygments/tests/examplefiles/objc_example.m (100%) rename {vendor => third_party}/pygments/tests/examplefiles/openedge_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pacman.conf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pacman.ijs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pawn_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/perl_misc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/perl_perl5db (100%) rename {vendor => third_party}/pygments/tests/examplefiles/perl_regex-delims (100%) rename {vendor => third_party}/pygments/tests/examplefiles/perlfunc.1 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/phpMyAdmin.spec (100%) rename {vendor => third_party}/pygments/tests/examplefiles/phpcomplete.vim (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pkgconfig_example.pc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pleac.in.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/postgresql_test.txt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pppoe.applescript (100%) rename {vendor => third_party}/pygments/tests/examplefiles/psql_session.txt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/py3_test.txt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/py3tb_test.py3tb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pycon_ctrlc_traceback (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pycon_test.pycon (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pytb_test2.pytb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/pytb_test3.pytb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/python25-bsd.mak (100%) rename {vendor => third_party}/pygments/tests/examplefiles/qbasic_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/qsort.prolog (100%) rename {vendor => third_party}/pygments/tests/examplefiles/r-console-transcript.Rout (100%) rename {vendor => third_party}/pygments/tests/examplefiles/r6rs-comments.scm (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ragel-cpp_rlscan (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ragel-cpp_snippet (100%) rename {vendor => third_party}/pygments/tests/examplefiles/regex.js (100%) rename {vendor => third_party}/pygments/tests/examplefiles/resourcebundle_demo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/reversi.lsp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/roboconf.graph (100%) rename {vendor => third_party}/pygments/tests/examplefiles/roboconf.instances (100%) rename {vendor => third_party}/pygments/tests/examplefiles/robotframework_test.txt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/rql-queries.rql (100%) rename {vendor => third_party}/pygments/tests/examplefiles/ruby_func_def.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/sample.qvto (100%) rename {vendor => third_party}/pygments/tests/examplefiles/scilab.sci (100%) rename {vendor => third_party}/pygments/tests/examplefiles/scope.cirru (100%) rename {vendor => third_party}/pygments/tests/examplefiles/session.dylan-console (100%) rename {vendor => third_party}/pygments/tests/examplefiles/sibling.prolog (100%) rename {vendor => third_party}/pygments/tests/examplefiles/simple.camkes (100%) rename {vendor => third_party}/pygments/tests/examplefiles/simple.croc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/smarty_example.html (100%) rename {vendor => third_party}/pygments/tests/examplefiles/source.lgt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/sources.list (100%) rename {vendor => third_party}/pygments/tests/examplefiles/sparql.rq (100%) rename {vendor => third_party}/pygments/tests/examplefiles/sphere.pov (100%) rename {vendor => third_party}/pygments/tests/examplefiles/sqlite3.sqlite3-console (100%) rename {vendor => third_party}/pygments/tests/examplefiles/squid.conf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/string.jl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/string_delimiters.d (100%) rename {vendor => third_party}/pygments/tests/examplefiles/stripheredoc.sh (100%) rename {vendor => third_party}/pygments/tests/examplefiles/subr.el (100%) rename {vendor => third_party}/pygments/tests/examplefiles/swig_java.swg (100%) rename {vendor => third_party}/pygments/tests/examplefiles/swig_std_vector.i (100%) rename {vendor => third_party}/pygments/tests/examplefiles/tads3_example.t (100%) rename {vendor => third_party}/pygments/tests/examplefiles/termcap (100%) rename {vendor => third_party}/pygments/tests/examplefiles/terminfo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test-3.0.xq (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test-exist-update.xq (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.R (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.adb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.adls (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.agda (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.apl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.asy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.awk (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.bb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.bmx (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.boo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.bpl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.bro (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.cadl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.cs (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.csd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.css (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.cu (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.cyp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.d (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.dart (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.dtd (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.ebnf (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.ec (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.eh (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.erl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.evoque (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.fan (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.flx (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.gdc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.gradle (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.groovy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.html (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.idr (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.ini (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.java (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.jsp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.lean (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.maql (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.mask (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.mod (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.moo (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.myt (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.nim (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.odin (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.opa (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.orc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.p6 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.pan (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.pas (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.php (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.pig (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.plot (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.ps1 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.psl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.pwn (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.pypylog (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.r3 (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.rb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.rhtml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.rsl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.scaml (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.sco (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.shen (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.ssp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.swift (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.tcsh (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.vb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.vhdl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.xqy (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.xsl (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test.zep (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test2.odin (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test2.pypylog (100%) rename {vendor => third_party}/pygments/tests/examplefiles/test_basic.adls (100%) rename {vendor => third_party}/pygments/tests/examplefiles/truncated.pytb (100%) rename {vendor => third_party}/pygments/tests/examplefiles/twig_test (100%) rename {vendor => third_party}/pygments/tests/examplefiles/type.lisp (100%) rename {vendor => third_party}/pygments/tests/examplefiles/underscore.coffee (100%) rename {vendor => third_party}/pygments/tests/examplefiles/unicode.applescript (100%) rename {vendor => third_party}/pygments/tests/examplefiles/unicode.go (100%) rename {vendor => third_party}/pygments/tests/examplefiles/unicode.js (100%) rename {vendor => third_party}/pygments/tests/examplefiles/unicodedoc.py (100%) rename {vendor => third_party}/pygments/tests/examplefiles/unix-io.lid (100%) rename {vendor => third_party}/pygments/tests/examplefiles/vbnet_test.bas (100%) rename {vendor => third_party}/pygments/tests/examplefiles/vctreestatus_hg (100%) rename {vendor => third_party}/pygments/tests/examplefiles/vimrc (100%) rename {vendor => third_party}/pygments/tests/examplefiles/vpath.mk (100%) rename {vendor => third_party}/pygments/tests/examplefiles/webkit-transition.css (100%) rename {vendor => third_party}/pygments/tests/examplefiles/while.pov (100%) rename {vendor => third_party}/pygments/tests/examplefiles/wiki.factor (100%) rename {vendor => third_party}/pygments/tests/examplefiles/xml_example (100%) rename {vendor => third_party}/pygments/tests/examplefiles/yahalom.cpsa (100%) rename {vendor => third_party}/pygments/tests/examplefiles/zmlrpc.f90 (100%) rename {vendor => third_party}/pygments/tests/run.py (100%) rename {vendor => third_party}/pygments/tests/string_asserts.py (100%) rename {vendor => third_party}/pygments/tests/support.py (100%) rename {vendor => third_party}/pygments/tests/support/tags (100%) rename {vendor => third_party}/pygments/tests/test_basic_api.py (100%) rename {vendor => third_party}/pygments/tests/test_cfm.py (100%) rename {vendor => third_party}/pygments/tests/test_clexer.py (100%) rename {vendor => third_party}/pygments/tests/test_cmdline.py (100%) rename {vendor => third_party}/pygments/tests/test_examplefiles.py (100%) rename {vendor => third_party}/pygments/tests/test_ezhil.py (100%) rename {vendor => third_party}/pygments/tests/test_html_formatter.py (100%) rename {vendor => third_party}/pygments/tests/test_inherit.py (100%) rename {vendor => third_party}/pygments/tests/test_irc_formatter.py (100%) rename {vendor => third_party}/pygments/tests/test_java.py (100%) rename {vendor => third_party}/pygments/tests/test_latex_formatter.py (100%) rename {vendor => third_party}/pygments/tests/test_lexers_other.py (100%) rename {vendor => third_party}/pygments/tests/test_objectiveclexer.py (100%) rename {vendor => third_party}/pygments/tests/test_perllexer.py (100%) rename {vendor => third_party}/pygments/tests/test_qbasiclexer.py (100%) rename {vendor => third_party}/pygments/tests/test_regexlexer.py (100%) rename {vendor => third_party}/pygments/tests/test_regexopt.py (100%) rename {vendor => third_party}/pygments/tests/test_rtf_formatter.py (100%) rename {vendor => third_party}/pygments/tests/test_ruby.py (100%) rename {vendor => third_party}/pygments/tests/test_shell.py (100%) rename {vendor => third_party}/pygments/tests/test_smarty.py (100%) rename {vendor => third_party}/pygments/tests/test_string_asserts.py (100%) rename {vendor => third_party}/pygments/tests/test_terminal_formatter.py (100%) rename {vendor => third_party}/pygments/tests/test_textfmts.py (100%) rename {vendor => third_party}/pygments/tests/test_token.py (100%) rename {vendor => third_party}/pygments/tests/test_unistring.py (100%) rename {vendor => third_party}/pygments/tests/test_using_api.py (100%) rename {vendor => third_party}/pygments/tests/test_util.py (100%) rename {vendor => third_party}/pygments/tox.ini (100%) create mode 100644 vendor/github.com/russross/blackfriday/.gitignore create mode 100644 vendor/github.com/russross/blackfriday/.travis.yml create mode 100644 vendor/github.com/russross/blackfriday/LICENSE.txt create mode 100644 vendor/github.com/russross/blackfriday/README.md create mode 100644 vendor/github.com/russross/blackfriday/block.go create mode 100644 vendor/github.com/russross/blackfriday/doc.go create mode 100644 vendor/github.com/russross/blackfriday/go.mod create mode 100644 vendor/github.com/russross/blackfriday/html.go create mode 100644 vendor/github.com/russross/blackfriday/inline.go create mode 100644 vendor/github.com/russross/blackfriday/latex.go create mode 100644 vendor/github.com/russross/blackfriday/markdown.go create mode 100644 vendor/github.com/russross/blackfriday/smartypants.go create mode 100644 vendor/modules.txt diff --git a/README.md b/README.md index a990d285b..cf2046703 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ comments from source files in `examples` and rendering them via the `templates` into a static `public` directory. The programs implementing this build process are in `tools`, along with some vendor'd dependencies -in `vendor`. +in `vendor` and `third_party`. The built `public` directory can be served by any static content system. The production site uses S3 and diff --git a/go.mod b/go.mod new file mode 100644 index 000000000..83e76765b --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/mmcgrana/gobyexample + +go 1.15 + +require github.com/russross/blackfriday v1.6.0 diff --git a/go.sum b/go.sum new file mode 100644 index 000000000..270cecfc7 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/russross/blackfriday v1.6.0 h1:KqfZb0pUVN2lYqZUYRddxF4OR8ZMURnJIG5Y3VRLtww= +github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= diff --git a/public/arrays b/public/arrays index 0a6010586..7c116e7e8 100644 --- a/public/arrays +++ b/public/arrays @@ -206,7 +206,7 @@ typical Go. We’ll look at slices next.

    diff --git a/public/atomic-counters b/public/atomic-counters index a6fef3537..b70cbc733 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -236,7 +236,7 @@ state.

    diff --git a/public/base64-encoding b/public/base64-encoding index 74ffc9ae7..9b2150b23 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -191,7 +191,7 @@ but they both decode to the original string as desired.

    diff --git a/public/channel-buffering b/public/channel-buffering index 0bea69d36..fe8793bb8 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -153,7 +153,7 @@ concurrent receive.

    diff --git a/public/channel-directions b/public/channel-directions index 2814e819a..763ec5bde 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -145,7 +145,7 @@ receive on this channel.

    diff --git a/public/channel-synchronization b/public/channel-synchronization index 804f06cfa..362b4300d 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -184,7 +184,7 @@ started.

    diff --git a/public/channels b/public/channels index c3f4a4a70..cde4702ce 100644 --- a/public/channels +++ b/public/channels @@ -168,7 +168,7 @@ message without having to use any other synchronization.

    diff --git a/public/closing-channels b/public/closing-channels index cba25386e..b1b5c677f 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -194,7 +194,7 @@ example: range over channels.

    diff --git a/public/closures b/public/closures index 3ef94eec0..acb435989 100644 --- a/public/closures +++ b/public/closures @@ -190,7 +190,7 @@ recursion.

    diff --git a/public/collection-functions b/public/collection-functions index 6d7db8c6c..00890c065 100644 --- a/public/collection-functions +++ b/public/collection-functions @@ -371,7 +371,7 @@ type.

    diff --git a/public/command-line-arguments b/public/command-line-arguments index a3f61e4ff..6c2251c00 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -170,7 +170,7 @@ with flags.

    diff --git a/public/command-line-flags b/public/command-line-flags index b30884473..ed2b9a9e1 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -310,7 +310,7 @@ and show the help text again.

    diff --git a/public/command-line-subcommands b/public/command-line-subcommands index 60e99281e..d226e51e8 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -263,7 +263,7 @@ way to parameterize programs.

    diff --git a/public/constants b/public/constants index 737bfc05c..8e80c8c09 100644 --- a/public/constants +++ b/public/constants @@ -183,7 +183,7 @@ assignment or function call. For example, here diff --git a/public/context b/public/context index d808591c8..603241980 100644 --- a/public/context +++ b/public/context @@ -205,7 +205,7 @@ cancellation.

    diff --git a/public/defer b/public/defer index b15ef1e94..328f752ee 100644 --- a/public/defer +++ b/public/defer @@ -212,7 +212,7 @@ after being written.

    diff --git a/public/directories b/public/directories index 0d7d9f5c2..19a325dc7 100644 --- a/public/directories +++ b/public/directories @@ -353,7 +353,7 @@ recursively by filepath.Walk.

    diff --git a/public/environment-variables b/public/environment-variables index 65b18c90e..6015252f2 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -186,7 +186,7 @@ program picks that value up.

    diff --git a/public/epoch b/public/epoch index 192c24c58..5ad5cebdc 100644 --- a/public/epoch +++ b/public/epoch @@ -177,7 +177,7 @@ parsing and formatting.

    diff --git a/public/errors b/public/errors index be57978b8..8dce6801e 100644 --- a/public/errors +++ b/public/errors @@ -299,7 +299,7 @@ on the Go blog for more on error handling.

    diff --git a/public/execing-processes b/public/execing-processes index 687da4a79..cfa31cfad 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -203,7 +203,7 @@ processes covers most use cases for fork.

    diff --git a/public/file-paths b/public/file-paths index 1e5e2046e..6c1e6f69f 100644 --- a/public/file-paths +++ b/public/file-paths @@ -250,7 +250,7 @@ be made relative to base.

    diff --git a/public/for b/public/for index e7b756bec..c5273e9ae 100644 --- a/public/for +++ b/public/for @@ -195,7 +195,7 @@ structures.

    diff --git a/public/functions b/public/functions index 2747daa7a..6fd4d8931 100644 --- a/public/functions +++ b/public/functions @@ -193,7 +193,7 @@ multiple return values, which we’ll look at next.

    diff --git a/public/goroutines b/public/goroutines index 0defc4cb5..2ebd5dcdf 100644 --- a/public/goroutines +++ b/public/goroutines @@ -207,7 +207,7 @@ concurrent Go programs: channels.

    diff --git a/public/http-clients b/public/http-clients index d3c773d35..e7dc06896 100644 --- a/public/http-clients +++ b/public/http-clients @@ -169,7 +169,7 @@ settings.

    diff --git a/public/http-servers b/public/http-servers index 72b4ef0f0..797f74e65 100644 --- a/public/http-servers +++ b/public/http-servers @@ -210,7 +210,7 @@ router we’ve just set up.

    diff --git a/public/if-else b/public/if-else index b599e0926..b684ea3ef 100644 --- a/public/if-else +++ b/public/if-else @@ -184,7 +184,7 @@ for basic conditions.

    diff --git a/public/index.html b/public/index.html index 470a699c2..a135d10b1 100644 --- a/public/index.html +++ b/public/index.html @@ -12,6 +12,10 @@

    Go by Example

    Go is an open source programming language designed for building simple, fast, and reliable software. + Please read the official + documentation + to learn a bit about Go code, tools packages, + and modules.

    diff --git a/public/interfaces b/public/interfaces index baf76af3f..ff1626f29 100644 --- a/public/interfaces +++ b/public/interfaces @@ -236,7 +236,7 @@ these structs as arguments to measure.

    diff --git a/public/json b/public/json index b39d5129f..ac13e5ee9 100644 --- a/public/json +++ b/public/json @@ -416,7 +416,7 @@ for more.

    diff --git a/public/line-filters b/public/line-filters index d7e5fea49..34f8e9a20 100644 --- a/public/line-filters +++ b/public/line-filters @@ -204,7 +204,7 @@ lowercase lines.

    diff --git a/public/maps b/public/maps index c3bb8822f..25cd47fe6 100644 --- a/public/maps +++ b/public/maps @@ -232,7 +232,7 @@ printed with fmt.Println.

    diff --git a/public/methods b/public/methods index b8e0a5888..44c275b4a 100644 --- a/public/methods +++ b/public/methods @@ -197,7 +197,7 @@ naming related sets of methods: interfaces.

    diff --git a/public/multiple-return-values b/public/multiple-return-values index fa3ca351d..08ab6eb19 100644 --- a/public/multiple-return-values +++ b/public/multiple-return-values @@ -166,7 +166,7 @@ feature of Go functions; we’ll look at this next.

    diff --git a/public/mutexes b/public/mutexes index 94208eb5e..e97f94b4e 100644 --- a/public/mutexes +++ b/public/mutexes @@ -297,7 +297,7 @@ management task using only goroutines and channels.

    diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations index ea30fd122..a874f0317 100644 --- a/public/non-blocking-channel-operations +++ b/public/non-blocking-channel-operations @@ -176,7 +176,7 @@ on both messages and signals.

    diff --git a/public/number-parsing b/public/number-parsing index e222bc792..798acfd35 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -213,7 +213,7 @@ bits.

    diff --git a/public/panic b/public/panic index 9242fcc43..eb180408e 100644 --- a/public/panic +++ b/public/panic @@ -172,7 +172,7 @@ to use error-indicating return values wherever possible.

    diff --git a/public/pointers b/public/pointers index 62d3a709c..716f4b33d 100644 --- a/public/pointers +++ b/public/pointers @@ -193,7 +193,7 @@ the memory address for that variable.

    diff --git a/public/random-numbers b/public/random-numbers index 39f924615..9bbddb120 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -229,7 +229,7 @@ that Go can provide.

    diff --git a/public/range b/public/range index 81877c9cb..593785d57 100644 --- a/public/range +++ b/public/range @@ -200,7 +200,7 @@ of the rune and the second the rune itself.

    diff --git a/public/range-over-channels b/public/range-over-channels index 6eedb6af4..1a36cc936 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -154,7 +154,7 @@ values be received.

    diff --git a/public/rate-limiting b/public/rate-limiting index 25900dd6f..06a79ff8b 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -261,7 +261,7 @@ then serve the remaining 2 with ~200ms delays each.

    diff --git a/public/reading-files b/public/reading-files index abed995c1..84cd8e4ff 100644 --- a/public/reading-files +++ b/public/reading-files @@ -287,7 +287,7 @@ be scheduled immediately after Opening with diff --git a/public/recursion b/public/recursion index d1125aa3d..ed6a80e5c 100644 --- a/public/recursion +++ b/public/recursion @@ -125,7 +125,7 @@ base case of fact(0).

    diff --git a/public/regular-expressions b/public/regular-expressions index ec3315778..4d0a55288 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -343,7 +343,7 @@ the regexp package docs diff --git a/public/select b/public/select index c92146fa8..9173db90f 100644 --- a/public/select +++ b/public/select @@ -183,7 +183,7 @@ concurrently.

    diff --git a/public/sha1-hashes b/public/sha1-hashes index 82dfb4fc4..59518881d 100644 --- a/public/sha1-hashes +++ b/public/sha1-hashes @@ -203,7 +203,7 @@ you should carefully research diff --git a/public/signals b/public/signals index af1a0018e..3d019dd1b 100644 --- a/public/signals +++ b/public/signals @@ -188,7 +188,7 @@ causing the program to print interrupt and then exit.

    diff --git a/public/slices b/public/slices index 798a0ca4d..053957e47 100644 --- a/public/slices +++ b/public/slices @@ -308,7 +308,7 @@ Go’s other key builtin data structure: maps.

    diff --git a/public/sorting b/public/sorting index e341758ed..6388d9741 100644 --- a/public/sorting +++ b/public/sorting @@ -160,7 +160,7 @@ slices and true as the result of our AreSorted test. diff --git a/public/sorting-by-functions b/public/sorting-by-functions index 4f0f50ea2..bcac96623 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -177,7 +177,7 @@ functions.

    diff --git a/public/spawning-processes b/public/spawning-processes index 568b7f212..66ed6380b 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -259,7 +259,7 @@ as if we had run them directly from the command-line.

    diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 88182c584..5799242b7 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -312,7 +312,7 @@ program.

    diff --git a/public/string-formatting b/public/string-formatting index 5c1f5741c..fb1c0eb5a 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -457,7 +457,7 @@ and returns a string without printing it anywhere.

    diff --git a/public/string-functions b/public/string-functions index f4869763d..3674107ae 100644 --- a/public/string-functions +++ b/public/string-functions @@ -209,7 +209,7 @@ for more information.

    diff --git a/public/structs b/public/structs index 552be5a30..93495d062 100644 --- a/public/structs +++ b/public/structs @@ -266,7 +266,7 @@ pointers are automatically dereferenced.

    diff --git a/public/switch b/public/switch index 3cf0fc607..8893bfc2f 100644 --- a/public/switch +++ b/public/switch @@ -203,7 +203,7 @@ type corresponding to its clause.

    diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 1110be081..881042c67 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -242,7 +242,7 @@ prefixing them with our temporary directory.

    diff --git a/public/testing b/public/testing index 673e027a1..1e18c07b1 100644 --- a/public/testing +++ b/public/testing @@ -231,7 +231,7 @@ when executing go test -v.

    diff --git a/public/tickers b/public/tickers index aa0fac7dd..e890ce490 100644 --- a/public/tickers +++ b/public/tickers @@ -171,7 +171,7 @@ before we stop it.

    diff --git a/public/time b/public/time index 246ffa8b3..b22da8c66 100644 --- a/public/time +++ b/public/time @@ -270,7 +270,7 @@ the Unix epoch.

    diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index 6e7fbcb70..18fe74d31 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -204,7 +204,7 @@ explaining the parsing problem.

    diff --git a/public/timeouts b/public/timeouts index b4d14e78b..8adcac27d 100644 --- a/public/timeouts +++ b/public/timeouts @@ -181,7 +181,7 @@ out and the second succeeding.

    diff --git a/public/timers b/public/timers index 4e7536838..090da3a3d 100644 --- a/public/timers +++ b/public/timers @@ -184,7 +184,7 @@ a chance to fire.

    diff --git a/public/url-parsing b/public/url-parsing index cb70ac77b..4df2e8a67 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -235,7 +235,7 @@ pieces that we extracted.

    diff --git a/public/values b/public/values index aee60a22a..dc3afc257 100644 --- a/public/values +++ b/public/values @@ -152,7 +152,7 @@ basic examples.

    diff --git a/public/variables b/public/variables index 312b5e59e..8f4b72fc8 100644 --- a/public/variables +++ b/public/variables @@ -183,7 +183,7 @@ initializing a variable, e.g. for diff --git a/public/variadic-functions b/public/variadic-functions index 0ce77f5d3..97e6c65c9 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -172,7 +172,7 @@ to form closures, which we’ll look at next.

    diff --git a/public/waitgroups b/public/waitgroups index 85856cee7..cb6b3dc21 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -229,7 +229,7 @@ is likely to be different for each invocation.

    diff --git a/public/worker-pools b/public/worker-pools index e7fec3230..7372dc027 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -224,7 +224,7 @@ there are 3 workers operating concurrently.

    diff --git a/public/writing-files b/public/writing-files index 751a9e873..fc2377092 100644 --- a/public/writing-files +++ b/public/writing-files @@ -289,7 +289,7 @@ we’ve just seen to the stdin and stdout streams. diff --git a/public/xml b/public/xml index 4c7e04815..337d722ec 100644 --- a/public/xml +++ b/public/xml @@ -281,7 +281,7 @@ to nest all plants under <parent><child>... diff --git a/vendor/pygments/.hgignore b/third_party/pygments/.hgignore similarity index 100% rename from vendor/pygments/.hgignore rename to third_party/pygments/.hgignore diff --git a/vendor/pygments/.hgtags b/third_party/pygments/.hgtags similarity index 100% rename from vendor/pygments/.hgtags rename to third_party/pygments/.hgtags diff --git a/vendor/pygments/AUTHORS b/third_party/pygments/AUTHORS similarity index 100% rename from vendor/pygments/AUTHORS rename to third_party/pygments/AUTHORS diff --git a/vendor/pygments/CHANGES b/third_party/pygments/CHANGES similarity index 100% rename from vendor/pygments/CHANGES rename to third_party/pygments/CHANGES diff --git a/vendor/pygments/LICENSE b/third_party/pygments/LICENSE similarity index 100% rename from vendor/pygments/LICENSE rename to third_party/pygments/LICENSE diff --git a/vendor/pygments/MANIFEST.in b/third_party/pygments/MANIFEST.in similarity index 100% rename from vendor/pygments/MANIFEST.in rename to third_party/pygments/MANIFEST.in diff --git a/vendor/pygments/Makefile b/third_party/pygments/Makefile similarity index 100% rename from vendor/pygments/Makefile rename to third_party/pygments/Makefile diff --git a/vendor/pygments/PKG-INFO b/third_party/pygments/PKG-INFO similarity index 100% rename from vendor/pygments/PKG-INFO rename to third_party/pygments/PKG-INFO diff --git a/vendor/pygments/Pygments.egg-info/PKG-INFO b/third_party/pygments/Pygments.egg-info/PKG-INFO similarity index 100% rename from vendor/pygments/Pygments.egg-info/PKG-INFO rename to third_party/pygments/Pygments.egg-info/PKG-INFO diff --git a/vendor/pygments/Pygments.egg-info/SOURCES.txt b/third_party/pygments/Pygments.egg-info/SOURCES.txt similarity index 100% rename from vendor/pygments/Pygments.egg-info/SOURCES.txt rename to third_party/pygments/Pygments.egg-info/SOURCES.txt diff --git a/vendor/pygments/Pygments.egg-info/dependency_links.txt b/third_party/pygments/Pygments.egg-info/dependency_links.txt similarity index 100% rename from vendor/pygments/Pygments.egg-info/dependency_links.txt rename to third_party/pygments/Pygments.egg-info/dependency_links.txt diff --git a/vendor/pygments/Pygments.egg-info/entry_points.txt b/third_party/pygments/Pygments.egg-info/entry_points.txt similarity index 100% rename from vendor/pygments/Pygments.egg-info/entry_points.txt rename to third_party/pygments/Pygments.egg-info/entry_points.txt diff --git a/vendor/pygments/Pygments.egg-info/not-zip-safe b/third_party/pygments/Pygments.egg-info/not-zip-safe similarity index 100% rename from vendor/pygments/Pygments.egg-info/not-zip-safe rename to third_party/pygments/Pygments.egg-info/not-zip-safe diff --git a/vendor/pygments/Pygments.egg-info/top_level.txt b/third_party/pygments/Pygments.egg-info/top_level.txt similarity index 100% rename from vendor/pygments/Pygments.egg-info/top_level.txt rename to third_party/pygments/Pygments.egg-info/top_level.txt diff --git a/vendor/pygments/README.rst b/third_party/pygments/README.rst similarity index 100% rename from vendor/pygments/README.rst rename to third_party/pygments/README.rst diff --git a/vendor/pygments/TODO b/third_party/pygments/TODO similarity index 100% rename from vendor/pygments/TODO rename to third_party/pygments/TODO diff --git a/vendor/pygments/doc/Makefile b/third_party/pygments/doc/Makefile similarity index 100% rename from vendor/pygments/doc/Makefile rename to third_party/pygments/doc/Makefile diff --git a/vendor/pygments/doc/_static/favicon.ico b/third_party/pygments/doc/_static/favicon.ico similarity index 100% rename from vendor/pygments/doc/_static/favicon.ico rename to third_party/pygments/doc/_static/favicon.ico diff --git a/vendor/pygments/doc/_static/logo_new.png b/third_party/pygments/doc/_static/logo_new.png similarity index 100% rename from vendor/pygments/doc/_static/logo_new.png rename to third_party/pygments/doc/_static/logo_new.png diff --git a/vendor/pygments/doc/_static/logo_only.png b/third_party/pygments/doc/_static/logo_only.png similarity index 100% rename from vendor/pygments/doc/_static/logo_only.png rename to third_party/pygments/doc/_static/logo_only.png diff --git a/vendor/pygments/doc/_templates/docssidebar.html b/third_party/pygments/doc/_templates/docssidebar.html similarity index 100% rename from vendor/pygments/doc/_templates/docssidebar.html rename to third_party/pygments/doc/_templates/docssidebar.html diff --git a/vendor/pygments/doc/_templates/indexsidebar.html b/third_party/pygments/doc/_templates/indexsidebar.html similarity index 100% rename from vendor/pygments/doc/_templates/indexsidebar.html rename to third_party/pygments/doc/_templates/indexsidebar.html diff --git a/vendor/pygments/doc/_themes/pygments14/layout.html b/third_party/pygments/doc/_themes/pygments14/layout.html similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/layout.html rename to third_party/pygments/doc/_themes/pygments14/layout.html diff --git a/vendor/pygments/doc/_themes/pygments14/static/bodybg.png b/third_party/pygments/doc/_themes/pygments14/static/bodybg.png similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/static/bodybg.png rename to third_party/pygments/doc/_themes/pygments14/static/bodybg.png diff --git a/vendor/pygments/doc/_themes/pygments14/static/docbg.png b/third_party/pygments/doc/_themes/pygments14/static/docbg.png similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/static/docbg.png rename to third_party/pygments/doc/_themes/pygments14/static/docbg.png diff --git a/vendor/pygments/doc/_themes/pygments14/static/listitem.png b/third_party/pygments/doc/_themes/pygments14/static/listitem.png similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/static/listitem.png rename to third_party/pygments/doc/_themes/pygments14/static/listitem.png diff --git a/vendor/pygments/doc/_themes/pygments14/static/logo.png b/third_party/pygments/doc/_themes/pygments14/static/logo.png similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/static/logo.png rename to third_party/pygments/doc/_themes/pygments14/static/logo.png diff --git a/vendor/pygments/doc/_themes/pygments14/static/pocoo.png b/third_party/pygments/doc/_themes/pygments14/static/pocoo.png similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/static/pocoo.png rename to third_party/pygments/doc/_themes/pygments14/static/pocoo.png diff --git a/vendor/pygments/doc/_themes/pygments14/static/pygments14.css_t b/third_party/pygments/doc/_themes/pygments14/static/pygments14.css_t similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/static/pygments14.css_t rename to third_party/pygments/doc/_themes/pygments14/static/pygments14.css_t diff --git a/vendor/pygments/doc/_themes/pygments14/theme.conf b/third_party/pygments/doc/_themes/pygments14/theme.conf similarity index 100% rename from vendor/pygments/doc/_themes/pygments14/theme.conf rename to third_party/pygments/doc/_themes/pygments14/theme.conf diff --git a/vendor/pygments/doc/conf.py b/third_party/pygments/doc/conf.py similarity index 100% rename from vendor/pygments/doc/conf.py rename to third_party/pygments/doc/conf.py diff --git a/vendor/pygments/doc/docs/api.rst b/third_party/pygments/doc/docs/api.rst similarity index 100% rename from vendor/pygments/doc/docs/api.rst rename to third_party/pygments/doc/docs/api.rst diff --git a/vendor/pygments/doc/docs/authors.rst b/third_party/pygments/doc/docs/authors.rst similarity index 100% rename from vendor/pygments/doc/docs/authors.rst rename to third_party/pygments/doc/docs/authors.rst diff --git a/vendor/pygments/doc/docs/changelog.rst b/third_party/pygments/doc/docs/changelog.rst similarity index 100% rename from vendor/pygments/doc/docs/changelog.rst rename to third_party/pygments/doc/docs/changelog.rst diff --git a/vendor/pygments/doc/docs/cmdline.rst b/third_party/pygments/doc/docs/cmdline.rst similarity index 100% rename from vendor/pygments/doc/docs/cmdline.rst rename to third_party/pygments/doc/docs/cmdline.rst diff --git a/vendor/pygments/doc/docs/filterdevelopment.rst b/third_party/pygments/doc/docs/filterdevelopment.rst similarity index 100% rename from vendor/pygments/doc/docs/filterdevelopment.rst rename to third_party/pygments/doc/docs/filterdevelopment.rst diff --git a/vendor/pygments/doc/docs/filters.rst b/third_party/pygments/doc/docs/filters.rst similarity index 100% rename from vendor/pygments/doc/docs/filters.rst rename to third_party/pygments/doc/docs/filters.rst diff --git a/vendor/pygments/doc/docs/formatterdevelopment.rst b/third_party/pygments/doc/docs/formatterdevelopment.rst similarity index 100% rename from vendor/pygments/doc/docs/formatterdevelopment.rst rename to third_party/pygments/doc/docs/formatterdevelopment.rst diff --git a/vendor/pygments/doc/docs/formatters.rst b/third_party/pygments/doc/docs/formatters.rst similarity index 100% rename from vendor/pygments/doc/docs/formatters.rst rename to third_party/pygments/doc/docs/formatters.rst diff --git a/vendor/pygments/doc/docs/index.rst b/third_party/pygments/doc/docs/index.rst similarity index 100% rename from vendor/pygments/doc/docs/index.rst rename to third_party/pygments/doc/docs/index.rst diff --git a/vendor/pygments/doc/docs/integrate.rst b/third_party/pygments/doc/docs/integrate.rst similarity index 100% rename from vendor/pygments/doc/docs/integrate.rst rename to third_party/pygments/doc/docs/integrate.rst diff --git a/vendor/pygments/doc/docs/java.rst b/third_party/pygments/doc/docs/java.rst similarity index 100% rename from vendor/pygments/doc/docs/java.rst rename to third_party/pygments/doc/docs/java.rst diff --git a/vendor/pygments/doc/docs/lexerdevelopment.rst b/third_party/pygments/doc/docs/lexerdevelopment.rst similarity index 100% rename from vendor/pygments/doc/docs/lexerdevelopment.rst rename to third_party/pygments/doc/docs/lexerdevelopment.rst diff --git a/vendor/pygments/doc/docs/lexers.rst b/third_party/pygments/doc/docs/lexers.rst similarity index 100% rename from vendor/pygments/doc/docs/lexers.rst rename to third_party/pygments/doc/docs/lexers.rst diff --git a/vendor/pygments/doc/docs/moinmoin.rst b/third_party/pygments/doc/docs/moinmoin.rst similarity index 100% rename from vendor/pygments/doc/docs/moinmoin.rst rename to third_party/pygments/doc/docs/moinmoin.rst diff --git a/vendor/pygments/doc/docs/plugins.rst b/third_party/pygments/doc/docs/plugins.rst similarity index 100% rename from vendor/pygments/doc/docs/plugins.rst rename to third_party/pygments/doc/docs/plugins.rst diff --git a/vendor/pygments/doc/docs/quickstart.rst b/third_party/pygments/doc/docs/quickstart.rst similarity index 100% rename from vendor/pygments/doc/docs/quickstart.rst rename to third_party/pygments/doc/docs/quickstart.rst diff --git a/vendor/pygments/doc/docs/rstdirective.rst b/third_party/pygments/doc/docs/rstdirective.rst similarity index 100% rename from vendor/pygments/doc/docs/rstdirective.rst rename to third_party/pygments/doc/docs/rstdirective.rst diff --git a/vendor/pygments/doc/docs/styles.rst b/third_party/pygments/doc/docs/styles.rst similarity index 100% rename from vendor/pygments/doc/docs/styles.rst rename to third_party/pygments/doc/docs/styles.rst diff --git a/vendor/pygments/doc/docs/tokens.rst b/third_party/pygments/doc/docs/tokens.rst similarity index 100% rename from vendor/pygments/doc/docs/tokens.rst rename to third_party/pygments/doc/docs/tokens.rst diff --git a/vendor/pygments/doc/docs/unicode.rst b/third_party/pygments/doc/docs/unicode.rst similarity index 100% rename from vendor/pygments/doc/docs/unicode.rst rename to third_party/pygments/doc/docs/unicode.rst diff --git a/vendor/pygments/doc/download.rst b/third_party/pygments/doc/download.rst similarity index 100% rename from vendor/pygments/doc/download.rst rename to third_party/pygments/doc/download.rst diff --git a/vendor/pygments/doc/faq.rst b/third_party/pygments/doc/faq.rst similarity index 100% rename from vendor/pygments/doc/faq.rst rename to third_party/pygments/doc/faq.rst diff --git a/vendor/pygments/doc/index.rst b/third_party/pygments/doc/index.rst similarity index 100% rename from vendor/pygments/doc/index.rst rename to third_party/pygments/doc/index.rst diff --git a/vendor/pygments/doc/languages.rst b/third_party/pygments/doc/languages.rst similarity index 100% rename from vendor/pygments/doc/languages.rst rename to third_party/pygments/doc/languages.rst diff --git a/vendor/pygments/doc/make.bat b/third_party/pygments/doc/make.bat similarity index 100% rename from vendor/pygments/doc/make.bat rename to third_party/pygments/doc/make.bat diff --git a/vendor/pygments/doc/pygmentize.1 b/third_party/pygments/doc/pygmentize.1 similarity index 100% rename from vendor/pygments/doc/pygmentize.1 rename to third_party/pygments/doc/pygmentize.1 diff --git a/vendor/pygments/external/autopygmentize b/third_party/pygments/external/autopygmentize similarity index 100% rename from vendor/pygments/external/autopygmentize rename to third_party/pygments/external/autopygmentize diff --git a/vendor/pygments/external/lasso-builtins-generator-9.lasso b/third_party/pygments/external/lasso-builtins-generator-9.lasso similarity index 100% rename from vendor/pygments/external/lasso-builtins-generator-9.lasso rename to third_party/pygments/external/lasso-builtins-generator-9.lasso diff --git a/vendor/pygments/external/markdown-processor.py b/third_party/pygments/external/markdown-processor.py similarity index 100% rename from vendor/pygments/external/markdown-processor.py rename to third_party/pygments/external/markdown-processor.py diff --git a/vendor/pygments/external/moin-parser.py b/third_party/pygments/external/moin-parser.py similarity index 100% rename from vendor/pygments/external/moin-parser.py rename to third_party/pygments/external/moin-parser.py diff --git a/vendor/pygments/external/pygments.bashcomp b/third_party/pygments/external/pygments.bashcomp similarity index 100% rename from vendor/pygments/external/pygments.bashcomp rename to third_party/pygments/external/pygments.bashcomp diff --git a/vendor/pygments/external/rst-directive.py b/third_party/pygments/external/rst-directive.py similarity index 100% rename from vendor/pygments/external/rst-directive.py rename to third_party/pygments/external/rst-directive.py diff --git a/vendor/pygments/ez_setup.py b/third_party/pygments/ez_setup.py similarity index 100% rename from vendor/pygments/ez_setup.py rename to third_party/pygments/ez_setup.py diff --git a/vendor/pygments/pygmentize b/third_party/pygments/pygmentize similarity index 100% rename from vendor/pygments/pygmentize rename to third_party/pygments/pygmentize diff --git a/vendor/pygments/pygments/__init__.py b/third_party/pygments/pygments/__init__.py similarity index 100% rename from vendor/pygments/pygments/__init__.py rename to third_party/pygments/pygments/__init__.py diff --git a/vendor/pygments/pygments/cmdline.py b/third_party/pygments/pygments/cmdline.py similarity index 100% rename from vendor/pygments/pygments/cmdline.py rename to third_party/pygments/pygments/cmdline.py diff --git a/vendor/pygments/pygments/console.py b/third_party/pygments/pygments/console.py similarity index 100% rename from vendor/pygments/pygments/console.py rename to third_party/pygments/pygments/console.py diff --git a/vendor/pygments/pygments/filter.py b/third_party/pygments/pygments/filter.py similarity index 100% rename from vendor/pygments/pygments/filter.py rename to third_party/pygments/pygments/filter.py diff --git a/vendor/pygments/pygments/filters/__init__.py b/third_party/pygments/pygments/filters/__init__.py similarity index 100% rename from vendor/pygments/pygments/filters/__init__.py rename to third_party/pygments/pygments/filters/__init__.py diff --git a/vendor/pygments/pygments/formatter.py b/third_party/pygments/pygments/formatter.py similarity index 100% rename from vendor/pygments/pygments/formatter.py rename to third_party/pygments/pygments/formatter.py diff --git a/vendor/pygments/pygments/formatters/__init__.py b/third_party/pygments/pygments/formatters/__init__.py similarity index 100% rename from vendor/pygments/pygments/formatters/__init__.py rename to third_party/pygments/pygments/formatters/__init__.py diff --git a/vendor/pygments/pygments/formatters/_mapping.py b/third_party/pygments/pygments/formatters/_mapping.py similarity index 100% rename from vendor/pygments/pygments/formatters/_mapping.py rename to third_party/pygments/pygments/formatters/_mapping.py diff --git a/vendor/pygments/pygments/formatters/bbcode.py b/third_party/pygments/pygments/formatters/bbcode.py similarity index 100% rename from vendor/pygments/pygments/formatters/bbcode.py rename to third_party/pygments/pygments/formatters/bbcode.py diff --git a/vendor/pygments/pygments/formatters/html.py b/third_party/pygments/pygments/formatters/html.py similarity index 100% rename from vendor/pygments/pygments/formatters/html.py rename to third_party/pygments/pygments/formatters/html.py diff --git a/vendor/pygments/pygments/formatters/img.py b/third_party/pygments/pygments/formatters/img.py similarity index 100% rename from vendor/pygments/pygments/formatters/img.py rename to third_party/pygments/pygments/formatters/img.py diff --git a/vendor/pygments/pygments/formatters/irc.py b/third_party/pygments/pygments/formatters/irc.py similarity index 100% rename from vendor/pygments/pygments/formatters/irc.py rename to third_party/pygments/pygments/formatters/irc.py diff --git a/vendor/pygments/pygments/formatters/latex.py b/third_party/pygments/pygments/formatters/latex.py similarity index 100% rename from vendor/pygments/pygments/formatters/latex.py rename to third_party/pygments/pygments/formatters/latex.py diff --git a/vendor/pygments/pygments/formatters/other.py b/third_party/pygments/pygments/formatters/other.py similarity index 100% rename from vendor/pygments/pygments/formatters/other.py rename to third_party/pygments/pygments/formatters/other.py diff --git a/vendor/pygments/pygments/formatters/rtf.py b/third_party/pygments/pygments/formatters/rtf.py similarity index 100% rename from vendor/pygments/pygments/formatters/rtf.py rename to third_party/pygments/pygments/formatters/rtf.py diff --git a/vendor/pygments/pygments/formatters/svg.py b/third_party/pygments/pygments/formatters/svg.py similarity index 100% rename from vendor/pygments/pygments/formatters/svg.py rename to third_party/pygments/pygments/formatters/svg.py diff --git a/vendor/pygments/pygments/formatters/terminal.py b/third_party/pygments/pygments/formatters/terminal.py similarity index 100% rename from vendor/pygments/pygments/formatters/terminal.py rename to third_party/pygments/pygments/formatters/terminal.py diff --git a/vendor/pygments/pygments/formatters/terminal256.py b/third_party/pygments/pygments/formatters/terminal256.py similarity index 100% rename from vendor/pygments/pygments/formatters/terminal256.py rename to third_party/pygments/pygments/formatters/terminal256.py diff --git a/vendor/pygments/pygments/lexer.py b/third_party/pygments/pygments/lexer.py similarity index 100% rename from vendor/pygments/pygments/lexer.py rename to third_party/pygments/pygments/lexer.py diff --git a/vendor/pygments/pygments/lexers/__init__.py b/third_party/pygments/pygments/lexers/__init__.py similarity index 100% rename from vendor/pygments/pygments/lexers/__init__.py rename to third_party/pygments/pygments/lexers/__init__.py diff --git a/vendor/pygments/pygments/lexers/_asy_builtins.py b/third_party/pygments/pygments/lexers/_asy_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_asy_builtins.py rename to third_party/pygments/pygments/lexers/_asy_builtins.py diff --git a/vendor/pygments/pygments/lexers/_cl_builtins.py b/third_party/pygments/pygments/lexers/_cl_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_cl_builtins.py rename to third_party/pygments/pygments/lexers/_cl_builtins.py diff --git a/vendor/pygments/pygments/lexers/_cocoa_builtins.py b/third_party/pygments/pygments/lexers/_cocoa_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_cocoa_builtins.py rename to third_party/pygments/pygments/lexers/_cocoa_builtins.py diff --git a/vendor/pygments/pygments/lexers/_csound_builtins.py b/third_party/pygments/pygments/lexers/_csound_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_csound_builtins.py rename to third_party/pygments/pygments/lexers/_csound_builtins.py diff --git a/vendor/pygments/pygments/lexers/_lasso_builtins.py b/third_party/pygments/pygments/lexers/_lasso_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_lasso_builtins.py rename to third_party/pygments/pygments/lexers/_lasso_builtins.py diff --git a/vendor/pygments/pygments/lexers/_lua_builtins.py b/third_party/pygments/pygments/lexers/_lua_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_lua_builtins.py rename to third_party/pygments/pygments/lexers/_lua_builtins.py diff --git a/vendor/pygments/pygments/lexers/_mapping.py b/third_party/pygments/pygments/lexers/_mapping.py similarity index 100% rename from vendor/pygments/pygments/lexers/_mapping.py rename to third_party/pygments/pygments/lexers/_mapping.py diff --git a/vendor/pygments/pygments/lexers/_mql_builtins.py b/third_party/pygments/pygments/lexers/_mql_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_mql_builtins.py rename to third_party/pygments/pygments/lexers/_mql_builtins.py diff --git a/vendor/pygments/pygments/lexers/_openedge_builtins.py b/third_party/pygments/pygments/lexers/_openedge_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_openedge_builtins.py rename to third_party/pygments/pygments/lexers/_openedge_builtins.py diff --git a/vendor/pygments/pygments/lexers/_php_builtins.py b/third_party/pygments/pygments/lexers/_php_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_php_builtins.py rename to third_party/pygments/pygments/lexers/_php_builtins.py diff --git a/vendor/pygments/pygments/lexers/_postgres_builtins.py b/third_party/pygments/pygments/lexers/_postgres_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_postgres_builtins.py rename to third_party/pygments/pygments/lexers/_postgres_builtins.py diff --git a/vendor/pygments/pygments/lexers/_scilab_builtins.py b/third_party/pygments/pygments/lexers/_scilab_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_scilab_builtins.py rename to third_party/pygments/pygments/lexers/_scilab_builtins.py diff --git a/vendor/pygments/pygments/lexers/_sourcemod_builtins.py b/third_party/pygments/pygments/lexers/_sourcemod_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_sourcemod_builtins.py rename to third_party/pygments/pygments/lexers/_sourcemod_builtins.py diff --git a/vendor/pygments/pygments/lexers/_stan_builtins.py b/third_party/pygments/pygments/lexers/_stan_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_stan_builtins.py rename to third_party/pygments/pygments/lexers/_stan_builtins.py diff --git a/vendor/pygments/pygments/lexers/_vim_builtins.py b/third_party/pygments/pygments/lexers/_vim_builtins.py similarity index 100% rename from vendor/pygments/pygments/lexers/_vim_builtins.py rename to third_party/pygments/pygments/lexers/_vim_builtins.py diff --git a/vendor/pygments/pygments/lexers/actionscript.py b/third_party/pygments/pygments/lexers/actionscript.py similarity index 100% rename from vendor/pygments/pygments/lexers/actionscript.py rename to third_party/pygments/pygments/lexers/actionscript.py diff --git a/vendor/pygments/pygments/lexers/agile.py b/third_party/pygments/pygments/lexers/agile.py similarity index 100% rename from vendor/pygments/pygments/lexers/agile.py rename to third_party/pygments/pygments/lexers/agile.py diff --git a/vendor/pygments/pygments/lexers/algebra.py b/third_party/pygments/pygments/lexers/algebra.py similarity index 100% rename from vendor/pygments/pygments/lexers/algebra.py rename to third_party/pygments/pygments/lexers/algebra.py diff --git a/vendor/pygments/pygments/lexers/ambient.py b/third_party/pygments/pygments/lexers/ambient.py similarity index 100% rename from vendor/pygments/pygments/lexers/ambient.py rename to third_party/pygments/pygments/lexers/ambient.py diff --git a/vendor/pygments/pygments/lexers/apl.py b/third_party/pygments/pygments/lexers/apl.py similarity index 100% rename from vendor/pygments/pygments/lexers/apl.py rename to third_party/pygments/pygments/lexers/apl.py diff --git a/vendor/pygments/pygments/lexers/archetype.py b/third_party/pygments/pygments/lexers/archetype.py similarity index 100% rename from vendor/pygments/pygments/lexers/archetype.py rename to third_party/pygments/pygments/lexers/archetype.py diff --git a/vendor/pygments/pygments/lexers/asm.py b/third_party/pygments/pygments/lexers/asm.py similarity index 100% rename from vendor/pygments/pygments/lexers/asm.py rename to third_party/pygments/pygments/lexers/asm.py diff --git a/vendor/pygments/pygments/lexers/automation.py b/third_party/pygments/pygments/lexers/automation.py similarity index 100% rename from vendor/pygments/pygments/lexers/automation.py rename to third_party/pygments/pygments/lexers/automation.py diff --git a/vendor/pygments/pygments/lexers/basic.py b/third_party/pygments/pygments/lexers/basic.py similarity index 100% rename from vendor/pygments/pygments/lexers/basic.py rename to third_party/pygments/pygments/lexers/basic.py diff --git a/vendor/pygments/pygments/lexers/business.py b/third_party/pygments/pygments/lexers/business.py similarity index 100% rename from vendor/pygments/pygments/lexers/business.py rename to third_party/pygments/pygments/lexers/business.py diff --git a/vendor/pygments/pygments/lexers/c_cpp.py b/third_party/pygments/pygments/lexers/c_cpp.py similarity index 100% rename from vendor/pygments/pygments/lexers/c_cpp.py rename to third_party/pygments/pygments/lexers/c_cpp.py diff --git a/vendor/pygments/pygments/lexers/c_like.py b/third_party/pygments/pygments/lexers/c_like.py similarity index 100% rename from vendor/pygments/pygments/lexers/c_like.py rename to third_party/pygments/pygments/lexers/c_like.py diff --git a/vendor/pygments/pygments/lexers/chapel.py b/third_party/pygments/pygments/lexers/chapel.py similarity index 100% rename from vendor/pygments/pygments/lexers/chapel.py rename to third_party/pygments/pygments/lexers/chapel.py diff --git a/vendor/pygments/pygments/lexers/compiled.py b/third_party/pygments/pygments/lexers/compiled.py similarity index 100% rename from vendor/pygments/pygments/lexers/compiled.py rename to third_party/pygments/pygments/lexers/compiled.py diff --git a/vendor/pygments/pygments/lexers/configs.py b/third_party/pygments/pygments/lexers/configs.py similarity index 100% rename from vendor/pygments/pygments/lexers/configs.py rename to third_party/pygments/pygments/lexers/configs.py diff --git a/vendor/pygments/pygments/lexers/console.py b/third_party/pygments/pygments/lexers/console.py similarity index 100% rename from vendor/pygments/pygments/lexers/console.py rename to third_party/pygments/pygments/lexers/console.py diff --git a/vendor/pygments/pygments/lexers/csound.py b/third_party/pygments/pygments/lexers/csound.py similarity index 100% rename from vendor/pygments/pygments/lexers/csound.py rename to third_party/pygments/pygments/lexers/csound.py diff --git a/vendor/pygments/pygments/lexers/css.py b/third_party/pygments/pygments/lexers/css.py similarity index 100% rename from vendor/pygments/pygments/lexers/css.py rename to third_party/pygments/pygments/lexers/css.py diff --git a/vendor/pygments/pygments/lexers/d.py b/third_party/pygments/pygments/lexers/d.py similarity index 100% rename from vendor/pygments/pygments/lexers/d.py rename to third_party/pygments/pygments/lexers/d.py diff --git a/vendor/pygments/pygments/lexers/dalvik.py b/third_party/pygments/pygments/lexers/dalvik.py similarity index 100% rename from vendor/pygments/pygments/lexers/dalvik.py rename to third_party/pygments/pygments/lexers/dalvik.py diff --git a/vendor/pygments/pygments/lexers/data.py b/third_party/pygments/pygments/lexers/data.py similarity index 100% rename from vendor/pygments/pygments/lexers/data.py rename to third_party/pygments/pygments/lexers/data.py diff --git a/vendor/pygments/pygments/lexers/diff.py b/third_party/pygments/pygments/lexers/diff.py similarity index 100% rename from vendor/pygments/pygments/lexers/diff.py rename to third_party/pygments/pygments/lexers/diff.py diff --git a/vendor/pygments/pygments/lexers/dotnet.py b/third_party/pygments/pygments/lexers/dotnet.py similarity index 100% rename from vendor/pygments/pygments/lexers/dotnet.py rename to third_party/pygments/pygments/lexers/dotnet.py diff --git a/vendor/pygments/pygments/lexers/dsls.py b/third_party/pygments/pygments/lexers/dsls.py similarity index 100% rename from vendor/pygments/pygments/lexers/dsls.py rename to third_party/pygments/pygments/lexers/dsls.py diff --git a/vendor/pygments/pygments/lexers/dylan.py b/third_party/pygments/pygments/lexers/dylan.py similarity index 100% rename from vendor/pygments/pygments/lexers/dylan.py rename to third_party/pygments/pygments/lexers/dylan.py diff --git a/vendor/pygments/pygments/lexers/ecl.py b/third_party/pygments/pygments/lexers/ecl.py similarity index 100% rename from vendor/pygments/pygments/lexers/ecl.py rename to third_party/pygments/pygments/lexers/ecl.py diff --git a/vendor/pygments/pygments/lexers/eiffel.py b/third_party/pygments/pygments/lexers/eiffel.py similarity index 100% rename from vendor/pygments/pygments/lexers/eiffel.py rename to third_party/pygments/pygments/lexers/eiffel.py diff --git a/vendor/pygments/pygments/lexers/elm.py b/third_party/pygments/pygments/lexers/elm.py similarity index 100% rename from vendor/pygments/pygments/lexers/elm.py rename to third_party/pygments/pygments/lexers/elm.py diff --git a/vendor/pygments/pygments/lexers/erlang.py b/third_party/pygments/pygments/lexers/erlang.py similarity index 100% rename from vendor/pygments/pygments/lexers/erlang.py rename to third_party/pygments/pygments/lexers/erlang.py diff --git a/vendor/pygments/pygments/lexers/esoteric.py b/third_party/pygments/pygments/lexers/esoteric.py similarity index 100% rename from vendor/pygments/pygments/lexers/esoteric.py rename to third_party/pygments/pygments/lexers/esoteric.py diff --git a/vendor/pygments/pygments/lexers/ezhil.py b/third_party/pygments/pygments/lexers/ezhil.py similarity index 100% rename from vendor/pygments/pygments/lexers/ezhil.py rename to third_party/pygments/pygments/lexers/ezhil.py diff --git a/vendor/pygments/pygments/lexers/factor.py b/third_party/pygments/pygments/lexers/factor.py similarity index 100% rename from vendor/pygments/pygments/lexers/factor.py rename to third_party/pygments/pygments/lexers/factor.py diff --git a/vendor/pygments/pygments/lexers/fantom.py b/third_party/pygments/pygments/lexers/fantom.py similarity index 100% rename from vendor/pygments/pygments/lexers/fantom.py rename to third_party/pygments/pygments/lexers/fantom.py diff --git a/vendor/pygments/pygments/lexers/felix.py b/third_party/pygments/pygments/lexers/felix.py similarity index 100% rename from vendor/pygments/pygments/lexers/felix.py rename to third_party/pygments/pygments/lexers/felix.py diff --git a/vendor/pygments/pygments/lexers/fortran.py b/third_party/pygments/pygments/lexers/fortran.py similarity index 100% rename from vendor/pygments/pygments/lexers/fortran.py rename to third_party/pygments/pygments/lexers/fortran.py diff --git a/vendor/pygments/pygments/lexers/foxpro.py b/third_party/pygments/pygments/lexers/foxpro.py similarity index 100% rename from vendor/pygments/pygments/lexers/foxpro.py rename to third_party/pygments/pygments/lexers/foxpro.py diff --git a/vendor/pygments/pygments/lexers/functional.py b/third_party/pygments/pygments/lexers/functional.py similarity index 100% rename from vendor/pygments/pygments/lexers/functional.py rename to third_party/pygments/pygments/lexers/functional.py diff --git a/vendor/pygments/pygments/lexers/go.py b/third_party/pygments/pygments/lexers/go.py similarity index 100% rename from vendor/pygments/pygments/lexers/go.py rename to third_party/pygments/pygments/lexers/go.py diff --git a/vendor/pygments/pygments/lexers/grammar_notation.py b/third_party/pygments/pygments/lexers/grammar_notation.py similarity index 100% rename from vendor/pygments/pygments/lexers/grammar_notation.py rename to third_party/pygments/pygments/lexers/grammar_notation.py diff --git a/vendor/pygments/pygments/lexers/graph.py b/third_party/pygments/pygments/lexers/graph.py similarity index 100% rename from vendor/pygments/pygments/lexers/graph.py rename to third_party/pygments/pygments/lexers/graph.py diff --git a/vendor/pygments/pygments/lexers/graphics.py b/third_party/pygments/pygments/lexers/graphics.py similarity index 100% rename from vendor/pygments/pygments/lexers/graphics.py rename to third_party/pygments/pygments/lexers/graphics.py diff --git a/vendor/pygments/pygments/lexers/haskell.py b/third_party/pygments/pygments/lexers/haskell.py similarity index 100% rename from vendor/pygments/pygments/lexers/haskell.py rename to third_party/pygments/pygments/lexers/haskell.py diff --git a/vendor/pygments/pygments/lexers/haxe.py b/third_party/pygments/pygments/lexers/haxe.py similarity index 100% rename from vendor/pygments/pygments/lexers/haxe.py rename to third_party/pygments/pygments/lexers/haxe.py diff --git a/vendor/pygments/pygments/lexers/hdl.py b/third_party/pygments/pygments/lexers/hdl.py similarity index 100% rename from vendor/pygments/pygments/lexers/hdl.py rename to third_party/pygments/pygments/lexers/hdl.py diff --git a/vendor/pygments/pygments/lexers/hexdump.py b/third_party/pygments/pygments/lexers/hexdump.py similarity index 100% rename from vendor/pygments/pygments/lexers/hexdump.py rename to third_party/pygments/pygments/lexers/hexdump.py diff --git a/vendor/pygments/pygments/lexers/html.py b/third_party/pygments/pygments/lexers/html.py similarity index 100% rename from vendor/pygments/pygments/lexers/html.py rename to third_party/pygments/pygments/lexers/html.py diff --git a/vendor/pygments/pygments/lexers/idl.py b/third_party/pygments/pygments/lexers/idl.py similarity index 100% rename from vendor/pygments/pygments/lexers/idl.py rename to third_party/pygments/pygments/lexers/idl.py diff --git a/vendor/pygments/pygments/lexers/igor.py b/third_party/pygments/pygments/lexers/igor.py similarity index 100% rename from vendor/pygments/pygments/lexers/igor.py rename to third_party/pygments/pygments/lexers/igor.py diff --git a/vendor/pygments/pygments/lexers/inferno.py b/third_party/pygments/pygments/lexers/inferno.py similarity index 100% rename from vendor/pygments/pygments/lexers/inferno.py rename to third_party/pygments/pygments/lexers/inferno.py diff --git a/vendor/pygments/pygments/lexers/installers.py b/third_party/pygments/pygments/lexers/installers.py similarity index 100% rename from vendor/pygments/pygments/lexers/installers.py rename to third_party/pygments/pygments/lexers/installers.py diff --git a/vendor/pygments/pygments/lexers/int_fiction.py b/third_party/pygments/pygments/lexers/int_fiction.py similarity index 100% rename from vendor/pygments/pygments/lexers/int_fiction.py rename to third_party/pygments/pygments/lexers/int_fiction.py diff --git a/vendor/pygments/pygments/lexers/iolang.py b/third_party/pygments/pygments/lexers/iolang.py similarity index 100% rename from vendor/pygments/pygments/lexers/iolang.py rename to third_party/pygments/pygments/lexers/iolang.py diff --git a/vendor/pygments/pygments/lexers/j.py b/third_party/pygments/pygments/lexers/j.py similarity index 100% rename from vendor/pygments/pygments/lexers/j.py rename to third_party/pygments/pygments/lexers/j.py diff --git a/vendor/pygments/pygments/lexers/javascript.py b/third_party/pygments/pygments/lexers/javascript.py similarity index 100% rename from vendor/pygments/pygments/lexers/javascript.py rename to third_party/pygments/pygments/lexers/javascript.py diff --git a/vendor/pygments/pygments/lexers/julia.py b/third_party/pygments/pygments/lexers/julia.py similarity index 100% rename from vendor/pygments/pygments/lexers/julia.py rename to third_party/pygments/pygments/lexers/julia.py diff --git a/vendor/pygments/pygments/lexers/jvm.py b/third_party/pygments/pygments/lexers/jvm.py similarity index 100% rename from vendor/pygments/pygments/lexers/jvm.py rename to third_party/pygments/pygments/lexers/jvm.py diff --git a/vendor/pygments/pygments/lexers/lisp.py b/third_party/pygments/pygments/lexers/lisp.py similarity index 100% rename from vendor/pygments/pygments/lexers/lisp.py rename to third_party/pygments/pygments/lexers/lisp.py diff --git a/vendor/pygments/pygments/lexers/make.py b/third_party/pygments/pygments/lexers/make.py similarity index 100% rename from vendor/pygments/pygments/lexers/make.py rename to third_party/pygments/pygments/lexers/make.py diff --git a/vendor/pygments/pygments/lexers/markup.py b/third_party/pygments/pygments/lexers/markup.py similarity index 100% rename from vendor/pygments/pygments/lexers/markup.py rename to third_party/pygments/pygments/lexers/markup.py diff --git a/vendor/pygments/pygments/lexers/math.py b/third_party/pygments/pygments/lexers/math.py similarity index 100% rename from vendor/pygments/pygments/lexers/math.py rename to third_party/pygments/pygments/lexers/math.py diff --git a/vendor/pygments/pygments/lexers/matlab.py b/third_party/pygments/pygments/lexers/matlab.py similarity index 100% rename from vendor/pygments/pygments/lexers/matlab.py rename to third_party/pygments/pygments/lexers/matlab.py diff --git a/vendor/pygments/pygments/lexers/ml.py b/third_party/pygments/pygments/lexers/ml.py similarity index 100% rename from vendor/pygments/pygments/lexers/ml.py rename to third_party/pygments/pygments/lexers/ml.py diff --git a/vendor/pygments/pygments/lexers/modeling.py b/third_party/pygments/pygments/lexers/modeling.py similarity index 100% rename from vendor/pygments/pygments/lexers/modeling.py rename to third_party/pygments/pygments/lexers/modeling.py diff --git a/vendor/pygments/pygments/lexers/modula2.py b/third_party/pygments/pygments/lexers/modula2.py similarity index 100% rename from vendor/pygments/pygments/lexers/modula2.py rename to third_party/pygments/pygments/lexers/modula2.py diff --git a/vendor/pygments/pygments/lexers/nimrod.py b/third_party/pygments/pygments/lexers/nimrod.py similarity index 100% rename from vendor/pygments/pygments/lexers/nimrod.py rename to third_party/pygments/pygments/lexers/nimrod.py diff --git a/vendor/pygments/pygments/lexers/nit.py b/third_party/pygments/pygments/lexers/nit.py similarity index 100% rename from vendor/pygments/pygments/lexers/nit.py rename to third_party/pygments/pygments/lexers/nit.py diff --git a/vendor/pygments/pygments/lexers/nix.py b/third_party/pygments/pygments/lexers/nix.py similarity index 100% rename from vendor/pygments/pygments/lexers/nix.py rename to third_party/pygments/pygments/lexers/nix.py diff --git a/vendor/pygments/pygments/lexers/oberon.py b/third_party/pygments/pygments/lexers/oberon.py similarity index 100% rename from vendor/pygments/pygments/lexers/oberon.py rename to third_party/pygments/pygments/lexers/oberon.py diff --git a/vendor/pygments/pygments/lexers/objective.py b/third_party/pygments/pygments/lexers/objective.py similarity index 100% rename from vendor/pygments/pygments/lexers/objective.py rename to third_party/pygments/pygments/lexers/objective.py diff --git a/vendor/pygments/pygments/lexers/ooc.py b/third_party/pygments/pygments/lexers/ooc.py similarity index 100% rename from vendor/pygments/pygments/lexers/ooc.py rename to third_party/pygments/pygments/lexers/ooc.py diff --git a/vendor/pygments/pygments/lexers/other.py b/third_party/pygments/pygments/lexers/other.py similarity index 100% rename from vendor/pygments/pygments/lexers/other.py rename to third_party/pygments/pygments/lexers/other.py diff --git a/vendor/pygments/pygments/lexers/parasail.py b/third_party/pygments/pygments/lexers/parasail.py similarity index 100% rename from vendor/pygments/pygments/lexers/parasail.py rename to third_party/pygments/pygments/lexers/parasail.py diff --git a/vendor/pygments/pygments/lexers/parsers.py b/third_party/pygments/pygments/lexers/parsers.py similarity index 100% rename from vendor/pygments/pygments/lexers/parsers.py rename to third_party/pygments/pygments/lexers/parsers.py diff --git a/vendor/pygments/pygments/lexers/pascal.py b/third_party/pygments/pygments/lexers/pascal.py similarity index 100% rename from vendor/pygments/pygments/lexers/pascal.py rename to third_party/pygments/pygments/lexers/pascal.py diff --git a/vendor/pygments/pygments/lexers/pawn.py b/third_party/pygments/pygments/lexers/pawn.py similarity index 100% rename from vendor/pygments/pygments/lexers/pawn.py rename to third_party/pygments/pygments/lexers/pawn.py diff --git a/vendor/pygments/pygments/lexers/perl.py b/third_party/pygments/pygments/lexers/perl.py similarity index 100% rename from vendor/pygments/pygments/lexers/perl.py rename to third_party/pygments/pygments/lexers/perl.py diff --git a/vendor/pygments/pygments/lexers/php.py b/third_party/pygments/pygments/lexers/php.py similarity index 100% rename from vendor/pygments/pygments/lexers/php.py rename to third_party/pygments/pygments/lexers/php.py diff --git a/vendor/pygments/pygments/lexers/praat.py b/third_party/pygments/pygments/lexers/praat.py similarity index 100% rename from vendor/pygments/pygments/lexers/praat.py rename to third_party/pygments/pygments/lexers/praat.py diff --git a/vendor/pygments/pygments/lexers/prolog.py b/third_party/pygments/pygments/lexers/prolog.py similarity index 100% rename from vendor/pygments/pygments/lexers/prolog.py rename to third_party/pygments/pygments/lexers/prolog.py diff --git a/vendor/pygments/pygments/lexers/python.py b/third_party/pygments/pygments/lexers/python.py similarity index 100% rename from vendor/pygments/pygments/lexers/python.py rename to third_party/pygments/pygments/lexers/python.py diff --git a/vendor/pygments/pygments/lexers/qvt.py b/third_party/pygments/pygments/lexers/qvt.py similarity index 100% rename from vendor/pygments/pygments/lexers/qvt.py rename to third_party/pygments/pygments/lexers/qvt.py diff --git a/vendor/pygments/pygments/lexers/r.py b/third_party/pygments/pygments/lexers/r.py similarity index 100% rename from vendor/pygments/pygments/lexers/r.py rename to third_party/pygments/pygments/lexers/r.py diff --git a/vendor/pygments/pygments/lexers/rdf.py b/third_party/pygments/pygments/lexers/rdf.py similarity index 100% rename from vendor/pygments/pygments/lexers/rdf.py rename to third_party/pygments/pygments/lexers/rdf.py diff --git a/vendor/pygments/pygments/lexers/rebol.py b/third_party/pygments/pygments/lexers/rebol.py similarity index 100% rename from vendor/pygments/pygments/lexers/rebol.py rename to third_party/pygments/pygments/lexers/rebol.py diff --git a/vendor/pygments/pygments/lexers/resource.py b/third_party/pygments/pygments/lexers/resource.py similarity index 100% rename from vendor/pygments/pygments/lexers/resource.py rename to third_party/pygments/pygments/lexers/resource.py diff --git a/vendor/pygments/pygments/lexers/roboconf.py b/third_party/pygments/pygments/lexers/roboconf.py similarity index 100% rename from vendor/pygments/pygments/lexers/roboconf.py rename to third_party/pygments/pygments/lexers/roboconf.py diff --git a/vendor/pygments/pygments/lexers/robotframework.py b/third_party/pygments/pygments/lexers/robotframework.py similarity index 100% rename from vendor/pygments/pygments/lexers/robotframework.py rename to third_party/pygments/pygments/lexers/robotframework.py diff --git a/vendor/pygments/pygments/lexers/ruby.py b/third_party/pygments/pygments/lexers/ruby.py similarity index 100% rename from vendor/pygments/pygments/lexers/ruby.py rename to third_party/pygments/pygments/lexers/ruby.py diff --git a/vendor/pygments/pygments/lexers/rust.py b/third_party/pygments/pygments/lexers/rust.py similarity index 100% rename from vendor/pygments/pygments/lexers/rust.py rename to third_party/pygments/pygments/lexers/rust.py diff --git a/vendor/pygments/pygments/lexers/scripting.py b/third_party/pygments/pygments/lexers/scripting.py similarity index 100% rename from vendor/pygments/pygments/lexers/scripting.py rename to third_party/pygments/pygments/lexers/scripting.py diff --git a/vendor/pygments/pygments/lexers/shell.py b/third_party/pygments/pygments/lexers/shell.py similarity index 100% rename from vendor/pygments/pygments/lexers/shell.py rename to third_party/pygments/pygments/lexers/shell.py diff --git a/vendor/pygments/pygments/lexers/smalltalk.py b/third_party/pygments/pygments/lexers/smalltalk.py similarity index 100% rename from vendor/pygments/pygments/lexers/smalltalk.py rename to third_party/pygments/pygments/lexers/smalltalk.py diff --git a/vendor/pygments/pygments/lexers/snobol.py b/third_party/pygments/pygments/lexers/snobol.py similarity index 100% rename from vendor/pygments/pygments/lexers/snobol.py rename to third_party/pygments/pygments/lexers/snobol.py diff --git a/vendor/pygments/pygments/lexers/special.py b/third_party/pygments/pygments/lexers/special.py similarity index 100% rename from vendor/pygments/pygments/lexers/special.py rename to third_party/pygments/pygments/lexers/special.py diff --git a/vendor/pygments/pygments/lexers/sql.py b/third_party/pygments/pygments/lexers/sql.py similarity index 100% rename from vendor/pygments/pygments/lexers/sql.py rename to third_party/pygments/pygments/lexers/sql.py diff --git a/vendor/pygments/pygments/lexers/supercollider.py b/third_party/pygments/pygments/lexers/supercollider.py similarity index 100% rename from vendor/pygments/pygments/lexers/supercollider.py rename to third_party/pygments/pygments/lexers/supercollider.py diff --git a/vendor/pygments/pygments/lexers/tcl.py b/third_party/pygments/pygments/lexers/tcl.py similarity index 100% rename from vendor/pygments/pygments/lexers/tcl.py rename to third_party/pygments/pygments/lexers/tcl.py diff --git a/vendor/pygments/pygments/lexers/templates.py b/third_party/pygments/pygments/lexers/templates.py similarity index 100% rename from vendor/pygments/pygments/lexers/templates.py rename to third_party/pygments/pygments/lexers/templates.py diff --git a/vendor/pygments/pygments/lexers/testing.py b/third_party/pygments/pygments/lexers/testing.py similarity index 100% rename from vendor/pygments/pygments/lexers/testing.py rename to third_party/pygments/pygments/lexers/testing.py diff --git a/vendor/pygments/pygments/lexers/text.py b/third_party/pygments/pygments/lexers/text.py similarity index 100% rename from vendor/pygments/pygments/lexers/text.py rename to third_party/pygments/pygments/lexers/text.py diff --git a/vendor/pygments/pygments/lexers/textedit.py b/third_party/pygments/pygments/lexers/textedit.py similarity index 100% rename from vendor/pygments/pygments/lexers/textedit.py rename to third_party/pygments/pygments/lexers/textedit.py diff --git a/vendor/pygments/pygments/lexers/textfmts.py b/third_party/pygments/pygments/lexers/textfmts.py similarity index 100% rename from vendor/pygments/pygments/lexers/textfmts.py rename to third_party/pygments/pygments/lexers/textfmts.py diff --git a/vendor/pygments/pygments/lexers/theorem.py b/third_party/pygments/pygments/lexers/theorem.py similarity index 100% rename from vendor/pygments/pygments/lexers/theorem.py rename to third_party/pygments/pygments/lexers/theorem.py diff --git a/vendor/pygments/pygments/lexers/trafficscript.py b/third_party/pygments/pygments/lexers/trafficscript.py similarity index 100% rename from vendor/pygments/pygments/lexers/trafficscript.py rename to third_party/pygments/pygments/lexers/trafficscript.py diff --git a/vendor/pygments/pygments/lexers/urbi.py b/third_party/pygments/pygments/lexers/urbi.py similarity index 100% rename from vendor/pygments/pygments/lexers/urbi.py rename to third_party/pygments/pygments/lexers/urbi.py diff --git a/vendor/pygments/pygments/lexers/web.py b/third_party/pygments/pygments/lexers/web.py similarity index 100% rename from vendor/pygments/pygments/lexers/web.py rename to third_party/pygments/pygments/lexers/web.py diff --git a/vendor/pygments/pygments/lexers/webmisc.py b/third_party/pygments/pygments/lexers/webmisc.py similarity index 100% rename from vendor/pygments/pygments/lexers/webmisc.py rename to third_party/pygments/pygments/lexers/webmisc.py diff --git a/vendor/pygments/pygments/lexers/x10.py b/third_party/pygments/pygments/lexers/x10.py similarity index 100% rename from vendor/pygments/pygments/lexers/x10.py rename to third_party/pygments/pygments/lexers/x10.py diff --git a/vendor/pygments/pygments/modeline.py b/third_party/pygments/pygments/modeline.py similarity index 100% rename from vendor/pygments/pygments/modeline.py rename to third_party/pygments/pygments/modeline.py diff --git a/vendor/pygments/pygments/plugin.py b/third_party/pygments/pygments/plugin.py similarity index 100% rename from vendor/pygments/pygments/plugin.py rename to third_party/pygments/pygments/plugin.py diff --git a/vendor/pygments/pygments/regexopt.py b/third_party/pygments/pygments/regexopt.py similarity index 100% rename from vendor/pygments/pygments/regexopt.py rename to third_party/pygments/pygments/regexopt.py diff --git a/vendor/pygments/pygments/scanner.py b/third_party/pygments/pygments/scanner.py similarity index 100% rename from vendor/pygments/pygments/scanner.py rename to third_party/pygments/pygments/scanner.py diff --git a/vendor/pygments/pygments/sphinxext.py b/third_party/pygments/pygments/sphinxext.py similarity index 100% rename from vendor/pygments/pygments/sphinxext.py rename to third_party/pygments/pygments/sphinxext.py diff --git a/vendor/pygments/pygments/style.py b/third_party/pygments/pygments/style.py similarity index 100% rename from vendor/pygments/pygments/style.py rename to third_party/pygments/pygments/style.py diff --git a/vendor/pygments/pygments/styles/__init__.py b/third_party/pygments/pygments/styles/__init__.py similarity index 100% rename from vendor/pygments/pygments/styles/__init__.py rename to third_party/pygments/pygments/styles/__init__.py diff --git a/vendor/pygments/pygments/styles/algol.py b/third_party/pygments/pygments/styles/algol.py similarity index 100% rename from vendor/pygments/pygments/styles/algol.py rename to third_party/pygments/pygments/styles/algol.py diff --git a/vendor/pygments/pygments/styles/algol_nu.py b/third_party/pygments/pygments/styles/algol_nu.py similarity index 100% rename from vendor/pygments/pygments/styles/algol_nu.py rename to third_party/pygments/pygments/styles/algol_nu.py diff --git a/vendor/pygments/pygments/styles/arduino.py b/third_party/pygments/pygments/styles/arduino.py similarity index 100% rename from vendor/pygments/pygments/styles/arduino.py rename to third_party/pygments/pygments/styles/arduino.py diff --git a/vendor/pygments/pygments/styles/autumn.py b/third_party/pygments/pygments/styles/autumn.py similarity index 100% rename from vendor/pygments/pygments/styles/autumn.py rename to third_party/pygments/pygments/styles/autumn.py diff --git a/vendor/pygments/pygments/styles/borland.py b/third_party/pygments/pygments/styles/borland.py similarity index 100% rename from vendor/pygments/pygments/styles/borland.py rename to third_party/pygments/pygments/styles/borland.py diff --git a/vendor/pygments/pygments/styles/bw.py b/third_party/pygments/pygments/styles/bw.py similarity index 100% rename from vendor/pygments/pygments/styles/bw.py rename to third_party/pygments/pygments/styles/bw.py diff --git a/vendor/pygments/pygments/styles/colorful.py b/third_party/pygments/pygments/styles/colorful.py similarity index 100% rename from vendor/pygments/pygments/styles/colorful.py rename to third_party/pygments/pygments/styles/colorful.py diff --git a/vendor/pygments/pygments/styles/default.py b/third_party/pygments/pygments/styles/default.py similarity index 100% rename from vendor/pygments/pygments/styles/default.py rename to third_party/pygments/pygments/styles/default.py diff --git a/vendor/pygments/pygments/styles/emacs.py b/third_party/pygments/pygments/styles/emacs.py similarity index 100% rename from vendor/pygments/pygments/styles/emacs.py rename to third_party/pygments/pygments/styles/emacs.py diff --git a/vendor/pygments/pygments/styles/friendly.py b/third_party/pygments/pygments/styles/friendly.py similarity index 100% rename from vendor/pygments/pygments/styles/friendly.py rename to third_party/pygments/pygments/styles/friendly.py diff --git a/vendor/pygments/pygments/styles/fruity.py b/third_party/pygments/pygments/styles/fruity.py similarity index 100% rename from vendor/pygments/pygments/styles/fruity.py rename to third_party/pygments/pygments/styles/fruity.py diff --git a/vendor/pygments/pygments/styles/igor.py b/third_party/pygments/pygments/styles/igor.py similarity index 100% rename from vendor/pygments/pygments/styles/igor.py rename to third_party/pygments/pygments/styles/igor.py diff --git a/vendor/pygments/pygments/styles/lovelace.py b/third_party/pygments/pygments/styles/lovelace.py similarity index 100% rename from vendor/pygments/pygments/styles/lovelace.py rename to third_party/pygments/pygments/styles/lovelace.py diff --git a/vendor/pygments/pygments/styles/manni.py b/third_party/pygments/pygments/styles/manni.py similarity index 100% rename from vendor/pygments/pygments/styles/manni.py rename to third_party/pygments/pygments/styles/manni.py diff --git a/vendor/pygments/pygments/styles/monokai.py b/third_party/pygments/pygments/styles/monokai.py similarity index 100% rename from vendor/pygments/pygments/styles/monokai.py rename to third_party/pygments/pygments/styles/monokai.py diff --git a/vendor/pygments/pygments/styles/murphy.py b/third_party/pygments/pygments/styles/murphy.py similarity index 100% rename from vendor/pygments/pygments/styles/murphy.py rename to third_party/pygments/pygments/styles/murphy.py diff --git a/vendor/pygments/pygments/styles/native.py b/third_party/pygments/pygments/styles/native.py similarity index 100% rename from vendor/pygments/pygments/styles/native.py rename to third_party/pygments/pygments/styles/native.py diff --git a/vendor/pygments/pygments/styles/paraiso_dark.py b/third_party/pygments/pygments/styles/paraiso_dark.py similarity index 100% rename from vendor/pygments/pygments/styles/paraiso_dark.py rename to third_party/pygments/pygments/styles/paraiso_dark.py diff --git a/vendor/pygments/pygments/styles/paraiso_light.py b/third_party/pygments/pygments/styles/paraiso_light.py similarity index 100% rename from vendor/pygments/pygments/styles/paraiso_light.py rename to third_party/pygments/pygments/styles/paraiso_light.py diff --git a/vendor/pygments/pygments/styles/pastie.py b/third_party/pygments/pygments/styles/pastie.py similarity index 100% rename from vendor/pygments/pygments/styles/pastie.py rename to third_party/pygments/pygments/styles/pastie.py diff --git a/vendor/pygments/pygments/styles/perldoc.py b/third_party/pygments/pygments/styles/perldoc.py similarity index 100% rename from vendor/pygments/pygments/styles/perldoc.py rename to third_party/pygments/pygments/styles/perldoc.py diff --git a/vendor/pygments/pygments/styles/rrt.py b/third_party/pygments/pygments/styles/rrt.py similarity index 100% rename from vendor/pygments/pygments/styles/rrt.py rename to third_party/pygments/pygments/styles/rrt.py diff --git a/vendor/pygments/pygments/styles/tango.py b/third_party/pygments/pygments/styles/tango.py similarity index 100% rename from vendor/pygments/pygments/styles/tango.py rename to third_party/pygments/pygments/styles/tango.py diff --git a/vendor/pygments/pygments/styles/trac.py b/third_party/pygments/pygments/styles/trac.py similarity index 100% rename from vendor/pygments/pygments/styles/trac.py rename to third_party/pygments/pygments/styles/trac.py diff --git a/vendor/pygments/pygments/styles/vim.py b/third_party/pygments/pygments/styles/vim.py similarity index 100% rename from vendor/pygments/pygments/styles/vim.py rename to third_party/pygments/pygments/styles/vim.py diff --git a/vendor/pygments/pygments/styles/vs.py b/third_party/pygments/pygments/styles/vs.py similarity index 100% rename from vendor/pygments/pygments/styles/vs.py rename to third_party/pygments/pygments/styles/vs.py diff --git a/vendor/pygments/pygments/styles/xcode.py b/third_party/pygments/pygments/styles/xcode.py similarity index 100% rename from vendor/pygments/pygments/styles/xcode.py rename to third_party/pygments/pygments/styles/xcode.py diff --git a/vendor/pygments/pygments/token.py b/third_party/pygments/pygments/token.py similarity index 100% rename from vendor/pygments/pygments/token.py rename to third_party/pygments/pygments/token.py diff --git a/vendor/pygments/pygments/unistring.py b/third_party/pygments/pygments/unistring.py similarity index 100% rename from vendor/pygments/pygments/unistring.py rename to third_party/pygments/pygments/unistring.py diff --git a/vendor/pygments/pygments/util.py b/third_party/pygments/pygments/util.py similarity index 100% rename from vendor/pygments/pygments/util.py rename to third_party/pygments/pygments/util.py diff --git a/vendor/pygments/requirements.txt b/third_party/pygments/requirements.txt similarity index 100% rename from vendor/pygments/requirements.txt rename to third_party/pygments/requirements.txt diff --git a/vendor/pygments/scripts/check_sources.py b/third_party/pygments/scripts/check_sources.py similarity index 100% rename from vendor/pygments/scripts/check_sources.py rename to third_party/pygments/scripts/check_sources.py diff --git a/vendor/pygments/scripts/debug_lexer.py b/third_party/pygments/scripts/debug_lexer.py similarity index 100% rename from vendor/pygments/scripts/debug_lexer.py rename to third_party/pygments/scripts/debug_lexer.py diff --git a/vendor/pygments/scripts/detect_missing_analyse_text.py b/third_party/pygments/scripts/detect_missing_analyse_text.py similarity index 100% rename from vendor/pygments/scripts/detect_missing_analyse_text.py rename to third_party/pygments/scripts/detect_missing_analyse_text.py diff --git a/vendor/pygments/scripts/epydoc.css b/third_party/pygments/scripts/epydoc.css similarity index 100% rename from vendor/pygments/scripts/epydoc.css rename to third_party/pygments/scripts/epydoc.css diff --git a/vendor/pygments/scripts/find_error.py b/third_party/pygments/scripts/find_error.py similarity index 100% rename from vendor/pygments/scripts/find_error.py rename to third_party/pygments/scripts/find_error.py diff --git a/vendor/pygments/scripts/get_vimkw.py b/third_party/pygments/scripts/get_vimkw.py similarity index 100% rename from vendor/pygments/scripts/get_vimkw.py rename to third_party/pygments/scripts/get_vimkw.py diff --git a/vendor/pygments/scripts/pylintrc b/third_party/pygments/scripts/pylintrc similarity index 100% rename from vendor/pygments/scripts/pylintrc rename to third_party/pygments/scripts/pylintrc diff --git a/vendor/pygments/scripts/vim2pygments.py b/third_party/pygments/scripts/vim2pygments.py similarity index 100% rename from vendor/pygments/scripts/vim2pygments.py rename to third_party/pygments/scripts/vim2pygments.py diff --git a/vendor/pygments/setup.cfg b/third_party/pygments/setup.cfg similarity index 100% rename from vendor/pygments/setup.cfg rename to third_party/pygments/setup.cfg diff --git a/vendor/pygments/setup.py b/third_party/pygments/setup.py similarity index 100% rename from vendor/pygments/setup.py rename to third_party/pygments/setup.py diff --git a/vendor/pygments/tests/.coverage b/third_party/pygments/tests/.coverage similarity index 100% rename from vendor/pygments/tests/.coverage rename to third_party/pygments/tests/.coverage diff --git a/vendor/pygments/tests/cover/coverage_html.js b/third_party/pygments/tests/cover/coverage_html.js similarity index 100% rename from vendor/pygments/tests/cover/coverage_html.js rename to third_party/pygments/tests/cover/coverage_html.js diff --git a/vendor/pygments/tests/cover/jquery.hotkeys.js b/third_party/pygments/tests/cover/jquery.hotkeys.js similarity index 100% rename from vendor/pygments/tests/cover/jquery.hotkeys.js rename to third_party/pygments/tests/cover/jquery.hotkeys.js diff --git a/vendor/pygments/tests/cover/jquery.isonscreen.js b/third_party/pygments/tests/cover/jquery.isonscreen.js similarity index 100% rename from vendor/pygments/tests/cover/jquery.isonscreen.js rename to third_party/pygments/tests/cover/jquery.isonscreen.js diff --git a/vendor/pygments/tests/cover/jquery.min.js b/third_party/pygments/tests/cover/jquery.min.js similarity index 100% rename from vendor/pygments/tests/cover/jquery.min.js rename to third_party/pygments/tests/cover/jquery.min.js diff --git a/vendor/pygments/tests/cover/jquery.tablesorter.min.js b/third_party/pygments/tests/cover/jquery.tablesorter.min.js similarity index 100% rename from vendor/pygments/tests/cover/jquery.tablesorter.min.js rename to third_party/pygments/tests/cover/jquery.tablesorter.min.js diff --git a/vendor/pygments/tests/cover/keybd_closed.png b/third_party/pygments/tests/cover/keybd_closed.png similarity index 100% rename from vendor/pygments/tests/cover/keybd_closed.png rename to third_party/pygments/tests/cover/keybd_closed.png diff --git a/vendor/pygments/tests/cover/keybd_open.png b/third_party/pygments/tests/cover/keybd_open.png similarity index 100% rename from vendor/pygments/tests/cover/keybd_open.png rename to third_party/pygments/tests/cover/keybd_open.png diff --git a/vendor/pygments/tests/cover/status.dat b/third_party/pygments/tests/cover/status.dat similarity index 100% rename from vendor/pygments/tests/cover/status.dat rename to third_party/pygments/tests/cover/status.dat diff --git a/vendor/pygments/tests/cover/style.css b/third_party/pygments/tests/cover/style.css similarity index 100% rename from vendor/pygments/tests/cover/style.css rename to third_party/pygments/tests/cover/style.css diff --git a/vendor/pygments/tests/dtds/HTML4-f.dtd b/third_party/pygments/tests/dtds/HTML4-f.dtd similarity index 100% rename from vendor/pygments/tests/dtds/HTML4-f.dtd rename to third_party/pygments/tests/dtds/HTML4-f.dtd diff --git a/vendor/pygments/tests/dtds/HTML4-s.dtd b/third_party/pygments/tests/dtds/HTML4-s.dtd similarity index 100% rename from vendor/pygments/tests/dtds/HTML4-s.dtd rename to third_party/pygments/tests/dtds/HTML4-s.dtd diff --git a/vendor/pygments/tests/dtds/HTML4.dcl b/third_party/pygments/tests/dtds/HTML4.dcl similarity index 100% rename from vendor/pygments/tests/dtds/HTML4.dcl rename to third_party/pygments/tests/dtds/HTML4.dcl diff --git a/vendor/pygments/tests/dtds/HTML4.dtd b/third_party/pygments/tests/dtds/HTML4.dtd similarity index 100% rename from vendor/pygments/tests/dtds/HTML4.dtd rename to third_party/pygments/tests/dtds/HTML4.dtd diff --git a/vendor/pygments/tests/dtds/HTML4.soc b/third_party/pygments/tests/dtds/HTML4.soc similarity index 100% rename from vendor/pygments/tests/dtds/HTML4.soc rename to third_party/pygments/tests/dtds/HTML4.soc diff --git a/vendor/pygments/tests/dtds/HTMLlat1.ent b/third_party/pygments/tests/dtds/HTMLlat1.ent similarity index 100% rename from vendor/pygments/tests/dtds/HTMLlat1.ent rename to third_party/pygments/tests/dtds/HTMLlat1.ent diff --git a/vendor/pygments/tests/dtds/HTMLspec.ent b/third_party/pygments/tests/dtds/HTMLspec.ent similarity index 100% rename from vendor/pygments/tests/dtds/HTMLspec.ent rename to third_party/pygments/tests/dtds/HTMLspec.ent diff --git a/vendor/pygments/tests/dtds/HTMLsym.ent b/third_party/pygments/tests/dtds/HTMLsym.ent similarity index 100% rename from vendor/pygments/tests/dtds/HTMLsym.ent rename to third_party/pygments/tests/dtds/HTMLsym.ent diff --git a/vendor/pygments/tests/examplefiles/99_bottles_of_beer.chpl b/third_party/pygments/tests/examplefiles/99_bottles_of_beer.chpl similarity index 100% rename from vendor/pygments/tests/examplefiles/99_bottles_of_beer.chpl rename to third_party/pygments/tests/examplefiles/99_bottles_of_beer.chpl diff --git a/vendor/pygments/tests/examplefiles/AcidStateAdvanced.hs b/third_party/pygments/tests/examplefiles/AcidStateAdvanced.hs similarity index 100% rename from vendor/pygments/tests/examplefiles/AcidStateAdvanced.hs rename to third_party/pygments/tests/examplefiles/AcidStateAdvanced.hs diff --git a/vendor/pygments/tests/examplefiles/AlternatingGroup.mu b/third_party/pygments/tests/examplefiles/AlternatingGroup.mu similarity index 100% rename from vendor/pygments/tests/examplefiles/AlternatingGroup.mu rename to third_party/pygments/tests/examplefiles/AlternatingGroup.mu diff --git a/vendor/pygments/tests/examplefiles/BOM.js b/third_party/pygments/tests/examplefiles/BOM.js similarity index 100% rename from vendor/pygments/tests/examplefiles/BOM.js rename to third_party/pygments/tests/examplefiles/BOM.js diff --git a/vendor/pygments/tests/examplefiles/Blink.ino b/third_party/pygments/tests/examplefiles/Blink.ino similarity index 100% rename from vendor/pygments/tests/examplefiles/Blink.ino rename to third_party/pygments/tests/examplefiles/Blink.ino diff --git a/vendor/pygments/tests/examplefiles/CPDictionary.j b/third_party/pygments/tests/examplefiles/CPDictionary.j similarity index 100% rename from vendor/pygments/tests/examplefiles/CPDictionary.j rename to third_party/pygments/tests/examplefiles/CPDictionary.j diff --git a/vendor/pygments/tests/examplefiles/Config.in.cache b/third_party/pygments/tests/examplefiles/Config.in.cache similarity index 100% rename from vendor/pygments/tests/examplefiles/Config.in.cache rename to third_party/pygments/tests/examplefiles/Config.in.cache diff --git a/vendor/pygments/tests/examplefiles/Constants.mo b/third_party/pygments/tests/examplefiles/Constants.mo similarity index 100% rename from vendor/pygments/tests/examplefiles/Constants.mo rename to third_party/pygments/tests/examplefiles/Constants.mo diff --git a/vendor/pygments/tests/examplefiles/DancingSudoku.lhs b/third_party/pygments/tests/examplefiles/DancingSudoku.lhs similarity index 100% rename from vendor/pygments/tests/examplefiles/DancingSudoku.lhs rename to third_party/pygments/tests/examplefiles/DancingSudoku.lhs diff --git a/vendor/pygments/tests/examplefiles/Deflate.fs b/third_party/pygments/tests/examplefiles/Deflate.fs similarity index 100% rename from vendor/pygments/tests/examplefiles/Deflate.fs rename to third_party/pygments/tests/examplefiles/Deflate.fs diff --git a/vendor/pygments/tests/examplefiles/Error.pmod b/third_party/pygments/tests/examplefiles/Error.pmod similarity index 100% rename from vendor/pygments/tests/examplefiles/Error.pmod rename to third_party/pygments/tests/examplefiles/Error.pmod diff --git a/vendor/pygments/tests/examplefiles/Errors.scala b/third_party/pygments/tests/examplefiles/Errors.scala similarity index 100% rename from vendor/pygments/tests/examplefiles/Errors.scala rename to third_party/pygments/tests/examplefiles/Errors.scala diff --git a/vendor/pygments/tests/examplefiles/FakeFile.pike b/third_party/pygments/tests/examplefiles/FakeFile.pike similarity index 100% rename from vendor/pygments/tests/examplefiles/FakeFile.pike rename to third_party/pygments/tests/examplefiles/FakeFile.pike diff --git a/vendor/pygments/tests/examplefiles/Get-CommandDefinitionHtml.ps1 b/third_party/pygments/tests/examplefiles/Get-CommandDefinitionHtml.ps1 similarity index 100% rename from vendor/pygments/tests/examplefiles/Get-CommandDefinitionHtml.ps1 rename to third_party/pygments/tests/examplefiles/Get-CommandDefinitionHtml.ps1 diff --git a/vendor/pygments/tests/examplefiles/IPDispatchC.nc b/third_party/pygments/tests/examplefiles/IPDispatchC.nc similarity index 100% rename from vendor/pygments/tests/examplefiles/IPDispatchC.nc rename to third_party/pygments/tests/examplefiles/IPDispatchC.nc diff --git a/vendor/pygments/tests/examplefiles/IPDispatchP.nc b/third_party/pygments/tests/examplefiles/IPDispatchP.nc similarity index 100% rename from vendor/pygments/tests/examplefiles/IPDispatchP.nc rename to third_party/pygments/tests/examplefiles/IPDispatchP.nc diff --git a/vendor/pygments/tests/examplefiles/Intro.java b/third_party/pygments/tests/examplefiles/Intro.java similarity index 100% rename from vendor/pygments/tests/examplefiles/Intro.java rename to third_party/pygments/tests/examplefiles/Intro.java diff --git a/vendor/pygments/tests/examplefiles/Makefile b/third_party/pygments/tests/examplefiles/Makefile similarity index 100% rename from vendor/pygments/tests/examplefiles/Makefile rename to third_party/pygments/tests/examplefiles/Makefile diff --git a/vendor/pygments/tests/examplefiles/Object.st b/third_party/pygments/tests/examplefiles/Object.st similarity index 100% rename from vendor/pygments/tests/examplefiles/Object.st rename to third_party/pygments/tests/examplefiles/Object.st diff --git a/vendor/pygments/tests/examplefiles/OrderedMap.hx b/third_party/pygments/tests/examplefiles/OrderedMap.hx similarity index 100% rename from vendor/pygments/tests/examplefiles/OrderedMap.hx rename to third_party/pygments/tests/examplefiles/OrderedMap.hx diff --git a/vendor/pygments/tests/examplefiles/RoleQ.pm6 b/third_party/pygments/tests/examplefiles/RoleQ.pm6 similarity index 100% rename from vendor/pygments/tests/examplefiles/RoleQ.pm6 rename to third_party/pygments/tests/examplefiles/RoleQ.pm6 diff --git a/vendor/pygments/tests/examplefiles/SmallCheck.hs b/third_party/pygments/tests/examplefiles/SmallCheck.hs similarity index 100% rename from vendor/pygments/tests/examplefiles/SmallCheck.hs rename to third_party/pygments/tests/examplefiles/SmallCheck.hs diff --git a/vendor/pygments/tests/examplefiles/Sorting.mod b/third_party/pygments/tests/examplefiles/Sorting.mod similarity index 100% rename from vendor/pygments/tests/examplefiles/Sorting.mod rename to third_party/pygments/tests/examplefiles/Sorting.mod diff --git a/vendor/pygments/tests/examplefiles/Sudoku.lhs b/third_party/pygments/tests/examplefiles/Sudoku.lhs similarity index 100% rename from vendor/pygments/tests/examplefiles/Sudoku.lhs rename to third_party/pygments/tests/examplefiles/Sudoku.lhs diff --git a/vendor/pygments/tests/examplefiles/abnf_example1.abnf b/third_party/pygments/tests/examplefiles/abnf_example1.abnf similarity index 100% rename from vendor/pygments/tests/examplefiles/abnf_example1.abnf rename to third_party/pygments/tests/examplefiles/abnf_example1.abnf diff --git a/vendor/pygments/tests/examplefiles/abnf_example2.abnf b/third_party/pygments/tests/examplefiles/abnf_example2.abnf similarity index 100% rename from vendor/pygments/tests/examplefiles/abnf_example2.abnf rename to third_party/pygments/tests/examplefiles/abnf_example2.abnf diff --git a/vendor/pygments/tests/examplefiles/addressbook.proto b/third_party/pygments/tests/examplefiles/addressbook.proto similarity index 100% rename from vendor/pygments/tests/examplefiles/addressbook.proto rename to third_party/pygments/tests/examplefiles/addressbook.proto diff --git a/vendor/pygments/tests/examplefiles/ahcon.f b/third_party/pygments/tests/examplefiles/ahcon.f similarity index 100% rename from vendor/pygments/tests/examplefiles/ahcon.f rename to third_party/pygments/tests/examplefiles/ahcon.f diff --git a/vendor/pygments/tests/examplefiles/all.nit b/third_party/pygments/tests/examplefiles/all.nit similarity index 100% rename from vendor/pygments/tests/examplefiles/all.nit rename to third_party/pygments/tests/examplefiles/all.nit diff --git a/vendor/pygments/tests/examplefiles/antlr_ANTLRv3.g b/third_party/pygments/tests/examplefiles/antlr_ANTLRv3.g similarity index 100% rename from vendor/pygments/tests/examplefiles/antlr_ANTLRv3.g rename to third_party/pygments/tests/examplefiles/antlr_ANTLRv3.g diff --git a/vendor/pygments/tests/examplefiles/antlr_throws b/third_party/pygments/tests/examplefiles/antlr_throws similarity index 100% rename from vendor/pygments/tests/examplefiles/antlr_throws rename to third_party/pygments/tests/examplefiles/antlr_throws diff --git a/vendor/pygments/tests/examplefiles/apache2.conf b/third_party/pygments/tests/examplefiles/apache2.conf similarity index 100% rename from vendor/pygments/tests/examplefiles/apache2.conf rename to third_party/pygments/tests/examplefiles/apache2.conf diff --git a/vendor/pygments/tests/examplefiles/as3_test.as b/third_party/pygments/tests/examplefiles/as3_test.as similarity index 100% rename from vendor/pygments/tests/examplefiles/as3_test.as rename to third_party/pygments/tests/examplefiles/as3_test.as diff --git a/vendor/pygments/tests/examplefiles/as3_test2.as b/third_party/pygments/tests/examplefiles/as3_test2.as similarity index 100% rename from vendor/pygments/tests/examplefiles/as3_test2.as rename to third_party/pygments/tests/examplefiles/as3_test2.as diff --git a/vendor/pygments/tests/examplefiles/as3_test3.as b/third_party/pygments/tests/examplefiles/as3_test3.as similarity index 100% rename from vendor/pygments/tests/examplefiles/as3_test3.as rename to third_party/pygments/tests/examplefiles/as3_test3.as diff --git a/vendor/pygments/tests/examplefiles/aspx-cs_example b/third_party/pygments/tests/examplefiles/aspx-cs_example similarity index 100% rename from vendor/pygments/tests/examplefiles/aspx-cs_example rename to third_party/pygments/tests/examplefiles/aspx-cs_example diff --git a/vendor/pygments/tests/examplefiles/autoit_submit.au3 b/third_party/pygments/tests/examplefiles/autoit_submit.au3 similarity index 100% rename from vendor/pygments/tests/examplefiles/autoit_submit.au3 rename to third_party/pygments/tests/examplefiles/autoit_submit.au3 diff --git a/vendor/pygments/tests/examplefiles/automake.mk b/third_party/pygments/tests/examplefiles/automake.mk similarity index 100% rename from vendor/pygments/tests/examplefiles/automake.mk rename to third_party/pygments/tests/examplefiles/automake.mk diff --git a/vendor/pygments/tests/examplefiles/badcase.java b/third_party/pygments/tests/examplefiles/badcase.java similarity index 100% rename from vendor/pygments/tests/examplefiles/badcase.java rename to third_party/pygments/tests/examplefiles/badcase.java diff --git a/vendor/pygments/tests/examplefiles/bigtest.nsi b/third_party/pygments/tests/examplefiles/bigtest.nsi similarity index 100% rename from vendor/pygments/tests/examplefiles/bigtest.nsi rename to third_party/pygments/tests/examplefiles/bigtest.nsi diff --git a/vendor/pygments/tests/examplefiles/bnf_example1.bnf b/third_party/pygments/tests/examplefiles/bnf_example1.bnf similarity index 100% rename from vendor/pygments/tests/examplefiles/bnf_example1.bnf rename to third_party/pygments/tests/examplefiles/bnf_example1.bnf diff --git a/vendor/pygments/tests/examplefiles/boot-9.scm b/third_party/pygments/tests/examplefiles/boot-9.scm similarity index 100% rename from vendor/pygments/tests/examplefiles/boot-9.scm rename to third_party/pygments/tests/examplefiles/boot-9.scm diff --git a/vendor/pygments/tests/examplefiles/ca65_example b/third_party/pygments/tests/examplefiles/ca65_example similarity index 100% rename from vendor/pygments/tests/examplefiles/ca65_example rename to third_party/pygments/tests/examplefiles/ca65_example diff --git a/vendor/pygments/tests/examplefiles/cbmbas_example b/third_party/pygments/tests/examplefiles/cbmbas_example similarity index 100% rename from vendor/pygments/tests/examplefiles/cbmbas_example rename to third_party/pygments/tests/examplefiles/cbmbas_example diff --git a/vendor/pygments/tests/examplefiles/cells.ps b/third_party/pygments/tests/examplefiles/cells.ps similarity index 100% rename from vendor/pygments/tests/examplefiles/cells.ps rename to third_party/pygments/tests/examplefiles/cells.ps diff --git a/vendor/pygments/tests/examplefiles/ceval.c b/third_party/pygments/tests/examplefiles/ceval.c similarity index 100% rename from vendor/pygments/tests/examplefiles/ceval.c rename to third_party/pygments/tests/examplefiles/ceval.c diff --git a/vendor/pygments/tests/examplefiles/char.scala b/third_party/pygments/tests/examplefiles/char.scala similarity index 100% rename from vendor/pygments/tests/examplefiles/char.scala rename to third_party/pygments/tests/examplefiles/char.scala diff --git a/vendor/pygments/tests/examplefiles/cheetah_example.html b/third_party/pygments/tests/examplefiles/cheetah_example.html similarity index 100% rename from vendor/pygments/tests/examplefiles/cheetah_example.html rename to third_party/pygments/tests/examplefiles/cheetah_example.html diff --git a/vendor/pygments/tests/examplefiles/classes.dylan b/third_party/pygments/tests/examplefiles/classes.dylan similarity index 100% rename from vendor/pygments/tests/examplefiles/classes.dylan rename to third_party/pygments/tests/examplefiles/classes.dylan diff --git a/vendor/pygments/tests/examplefiles/clojure-weird-keywords.clj b/third_party/pygments/tests/examplefiles/clojure-weird-keywords.clj similarity index 100% rename from vendor/pygments/tests/examplefiles/clojure-weird-keywords.clj rename to third_party/pygments/tests/examplefiles/clojure-weird-keywords.clj diff --git a/vendor/pygments/tests/examplefiles/condensed_ruby.rb b/third_party/pygments/tests/examplefiles/condensed_ruby.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/condensed_ruby.rb rename to third_party/pygments/tests/examplefiles/condensed_ruby.rb diff --git a/vendor/pygments/tests/examplefiles/coq_RelationClasses b/third_party/pygments/tests/examplefiles/coq_RelationClasses similarity index 100% rename from vendor/pygments/tests/examplefiles/coq_RelationClasses rename to third_party/pygments/tests/examplefiles/coq_RelationClasses diff --git a/vendor/pygments/tests/examplefiles/core.cljs b/third_party/pygments/tests/examplefiles/core.cljs similarity index 100% rename from vendor/pygments/tests/examplefiles/core.cljs rename to third_party/pygments/tests/examplefiles/core.cljs diff --git a/vendor/pygments/tests/examplefiles/database.pytb b/third_party/pygments/tests/examplefiles/database.pytb similarity index 100% rename from vendor/pygments/tests/examplefiles/database.pytb rename to third_party/pygments/tests/examplefiles/database.pytb diff --git a/vendor/pygments/tests/examplefiles/de.MoinMoin.po b/third_party/pygments/tests/examplefiles/de.MoinMoin.po similarity index 100% rename from vendor/pygments/tests/examplefiles/de.MoinMoin.po rename to third_party/pygments/tests/examplefiles/de.MoinMoin.po diff --git a/vendor/pygments/tests/examplefiles/demo.ahk b/third_party/pygments/tests/examplefiles/demo.ahk similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.ahk rename to third_party/pygments/tests/examplefiles/demo.ahk diff --git a/vendor/pygments/tests/examplefiles/demo.cfm b/third_party/pygments/tests/examplefiles/demo.cfm similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.cfm rename to third_party/pygments/tests/examplefiles/demo.cfm diff --git a/vendor/pygments/tests/examplefiles/demo.css.in b/third_party/pygments/tests/examplefiles/demo.css.in similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.css.in rename to third_party/pygments/tests/examplefiles/demo.css.in diff --git a/vendor/pygments/tests/examplefiles/demo.hbs b/third_party/pygments/tests/examplefiles/demo.hbs similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.hbs rename to third_party/pygments/tests/examplefiles/demo.hbs diff --git a/vendor/pygments/tests/examplefiles/demo.js.in b/third_party/pygments/tests/examplefiles/demo.js.in similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.js.in rename to third_party/pygments/tests/examplefiles/demo.js.in diff --git a/vendor/pygments/tests/examplefiles/demo.thrift b/third_party/pygments/tests/examplefiles/demo.thrift similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.thrift rename to third_party/pygments/tests/examplefiles/demo.thrift diff --git a/vendor/pygments/tests/examplefiles/demo.xul.in b/third_party/pygments/tests/examplefiles/demo.xul.in similarity index 100% rename from vendor/pygments/tests/examplefiles/demo.xul.in rename to third_party/pygments/tests/examplefiles/demo.xul.in diff --git a/vendor/pygments/tests/examplefiles/django_sample.html+django b/third_party/pygments/tests/examplefiles/django_sample.html+django similarity index 100% rename from vendor/pygments/tests/examplefiles/django_sample.html+django rename to third_party/pygments/tests/examplefiles/django_sample.html+django diff --git a/vendor/pygments/tests/examplefiles/docker.docker b/third_party/pygments/tests/examplefiles/docker.docker similarity index 100% rename from vendor/pygments/tests/examplefiles/docker.docker rename to third_party/pygments/tests/examplefiles/docker.docker diff --git a/vendor/pygments/tests/examplefiles/dwarf.cw b/third_party/pygments/tests/examplefiles/dwarf.cw similarity index 100% rename from vendor/pygments/tests/examplefiles/dwarf.cw rename to third_party/pygments/tests/examplefiles/dwarf.cw diff --git a/vendor/pygments/tests/examplefiles/eg_example1.eg b/third_party/pygments/tests/examplefiles/eg_example1.eg similarity index 100% rename from vendor/pygments/tests/examplefiles/eg_example1.eg rename to third_party/pygments/tests/examplefiles/eg_example1.eg diff --git a/vendor/pygments/tests/examplefiles/ember.handlebars b/third_party/pygments/tests/examplefiles/ember.handlebars similarity index 100% rename from vendor/pygments/tests/examplefiles/ember.handlebars rename to third_party/pygments/tests/examplefiles/ember.handlebars diff --git a/vendor/pygments/tests/examplefiles/erl_session b/third_party/pygments/tests/examplefiles/erl_session similarity index 100% rename from vendor/pygments/tests/examplefiles/erl_session rename to third_party/pygments/tests/examplefiles/erl_session diff --git a/vendor/pygments/tests/examplefiles/es6.js b/third_party/pygments/tests/examplefiles/es6.js similarity index 100% rename from vendor/pygments/tests/examplefiles/es6.js rename to third_party/pygments/tests/examplefiles/es6.js diff --git a/vendor/pygments/tests/examplefiles/escape_semicolon.clj b/third_party/pygments/tests/examplefiles/escape_semicolon.clj similarity index 100% rename from vendor/pygments/tests/examplefiles/escape_semicolon.clj rename to third_party/pygments/tests/examplefiles/escape_semicolon.clj diff --git a/vendor/pygments/tests/examplefiles/eval.rs b/third_party/pygments/tests/examplefiles/eval.rs similarity index 100% rename from vendor/pygments/tests/examplefiles/eval.rs rename to third_party/pygments/tests/examplefiles/eval.rs diff --git a/vendor/pygments/tests/examplefiles/evil_regex.js b/third_party/pygments/tests/examplefiles/evil_regex.js similarity index 100% rename from vendor/pygments/tests/examplefiles/evil_regex.js rename to third_party/pygments/tests/examplefiles/evil_regex.js diff --git a/vendor/pygments/tests/examplefiles/example.Rd b/third_party/pygments/tests/examplefiles/example.Rd similarity index 100% rename from vendor/pygments/tests/examplefiles/example.Rd rename to third_party/pygments/tests/examplefiles/example.Rd diff --git a/vendor/pygments/tests/examplefiles/example.als b/third_party/pygments/tests/examplefiles/example.als similarity index 100% rename from vendor/pygments/tests/examplefiles/example.als rename to third_party/pygments/tests/examplefiles/example.als diff --git a/vendor/pygments/tests/examplefiles/example.bat b/third_party/pygments/tests/examplefiles/example.bat similarity index 100% rename from vendor/pygments/tests/examplefiles/example.bat rename to third_party/pygments/tests/examplefiles/example.bat diff --git a/vendor/pygments/tests/examplefiles/example.bc b/third_party/pygments/tests/examplefiles/example.bc similarity index 100% rename from vendor/pygments/tests/examplefiles/example.bc rename to third_party/pygments/tests/examplefiles/example.bc diff --git a/vendor/pygments/tests/examplefiles/example.bug b/third_party/pygments/tests/examplefiles/example.bug similarity index 100% rename from vendor/pygments/tests/examplefiles/example.bug rename to third_party/pygments/tests/examplefiles/example.bug diff --git a/vendor/pygments/tests/examplefiles/example.c b/third_party/pygments/tests/examplefiles/example.c similarity index 100% rename from vendor/pygments/tests/examplefiles/example.c rename to third_party/pygments/tests/examplefiles/example.c diff --git a/vendor/pygments/tests/examplefiles/example.ceylon b/third_party/pygments/tests/examplefiles/example.ceylon similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ceylon rename to third_party/pygments/tests/examplefiles/example.ceylon diff --git a/vendor/pygments/tests/examplefiles/example.chai b/third_party/pygments/tests/examplefiles/example.chai similarity index 100% rename from vendor/pygments/tests/examplefiles/example.chai rename to third_party/pygments/tests/examplefiles/example.chai diff --git a/vendor/pygments/tests/examplefiles/example.clay b/third_party/pygments/tests/examplefiles/example.clay similarity index 100% rename from vendor/pygments/tests/examplefiles/example.clay rename to third_party/pygments/tests/examplefiles/example.clay diff --git a/vendor/pygments/tests/examplefiles/example.cls b/third_party/pygments/tests/examplefiles/example.cls similarity index 100% rename from vendor/pygments/tests/examplefiles/example.cls rename to third_party/pygments/tests/examplefiles/example.cls diff --git a/vendor/pygments/tests/examplefiles/example.cob b/third_party/pygments/tests/examplefiles/example.cob similarity index 100% rename from vendor/pygments/tests/examplefiles/example.cob rename to third_party/pygments/tests/examplefiles/example.cob diff --git a/vendor/pygments/tests/examplefiles/example.coffee b/third_party/pygments/tests/examplefiles/example.coffee similarity index 100% rename from vendor/pygments/tests/examplefiles/example.coffee rename to third_party/pygments/tests/examplefiles/example.coffee diff --git a/vendor/pygments/tests/examplefiles/example.cpp b/third_party/pygments/tests/examplefiles/example.cpp similarity index 100% rename from vendor/pygments/tests/examplefiles/example.cpp rename to third_party/pygments/tests/examplefiles/example.cpp diff --git a/vendor/pygments/tests/examplefiles/example.e b/third_party/pygments/tests/examplefiles/example.e similarity index 100% rename from vendor/pygments/tests/examplefiles/example.e rename to third_party/pygments/tests/examplefiles/example.e diff --git a/vendor/pygments/tests/examplefiles/example.elm b/third_party/pygments/tests/examplefiles/example.elm similarity index 100% rename from vendor/pygments/tests/examplefiles/example.elm rename to third_party/pygments/tests/examplefiles/example.elm diff --git a/vendor/pygments/tests/examplefiles/example.ezt b/third_party/pygments/tests/examplefiles/example.ezt similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ezt rename to third_party/pygments/tests/examplefiles/example.ezt diff --git a/vendor/pygments/tests/examplefiles/example.f90 b/third_party/pygments/tests/examplefiles/example.f90 similarity index 100% rename from vendor/pygments/tests/examplefiles/example.f90 rename to third_party/pygments/tests/examplefiles/example.f90 diff --git a/vendor/pygments/tests/examplefiles/example.feature b/third_party/pygments/tests/examplefiles/example.feature similarity index 100% rename from vendor/pygments/tests/examplefiles/example.feature rename to third_party/pygments/tests/examplefiles/example.feature diff --git a/vendor/pygments/tests/examplefiles/example.fish b/third_party/pygments/tests/examplefiles/example.fish similarity index 100% rename from vendor/pygments/tests/examplefiles/example.fish rename to third_party/pygments/tests/examplefiles/example.fish diff --git a/vendor/pygments/tests/examplefiles/example.gd b/third_party/pygments/tests/examplefiles/example.gd similarity index 100% rename from vendor/pygments/tests/examplefiles/example.gd rename to third_party/pygments/tests/examplefiles/example.gd diff --git a/vendor/pygments/tests/examplefiles/example.gi b/third_party/pygments/tests/examplefiles/example.gi similarity index 100% rename from vendor/pygments/tests/examplefiles/example.gi rename to third_party/pygments/tests/examplefiles/example.gi diff --git a/vendor/pygments/tests/examplefiles/example.golo b/third_party/pygments/tests/examplefiles/example.golo similarity index 100% rename from vendor/pygments/tests/examplefiles/example.golo rename to third_party/pygments/tests/examplefiles/example.golo diff --git a/vendor/pygments/tests/examplefiles/example.groovy b/third_party/pygments/tests/examplefiles/example.groovy similarity index 100% rename from vendor/pygments/tests/examplefiles/example.groovy rename to third_party/pygments/tests/examplefiles/example.groovy diff --git a/vendor/pygments/tests/examplefiles/example.gs b/third_party/pygments/tests/examplefiles/example.gs similarity index 100% rename from vendor/pygments/tests/examplefiles/example.gs rename to third_party/pygments/tests/examplefiles/example.gs diff --git a/vendor/pygments/tests/examplefiles/example.gst b/third_party/pygments/tests/examplefiles/example.gst similarity index 100% rename from vendor/pygments/tests/examplefiles/example.gst rename to third_party/pygments/tests/examplefiles/example.gst diff --git a/vendor/pygments/tests/examplefiles/example.hs b/third_party/pygments/tests/examplefiles/example.hs similarity index 100% rename from vendor/pygments/tests/examplefiles/example.hs rename to third_party/pygments/tests/examplefiles/example.hs diff --git a/vendor/pygments/tests/examplefiles/example.hx b/third_party/pygments/tests/examplefiles/example.hx similarity index 100% rename from vendor/pygments/tests/examplefiles/example.hx rename to third_party/pygments/tests/examplefiles/example.hx diff --git a/vendor/pygments/tests/examplefiles/example.i6t b/third_party/pygments/tests/examplefiles/example.i6t similarity index 100% rename from vendor/pygments/tests/examplefiles/example.i6t rename to third_party/pygments/tests/examplefiles/example.i6t diff --git a/vendor/pygments/tests/examplefiles/example.i7x b/third_party/pygments/tests/examplefiles/example.i7x similarity index 100% rename from vendor/pygments/tests/examplefiles/example.i7x rename to third_party/pygments/tests/examplefiles/example.i7x diff --git a/vendor/pygments/tests/examplefiles/example.j b/third_party/pygments/tests/examplefiles/example.j similarity index 100% rename from vendor/pygments/tests/examplefiles/example.j rename to third_party/pygments/tests/examplefiles/example.j diff --git a/vendor/pygments/tests/examplefiles/example.jag b/third_party/pygments/tests/examplefiles/example.jag similarity index 100% rename from vendor/pygments/tests/examplefiles/example.jag rename to third_party/pygments/tests/examplefiles/example.jag diff --git a/vendor/pygments/tests/examplefiles/example.java b/third_party/pygments/tests/examplefiles/example.java similarity index 100% rename from vendor/pygments/tests/examplefiles/example.java rename to third_party/pygments/tests/examplefiles/example.java diff --git a/vendor/pygments/tests/examplefiles/example.jcl b/third_party/pygments/tests/examplefiles/example.jcl similarity index 100% rename from vendor/pygments/tests/examplefiles/example.jcl rename to third_party/pygments/tests/examplefiles/example.jcl diff --git a/vendor/pygments/tests/examplefiles/example.jsonld b/third_party/pygments/tests/examplefiles/example.jsonld similarity index 100% rename from vendor/pygments/tests/examplefiles/example.jsonld rename to third_party/pygments/tests/examplefiles/example.jsonld diff --git a/vendor/pygments/tests/examplefiles/example.kal b/third_party/pygments/tests/examplefiles/example.kal similarity index 100% rename from vendor/pygments/tests/examplefiles/example.kal rename to third_party/pygments/tests/examplefiles/example.kal diff --git a/vendor/pygments/tests/examplefiles/example.kt b/third_party/pygments/tests/examplefiles/example.kt similarity index 100% rename from vendor/pygments/tests/examplefiles/example.kt rename to third_party/pygments/tests/examplefiles/example.kt diff --git a/vendor/pygments/tests/examplefiles/example.lagda b/third_party/pygments/tests/examplefiles/example.lagda similarity index 100% rename from vendor/pygments/tests/examplefiles/example.lagda rename to third_party/pygments/tests/examplefiles/example.lagda diff --git a/vendor/pygments/tests/examplefiles/example.liquid b/third_party/pygments/tests/examplefiles/example.liquid similarity index 100% rename from vendor/pygments/tests/examplefiles/example.liquid rename to third_party/pygments/tests/examplefiles/example.liquid diff --git a/vendor/pygments/tests/examplefiles/example.lua b/third_party/pygments/tests/examplefiles/example.lua similarity index 100% rename from vendor/pygments/tests/examplefiles/example.lua rename to third_party/pygments/tests/examplefiles/example.lua diff --git a/vendor/pygments/tests/examplefiles/example.ma b/third_party/pygments/tests/examplefiles/example.ma similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ma rename to third_party/pygments/tests/examplefiles/example.ma diff --git a/vendor/pygments/tests/examplefiles/example.mac b/third_party/pygments/tests/examplefiles/example.mac similarity index 100% rename from vendor/pygments/tests/examplefiles/example.mac rename to third_party/pygments/tests/examplefiles/example.mac diff --git a/vendor/pygments/tests/examplefiles/example.monkey b/third_party/pygments/tests/examplefiles/example.monkey similarity index 100% rename from vendor/pygments/tests/examplefiles/example.monkey rename to third_party/pygments/tests/examplefiles/example.monkey diff --git a/vendor/pygments/tests/examplefiles/example.moo b/third_party/pygments/tests/examplefiles/example.moo similarity index 100% rename from vendor/pygments/tests/examplefiles/example.moo rename to third_party/pygments/tests/examplefiles/example.moo diff --git a/vendor/pygments/tests/examplefiles/example.moon b/third_party/pygments/tests/examplefiles/example.moon similarity index 100% rename from vendor/pygments/tests/examplefiles/example.moon rename to third_party/pygments/tests/examplefiles/example.moon diff --git a/vendor/pygments/tests/examplefiles/example.mq4 b/third_party/pygments/tests/examplefiles/example.mq4 similarity index 100% rename from vendor/pygments/tests/examplefiles/example.mq4 rename to third_party/pygments/tests/examplefiles/example.mq4 diff --git a/vendor/pygments/tests/examplefiles/example.mqh b/third_party/pygments/tests/examplefiles/example.mqh similarity index 100% rename from vendor/pygments/tests/examplefiles/example.mqh rename to third_party/pygments/tests/examplefiles/example.mqh diff --git a/vendor/pygments/tests/examplefiles/example.msc b/third_party/pygments/tests/examplefiles/example.msc similarity index 100% rename from vendor/pygments/tests/examplefiles/example.msc rename to third_party/pygments/tests/examplefiles/example.msc diff --git a/vendor/pygments/tests/examplefiles/example.ni b/third_party/pygments/tests/examplefiles/example.ni similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ni rename to third_party/pygments/tests/examplefiles/example.ni diff --git a/vendor/pygments/tests/examplefiles/example.nim b/third_party/pygments/tests/examplefiles/example.nim similarity index 100% rename from vendor/pygments/tests/examplefiles/example.nim rename to third_party/pygments/tests/examplefiles/example.nim diff --git a/vendor/pygments/tests/examplefiles/example.nix b/third_party/pygments/tests/examplefiles/example.nix similarity index 100% rename from vendor/pygments/tests/examplefiles/example.nix rename to third_party/pygments/tests/examplefiles/example.nix diff --git a/vendor/pygments/tests/examplefiles/example.ns2 b/third_party/pygments/tests/examplefiles/example.ns2 similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ns2 rename to third_party/pygments/tests/examplefiles/example.ns2 diff --git a/vendor/pygments/tests/examplefiles/example.pas b/third_party/pygments/tests/examplefiles/example.pas similarity index 100% rename from vendor/pygments/tests/examplefiles/example.pas rename to third_party/pygments/tests/examplefiles/example.pas diff --git a/vendor/pygments/tests/examplefiles/example.pcmk b/third_party/pygments/tests/examplefiles/example.pcmk similarity index 100% rename from vendor/pygments/tests/examplefiles/example.pcmk rename to third_party/pygments/tests/examplefiles/example.pcmk diff --git a/vendor/pygments/tests/examplefiles/example.pp b/third_party/pygments/tests/examplefiles/example.pp similarity index 100% rename from vendor/pygments/tests/examplefiles/example.pp rename to third_party/pygments/tests/examplefiles/example.pp diff --git a/vendor/pygments/tests/examplefiles/example.praat b/third_party/pygments/tests/examplefiles/example.praat similarity index 100% rename from vendor/pygments/tests/examplefiles/example.praat rename to third_party/pygments/tests/examplefiles/example.praat diff --git a/vendor/pygments/tests/examplefiles/example.prg b/third_party/pygments/tests/examplefiles/example.prg similarity index 100% rename from vendor/pygments/tests/examplefiles/example.prg rename to third_party/pygments/tests/examplefiles/example.prg diff --git a/vendor/pygments/tests/examplefiles/example.rb b/third_party/pygments/tests/examplefiles/example.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/example.rb rename to third_party/pygments/tests/examplefiles/example.rb diff --git a/vendor/pygments/tests/examplefiles/example.red b/third_party/pygments/tests/examplefiles/example.red similarity index 100% rename from vendor/pygments/tests/examplefiles/example.red rename to third_party/pygments/tests/examplefiles/example.red diff --git a/vendor/pygments/tests/examplefiles/example.reds b/third_party/pygments/tests/examplefiles/example.reds similarity index 100% rename from vendor/pygments/tests/examplefiles/example.reds rename to third_party/pygments/tests/examplefiles/example.reds diff --git a/vendor/pygments/tests/examplefiles/example.reg b/third_party/pygments/tests/examplefiles/example.reg similarity index 100% rename from vendor/pygments/tests/examplefiles/example.reg rename to third_party/pygments/tests/examplefiles/example.reg diff --git a/vendor/pygments/tests/examplefiles/example.rexx b/third_party/pygments/tests/examplefiles/example.rexx similarity index 100% rename from vendor/pygments/tests/examplefiles/example.rexx rename to third_party/pygments/tests/examplefiles/example.rexx diff --git a/vendor/pygments/tests/examplefiles/example.rhtml b/third_party/pygments/tests/examplefiles/example.rhtml similarity index 100% rename from vendor/pygments/tests/examplefiles/example.rhtml rename to third_party/pygments/tests/examplefiles/example.rhtml diff --git a/vendor/pygments/tests/examplefiles/example.rkt b/third_party/pygments/tests/examplefiles/example.rkt similarity index 100% rename from vendor/pygments/tests/examplefiles/example.rkt rename to third_party/pygments/tests/examplefiles/example.rkt diff --git a/vendor/pygments/tests/examplefiles/example.rpf b/third_party/pygments/tests/examplefiles/example.rpf similarity index 100% rename from vendor/pygments/tests/examplefiles/example.rpf rename to third_party/pygments/tests/examplefiles/example.rpf diff --git a/vendor/pygments/tests/examplefiles/example.rts b/third_party/pygments/tests/examplefiles/example.rts similarity index 100% rename from vendor/pygments/tests/examplefiles/example.rts rename to third_party/pygments/tests/examplefiles/example.rts diff --git a/vendor/pygments/tests/examplefiles/example.scd b/third_party/pygments/tests/examplefiles/example.scd similarity index 100% rename from vendor/pygments/tests/examplefiles/example.scd rename to third_party/pygments/tests/examplefiles/example.scd diff --git a/vendor/pygments/tests/examplefiles/example.sh b/third_party/pygments/tests/examplefiles/example.sh similarity index 100% rename from vendor/pygments/tests/examplefiles/example.sh rename to third_party/pygments/tests/examplefiles/example.sh diff --git a/vendor/pygments/tests/examplefiles/example.sh-session b/third_party/pygments/tests/examplefiles/example.sh-session similarity index 100% rename from vendor/pygments/tests/examplefiles/example.sh-session rename to third_party/pygments/tests/examplefiles/example.sh-session diff --git a/vendor/pygments/tests/examplefiles/example.shell-session b/third_party/pygments/tests/examplefiles/example.shell-session similarity index 100% rename from vendor/pygments/tests/examplefiles/example.shell-session rename to third_party/pygments/tests/examplefiles/example.shell-session diff --git a/vendor/pygments/tests/examplefiles/example.slim b/third_party/pygments/tests/examplefiles/example.slim similarity index 100% rename from vendor/pygments/tests/examplefiles/example.slim rename to third_party/pygments/tests/examplefiles/example.slim diff --git a/vendor/pygments/tests/examplefiles/example.sls b/third_party/pygments/tests/examplefiles/example.sls similarity index 100% rename from vendor/pygments/tests/examplefiles/example.sls rename to third_party/pygments/tests/examplefiles/example.sls diff --git a/vendor/pygments/tests/examplefiles/example.sml b/third_party/pygments/tests/examplefiles/example.sml similarity index 100% rename from vendor/pygments/tests/examplefiles/example.sml rename to third_party/pygments/tests/examplefiles/example.sml diff --git a/vendor/pygments/tests/examplefiles/example.snobol b/third_party/pygments/tests/examplefiles/example.snobol similarity index 100% rename from vendor/pygments/tests/examplefiles/example.snobol rename to third_party/pygments/tests/examplefiles/example.snobol diff --git a/vendor/pygments/tests/examplefiles/example.stan b/third_party/pygments/tests/examplefiles/example.stan similarity index 100% rename from vendor/pygments/tests/examplefiles/example.stan rename to third_party/pygments/tests/examplefiles/example.stan diff --git a/vendor/pygments/tests/examplefiles/example.tap b/third_party/pygments/tests/examplefiles/example.tap similarity index 100% rename from vendor/pygments/tests/examplefiles/example.tap rename to third_party/pygments/tests/examplefiles/example.tap diff --git a/vendor/pygments/tests/examplefiles/example.tea b/third_party/pygments/tests/examplefiles/example.tea similarity index 100% rename from vendor/pygments/tests/examplefiles/example.tea rename to third_party/pygments/tests/examplefiles/example.tea diff --git a/vendor/pygments/tests/examplefiles/example.tf b/third_party/pygments/tests/examplefiles/example.tf similarity index 100% rename from vendor/pygments/tests/examplefiles/example.tf rename to third_party/pygments/tests/examplefiles/example.tf diff --git a/vendor/pygments/tests/examplefiles/example.thy b/third_party/pygments/tests/examplefiles/example.thy similarity index 100% rename from vendor/pygments/tests/examplefiles/example.thy rename to third_party/pygments/tests/examplefiles/example.thy diff --git a/vendor/pygments/tests/examplefiles/example.todotxt b/third_party/pygments/tests/examplefiles/example.todotxt similarity index 100% rename from vendor/pygments/tests/examplefiles/example.todotxt rename to third_party/pygments/tests/examplefiles/example.todotxt diff --git a/vendor/pygments/tests/examplefiles/example.ts b/third_party/pygments/tests/examplefiles/example.ts similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ts rename to third_party/pygments/tests/examplefiles/example.ts diff --git a/vendor/pygments/tests/examplefiles/example.ttl b/third_party/pygments/tests/examplefiles/example.ttl similarity index 100% rename from vendor/pygments/tests/examplefiles/example.ttl rename to third_party/pygments/tests/examplefiles/example.ttl diff --git a/vendor/pygments/tests/examplefiles/example.u b/third_party/pygments/tests/examplefiles/example.u similarity index 100% rename from vendor/pygments/tests/examplefiles/example.u rename to third_party/pygments/tests/examplefiles/example.u diff --git a/vendor/pygments/tests/examplefiles/example.weechatlog b/third_party/pygments/tests/examplefiles/example.weechatlog similarity index 100% rename from vendor/pygments/tests/examplefiles/example.weechatlog rename to third_party/pygments/tests/examplefiles/example.weechatlog diff --git a/vendor/pygments/tests/examplefiles/example.x10 b/third_party/pygments/tests/examplefiles/example.x10 similarity index 100% rename from vendor/pygments/tests/examplefiles/example.x10 rename to third_party/pygments/tests/examplefiles/example.x10 diff --git a/vendor/pygments/tests/examplefiles/example.xhtml b/third_party/pygments/tests/examplefiles/example.xhtml similarity index 100% rename from vendor/pygments/tests/examplefiles/example.xhtml rename to third_party/pygments/tests/examplefiles/example.xhtml diff --git a/vendor/pygments/tests/examplefiles/example.xtend b/third_party/pygments/tests/examplefiles/example.xtend similarity index 100% rename from vendor/pygments/tests/examplefiles/example.xtend rename to third_party/pygments/tests/examplefiles/example.xtend diff --git a/vendor/pygments/tests/examplefiles/example.yaml b/third_party/pygments/tests/examplefiles/example.yaml similarity index 100% rename from vendor/pygments/tests/examplefiles/example.yaml rename to third_party/pygments/tests/examplefiles/example.yaml diff --git a/vendor/pygments/tests/examplefiles/example1.cadl b/third_party/pygments/tests/examplefiles/example1.cadl similarity index 100% rename from vendor/pygments/tests/examplefiles/example1.cadl rename to third_party/pygments/tests/examplefiles/example1.cadl diff --git a/vendor/pygments/tests/examplefiles/example2.aspx b/third_party/pygments/tests/examplefiles/example2.aspx similarity index 100% rename from vendor/pygments/tests/examplefiles/example2.aspx rename to third_party/pygments/tests/examplefiles/example2.aspx diff --git a/vendor/pygments/tests/examplefiles/example2.msc b/third_party/pygments/tests/examplefiles/example2.msc similarity index 100% rename from vendor/pygments/tests/examplefiles/example2.msc rename to third_party/pygments/tests/examplefiles/example2.msc diff --git a/vendor/pygments/tests/examplefiles/exampleScript.cfc b/third_party/pygments/tests/examplefiles/exampleScript.cfc similarity index 100% rename from vendor/pygments/tests/examplefiles/exampleScript.cfc rename to third_party/pygments/tests/examplefiles/exampleScript.cfc diff --git a/vendor/pygments/tests/examplefiles/exampleTag.cfc b/third_party/pygments/tests/examplefiles/exampleTag.cfc similarity index 100% rename from vendor/pygments/tests/examplefiles/exampleTag.cfc rename to third_party/pygments/tests/examplefiles/exampleTag.cfc diff --git a/vendor/pygments/tests/examplefiles/example_coq.v b/third_party/pygments/tests/examplefiles/example_coq.v similarity index 100% rename from vendor/pygments/tests/examplefiles/example_coq.v rename to third_party/pygments/tests/examplefiles/example_coq.v diff --git a/vendor/pygments/tests/examplefiles/example_elixir.ex b/third_party/pygments/tests/examplefiles/example_elixir.ex similarity index 100% rename from vendor/pygments/tests/examplefiles/example_elixir.ex rename to third_party/pygments/tests/examplefiles/example_elixir.ex diff --git a/vendor/pygments/tests/examplefiles/example_file.fy b/third_party/pygments/tests/examplefiles/example_file.fy similarity index 100% rename from vendor/pygments/tests/examplefiles/example_file.fy rename to third_party/pygments/tests/examplefiles/example_file.fy diff --git a/vendor/pygments/tests/examplefiles/ezhil_primefactors.n b/third_party/pygments/tests/examplefiles/ezhil_primefactors.n similarity index 100% rename from vendor/pygments/tests/examplefiles/ezhil_primefactors.n rename to third_party/pygments/tests/examplefiles/ezhil_primefactors.n diff --git a/vendor/pygments/tests/examplefiles/firefox.mak b/third_party/pygments/tests/examplefiles/firefox.mak similarity index 100% rename from vendor/pygments/tests/examplefiles/firefox.mak rename to third_party/pygments/tests/examplefiles/firefox.mak diff --git a/vendor/pygments/tests/examplefiles/flipflop.sv b/third_party/pygments/tests/examplefiles/flipflop.sv similarity index 100% rename from vendor/pygments/tests/examplefiles/flipflop.sv rename to third_party/pygments/tests/examplefiles/flipflop.sv diff --git a/vendor/pygments/tests/examplefiles/foo.sce b/third_party/pygments/tests/examplefiles/foo.sce similarity index 100% rename from vendor/pygments/tests/examplefiles/foo.sce rename to third_party/pygments/tests/examplefiles/foo.sce diff --git a/vendor/pygments/tests/examplefiles/format.ml b/third_party/pygments/tests/examplefiles/format.ml similarity index 100% rename from vendor/pygments/tests/examplefiles/format.ml rename to third_party/pygments/tests/examplefiles/format.ml diff --git a/vendor/pygments/tests/examplefiles/fucked_up.rb b/third_party/pygments/tests/examplefiles/fucked_up.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/fucked_up.rb rename to third_party/pygments/tests/examplefiles/fucked_up.rb diff --git a/vendor/pygments/tests/examplefiles/function.mu b/third_party/pygments/tests/examplefiles/function.mu similarity index 100% rename from vendor/pygments/tests/examplefiles/function.mu rename to third_party/pygments/tests/examplefiles/function.mu diff --git a/vendor/pygments/tests/examplefiles/functional.rst b/third_party/pygments/tests/examplefiles/functional.rst similarity index 100% rename from vendor/pygments/tests/examplefiles/functional.rst rename to third_party/pygments/tests/examplefiles/functional.rst diff --git a/vendor/pygments/tests/examplefiles/garcia-wachs.kk b/third_party/pygments/tests/examplefiles/garcia-wachs.kk similarity index 100% rename from vendor/pygments/tests/examplefiles/garcia-wachs.kk rename to third_party/pygments/tests/examplefiles/garcia-wachs.kk diff --git a/vendor/pygments/tests/examplefiles/genclass.clj b/third_party/pygments/tests/examplefiles/genclass.clj similarity index 100% rename from vendor/pygments/tests/examplefiles/genclass.clj rename to third_party/pygments/tests/examplefiles/genclass.clj diff --git a/vendor/pygments/tests/examplefiles/genshi_example.xml+genshi b/third_party/pygments/tests/examplefiles/genshi_example.xml+genshi similarity index 100% rename from vendor/pygments/tests/examplefiles/genshi_example.xml+genshi rename to third_party/pygments/tests/examplefiles/genshi_example.xml+genshi diff --git a/vendor/pygments/tests/examplefiles/genshitext_example.genshitext b/third_party/pygments/tests/examplefiles/genshitext_example.genshitext similarity index 100% rename from vendor/pygments/tests/examplefiles/genshitext_example.genshitext rename to third_party/pygments/tests/examplefiles/genshitext_example.genshitext diff --git a/vendor/pygments/tests/examplefiles/glsl.frag b/third_party/pygments/tests/examplefiles/glsl.frag similarity index 100% rename from vendor/pygments/tests/examplefiles/glsl.frag rename to third_party/pygments/tests/examplefiles/glsl.frag diff --git a/vendor/pygments/tests/examplefiles/glsl.vert b/third_party/pygments/tests/examplefiles/glsl.vert similarity index 100% rename from vendor/pygments/tests/examplefiles/glsl.vert rename to third_party/pygments/tests/examplefiles/glsl.vert diff --git a/vendor/pygments/tests/examplefiles/grammar-test.p6 b/third_party/pygments/tests/examplefiles/grammar-test.p6 similarity index 100% rename from vendor/pygments/tests/examplefiles/grammar-test.p6 rename to third_party/pygments/tests/examplefiles/grammar-test.p6 diff --git a/vendor/pygments/tests/examplefiles/hash_syntax.rb b/third_party/pygments/tests/examplefiles/hash_syntax.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/hash_syntax.rb rename to third_party/pygments/tests/examplefiles/hash_syntax.rb diff --git a/vendor/pygments/tests/examplefiles/hello.at b/third_party/pygments/tests/examplefiles/hello.at similarity index 100% rename from vendor/pygments/tests/examplefiles/hello.at rename to third_party/pygments/tests/examplefiles/hello.at diff --git a/vendor/pygments/tests/examplefiles/hello.golo b/third_party/pygments/tests/examplefiles/hello.golo similarity index 100% rename from vendor/pygments/tests/examplefiles/hello.golo rename to third_party/pygments/tests/examplefiles/hello.golo diff --git a/vendor/pygments/tests/examplefiles/hello.lsl b/third_party/pygments/tests/examplefiles/hello.lsl similarity index 100% rename from vendor/pygments/tests/examplefiles/hello.lsl rename to third_party/pygments/tests/examplefiles/hello.lsl diff --git a/vendor/pygments/tests/examplefiles/hello.smali b/third_party/pygments/tests/examplefiles/hello.smali similarity index 100% rename from vendor/pygments/tests/examplefiles/hello.smali rename to third_party/pygments/tests/examplefiles/hello.smali diff --git a/vendor/pygments/tests/examplefiles/hello.sp b/third_party/pygments/tests/examplefiles/hello.sp similarity index 100% rename from vendor/pygments/tests/examplefiles/hello.sp rename to third_party/pygments/tests/examplefiles/hello.sp diff --git a/vendor/pygments/tests/examplefiles/hexdump_debugexe b/third_party/pygments/tests/examplefiles/hexdump_debugexe similarity index 100% rename from vendor/pygments/tests/examplefiles/hexdump_debugexe rename to third_party/pygments/tests/examplefiles/hexdump_debugexe diff --git a/vendor/pygments/tests/examplefiles/hexdump_hd b/third_party/pygments/tests/examplefiles/hexdump_hd similarity index 100% rename from vendor/pygments/tests/examplefiles/hexdump_hd rename to third_party/pygments/tests/examplefiles/hexdump_hd diff --git a/vendor/pygments/tests/examplefiles/hexdump_hexcat b/third_party/pygments/tests/examplefiles/hexdump_hexcat similarity index 100% rename from vendor/pygments/tests/examplefiles/hexdump_hexcat rename to third_party/pygments/tests/examplefiles/hexdump_hexcat diff --git a/vendor/pygments/tests/examplefiles/hexdump_hexdump b/third_party/pygments/tests/examplefiles/hexdump_hexdump similarity index 100% rename from vendor/pygments/tests/examplefiles/hexdump_hexdump rename to third_party/pygments/tests/examplefiles/hexdump_hexdump diff --git a/vendor/pygments/tests/examplefiles/hexdump_od b/third_party/pygments/tests/examplefiles/hexdump_od similarity index 100% rename from vendor/pygments/tests/examplefiles/hexdump_od rename to third_party/pygments/tests/examplefiles/hexdump_od diff --git a/vendor/pygments/tests/examplefiles/hexdump_xxd b/third_party/pygments/tests/examplefiles/hexdump_xxd similarity index 100% rename from vendor/pygments/tests/examplefiles/hexdump_xxd rename to third_party/pygments/tests/examplefiles/hexdump_xxd diff --git a/vendor/pygments/tests/examplefiles/html+php_faulty.php b/third_party/pygments/tests/examplefiles/html+php_faulty.php similarity index 100% rename from vendor/pygments/tests/examplefiles/html+php_faulty.php rename to third_party/pygments/tests/examplefiles/html+php_faulty.php diff --git a/vendor/pygments/tests/examplefiles/http_request_example b/third_party/pygments/tests/examplefiles/http_request_example similarity index 100% rename from vendor/pygments/tests/examplefiles/http_request_example rename to third_party/pygments/tests/examplefiles/http_request_example diff --git a/vendor/pygments/tests/examplefiles/http_response_example b/third_party/pygments/tests/examplefiles/http_response_example similarity index 100% rename from vendor/pygments/tests/examplefiles/http_response_example rename to third_party/pygments/tests/examplefiles/http_response_example diff --git a/vendor/pygments/tests/examplefiles/hybris_File.hy b/third_party/pygments/tests/examplefiles/hybris_File.hy similarity index 100% rename from vendor/pygments/tests/examplefiles/hybris_File.hy rename to third_party/pygments/tests/examplefiles/hybris_File.hy diff --git a/vendor/pygments/tests/examplefiles/idl_sample.pro b/third_party/pygments/tests/examplefiles/idl_sample.pro similarity index 100% rename from vendor/pygments/tests/examplefiles/idl_sample.pro rename to third_party/pygments/tests/examplefiles/idl_sample.pro diff --git a/vendor/pygments/tests/examplefiles/iex_example b/third_party/pygments/tests/examplefiles/iex_example similarity index 100% rename from vendor/pygments/tests/examplefiles/iex_example rename to third_party/pygments/tests/examplefiles/iex_example diff --git a/vendor/pygments/tests/examplefiles/inet_pton6.dg b/third_party/pygments/tests/examplefiles/inet_pton6.dg similarity index 100% rename from vendor/pygments/tests/examplefiles/inet_pton6.dg rename to third_party/pygments/tests/examplefiles/inet_pton6.dg diff --git a/vendor/pygments/tests/examplefiles/inform6_example b/third_party/pygments/tests/examplefiles/inform6_example similarity index 100% rename from vendor/pygments/tests/examplefiles/inform6_example rename to third_party/pygments/tests/examplefiles/inform6_example diff --git a/vendor/pygments/tests/examplefiles/interp.scala b/third_party/pygments/tests/examplefiles/interp.scala similarity index 100% rename from vendor/pygments/tests/examplefiles/interp.scala rename to third_party/pygments/tests/examplefiles/interp.scala diff --git a/vendor/pygments/tests/examplefiles/intro.ik b/third_party/pygments/tests/examplefiles/intro.ik similarity index 100% rename from vendor/pygments/tests/examplefiles/intro.ik rename to third_party/pygments/tests/examplefiles/intro.ik diff --git a/vendor/pygments/tests/examplefiles/ints.php b/third_party/pygments/tests/examplefiles/ints.php similarity index 100% rename from vendor/pygments/tests/examplefiles/ints.php rename to third_party/pygments/tests/examplefiles/ints.php diff --git a/vendor/pygments/tests/examplefiles/intsyn.fun b/third_party/pygments/tests/examplefiles/intsyn.fun similarity index 100% rename from vendor/pygments/tests/examplefiles/intsyn.fun rename to third_party/pygments/tests/examplefiles/intsyn.fun diff --git a/vendor/pygments/tests/examplefiles/intsyn.sig b/third_party/pygments/tests/examplefiles/intsyn.sig similarity index 100% rename from vendor/pygments/tests/examplefiles/intsyn.sig rename to third_party/pygments/tests/examplefiles/intsyn.sig diff --git a/vendor/pygments/tests/examplefiles/irb_heredoc b/third_party/pygments/tests/examplefiles/irb_heredoc similarity index 100% rename from vendor/pygments/tests/examplefiles/irb_heredoc rename to third_party/pygments/tests/examplefiles/irb_heredoc diff --git a/vendor/pygments/tests/examplefiles/irc.lsp b/third_party/pygments/tests/examplefiles/irc.lsp similarity index 100% rename from vendor/pygments/tests/examplefiles/irc.lsp rename to third_party/pygments/tests/examplefiles/irc.lsp diff --git a/vendor/pygments/tests/examplefiles/java.properties b/third_party/pygments/tests/examplefiles/java.properties similarity index 100% rename from vendor/pygments/tests/examplefiles/java.properties rename to third_party/pygments/tests/examplefiles/java.properties diff --git a/vendor/pygments/tests/examplefiles/jbst_example1.jbst b/third_party/pygments/tests/examplefiles/jbst_example1.jbst similarity index 100% rename from vendor/pygments/tests/examplefiles/jbst_example1.jbst rename to third_party/pygments/tests/examplefiles/jbst_example1.jbst diff --git a/vendor/pygments/tests/examplefiles/jbst_example2.jbst b/third_party/pygments/tests/examplefiles/jbst_example2.jbst similarity index 100% rename from vendor/pygments/tests/examplefiles/jbst_example2.jbst rename to third_party/pygments/tests/examplefiles/jbst_example2.jbst diff --git a/vendor/pygments/tests/examplefiles/jinjadesignerdoc.rst b/third_party/pygments/tests/examplefiles/jinjadesignerdoc.rst similarity index 100% rename from vendor/pygments/tests/examplefiles/jinjadesignerdoc.rst rename to third_party/pygments/tests/examplefiles/jinjadesignerdoc.rst diff --git a/vendor/pygments/tests/examplefiles/json.lasso b/third_party/pygments/tests/examplefiles/json.lasso similarity index 100% rename from vendor/pygments/tests/examplefiles/json.lasso rename to third_party/pygments/tests/examplefiles/json.lasso diff --git a/vendor/pygments/tests/examplefiles/json.lasso9 b/third_party/pygments/tests/examplefiles/json.lasso9 similarity index 100% rename from vendor/pygments/tests/examplefiles/json.lasso9 rename to third_party/pygments/tests/examplefiles/json.lasso9 diff --git a/vendor/pygments/tests/examplefiles/language.hy b/third_party/pygments/tests/examplefiles/language.hy similarity index 100% rename from vendor/pygments/tests/examplefiles/language.hy rename to third_party/pygments/tests/examplefiles/language.hy diff --git a/vendor/pygments/tests/examplefiles/lighttpd_config.conf b/third_party/pygments/tests/examplefiles/lighttpd_config.conf similarity index 100% rename from vendor/pygments/tests/examplefiles/lighttpd_config.conf rename to third_party/pygments/tests/examplefiles/lighttpd_config.conf diff --git a/vendor/pygments/tests/examplefiles/limbo.b b/third_party/pygments/tests/examplefiles/limbo.b similarity index 100% rename from vendor/pygments/tests/examplefiles/limbo.b rename to third_party/pygments/tests/examplefiles/limbo.b diff --git a/vendor/pygments/tests/examplefiles/linecontinuation.py b/third_party/pygments/tests/examplefiles/linecontinuation.py similarity index 100% rename from vendor/pygments/tests/examplefiles/linecontinuation.py rename to third_party/pygments/tests/examplefiles/linecontinuation.py diff --git a/vendor/pygments/tests/examplefiles/livescript-demo.ls b/third_party/pygments/tests/examplefiles/livescript-demo.ls similarity index 100% rename from vendor/pygments/tests/examplefiles/livescript-demo.ls rename to third_party/pygments/tests/examplefiles/livescript-demo.ls diff --git a/vendor/pygments/tests/examplefiles/logos_example.xm b/third_party/pygments/tests/examplefiles/logos_example.xm similarity index 100% rename from vendor/pygments/tests/examplefiles/logos_example.xm rename to third_party/pygments/tests/examplefiles/logos_example.xm diff --git a/vendor/pygments/tests/examplefiles/ltmain.sh b/third_party/pygments/tests/examplefiles/ltmain.sh similarity index 100% rename from vendor/pygments/tests/examplefiles/ltmain.sh rename to third_party/pygments/tests/examplefiles/ltmain.sh diff --git a/vendor/pygments/tests/examplefiles/main.cmake b/third_party/pygments/tests/examplefiles/main.cmake similarity index 100% rename from vendor/pygments/tests/examplefiles/main.cmake rename to third_party/pygments/tests/examplefiles/main.cmake diff --git a/vendor/pygments/tests/examplefiles/markdown.lsp b/third_party/pygments/tests/examplefiles/markdown.lsp similarity index 100% rename from vendor/pygments/tests/examplefiles/markdown.lsp rename to third_party/pygments/tests/examplefiles/markdown.lsp diff --git a/vendor/pygments/tests/examplefiles/matlab_noreturn b/third_party/pygments/tests/examplefiles/matlab_noreturn similarity index 100% rename from vendor/pygments/tests/examplefiles/matlab_noreturn rename to third_party/pygments/tests/examplefiles/matlab_noreturn diff --git a/vendor/pygments/tests/examplefiles/matlab_sample b/third_party/pygments/tests/examplefiles/matlab_sample similarity index 100% rename from vendor/pygments/tests/examplefiles/matlab_sample rename to third_party/pygments/tests/examplefiles/matlab_sample diff --git a/vendor/pygments/tests/examplefiles/matlabsession_sample.txt b/third_party/pygments/tests/examplefiles/matlabsession_sample.txt similarity index 100% rename from vendor/pygments/tests/examplefiles/matlabsession_sample.txt rename to third_party/pygments/tests/examplefiles/matlabsession_sample.txt diff --git a/vendor/pygments/tests/examplefiles/metagrammar.treetop b/third_party/pygments/tests/examplefiles/metagrammar.treetop similarity index 100% rename from vendor/pygments/tests/examplefiles/metagrammar.treetop rename to third_party/pygments/tests/examplefiles/metagrammar.treetop diff --git a/vendor/pygments/tests/examplefiles/minehunt.qml b/third_party/pygments/tests/examplefiles/minehunt.qml similarity index 100% rename from vendor/pygments/tests/examplefiles/minehunt.qml rename to third_party/pygments/tests/examplefiles/minehunt.qml diff --git a/vendor/pygments/tests/examplefiles/minimal.ns2 b/third_party/pygments/tests/examplefiles/minimal.ns2 similarity index 100% rename from vendor/pygments/tests/examplefiles/minimal.ns2 rename to third_party/pygments/tests/examplefiles/minimal.ns2 diff --git a/vendor/pygments/tests/examplefiles/modula2_test_cases.def b/third_party/pygments/tests/examplefiles/modula2_test_cases.def similarity index 100% rename from vendor/pygments/tests/examplefiles/modula2_test_cases.def rename to third_party/pygments/tests/examplefiles/modula2_test_cases.def diff --git a/vendor/pygments/tests/examplefiles/moin_SyntaxReference.txt b/third_party/pygments/tests/examplefiles/moin_SyntaxReference.txt similarity index 100% rename from vendor/pygments/tests/examplefiles/moin_SyntaxReference.txt rename to third_party/pygments/tests/examplefiles/moin_SyntaxReference.txt diff --git a/vendor/pygments/tests/examplefiles/multiline_regexes.rb b/third_party/pygments/tests/examplefiles/multiline_regexes.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/multiline_regexes.rb rename to third_party/pygments/tests/examplefiles/multiline_regexes.rb diff --git a/vendor/pygments/tests/examplefiles/nanomsg.intr b/third_party/pygments/tests/examplefiles/nanomsg.intr similarity index 100% rename from vendor/pygments/tests/examplefiles/nanomsg.intr rename to third_party/pygments/tests/examplefiles/nanomsg.intr diff --git a/vendor/pygments/tests/examplefiles/nasm_aoutso.asm b/third_party/pygments/tests/examplefiles/nasm_aoutso.asm similarity index 100% rename from vendor/pygments/tests/examplefiles/nasm_aoutso.asm rename to third_party/pygments/tests/examplefiles/nasm_aoutso.asm diff --git a/vendor/pygments/tests/examplefiles/nasm_objexe.asm b/third_party/pygments/tests/examplefiles/nasm_objexe.asm similarity index 100% rename from vendor/pygments/tests/examplefiles/nasm_objexe.asm rename to third_party/pygments/tests/examplefiles/nasm_objexe.asm diff --git a/vendor/pygments/tests/examplefiles/nemerle_sample.n b/third_party/pygments/tests/examplefiles/nemerle_sample.n similarity index 100% rename from vendor/pygments/tests/examplefiles/nemerle_sample.n rename to third_party/pygments/tests/examplefiles/nemerle_sample.n diff --git a/vendor/pygments/tests/examplefiles/nginx_nginx.conf b/third_party/pygments/tests/examplefiles/nginx_nginx.conf similarity index 100% rename from vendor/pygments/tests/examplefiles/nginx_nginx.conf rename to third_party/pygments/tests/examplefiles/nginx_nginx.conf diff --git a/vendor/pygments/tests/examplefiles/noexcept.cpp b/third_party/pygments/tests/examplefiles/noexcept.cpp similarity index 100% rename from vendor/pygments/tests/examplefiles/noexcept.cpp rename to third_party/pygments/tests/examplefiles/noexcept.cpp diff --git a/vendor/pygments/tests/examplefiles/numbers.c b/third_party/pygments/tests/examplefiles/numbers.c similarity index 100% rename from vendor/pygments/tests/examplefiles/numbers.c rename to third_party/pygments/tests/examplefiles/numbers.c diff --git a/vendor/pygments/tests/examplefiles/objc_example.m b/third_party/pygments/tests/examplefiles/objc_example.m similarity index 100% rename from vendor/pygments/tests/examplefiles/objc_example.m rename to third_party/pygments/tests/examplefiles/objc_example.m diff --git a/vendor/pygments/tests/examplefiles/openedge_example b/third_party/pygments/tests/examplefiles/openedge_example similarity index 100% rename from vendor/pygments/tests/examplefiles/openedge_example rename to third_party/pygments/tests/examplefiles/openedge_example diff --git a/vendor/pygments/tests/examplefiles/pacman.conf b/third_party/pygments/tests/examplefiles/pacman.conf similarity index 100% rename from vendor/pygments/tests/examplefiles/pacman.conf rename to third_party/pygments/tests/examplefiles/pacman.conf diff --git a/vendor/pygments/tests/examplefiles/pacman.ijs b/third_party/pygments/tests/examplefiles/pacman.ijs similarity index 100% rename from vendor/pygments/tests/examplefiles/pacman.ijs rename to third_party/pygments/tests/examplefiles/pacman.ijs diff --git a/vendor/pygments/tests/examplefiles/pawn_example b/third_party/pygments/tests/examplefiles/pawn_example similarity index 100% rename from vendor/pygments/tests/examplefiles/pawn_example rename to third_party/pygments/tests/examplefiles/pawn_example diff --git a/vendor/pygments/tests/examplefiles/perl_misc b/third_party/pygments/tests/examplefiles/perl_misc similarity index 100% rename from vendor/pygments/tests/examplefiles/perl_misc rename to third_party/pygments/tests/examplefiles/perl_misc diff --git a/vendor/pygments/tests/examplefiles/perl_perl5db b/third_party/pygments/tests/examplefiles/perl_perl5db similarity index 100% rename from vendor/pygments/tests/examplefiles/perl_perl5db rename to third_party/pygments/tests/examplefiles/perl_perl5db diff --git a/vendor/pygments/tests/examplefiles/perl_regex-delims b/third_party/pygments/tests/examplefiles/perl_regex-delims similarity index 100% rename from vendor/pygments/tests/examplefiles/perl_regex-delims rename to third_party/pygments/tests/examplefiles/perl_regex-delims diff --git a/vendor/pygments/tests/examplefiles/perlfunc.1 b/third_party/pygments/tests/examplefiles/perlfunc.1 similarity index 100% rename from vendor/pygments/tests/examplefiles/perlfunc.1 rename to third_party/pygments/tests/examplefiles/perlfunc.1 diff --git a/vendor/pygments/tests/examplefiles/phpMyAdmin.spec b/third_party/pygments/tests/examplefiles/phpMyAdmin.spec similarity index 100% rename from vendor/pygments/tests/examplefiles/phpMyAdmin.spec rename to third_party/pygments/tests/examplefiles/phpMyAdmin.spec diff --git a/vendor/pygments/tests/examplefiles/phpcomplete.vim b/third_party/pygments/tests/examplefiles/phpcomplete.vim similarity index 100% rename from vendor/pygments/tests/examplefiles/phpcomplete.vim rename to third_party/pygments/tests/examplefiles/phpcomplete.vim diff --git a/vendor/pygments/tests/examplefiles/pkgconfig_example.pc b/third_party/pygments/tests/examplefiles/pkgconfig_example.pc similarity index 100% rename from vendor/pygments/tests/examplefiles/pkgconfig_example.pc rename to third_party/pygments/tests/examplefiles/pkgconfig_example.pc diff --git a/vendor/pygments/tests/examplefiles/pleac.in.rb b/third_party/pygments/tests/examplefiles/pleac.in.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/pleac.in.rb rename to third_party/pygments/tests/examplefiles/pleac.in.rb diff --git a/vendor/pygments/tests/examplefiles/postgresql_test.txt b/third_party/pygments/tests/examplefiles/postgresql_test.txt similarity index 100% rename from vendor/pygments/tests/examplefiles/postgresql_test.txt rename to third_party/pygments/tests/examplefiles/postgresql_test.txt diff --git a/vendor/pygments/tests/examplefiles/pppoe.applescript b/third_party/pygments/tests/examplefiles/pppoe.applescript similarity index 100% rename from vendor/pygments/tests/examplefiles/pppoe.applescript rename to third_party/pygments/tests/examplefiles/pppoe.applescript diff --git a/vendor/pygments/tests/examplefiles/psql_session.txt b/third_party/pygments/tests/examplefiles/psql_session.txt similarity index 100% rename from vendor/pygments/tests/examplefiles/psql_session.txt rename to third_party/pygments/tests/examplefiles/psql_session.txt diff --git a/vendor/pygments/tests/examplefiles/py3_test.txt b/third_party/pygments/tests/examplefiles/py3_test.txt similarity index 100% rename from vendor/pygments/tests/examplefiles/py3_test.txt rename to third_party/pygments/tests/examplefiles/py3_test.txt diff --git a/vendor/pygments/tests/examplefiles/py3tb_test.py3tb b/third_party/pygments/tests/examplefiles/py3tb_test.py3tb similarity index 100% rename from vendor/pygments/tests/examplefiles/py3tb_test.py3tb rename to third_party/pygments/tests/examplefiles/py3tb_test.py3tb diff --git a/vendor/pygments/tests/examplefiles/pycon_ctrlc_traceback b/third_party/pygments/tests/examplefiles/pycon_ctrlc_traceback similarity index 100% rename from vendor/pygments/tests/examplefiles/pycon_ctrlc_traceback rename to third_party/pygments/tests/examplefiles/pycon_ctrlc_traceback diff --git a/vendor/pygments/tests/examplefiles/pycon_test.pycon b/third_party/pygments/tests/examplefiles/pycon_test.pycon similarity index 100% rename from vendor/pygments/tests/examplefiles/pycon_test.pycon rename to third_party/pygments/tests/examplefiles/pycon_test.pycon diff --git a/vendor/pygments/tests/examplefiles/pytb_test2.pytb b/third_party/pygments/tests/examplefiles/pytb_test2.pytb similarity index 100% rename from vendor/pygments/tests/examplefiles/pytb_test2.pytb rename to third_party/pygments/tests/examplefiles/pytb_test2.pytb diff --git a/vendor/pygments/tests/examplefiles/pytb_test3.pytb b/third_party/pygments/tests/examplefiles/pytb_test3.pytb similarity index 100% rename from vendor/pygments/tests/examplefiles/pytb_test3.pytb rename to third_party/pygments/tests/examplefiles/pytb_test3.pytb diff --git a/vendor/pygments/tests/examplefiles/python25-bsd.mak b/third_party/pygments/tests/examplefiles/python25-bsd.mak similarity index 100% rename from vendor/pygments/tests/examplefiles/python25-bsd.mak rename to third_party/pygments/tests/examplefiles/python25-bsd.mak diff --git a/vendor/pygments/tests/examplefiles/qbasic_example b/third_party/pygments/tests/examplefiles/qbasic_example similarity index 100% rename from vendor/pygments/tests/examplefiles/qbasic_example rename to third_party/pygments/tests/examplefiles/qbasic_example diff --git a/vendor/pygments/tests/examplefiles/qsort.prolog b/third_party/pygments/tests/examplefiles/qsort.prolog similarity index 100% rename from vendor/pygments/tests/examplefiles/qsort.prolog rename to third_party/pygments/tests/examplefiles/qsort.prolog diff --git a/vendor/pygments/tests/examplefiles/r-console-transcript.Rout b/third_party/pygments/tests/examplefiles/r-console-transcript.Rout similarity index 100% rename from vendor/pygments/tests/examplefiles/r-console-transcript.Rout rename to third_party/pygments/tests/examplefiles/r-console-transcript.Rout diff --git a/vendor/pygments/tests/examplefiles/r6rs-comments.scm b/third_party/pygments/tests/examplefiles/r6rs-comments.scm similarity index 100% rename from vendor/pygments/tests/examplefiles/r6rs-comments.scm rename to third_party/pygments/tests/examplefiles/r6rs-comments.scm diff --git a/vendor/pygments/tests/examplefiles/ragel-cpp_rlscan b/third_party/pygments/tests/examplefiles/ragel-cpp_rlscan similarity index 100% rename from vendor/pygments/tests/examplefiles/ragel-cpp_rlscan rename to third_party/pygments/tests/examplefiles/ragel-cpp_rlscan diff --git a/vendor/pygments/tests/examplefiles/ragel-cpp_snippet b/third_party/pygments/tests/examplefiles/ragel-cpp_snippet similarity index 100% rename from vendor/pygments/tests/examplefiles/ragel-cpp_snippet rename to third_party/pygments/tests/examplefiles/ragel-cpp_snippet diff --git a/vendor/pygments/tests/examplefiles/regex.js b/third_party/pygments/tests/examplefiles/regex.js similarity index 100% rename from vendor/pygments/tests/examplefiles/regex.js rename to third_party/pygments/tests/examplefiles/regex.js diff --git a/vendor/pygments/tests/examplefiles/resourcebundle_demo b/third_party/pygments/tests/examplefiles/resourcebundle_demo similarity index 100% rename from vendor/pygments/tests/examplefiles/resourcebundle_demo rename to third_party/pygments/tests/examplefiles/resourcebundle_demo diff --git a/vendor/pygments/tests/examplefiles/reversi.lsp b/third_party/pygments/tests/examplefiles/reversi.lsp similarity index 100% rename from vendor/pygments/tests/examplefiles/reversi.lsp rename to third_party/pygments/tests/examplefiles/reversi.lsp diff --git a/vendor/pygments/tests/examplefiles/roboconf.graph b/third_party/pygments/tests/examplefiles/roboconf.graph similarity index 100% rename from vendor/pygments/tests/examplefiles/roboconf.graph rename to third_party/pygments/tests/examplefiles/roboconf.graph diff --git a/vendor/pygments/tests/examplefiles/roboconf.instances b/third_party/pygments/tests/examplefiles/roboconf.instances similarity index 100% rename from vendor/pygments/tests/examplefiles/roboconf.instances rename to third_party/pygments/tests/examplefiles/roboconf.instances diff --git a/vendor/pygments/tests/examplefiles/robotframework_test.txt b/third_party/pygments/tests/examplefiles/robotframework_test.txt similarity index 100% rename from vendor/pygments/tests/examplefiles/robotframework_test.txt rename to third_party/pygments/tests/examplefiles/robotframework_test.txt diff --git a/vendor/pygments/tests/examplefiles/rql-queries.rql b/third_party/pygments/tests/examplefiles/rql-queries.rql similarity index 100% rename from vendor/pygments/tests/examplefiles/rql-queries.rql rename to third_party/pygments/tests/examplefiles/rql-queries.rql diff --git a/vendor/pygments/tests/examplefiles/ruby_func_def.rb b/third_party/pygments/tests/examplefiles/ruby_func_def.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/ruby_func_def.rb rename to third_party/pygments/tests/examplefiles/ruby_func_def.rb diff --git a/vendor/pygments/tests/examplefiles/sample.qvto b/third_party/pygments/tests/examplefiles/sample.qvto similarity index 100% rename from vendor/pygments/tests/examplefiles/sample.qvto rename to third_party/pygments/tests/examplefiles/sample.qvto diff --git a/vendor/pygments/tests/examplefiles/scilab.sci b/third_party/pygments/tests/examplefiles/scilab.sci similarity index 100% rename from vendor/pygments/tests/examplefiles/scilab.sci rename to third_party/pygments/tests/examplefiles/scilab.sci diff --git a/vendor/pygments/tests/examplefiles/scope.cirru b/third_party/pygments/tests/examplefiles/scope.cirru similarity index 100% rename from vendor/pygments/tests/examplefiles/scope.cirru rename to third_party/pygments/tests/examplefiles/scope.cirru diff --git a/vendor/pygments/tests/examplefiles/session.dylan-console b/third_party/pygments/tests/examplefiles/session.dylan-console similarity index 100% rename from vendor/pygments/tests/examplefiles/session.dylan-console rename to third_party/pygments/tests/examplefiles/session.dylan-console diff --git a/vendor/pygments/tests/examplefiles/sibling.prolog b/third_party/pygments/tests/examplefiles/sibling.prolog similarity index 100% rename from vendor/pygments/tests/examplefiles/sibling.prolog rename to third_party/pygments/tests/examplefiles/sibling.prolog diff --git a/vendor/pygments/tests/examplefiles/simple.camkes b/third_party/pygments/tests/examplefiles/simple.camkes similarity index 100% rename from vendor/pygments/tests/examplefiles/simple.camkes rename to third_party/pygments/tests/examplefiles/simple.camkes diff --git a/vendor/pygments/tests/examplefiles/simple.croc b/third_party/pygments/tests/examplefiles/simple.croc similarity index 100% rename from vendor/pygments/tests/examplefiles/simple.croc rename to third_party/pygments/tests/examplefiles/simple.croc diff --git a/vendor/pygments/tests/examplefiles/smarty_example.html b/third_party/pygments/tests/examplefiles/smarty_example.html similarity index 100% rename from vendor/pygments/tests/examplefiles/smarty_example.html rename to third_party/pygments/tests/examplefiles/smarty_example.html diff --git a/vendor/pygments/tests/examplefiles/source.lgt b/third_party/pygments/tests/examplefiles/source.lgt similarity index 100% rename from vendor/pygments/tests/examplefiles/source.lgt rename to third_party/pygments/tests/examplefiles/source.lgt diff --git a/vendor/pygments/tests/examplefiles/sources.list b/third_party/pygments/tests/examplefiles/sources.list similarity index 100% rename from vendor/pygments/tests/examplefiles/sources.list rename to third_party/pygments/tests/examplefiles/sources.list diff --git a/vendor/pygments/tests/examplefiles/sparql.rq b/third_party/pygments/tests/examplefiles/sparql.rq similarity index 100% rename from vendor/pygments/tests/examplefiles/sparql.rq rename to third_party/pygments/tests/examplefiles/sparql.rq diff --git a/vendor/pygments/tests/examplefiles/sphere.pov b/third_party/pygments/tests/examplefiles/sphere.pov similarity index 100% rename from vendor/pygments/tests/examplefiles/sphere.pov rename to third_party/pygments/tests/examplefiles/sphere.pov diff --git a/vendor/pygments/tests/examplefiles/sqlite3.sqlite3-console b/third_party/pygments/tests/examplefiles/sqlite3.sqlite3-console similarity index 100% rename from vendor/pygments/tests/examplefiles/sqlite3.sqlite3-console rename to third_party/pygments/tests/examplefiles/sqlite3.sqlite3-console diff --git a/vendor/pygments/tests/examplefiles/squid.conf b/third_party/pygments/tests/examplefiles/squid.conf similarity index 100% rename from vendor/pygments/tests/examplefiles/squid.conf rename to third_party/pygments/tests/examplefiles/squid.conf diff --git a/vendor/pygments/tests/examplefiles/string.jl b/third_party/pygments/tests/examplefiles/string.jl similarity index 100% rename from vendor/pygments/tests/examplefiles/string.jl rename to third_party/pygments/tests/examplefiles/string.jl diff --git a/vendor/pygments/tests/examplefiles/string_delimiters.d b/third_party/pygments/tests/examplefiles/string_delimiters.d similarity index 100% rename from vendor/pygments/tests/examplefiles/string_delimiters.d rename to third_party/pygments/tests/examplefiles/string_delimiters.d diff --git a/vendor/pygments/tests/examplefiles/stripheredoc.sh b/third_party/pygments/tests/examplefiles/stripheredoc.sh similarity index 100% rename from vendor/pygments/tests/examplefiles/stripheredoc.sh rename to third_party/pygments/tests/examplefiles/stripheredoc.sh diff --git a/vendor/pygments/tests/examplefiles/subr.el b/third_party/pygments/tests/examplefiles/subr.el similarity index 100% rename from vendor/pygments/tests/examplefiles/subr.el rename to third_party/pygments/tests/examplefiles/subr.el diff --git a/vendor/pygments/tests/examplefiles/swig_java.swg b/third_party/pygments/tests/examplefiles/swig_java.swg similarity index 100% rename from vendor/pygments/tests/examplefiles/swig_java.swg rename to third_party/pygments/tests/examplefiles/swig_java.swg diff --git a/vendor/pygments/tests/examplefiles/swig_std_vector.i b/third_party/pygments/tests/examplefiles/swig_std_vector.i similarity index 100% rename from vendor/pygments/tests/examplefiles/swig_std_vector.i rename to third_party/pygments/tests/examplefiles/swig_std_vector.i diff --git a/vendor/pygments/tests/examplefiles/tads3_example.t b/third_party/pygments/tests/examplefiles/tads3_example.t similarity index 100% rename from vendor/pygments/tests/examplefiles/tads3_example.t rename to third_party/pygments/tests/examplefiles/tads3_example.t diff --git a/vendor/pygments/tests/examplefiles/termcap b/third_party/pygments/tests/examplefiles/termcap similarity index 100% rename from vendor/pygments/tests/examplefiles/termcap rename to third_party/pygments/tests/examplefiles/termcap diff --git a/vendor/pygments/tests/examplefiles/terminfo b/third_party/pygments/tests/examplefiles/terminfo similarity index 100% rename from vendor/pygments/tests/examplefiles/terminfo rename to third_party/pygments/tests/examplefiles/terminfo diff --git a/vendor/pygments/tests/examplefiles/test-3.0.xq b/third_party/pygments/tests/examplefiles/test-3.0.xq similarity index 100% rename from vendor/pygments/tests/examplefiles/test-3.0.xq rename to third_party/pygments/tests/examplefiles/test-3.0.xq diff --git a/vendor/pygments/tests/examplefiles/test-exist-update.xq b/third_party/pygments/tests/examplefiles/test-exist-update.xq similarity index 100% rename from vendor/pygments/tests/examplefiles/test-exist-update.xq rename to third_party/pygments/tests/examplefiles/test-exist-update.xq diff --git a/vendor/pygments/tests/examplefiles/test.R b/third_party/pygments/tests/examplefiles/test.R similarity index 100% rename from vendor/pygments/tests/examplefiles/test.R rename to third_party/pygments/tests/examplefiles/test.R diff --git a/vendor/pygments/tests/examplefiles/test.adb b/third_party/pygments/tests/examplefiles/test.adb similarity index 100% rename from vendor/pygments/tests/examplefiles/test.adb rename to third_party/pygments/tests/examplefiles/test.adb diff --git a/vendor/pygments/tests/examplefiles/test.adls b/third_party/pygments/tests/examplefiles/test.adls similarity index 100% rename from vendor/pygments/tests/examplefiles/test.adls rename to third_party/pygments/tests/examplefiles/test.adls diff --git a/vendor/pygments/tests/examplefiles/test.agda b/third_party/pygments/tests/examplefiles/test.agda similarity index 100% rename from vendor/pygments/tests/examplefiles/test.agda rename to third_party/pygments/tests/examplefiles/test.agda diff --git a/vendor/pygments/tests/examplefiles/test.apl b/third_party/pygments/tests/examplefiles/test.apl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.apl rename to third_party/pygments/tests/examplefiles/test.apl diff --git a/vendor/pygments/tests/examplefiles/test.asy b/third_party/pygments/tests/examplefiles/test.asy similarity index 100% rename from vendor/pygments/tests/examplefiles/test.asy rename to third_party/pygments/tests/examplefiles/test.asy diff --git a/vendor/pygments/tests/examplefiles/test.awk b/third_party/pygments/tests/examplefiles/test.awk similarity index 100% rename from vendor/pygments/tests/examplefiles/test.awk rename to third_party/pygments/tests/examplefiles/test.awk diff --git a/vendor/pygments/tests/examplefiles/test.bb b/third_party/pygments/tests/examplefiles/test.bb similarity index 100% rename from vendor/pygments/tests/examplefiles/test.bb rename to third_party/pygments/tests/examplefiles/test.bb diff --git a/vendor/pygments/tests/examplefiles/test.bmx b/third_party/pygments/tests/examplefiles/test.bmx similarity index 100% rename from vendor/pygments/tests/examplefiles/test.bmx rename to third_party/pygments/tests/examplefiles/test.bmx diff --git a/vendor/pygments/tests/examplefiles/test.boo b/third_party/pygments/tests/examplefiles/test.boo similarity index 100% rename from vendor/pygments/tests/examplefiles/test.boo rename to third_party/pygments/tests/examplefiles/test.boo diff --git a/vendor/pygments/tests/examplefiles/test.bpl b/third_party/pygments/tests/examplefiles/test.bpl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.bpl rename to third_party/pygments/tests/examplefiles/test.bpl diff --git a/vendor/pygments/tests/examplefiles/test.bro b/third_party/pygments/tests/examplefiles/test.bro similarity index 100% rename from vendor/pygments/tests/examplefiles/test.bro rename to third_party/pygments/tests/examplefiles/test.bro diff --git a/vendor/pygments/tests/examplefiles/test.cadl b/third_party/pygments/tests/examplefiles/test.cadl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.cadl rename to third_party/pygments/tests/examplefiles/test.cadl diff --git a/vendor/pygments/tests/examplefiles/test.cs b/third_party/pygments/tests/examplefiles/test.cs similarity index 100% rename from vendor/pygments/tests/examplefiles/test.cs rename to third_party/pygments/tests/examplefiles/test.cs diff --git a/vendor/pygments/tests/examplefiles/test.csd b/third_party/pygments/tests/examplefiles/test.csd similarity index 100% rename from vendor/pygments/tests/examplefiles/test.csd rename to third_party/pygments/tests/examplefiles/test.csd diff --git a/vendor/pygments/tests/examplefiles/test.css b/third_party/pygments/tests/examplefiles/test.css similarity index 100% rename from vendor/pygments/tests/examplefiles/test.css rename to third_party/pygments/tests/examplefiles/test.css diff --git a/vendor/pygments/tests/examplefiles/test.cu b/third_party/pygments/tests/examplefiles/test.cu similarity index 100% rename from vendor/pygments/tests/examplefiles/test.cu rename to third_party/pygments/tests/examplefiles/test.cu diff --git a/vendor/pygments/tests/examplefiles/test.cyp b/third_party/pygments/tests/examplefiles/test.cyp similarity index 100% rename from vendor/pygments/tests/examplefiles/test.cyp rename to third_party/pygments/tests/examplefiles/test.cyp diff --git a/vendor/pygments/tests/examplefiles/test.d b/third_party/pygments/tests/examplefiles/test.d similarity index 100% rename from vendor/pygments/tests/examplefiles/test.d rename to third_party/pygments/tests/examplefiles/test.d diff --git a/vendor/pygments/tests/examplefiles/test.dart b/third_party/pygments/tests/examplefiles/test.dart similarity index 100% rename from vendor/pygments/tests/examplefiles/test.dart rename to third_party/pygments/tests/examplefiles/test.dart diff --git a/vendor/pygments/tests/examplefiles/test.dtd b/third_party/pygments/tests/examplefiles/test.dtd similarity index 100% rename from vendor/pygments/tests/examplefiles/test.dtd rename to third_party/pygments/tests/examplefiles/test.dtd diff --git a/vendor/pygments/tests/examplefiles/test.ebnf b/third_party/pygments/tests/examplefiles/test.ebnf similarity index 100% rename from vendor/pygments/tests/examplefiles/test.ebnf rename to third_party/pygments/tests/examplefiles/test.ebnf diff --git a/vendor/pygments/tests/examplefiles/test.ec b/third_party/pygments/tests/examplefiles/test.ec similarity index 100% rename from vendor/pygments/tests/examplefiles/test.ec rename to third_party/pygments/tests/examplefiles/test.ec diff --git a/vendor/pygments/tests/examplefiles/test.eh b/third_party/pygments/tests/examplefiles/test.eh similarity index 100% rename from vendor/pygments/tests/examplefiles/test.eh rename to third_party/pygments/tests/examplefiles/test.eh diff --git a/vendor/pygments/tests/examplefiles/test.erl b/third_party/pygments/tests/examplefiles/test.erl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.erl rename to third_party/pygments/tests/examplefiles/test.erl diff --git a/vendor/pygments/tests/examplefiles/test.evoque b/third_party/pygments/tests/examplefiles/test.evoque similarity index 100% rename from vendor/pygments/tests/examplefiles/test.evoque rename to third_party/pygments/tests/examplefiles/test.evoque diff --git a/vendor/pygments/tests/examplefiles/test.fan b/third_party/pygments/tests/examplefiles/test.fan similarity index 100% rename from vendor/pygments/tests/examplefiles/test.fan rename to third_party/pygments/tests/examplefiles/test.fan diff --git a/vendor/pygments/tests/examplefiles/test.flx b/third_party/pygments/tests/examplefiles/test.flx similarity index 100% rename from vendor/pygments/tests/examplefiles/test.flx rename to third_party/pygments/tests/examplefiles/test.flx diff --git a/vendor/pygments/tests/examplefiles/test.gdc b/third_party/pygments/tests/examplefiles/test.gdc similarity index 100% rename from vendor/pygments/tests/examplefiles/test.gdc rename to third_party/pygments/tests/examplefiles/test.gdc diff --git a/vendor/pygments/tests/examplefiles/test.gradle b/third_party/pygments/tests/examplefiles/test.gradle similarity index 100% rename from vendor/pygments/tests/examplefiles/test.gradle rename to third_party/pygments/tests/examplefiles/test.gradle diff --git a/vendor/pygments/tests/examplefiles/test.groovy b/third_party/pygments/tests/examplefiles/test.groovy similarity index 100% rename from vendor/pygments/tests/examplefiles/test.groovy rename to third_party/pygments/tests/examplefiles/test.groovy diff --git a/vendor/pygments/tests/examplefiles/test.html b/third_party/pygments/tests/examplefiles/test.html similarity index 100% rename from vendor/pygments/tests/examplefiles/test.html rename to third_party/pygments/tests/examplefiles/test.html diff --git a/vendor/pygments/tests/examplefiles/test.idr b/third_party/pygments/tests/examplefiles/test.idr similarity index 100% rename from vendor/pygments/tests/examplefiles/test.idr rename to third_party/pygments/tests/examplefiles/test.idr diff --git a/vendor/pygments/tests/examplefiles/test.ini b/third_party/pygments/tests/examplefiles/test.ini similarity index 100% rename from vendor/pygments/tests/examplefiles/test.ini rename to third_party/pygments/tests/examplefiles/test.ini diff --git a/vendor/pygments/tests/examplefiles/test.java b/third_party/pygments/tests/examplefiles/test.java similarity index 100% rename from vendor/pygments/tests/examplefiles/test.java rename to third_party/pygments/tests/examplefiles/test.java diff --git a/vendor/pygments/tests/examplefiles/test.jsp b/third_party/pygments/tests/examplefiles/test.jsp similarity index 100% rename from vendor/pygments/tests/examplefiles/test.jsp rename to third_party/pygments/tests/examplefiles/test.jsp diff --git a/vendor/pygments/tests/examplefiles/test.lean b/third_party/pygments/tests/examplefiles/test.lean similarity index 100% rename from vendor/pygments/tests/examplefiles/test.lean rename to third_party/pygments/tests/examplefiles/test.lean diff --git a/vendor/pygments/tests/examplefiles/test.maql b/third_party/pygments/tests/examplefiles/test.maql similarity index 100% rename from vendor/pygments/tests/examplefiles/test.maql rename to third_party/pygments/tests/examplefiles/test.maql diff --git a/vendor/pygments/tests/examplefiles/test.mask b/third_party/pygments/tests/examplefiles/test.mask similarity index 100% rename from vendor/pygments/tests/examplefiles/test.mask rename to third_party/pygments/tests/examplefiles/test.mask diff --git a/vendor/pygments/tests/examplefiles/test.mod b/third_party/pygments/tests/examplefiles/test.mod similarity index 100% rename from vendor/pygments/tests/examplefiles/test.mod rename to third_party/pygments/tests/examplefiles/test.mod diff --git a/vendor/pygments/tests/examplefiles/test.moo b/third_party/pygments/tests/examplefiles/test.moo similarity index 100% rename from vendor/pygments/tests/examplefiles/test.moo rename to third_party/pygments/tests/examplefiles/test.moo diff --git a/vendor/pygments/tests/examplefiles/test.myt b/third_party/pygments/tests/examplefiles/test.myt similarity index 100% rename from vendor/pygments/tests/examplefiles/test.myt rename to third_party/pygments/tests/examplefiles/test.myt diff --git a/vendor/pygments/tests/examplefiles/test.nim b/third_party/pygments/tests/examplefiles/test.nim similarity index 100% rename from vendor/pygments/tests/examplefiles/test.nim rename to third_party/pygments/tests/examplefiles/test.nim diff --git a/vendor/pygments/tests/examplefiles/test.odin b/third_party/pygments/tests/examplefiles/test.odin similarity index 100% rename from vendor/pygments/tests/examplefiles/test.odin rename to third_party/pygments/tests/examplefiles/test.odin diff --git a/vendor/pygments/tests/examplefiles/test.opa b/third_party/pygments/tests/examplefiles/test.opa similarity index 100% rename from vendor/pygments/tests/examplefiles/test.opa rename to third_party/pygments/tests/examplefiles/test.opa diff --git a/vendor/pygments/tests/examplefiles/test.orc b/third_party/pygments/tests/examplefiles/test.orc similarity index 100% rename from vendor/pygments/tests/examplefiles/test.orc rename to third_party/pygments/tests/examplefiles/test.orc diff --git a/vendor/pygments/tests/examplefiles/test.p6 b/third_party/pygments/tests/examplefiles/test.p6 similarity index 100% rename from vendor/pygments/tests/examplefiles/test.p6 rename to third_party/pygments/tests/examplefiles/test.p6 diff --git a/vendor/pygments/tests/examplefiles/test.pan b/third_party/pygments/tests/examplefiles/test.pan similarity index 100% rename from vendor/pygments/tests/examplefiles/test.pan rename to third_party/pygments/tests/examplefiles/test.pan diff --git a/vendor/pygments/tests/examplefiles/test.pas b/third_party/pygments/tests/examplefiles/test.pas similarity index 100% rename from vendor/pygments/tests/examplefiles/test.pas rename to third_party/pygments/tests/examplefiles/test.pas diff --git a/vendor/pygments/tests/examplefiles/test.php b/third_party/pygments/tests/examplefiles/test.php similarity index 100% rename from vendor/pygments/tests/examplefiles/test.php rename to third_party/pygments/tests/examplefiles/test.php diff --git a/vendor/pygments/tests/examplefiles/test.pig b/third_party/pygments/tests/examplefiles/test.pig similarity index 100% rename from vendor/pygments/tests/examplefiles/test.pig rename to third_party/pygments/tests/examplefiles/test.pig diff --git a/vendor/pygments/tests/examplefiles/test.plot b/third_party/pygments/tests/examplefiles/test.plot similarity index 100% rename from vendor/pygments/tests/examplefiles/test.plot rename to third_party/pygments/tests/examplefiles/test.plot diff --git a/vendor/pygments/tests/examplefiles/test.ps1 b/third_party/pygments/tests/examplefiles/test.ps1 similarity index 100% rename from vendor/pygments/tests/examplefiles/test.ps1 rename to third_party/pygments/tests/examplefiles/test.ps1 diff --git a/vendor/pygments/tests/examplefiles/test.psl b/third_party/pygments/tests/examplefiles/test.psl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.psl rename to third_party/pygments/tests/examplefiles/test.psl diff --git a/vendor/pygments/tests/examplefiles/test.pwn b/third_party/pygments/tests/examplefiles/test.pwn similarity index 100% rename from vendor/pygments/tests/examplefiles/test.pwn rename to third_party/pygments/tests/examplefiles/test.pwn diff --git a/vendor/pygments/tests/examplefiles/test.pypylog b/third_party/pygments/tests/examplefiles/test.pypylog similarity index 100% rename from vendor/pygments/tests/examplefiles/test.pypylog rename to third_party/pygments/tests/examplefiles/test.pypylog diff --git a/vendor/pygments/tests/examplefiles/test.r3 b/third_party/pygments/tests/examplefiles/test.r3 similarity index 100% rename from vendor/pygments/tests/examplefiles/test.r3 rename to third_party/pygments/tests/examplefiles/test.r3 diff --git a/vendor/pygments/tests/examplefiles/test.rb b/third_party/pygments/tests/examplefiles/test.rb similarity index 100% rename from vendor/pygments/tests/examplefiles/test.rb rename to third_party/pygments/tests/examplefiles/test.rb diff --git a/vendor/pygments/tests/examplefiles/test.rhtml b/third_party/pygments/tests/examplefiles/test.rhtml similarity index 100% rename from vendor/pygments/tests/examplefiles/test.rhtml rename to third_party/pygments/tests/examplefiles/test.rhtml diff --git a/vendor/pygments/tests/examplefiles/test.rsl b/third_party/pygments/tests/examplefiles/test.rsl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.rsl rename to third_party/pygments/tests/examplefiles/test.rsl diff --git a/vendor/pygments/tests/examplefiles/test.scaml b/third_party/pygments/tests/examplefiles/test.scaml similarity index 100% rename from vendor/pygments/tests/examplefiles/test.scaml rename to third_party/pygments/tests/examplefiles/test.scaml diff --git a/vendor/pygments/tests/examplefiles/test.sco b/third_party/pygments/tests/examplefiles/test.sco similarity index 100% rename from vendor/pygments/tests/examplefiles/test.sco rename to third_party/pygments/tests/examplefiles/test.sco diff --git a/vendor/pygments/tests/examplefiles/test.shen b/third_party/pygments/tests/examplefiles/test.shen similarity index 100% rename from vendor/pygments/tests/examplefiles/test.shen rename to third_party/pygments/tests/examplefiles/test.shen diff --git a/vendor/pygments/tests/examplefiles/test.ssp b/third_party/pygments/tests/examplefiles/test.ssp similarity index 100% rename from vendor/pygments/tests/examplefiles/test.ssp rename to third_party/pygments/tests/examplefiles/test.ssp diff --git a/vendor/pygments/tests/examplefiles/test.swift b/third_party/pygments/tests/examplefiles/test.swift similarity index 100% rename from vendor/pygments/tests/examplefiles/test.swift rename to third_party/pygments/tests/examplefiles/test.swift diff --git a/vendor/pygments/tests/examplefiles/test.tcsh b/third_party/pygments/tests/examplefiles/test.tcsh similarity index 100% rename from vendor/pygments/tests/examplefiles/test.tcsh rename to third_party/pygments/tests/examplefiles/test.tcsh diff --git a/vendor/pygments/tests/examplefiles/test.vb b/third_party/pygments/tests/examplefiles/test.vb similarity index 100% rename from vendor/pygments/tests/examplefiles/test.vb rename to third_party/pygments/tests/examplefiles/test.vb diff --git a/vendor/pygments/tests/examplefiles/test.vhdl b/third_party/pygments/tests/examplefiles/test.vhdl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.vhdl rename to third_party/pygments/tests/examplefiles/test.vhdl diff --git a/vendor/pygments/tests/examplefiles/test.xqy b/third_party/pygments/tests/examplefiles/test.xqy similarity index 100% rename from vendor/pygments/tests/examplefiles/test.xqy rename to third_party/pygments/tests/examplefiles/test.xqy diff --git a/vendor/pygments/tests/examplefiles/test.xsl b/third_party/pygments/tests/examplefiles/test.xsl similarity index 100% rename from vendor/pygments/tests/examplefiles/test.xsl rename to third_party/pygments/tests/examplefiles/test.xsl diff --git a/vendor/pygments/tests/examplefiles/test.zep b/third_party/pygments/tests/examplefiles/test.zep similarity index 100% rename from vendor/pygments/tests/examplefiles/test.zep rename to third_party/pygments/tests/examplefiles/test.zep diff --git a/vendor/pygments/tests/examplefiles/test2.odin b/third_party/pygments/tests/examplefiles/test2.odin similarity index 100% rename from vendor/pygments/tests/examplefiles/test2.odin rename to third_party/pygments/tests/examplefiles/test2.odin diff --git a/vendor/pygments/tests/examplefiles/test2.pypylog b/third_party/pygments/tests/examplefiles/test2.pypylog similarity index 100% rename from vendor/pygments/tests/examplefiles/test2.pypylog rename to third_party/pygments/tests/examplefiles/test2.pypylog diff --git a/vendor/pygments/tests/examplefiles/test_basic.adls b/third_party/pygments/tests/examplefiles/test_basic.adls similarity index 100% rename from vendor/pygments/tests/examplefiles/test_basic.adls rename to third_party/pygments/tests/examplefiles/test_basic.adls diff --git a/vendor/pygments/tests/examplefiles/truncated.pytb b/third_party/pygments/tests/examplefiles/truncated.pytb similarity index 100% rename from vendor/pygments/tests/examplefiles/truncated.pytb rename to third_party/pygments/tests/examplefiles/truncated.pytb diff --git a/vendor/pygments/tests/examplefiles/twig_test b/third_party/pygments/tests/examplefiles/twig_test similarity index 100% rename from vendor/pygments/tests/examplefiles/twig_test rename to third_party/pygments/tests/examplefiles/twig_test diff --git a/vendor/pygments/tests/examplefiles/type.lisp b/third_party/pygments/tests/examplefiles/type.lisp similarity index 100% rename from vendor/pygments/tests/examplefiles/type.lisp rename to third_party/pygments/tests/examplefiles/type.lisp diff --git a/vendor/pygments/tests/examplefiles/underscore.coffee b/third_party/pygments/tests/examplefiles/underscore.coffee similarity index 100% rename from vendor/pygments/tests/examplefiles/underscore.coffee rename to third_party/pygments/tests/examplefiles/underscore.coffee diff --git a/vendor/pygments/tests/examplefiles/unicode.applescript b/third_party/pygments/tests/examplefiles/unicode.applescript similarity index 100% rename from vendor/pygments/tests/examplefiles/unicode.applescript rename to third_party/pygments/tests/examplefiles/unicode.applescript diff --git a/vendor/pygments/tests/examplefiles/unicode.go b/third_party/pygments/tests/examplefiles/unicode.go similarity index 100% rename from vendor/pygments/tests/examplefiles/unicode.go rename to third_party/pygments/tests/examplefiles/unicode.go diff --git a/vendor/pygments/tests/examplefiles/unicode.js b/third_party/pygments/tests/examplefiles/unicode.js similarity index 100% rename from vendor/pygments/tests/examplefiles/unicode.js rename to third_party/pygments/tests/examplefiles/unicode.js diff --git a/vendor/pygments/tests/examplefiles/unicodedoc.py b/third_party/pygments/tests/examplefiles/unicodedoc.py similarity index 100% rename from vendor/pygments/tests/examplefiles/unicodedoc.py rename to third_party/pygments/tests/examplefiles/unicodedoc.py diff --git a/vendor/pygments/tests/examplefiles/unix-io.lid b/third_party/pygments/tests/examplefiles/unix-io.lid similarity index 100% rename from vendor/pygments/tests/examplefiles/unix-io.lid rename to third_party/pygments/tests/examplefiles/unix-io.lid diff --git a/vendor/pygments/tests/examplefiles/vbnet_test.bas b/third_party/pygments/tests/examplefiles/vbnet_test.bas similarity index 100% rename from vendor/pygments/tests/examplefiles/vbnet_test.bas rename to third_party/pygments/tests/examplefiles/vbnet_test.bas diff --git a/vendor/pygments/tests/examplefiles/vctreestatus_hg b/third_party/pygments/tests/examplefiles/vctreestatus_hg similarity index 100% rename from vendor/pygments/tests/examplefiles/vctreestatus_hg rename to third_party/pygments/tests/examplefiles/vctreestatus_hg diff --git a/vendor/pygments/tests/examplefiles/vimrc b/third_party/pygments/tests/examplefiles/vimrc similarity index 100% rename from vendor/pygments/tests/examplefiles/vimrc rename to third_party/pygments/tests/examplefiles/vimrc diff --git a/vendor/pygments/tests/examplefiles/vpath.mk b/third_party/pygments/tests/examplefiles/vpath.mk similarity index 100% rename from vendor/pygments/tests/examplefiles/vpath.mk rename to third_party/pygments/tests/examplefiles/vpath.mk diff --git a/vendor/pygments/tests/examplefiles/webkit-transition.css b/third_party/pygments/tests/examplefiles/webkit-transition.css similarity index 100% rename from vendor/pygments/tests/examplefiles/webkit-transition.css rename to third_party/pygments/tests/examplefiles/webkit-transition.css diff --git a/vendor/pygments/tests/examplefiles/while.pov b/third_party/pygments/tests/examplefiles/while.pov similarity index 100% rename from vendor/pygments/tests/examplefiles/while.pov rename to third_party/pygments/tests/examplefiles/while.pov diff --git a/vendor/pygments/tests/examplefiles/wiki.factor b/third_party/pygments/tests/examplefiles/wiki.factor similarity index 100% rename from vendor/pygments/tests/examplefiles/wiki.factor rename to third_party/pygments/tests/examplefiles/wiki.factor diff --git a/vendor/pygments/tests/examplefiles/xml_example b/third_party/pygments/tests/examplefiles/xml_example similarity index 100% rename from vendor/pygments/tests/examplefiles/xml_example rename to third_party/pygments/tests/examplefiles/xml_example diff --git a/vendor/pygments/tests/examplefiles/yahalom.cpsa b/third_party/pygments/tests/examplefiles/yahalom.cpsa similarity index 100% rename from vendor/pygments/tests/examplefiles/yahalom.cpsa rename to third_party/pygments/tests/examplefiles/yahalom.cpsa diff --git a/vendor/pygments/tests/examplefiles/zmlrpc.f90 b/third_party/pygments/tests/examplefiles/zmlrpc.f90 similarity index 100% rename from vendor/pygments/tests/examplefiles/zmlrpc.f90 rename to third_party/pygments/tests/examplefiles/zmlrpc.f90 diff --git a/vendor/pygments/tests/run.py b/third_party/pygments/tests/run.py similarity index 100% rename from vendor/pygments/tests/run.py rename to third_party/pygments/tests/run.py diff --git a/vendor/pygments/tests/string_asserts.py b/third_party/pygments/tests/string_asserts.py similarity index 100% rename from vendor/pygments/tests/string_asserts.py rename to third_party/pygments/tests/string_asserts.py diff --git a/vendor/pygments/tests/support.py b/third_party/pygments/tests/support.py similarity index 100% rename from vendor/pygments/tests/support.py rename to third_party/pygments/tests/support.py diff --git a/vendor/pygments/tests/support/tags b/third_party/pygments/tests/support/tags similarity index 100% rename from vendor/pygments/tests/support/tags rename to third_party/pygments/tests/support/tags diff --git a/vendor/pygments/tests/test_basic_api.py b/third_party/pygments/tests/test_basic_api.py similarity index 100% rename from vendor/pygments/tests/test_basic_api.py rename to third_party/pygments/tests/test_basic_api.py diff --git a/vendor/pygments/tests/test_cfm.py b/third_party/pygments/tests/test_cfm.py similarity index 100% rename from vendor/pygments/tests/test_cfm.py rename to third_party/pygments/tests/test_cfm.py diff --git a/vendor/pygments/tests/test_clexer.py b/third_party/pygments/tests/test_clexer.py similarity index 100% rename from vendor/pygments/tests/test_clexer.py rename to third_party/pygments/tests/test_clexer.py diff --git a/vendor/pygments/tests/test_cmdline.py b/third_party/pygments/tests/test_cmdline.py similarity index 100% rename from vendor/pygments/tests/test_cmdline.py rename to third_party/pygments/tests/test_cmdline.py diff --git a/vendor/pygments/tests/test_examplefiles.py b/third_party/pygments/tests/test_examplefiles.py similarity index 100% rename from vendor/pygments/tests/test_examplefiles.py rename to third_party/pygments/tests/test_examplefiles.py diff --git a/vendor/pygments/tests/test_ezhil.py b/third_party/pygments/tests/test_ezhil.py similarity index 100% rename from vendor/pygments/tests/test_ezhil.py rename to third_party/pygments/tests/test_ezhil.py diff --git a/vendor/pygments/tests/test_html_formatter.py b/third_party/pygments/tests/test_html_formatter.py similarity index 100% rename from vendor/pygments/tests/test_html_formatter.py rename to third_party/pygments/tests/test_html_formatter.py diff --git a/vendor/pygments/tests/test_inherit.py b/third_party/pygments/tests/test_inherit.py similarity index 100% rename from vendor/pygments/tests/test_inherit.py rename to third_party/pygments/tests/test_inherit.py diff --git a/vendor/pygments/tests/test_irc_formatter.py b/third_party/pygments/tests/test_irc_formatter.py similarity index 100% rename from vendor/pygments/tests/test_irc_formatter.py rename to third_party/pygments/tests/test_irc_formatter.py diff --git a/vendor/pygments/tests/test_java.py b/third_party/pygments/tests/test_java.py similarity index 100% rename from vendor/pygments/tests/test_java.py rename to third_party/pygments/tests/test_java.py diff --git a/vendor/pygments/tests/test_latex_formatter.py b/third_party/pygments/tests/test_latex_formatter.py similarity index 100% rename from vendor/pygments/tests/test_latex_formatter.py rename to third_party/pygments/tests/test_latex_formatter.py diff --git a/vendor/pygments/tests/test_lexers_other.py b/third_party/pygments/tests/test_lexers_other.py similarity index 100% rename from vendor/pygments/tests/test_lexers_other.py rename to third_party/pygments/tests/test_lexers_other.py diff --git a/vendor/pygments/tests/test_objectiveclexer.py b/third_party/pygments/tests/test_objectiveclexer.py similarity index 100% rename from vendor/pygments/tests/test_objectiveclexer.py rename to third_party/pygments/tests/test_objectiveclexer.py diff --git a/vendor/pygments/tests/test_perllexer.py b/third_party/pygments/tests/test_perllexer.py similarity index 100% rename from vendor/pygments/tests/test_perllexer.py rename to third_party/pygments/tests/test_perllexer.py diff --git a/vendor/pygments/tests/test_qbasiclexer.py b/third_party/pygments/tests/test_qbasiclexer.py similarity index 100% rename from vendor/pygments/tests/test_qbasiclexer.py rename to third_party/pygments/tests/test_qbasiclexer.py diff --git a/vendor/pygments/tests/test_regexlexer.py b/third_party/pygments/tests/test_regexlexer.py similarity index 100% rename from vendor/pygments/tests/test_regexlexer.py rename to third_party/pygments/tests/test_regexlexer.py diff --git a/vendor/pygments/tests/test_regexopt.py b/third_party/pygments/tests/test_regexopt.py similarity index 100% rename from vendor/pygments/tests/test_regexopt.py rename to third_party/pygments/tests/test_regexopt.py diff --git a/vendor/pygments/tests/test_rtf_formatter.py b/third_party/pygments/tests/test_rtf_formatter.py similarity index 100% rename from vendor/pygments/tests/test_rtf_formatter.py rename to third_party/pygments/tests/test_rtf_formatter.py diff --git a/vendor/pygments/tests/test_ruby.py b/third_party/pygments/tests/test_ruby.py similarity index 100% rename from vendor/pygments/tests/test_ruby.py rename to third_party/pygments/tests/test_ruby.py diff --git a/vendor/pygments/tests/test_shell.py b/third_party/pygments/tests/test_shell.py similarity index 100% rename from vendor/pygments/tests/test_shell.py rename to third_party/pygments/tests/test_shell.py diff --git a/vendor/pygments/tests/test_smarty.py b/third_party/pygments/tests/test_smarty.py similarity index 100% rename from vendor/pygments/tests/test_smarty.py rename to third_party/pygments/tests/test_smarty.py diff --git a/vendor/pygments/tests/test_string_asserts.py b/third_party/pygments/tests/test_string_asserts.py similarity index 100% rename from vendor/pygments/tests/test_string_asserts.py rename to third_party/pygments/tests/test_string_asserts.py diff --git a/vendor/pygments/tests/test_terminal_formatter.py b/third_party/pygments/tests/test_terminal_formatter.py similarity index 100% rename from vendor/pygments/tests/test_terminal_formatter.py rename to third_party/pygments/tests/test_terminal_formatter.py diff --git a/vendor/pygments/tests/test_textfmts.py b/third_party/pygments/tests/test_textfmts.py similarity index 100% rename from vendor/pygments/tests/test_textfmts.py rename to third_party/pygments/tests/test_textfmts.py diff --git a/vendor/pygments/tests/test_token.py b/third_party/pygments/tests/test_token.py similarity index 100% rename from vendor/pygments/tests/test_token.py rename to third_party/pygments/tests/test_token.py diff --git a/vendor/pygments/tests/test_unistring.py b/third_party/pygments/tests/test_unistring.py similarity index 100% rename from vendor/pygments/tests/test_unistring.py rename to third_party/pygments/tests/test_unistring.py diff --git a/vendor/pygments/tests/test_using_api.py b/third_party/pygments/tests/test_using_api.py similarity index 100% rename from vendor/pygments/tests/test_using_api.py rename to third_party/pygments/tests/test_using_api.py diff --git a/vendor/pygments/tests/test_util.py b/third_party/pygments/tests/test_util.py similarity index 100% rename from vendor/pygments/tests/test_util.py rename to third_party/pygments/tests/test_util.py diff --git a/vendor/pygments/tox.ini b/third_party/pygments/tox.ini similarity index 100% rename from vendor/pygments/tox.ini rename to third_party/pygments/tox.ini diff --git a/tools/generate.go b/tools/generate.go index ad6af0f5e..3adacf18e 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -21,7 +21,7 @@ import ( var siteDir = "./public" var cacheDir = "/tmp/gobyexample-cache" -var pygmentizeBin = "./vendor/pygments/pygmentize" +var pygmentizeBin = "./third_party/pygments/pygmentize" func verbose() bool { return len(os.Getenv("VERBOSE")) > 0 diff --git a/vendor/github.com/russross/blackfriday/.gitignore b/vendor/github.com/russross/blackfriday/.gitignore new file mode 100644 index 000000000..75623dccc --- /dev/null +++ b/vendor/github.com/russross/blackfriday/.gitignore @@ -0,0 +1,8 @@ +*.out +*.swp +*.8 +*.6 +_obj +_test* +markdown +tags diff --git a/vendor/github.com/russross/blackfriday/.travis.yml b/vendor/github.com/russross/blackfriday/.travis.yml new file mode 100644 index 000000000..a49fff15a --- /dev/null +++ b/vendor/github.com/russross/blackfriday/.travis.yml @@ -0,0 +1,18 @@ +sudo: false +language: go +go: + - "1.9.x" + - "1.10.x" + - "1.11.x" + - tip +matrix: + fast_finish: true + allow_failures: + - go: tip +install: + - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d -s .) + - go tool vet . + - go test -v -race ./... diff --git a/vendor/github.com/russross/blackfriday/LICENSE.txt b/vendor/github.com/russross/blackfriday/LICENSE.txt new file mode 100644 index 000000000..7fbb253a8 --- /dev/null +++ b/vendor/github.com/russross/blackfriday/LICENSE.txt @@ -0,0 +1,28 @@ +Blackfriday is distributed under the Simplified BSD License: + +Copyright © 2011 Russ Ross +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/vendor/github.com/russross/blackfriday/README.md b/vendor/github.com/russross/blackfriday/README.md new file mode 100644 index 000000000..997ef5d42 --- /dev/null +++ b/vendor/github.com/russross/blackfriday/README.md @@ -0,0 +1,364 @@ +Blackfriday +[![Build Status][BuildV2SVG]][BuildV2URL] +[![PkgGoDev][PkgGoDevV2SVG]][PkgGoDevV2URL] +=========== + +Blackfriday is a [Markdown][1] processor implemented in [Go][2]. It +is paranoid about its input (so you can safely feed it user-supplied +data), it is fast, it supports common extensions (tables, smart +punctuation substitutions, etc.), and it is safe for all utf-8 +(unicode) input. + +HTML output is currently supported, along with Smartypants +extensions. + +It started as a translation from C of [Sundown][3]. + + +Installation +------------ + +Blackfriday is compatible with modern Go releases in module mode. +With Go installed: + + go get github.com/russross/blackfriday + +will resolve and add the package to the current development module, +then build and install it. Alternatively, you can achieve the same +if you import it in a package: + + import "github.com/russross/blackfriday" + +and `go get` without parameters. + +Old versions of Go and legacy GOPATH mode might work, +but no effort is made to keep them working. + + +Versions +-------- + +Currently maintained and recommended version of Blackfriday is `v2`. It's being +developed on its own branch: https://github.com/russross/blackfriday/tree/v2 and the +documentation is available at +https://pkg.go.dev/github.com/russross/blackfriday/v2. + +It is `go get`-able in module mode at `github.com/russross/blackfriday/v2`. + +Version 2 offers a number of improvements over v1: + +* Cleaned up API +* A separate call to [`Parse`][4], which produces an abstract syntax tree for + the document +* Latest bug fixes +* Flexibility to easily add your own rendering extensions + +Potential drawbacks: + +* Our benchmarks show v2 to be slightly slower than v1. Currently in the + ballpark of around 15%. +* API breakage. If you can't afford modifying your code to adhere to the new API + and don't care too much about the new features, v2 is probably not for you. +* Several bug fixes are trailing behind and still need to be forward-ported to + v2. See issue [#348](https://github.com/russross/blackfriday/issues/348) for + tracking. + +If you are still interested in the legacy `v1`, you can import it from +`github.com/russross/blackfriday`. Documentation for the legacy v1 can be found +here: https://pkg.go.dev/github.com/russross/blackfriday. + + +Usage +----- + +### v1 + +For basic usage, it is as simple as getting your input into a byte +slice and calling: + +```go +output := blackfriday.MarkdownBasic(input) +``` + +This renders it with no extensions enabled. To get a more useful +feature set, use this instead: + +```go +output := blackfriday.MarkdownCommon(input) +``` + +### v2 + +For the most sensible markdown processing, it is as simple as getting your input +into a byte slice and calling: + +```go +output := blackfriday.Run(input) +``` + +Your input will be parsed and the output rendered with a set of most popular +extensions enabled. If you want the most basic feature set, corresponding with +the bare Markdown specification, use: + +```go +output := blackfriday.Run(input, blackfriday.WithNoExtensions()) +``` + +### Sanitize untrusted content + +Blackfriday itself does nothing to protect against malicious content. If you are +dealing with user-supplied markdown, we recommend running Blackfriday's output +through HTML sanitizer such as [Bluemonday][5]. + +Here's an example of simple usage of Blackfriday together with Bluemonday: + +```go +import ( + "github.com/microcosm-cc/bluemonday" + "github.com/russross/blackfriday" +) + +// ... +unsafe := blackfriday.Run(input) +html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) +``` + +### Custom options, v1 + +If you want to customize the set of options, first get a renderer +(currently only the HTML output engine), then use it to +call the more general `Markdown` function. For examples, see the +implementations of `MarkdownBasic` and `MarkdownCommon` in +`markdown.go`. + +### Custom options, v2 + +If you want to customize the set of options, use `blackfriday.WithExtensions`, +`blackfriday.WithRenderer` and `blackfriday.WithRefOverride`. + +### `blackfriday-tool` + +You can also check out `blackfriday-tool` for a more complete example +of how to use it. Download and install it using: + + go get github.com/russross/blackfriday-tool + +This is a simple command-line tool that allows you to process a +markdown file using a standalone program. You can also browse the +source directly on github if you are just looking for some example +code: + +* + +Note that if you have not already done so, installing +`blackfriday-tool` will be sufficient to download and install +blackfriday in addition to the tool itself. The tool binary will be +installed in `$GOPATH/bin`. This is a statically-linked binary that +can be copied to wherever you need it without worrying about +dependencies and library versions. + +### Sanitized anchor names + +Blackfriday includes an algorithm for creating sanitized anchor names +corresponding to a given input text. This algorithm is used to create +anchors for headings when `EXTENSION_AUTO_HEADER_IDS` is enabled. The +algorithm has a specification, so that other packages can create +compatible anchor names and links to those anchors. + +The specification is located at https://pkg.go.dev/github.com/russross/blackfriday#hdr-Sanitized_Anchor_Names. + +[`SanitizedAnchorName`](https://pkg.go.dev/github.com/russross/blackfriday#SanitizedAnchorName) exposes this functionality, and can be used to +create compatible links to the anchor names generated by blackfriday. +This algorithm is also implemented in a small standalone package at +[`github.com/shurcooL/sanitized_anchor_name`](https://pkg.go.dev/github.com/shurcooL/sanitized_anchor_name). It can be useful for clients +that want a small package and don't need full functionality of blackfriday. + + +Features +-------- + +All features of Sundown are supported, including: + +* **Compatibility**. The Markdown v1.0.3 test suite passes with + the `--tidy` option. Without `--tidy`, the differences are + mostly in whitespace and entity escaping, where blackfriday is + more consistent and cleaner. + +* **Common extensions**, including table support, fenced code + blocks, autolinks, strikethroughs, non-strict emphasis, etc. + +* **Safety**. Blackfriday is paranoid when parsing, making it safe + to feed untrusted user input without fear of bad things + happening. The test suite stress tests this and there are no + known inputs that make it crash. If you find one, please let me + know and send me the input that does it. + + NOTE: "safety" in this context means *runtime safety only*. In order to + protect yourself against JavaScript injection in untrusted content, see + [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content). + +* **Fast processing**. It is fast enough to render on-demand in + most web applications without having to cache the output. + +* **Thread safety**. You can run multiple parsers in different + goroutines without ill effect. There is no dependence on global + shared state. + +* **Minimal dependencies**. Blackfriday only depends on standard + library packages in Go. The source code is pretty + self-contained, so it is easy to add to any project, including + Google App Engine projects. + +* **Standards compliant**. Output successfully validates using the + W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional. + + +Extensions +---------- + +In addition to the standard markdown syntax, this package +implements the following extensions: + +* **Intra-word emphasis supression**. The `_` character is + commonly used inside words when discussing code, so having + markdown interpret it as an emphasis command is usually the + wrong thing. Blackfriday lets you treat all emphasis markers as + normal characters when they occur inside a word. + +* **Tables**. Tables can be created by drawing them in the input + using a simple syntax: + + ``` + Name | Age + --------|------ + Bob | 27 + Alice | 23 + ``` + +* **Fenced code blocks**. In addition to the normal 4-space + indentation to mark code blocks, you can explicitly mark them + and supply a language (to make syntax highlighting simple). Just + mark it like this: + + ```go + func getTrue() bool { + return true + } + ``` + + You can use 3 or more backticks to mark the beginning of the + block, and the same number to mark the end of the block. + + To preserve classes of fenced code blocks while using the bluemonday + HTML sanitizer, use the following policy: + + ```go + p := bluemonday.UGCPolicy() + p.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code") + html := p.SanitizeBytes(unsafe) + ``` + +* **Definition lists**. A simple definition list is made of a single-line + term followed by a colon and the definition for that term. + + Cat + : Fluffy animal everyone likes + + Internet + : Vector of transmission for pictures of cats + + Terms must be separated from the previous definition by a blank line. + +* **Footnotes**. A marker in the text that will become a superscript number; + a footnote definition that will be placed in a list of footnotes at the + end of the document. A footnote looks like this: + + This is a footnote.[^1] + + [^1]: the footnote text. + +* **Autolinking**. Blackfriday can find URLs that have not been + explicitly marked as links and turn them into links. + +* **Strikethrough**. Use two tildes (`~~`) to mark text that + should be crossed out. + +* **Hard line breaks**. With this extension enabled (it is off by + default in the `MarkdownBasic` and `MarkdownCommon` convenience + functions), newlines in the input translate into line breaks in + the output. + +* **Smart quotes**. Smartypants-style punctuation substitution is + supported, turning normal double- and single-quote marks into + curly quotes, etc. + +* **LaTeX-style dash parsing** is an additional option, where `--` + is translated into `–`, and `---` is translated into + `—`. This differs from most smartypants processors, which + turn a single hyphen into an ndash and a double hyphen into an + mdash. + +* **Smart fractions**, where anything that looks like a fraction + is translated into suitable HTML (instead of just a few special + cases like most smartypant processors). For example, `4/5` + becomes `45`, which renders as + 45. + + +Other renderers +--------------- + +Blackfriday is structured to allow alternative rendering engines. Here +are a few of note: + +* [github_flavored_markdown](https://pkg.go.dev/github.com/shurcooL/github_flavored_markdown): + provides a GitHub Flavored Markdown renderer with fenced code block + highlighting, clickable heading anchor links. + + It's not customizable, and its goal is to produce HTML output + equivalent to the [GitHub Markdown API endpoint](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode), + except the rendering is performed locally. + +* [markdownfmt](https://github.com/shurcooL/markdownfmt): like gofmt, + but for markdown. + +* [LaTeX output](https://gitlab.com/ambrevar/blackfriday-latex): + renders output as LaTeX. + +* [bfchroma](https://github.com/Depado/bfchroma/): provides convenience + integration with the [Chroma](https://github.com/alecthomas/chroma) code + highlighting library. bfchroma is only compatible with v2 of Blackfriday and + provides a drop-in renderer ready to use with Blackfriday, as well as + options and means for further customization. + +* [Blackfriday-Confluence](https://github.com/kentaro-m/blackfriday-confluence): provides a [Confluence Wiki Markup](https://confluence.atlassian.com/doc/confluence-wiki-markup-251003035.html) renderer. + +* [Blackfriday-Slack](https://github.com/karriereat/blackfriday-slack): converts markdown to slack message style + + +TODO +---- + +* More unit testing +* Improve Unicode support. It does not understand all Unicode + rules (about what constitutes a letter, a punctuation symbol, + etc.), so it may fail to detect word boundaries correctly in + some instances. It is safe on all UTF-8 input. + + +License +------- + +[Blackfriday is distributed under the Simplified BSD License](LICENSE.txt) + + + [1]: https://daringfireball.net/projects/markdown/ "Markdown" + [2]: https://golang.org/ "Go Language" + [3]: https://github.com/vmg/sundown "Sundown" + [4]: https://pkg.go.dev/github.com/russross/blackfriday/v2#Parse "Parse func" + [5]: https://github.com/microcosm-cc/bluemonday "Bluemonday" + + [BuildV2SVG]: https://travis-ci.org/russross/blackfriday.svg?branch=v2 + [BuildV2URL]: https://travis-ci.org/russross/blackfriday + [PkgGoDevV2SVG]: https://pkg.go.dev/badge/github.com/russross/blackfriday/v2 + [PkgGoDevV2URL]: https://pkg.go.dev/github.com/russross/blackfriday/v2 diff --git a/vendor/github.com/russross/blackfriday/block.go b/vendor/github.com/russross/blackfriday/block.go new file mode 100644 index 000000000..563cb2903 --- /dev/null +++ b/vendor/github.com/russross/blackfriday/block.go @@ -0,0 +1,1480 @@ +// +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. +// + +// +// Functions to parse block-level elements. +// + +package blackfriday + +import ( + "bytes" + "strings" + "unicode" +) + +// Parse block-level data. +// Note: this function and many that it calls assume that +// the input buffer ends with a newline. +func (p *parser) block(out *bytes.Buffer, data []byte) { + if len(data) == 0 || data[len(data)-1] != '\n' { + panic("block input is missing terminating newline") + } + + // this is called recursively: enforce a maximum depth + if p.nesting >= p.maxNesting { + return + } + p.nesting++ + + // parse out one block-level construct at a time + for len(data) > 0 { + // prefixed header: + // + // # Header 1 + // ## Header 2 + // ... + // ###### Header 6 + if p.isPrefixHeader(data) { + data = data[p.prefixHeader(out, data):] + continue + } + + // block of preformatted HTML: + // + //
    + // ... + //
    + if data[0] == '<' { + if i := p.html(out, data, true); i > 0 { + data = data[i:] + continue + } + } + + // title block + // + // % stuff + // % more stuff + // % even more stuff + if p.flags&EXTENSION_TITLEBLOCK != 0 { + if data[0] == '%' { + if i := p.titleBlock(out, data, true); i > 0 { + data = data[i:] + continue + } + } + } + + // blank lines. note: returns the # of bytes to skip + if i := p.isEmpty(data); i > 0 { + data = data[i:] + continue + } + + // indented code block: + // + // func max(a, b int) int { + // if a > b { + // return a + // } + // return b + // } + if p.codePrefix(data) > 0 { + data = data[p.code(out, data):] + continue + } + + // fenced code block: + // + // ``` go info string here + // func fact(n int) int { + // if n <= 1 { + // return n + // } + // return n * fact(n-1) + // } + // ``` + if p.flags&EXTENSION_FENCED_CODE != 0 { + if i := p.fencedCodeBlock(out, data, true); i > 0 { + data = data[i:] + continue + } + } + + // horizontal rule: + // + // ------ + // or + // ****** + // or + // ______ + if p.isHRule(data) { + p.r.HRule(out) + var i int + for i = 0; data[i] != '\n'; i++ { + } + data = data[i:] + continue + } + + // block quote: + // + // > A big quote I found somewhere + // > on the web + if p.quotePrefix(data) > 0 { + data = data[p.quote(out, data):] + continue + } + + // table: + // + // Name | Age | Phone + // ------|-----|--------- + // Bob | 31 | 555-1234 + // Alice | 27 | 555-4321 + if p.flags&EXTENSION_TABLES != 0 { + if i := p.table(out, data); i > 0 { + data = data[i:] + continue + } + } + + // an itemized/unordered list: + // + // * Item 1 + // * Item 2 + // + // also works with + or - + if p.uliPrefix(data) > 0 { + data = data[p.list(out, data, 0):] + continue + } + + // a numbered/ordered list: + // + // 1. Item 1 + // 2. Item 2 + if p.oliPrefix(data) > 0 { + data = data[p.list(out, data, LIST_TYPE_ORDERED):] + continue + } + + // definition lists: + // + // Term 1 + // : Definition a + // : Definition b + // + // Term 2 + // : Definition c + if p.flags&EXTENSION_DEFINITION_LISTS != 0 { + if p.dliPrefix(data) > 0 { + data = data[p.list(out, data, LIST_TYPE_DEFINITION):] + continue + } + } + + // anything else must look like a normal paragraph + // note: this finds underlined headers, too + data = data[p.paragraph(out, data):] + } + + p.nesting-- +} + +func (p *parser) isPrefixHeader(data []byte) bool { + if data[0] != '#' { + return false + } + + if p.flags&EXTENSION_SPACE_HEADERS != 0 { + level := 0 + for level < 6 && data[level] == '#' { + level++ + } + if data[level] != ' ' { + return false + } + } + return true +} + +func (p *parser) prefixHeader(out *bytes.Buffer, data []byte) int { + level := 0 + for level < 6 && data[level] == '#' { + level++ + } + i := skipChar(data, level, ' ') + end := skipUntilChar(data, i, '\n') + skip := end + id := "" + if p.flags&EXTENSION_HEADER_IDS != 0 { + j, k := 0, 0 + // find start/end of header id + for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ { + } + for k = j + 1; k < end && data[k] != '}'; k++ { + } + // extract header id iff found + if j < end && k < end { + id = string(data[j+2 : k]) + end = j + skip = k + 1 + for end > 0 && data[end-1] == ' ' { + end-- + } + } + } + for end > 0 && data[end-1] == '#' { + if isBackslashEscaped(data, end-1) { + break + } + end-- + } + for end > 0 && data[end-1] == ' ' { + end-- + } + if end > i { + if id == "" && p.flags&EXTENSION_AUTO_HEADER_IDS != 0 { + id = SanitizedAnchorName(string(data[i:end])) + } + work := func() bool { + p.inline(out, data[i:end]) + return true + } + p.r.Header(out, work, level, id) + } + return skip +} + +func (p *parser) isUnderlinedHeader(data []byte) int { + // test of level 1 header + if data[0] == '=' { + i := skipChar(data, 1, '=') + i = skipChar(data, i, ' ') + if data[i] == '\n' { + return 1 + } else { + return 0 + } + } + + // test of level 2 header + if data[0] == '-' { + i := skipChar(data, 1, '-') + i = skipChar(data, i, ' ') + if data[i] == '\n' { + return 2 + } else { + return 0 + } + } + + return 0 +} + +func (p *parser) titleBlock(out *bytes.Buffer, data []byte, doRender bool) int { + if data[0] != '%' { + return 0 + } + splitData := bytes.Split(data, []byte("\n")) + var i int + for idx, b := range splitData { + if !bytes.HasPrefix(b, []byte("%")) { + i = idx // - 1 + break + } + } + + data = bytes.Join(splitData[0:i], []byte("\n")) + p.r.TitleBlock(out, data) + + return len(data) +} + +func (p *parser) html(out *bytes.Buffer, data []byte, doRender bool) int { + var i, j int + + // identify the opening tag + if data[0] != '<' { + return 0 + } + curtag, tagfound := p.htmlFindTag(data[1:]) + + // handle special cases + if !tagfound { + // check for an HTML comment + if size := p.htmlComment(out, data, doRender); size > 0 { + return size + } + + // check for an
    tag + if size := p.htmlHr(out, data, doRender); size > 0 { + return size + } + + // check for HTML CDATA + if size := p.htmlCDATA(out, data, doRender); size > 0 { + return size + } + + // no special case recognized + return 0 + } + + // look for an unindented matching closing tag + // followed by a blank line + found := false + /* + closetag := []byte("\n") + j = len(curtag) + 1 + for !found { + // scan for a closing tag at the beginning of a line + if skip := bytes.Index(data[j:], closetag); skip >= 0 { + j += skip + len(closetag) + } else { + break + } + + // see if it is the only thing on the line + if skip := p.isEmpty(data[j:]); skip > 0 { + // see if it is followed by a blank line/eof + j += skip + if j >= len(data) { + found = true + i = j + } else { + if skip := p.isEmpty(data[j:]); skip > 0 { + j += skip + found = true + i = j + } + } + } + } + */ + + // if not found, try a second pass looking for indented match + // but not if tag is "ins" or "del" (following original Markdown.pl) + if !found && curtag != "ins" && curtag != "del" { + i = 1 + for i < len(data) { + i++ + for i < len(data) && !(data[i-1] == '<' && data[i] == '/') { + i++ + } + + if i+2+len(curtag) >= len(data) { + break + } + + j = p.htmlFindEnd(curtag, data[i-1:]) + + if j > 0 { + i += j - 1 + found = true + break + } + } + } + + if !found { + return 0 + } + + // the end of the block has been found + if doRender { + // trim newlines + end := i + for end > 0 && data[end-1] == '\n' { + end-- + } + p.r.BlockHtml(out, data[:end]) + } + + return i +} + +func (p *parser) renderHTMLBlock(out *bytes.Buffer, data []byte, start int, doRender bool) int { + // html block needs to end with a blank line + if i := p.isEmpty(data[start:]); i > 0 { + size := start + i + if doRender { + // trim trailing newlines + end := size + for end > 0 && data[end-1] == '\n' { + end-- + } + p.r.BlockHtml(out, data[:end]) + } + return size + } + return 0 +} + +// HTML comment, lax form +func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int { + i := p.inlineHTMLComment(out, data) + return p.renderHTMLBlock(out, data, i, doRender) +} + +// HTML CDATA section +func (p *parser) htmlCDATA(out *bytes.Buffer, data []byte, doRender bool) int { + const cdataTag = "') { + i++ + } + i++ + // no end-of-comment marker + if i >= len(data) { + return 0 + } + return p.renderHTMLBlock(out, data, i, doRender) +} + +// HR, which is the only self-closing block tag considered +func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int { + if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') { + return 0 + } + if data[3] != ' ' && data[3] != '/' && data[3] != '>' { + // not an
    tag after all; at least not a valid one + return 0 + } + + i := 3 + for data[i] != '>' && data[i] != '\n' { + i++ + } + + if data[i] == '>' { + return p.renderHTMLBlock(out, data, i+1, doRender) + } + + return 0 +} + +func (p *parser) htmlFindTag(data []byte) (string, bool) { + i := 0 + for isalnum(data[i]) { + i++ + } + key := string(data[:i]) + if _, ok := blockTags[key]; ok { + return key, true + } + return "", false +} + +func (p *parser) htmlFindEnd(tag string, data []byte) int { + // assume data[0] == '<' && data[1] == '/' already tested + + // check if tag is a match + closetag := []byte("") + if !bytes.HasPrefix(data, closetag) { + return 0 + } + i := len(closetag) + + // check that the rest of the line is blank + skip := 0 + if skip = p.isEmpty(data[i:]); skip == 0 { + return 0 + } + i += skip + skip = 0 + + if i >= len(data) { + return i + } + + if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 { + return i + } + if skip = p.isEmpty(data[i:]); skip == 0 { + // following line must be blank + return 0 + } + + return i + skip +} + +func (*parser) isEmpty(data []byte) int { + // it is okay to call isEmpty on an empty buffer + if len(data) == 0 { + return 0 + } + + var i int + for i = 0; i < len(data) && data[i] != '\n'; i++ { + if data[i] != ' ' && data[i] != '\t' { + return 0 + } + } + return i + 1 +} + +func (*parser) isHRule(data []byte) bool { + i := 0 + + // skip up to three spaces + for i < 3 && data[i] == ' ' { + i++ + } + + // look at the hrule char + if data[i] != '*' && data[i] != '-' && data[i] != '_' { + return false + } + c := data[i] + + // the whole line must be the char or whitespace + n := 0 + for data[i] != '\n' { + switch { + case data[i] == c: + n++ + case data[i] != ' ': + return false + } + i++ + } + + return n >= 3 +} + +// isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data, +// and returns the end index if so, or 0 otherwise. It also returns the marker found. +// If syntax is not nil, it gets set to the syntax specified in the fence line. +// A final newline is mandatory to recognize the fence line, unless newlineOptional is true. +func isFenceLine(data []byte, info *string, oldmarker string, newlineOptional bool) (end int, marker string) { + i, size := 0, 0 + + // skip up to three spaces + for i < len(data) && i < 3 && data[i] == ' ' { + i++ + } + + // check for the marker characters: ~ or ` + if i >= len(data) { + return 0, "" + } + if data[i] != '~' && data[i] != '`' { + return 0, "" + } + + c := data[i] + + // the whole line must be the same char or whitespace + for i < len(data) && data[i] == c { + size++ + i++ + } + + // the marker char must occur at least 3 times + if size < 3 { + return 0, "" + } + marker = string(data[i-size : i]) + + // if this is the end marker, it must match the beginning marker + if oldmarker != "" && marker != oldmarker { + return 0, "" + } + + // TODO(shurcooL): It's probably a good idea to simplify the 2 code paths here + // into one, always get the info string, and discard it if the caller doesn't care. + if info != nil { + infoLength := 0 + i = skipChar(data, i, ' ') + + if i >= len(data) { + if newlineOptional && i == len(data) { + return i, marker + } + return 0, "" + } + + infoStart := i + + if data[i] == '{' { + i++ + infoStart++ + + for i < len(data) && data[i] != '}' && data[i] != '\n' { + infoLength++ + i++ + } + + if i >= len(data) || data[i] != '}' { + return 0, "" + } + + // strip all whitespace at the beginning and the end + // of the {} block + for infoLength > 0 && isspace(data[infoStart]) { + infoStart++ + infoLength-- + } + + for infoLength > 0 && isspace(data[infoStart+infoLength-1]) { + infoLength-- + } + + i++ + } else { + for i < len(data) && !isverticalspace(data[i]) { + infoLength++ + i++ + } + } + + *info = strings.TrimSpace(string(data[infoStart : infoStart+infoLength])) + } + + i = skipChar(data, i, ' ') + if i >= len(data) { + if newlineOptional { + return i, marker + } + return 0, "" + } + if data[i] == '\n' { + i++ // Take newline into account + } + + return i, marker +} + +// fencedCodeBlock returns the end index if data contains a fenced code block at the beginning, +// or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects. +// If doRender is true, a final newline is mandatory to recognize the fenced code block. +func (p *parser) fencedCodeBlock(out *bytes.Buffer, data []byte, doRender bool) int { + var infoString string + beg, marker := isFenceLine(data, &infoString, "", false) + if beg == 0 || beg >= len(data) { + return 0 + } + + var work bytes.Buffer + + for { + // safe to assume beg < len(data) + + // check for the end of the code block + newlineOptional := !doRender + fenceEnd, _ := isFenceLine(data[beg:], nil, marker, newlineOptional) + if fenceEnd != 0 { + beg += fenceEnd + break + } + + // copy the current line + end := skipUntilChar(data, beg, '\n') + 1 + + // did we reach the end of the buffer without a closing marker? + if end >= len(data) { + return 0 + } + + // verbatim copy to the working buffer + if doRender { + work.Write(data[beg:end]) + } + beg = end + } + + if doRender { + p.r.BlockCode(out, work.Bytes(), infoString) + } + + return beg +} + +func (p *parser) table(out *bytes.Buffer, data []byte) int { + var header bytes.Buffer + i, columns := p.tableHeader(&header, data) + if i == 0 { + return 0 + } + + var body bytes.Buffer + + for i < len(data) { + pipes, rowStart := 0, i + for ; data[i] != '\n'; i++ { + if data[i] == '|' { + pipes++ + } + } + + if pipes == 0 { + i = rowStart + break + } + + // include the newline in data sent to tableRow + i++ + p.tableRow(&body, data[rowStart:i], columns, false) + } + + p.r.Table(out, header.Bytes(), body.Bytes(), columns) + + return i +} + +// check if the specified position is preceded by an odd number of backslashes +func isBackslashEscaped(data []byte, i int) bool { + backslashes := 0 + for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' { + backslashes++ + } + return backslashes&1 == 1 +} + +func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) { + i := 0 + colCount := 1 + for i = 0; data[i] != '\n'; i++ { + if data[i] == '|' && !isBackslashEscaped(data, i) { + colCount++ + } + } + + // doesn't look like a table header + if colCount == 1 { + return + } + + // include the newline in the data sent to tableRow + header := data[:i+1] + + // column count ignores pipes at beginning or end of line + if data[0] == '|' { + colCount-- + } + if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) { + colCount-- + } + + columns = make([]int, colCount) + + // move on to the header underline + i++ + if i >= len(data) { + return + } + + if data[i] == '|' && !isBackslashEscaped(data, i) { + i++ + } + i = skipChar(data, i, ' ') + + // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3 + // and trailing | optional on last column + col := 0 + for data[i] != '\n' { + dashes := 0 + + if data[i] == ':' { + i++ + columns[col] |= TABLE_ALIGNMENT_LEFT + dashes++ + } + for data[i] == '-' { + i++ + dashes++ + } + if data[i] == ':' { + i++ + columns[col] |= TABLE_ALIGNMENT_RIGHT + dashes++ + } + for data[i] == ' ' { + i++ + } + + // end of column test is messy + switch { + case dashes < 3: + // not a valid column + return + + case data[i] == '|' && !isBackslashEscaped(data, i): + // marker found, now skip past trailing whitespace + col++ + i++ + for data[i] == ' ' { + i++ + } + + // trailing junk found after last column + if col >= colCount && data[i] != '\n' { + return + } + + case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount: + // something else found where marker was required + return + + case data[i] == '\n': + // marker is optional for the last column + col++ + + default: + // trailing junk found after last column + return + } + } + if col != colCount { + return + } + + p.tableRow(out, header, columns, true) + size = i + 1 + return +} + +func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) { + i, col := 0, 0 + var rowWork bytes.Buffer + + if data[i] == '|' && !isBackslashEscaped(data, i) { + i++ + } + + for col = 0; col < len(columns) && i < len(data); col++ { + for data[i] == ' ' { + i++ + } + + cellStart := i + + for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' { + i++ + } + + cellEnd := i + + // skip the end-of-cell marker, possibly taking us past end of buffer + i++ + + for cellEnd > cellStart && data[cellEnd-1] == ' ' { + cellEnd-- + } + + var cellWork bytes.Buffer + p.inline(&cellWork, data[cellStart:cellEnd]) + + if header { + p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col]) + } else { + p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col]) + } + } + + // pad it out with empty columns to get the right number + for ; col < len(columns); col++ { + if header { + p.r.TableHeaderCell(&rowWork, nil, columns[col]) + } else { + p.r.TableCell(&rowWork, nil, columns[col]) + } + } + + // silently ignore rows with too many cells + + p.r.TableRow(out, rowWork.Bytes()) +} + +// returns blockquote prefix length +func (p *parser) quotePrefix(data []byte) int { + i := 0 + for i < 3 && data[i] == ' ' { + i++ + } + if data[i] == '>' { + if data[i+1] == ' ' { + return i + 2 + } + return i + 1 + } + return 0 +} + +// blockquote ends with at least one blank line +// followed by something without a blockquote prefix +func (p *parser) terminateBlockquote(data []byte, beg, end int) bool { + if p.isEmpty(data[beg:]) <= 0 { + return false + } + if end >= len(data) { + return true + } + return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0 +} + +// parse a blockquote fragment +func (p *parser) quote(out *bytes.Buffer, data []byte) int { + var raw bytes.Buffer + beg, end := 0, 0 + for beg < len(data) { + end = beg + // Step over whole lines, collecting them. While doing that, check for + // fenced code and if one's found, incorporate it altogether, + // irregardless of any contents inside it + for data[end] != '\n' { + if p.flags&EXTENSION_FENCED_CODE != 0 { + if i := p.fencedCodeBlock(out, data[end:], false); i > 0 { + // -1 to compensate for the extra end++ after the loop: + end += i - 1 + break + } + } + end++ + } + end++ + + if pre := p.quotePrefix(data[beg:]); pre > 0 { + // skip the prefix + beg += pre + } else if p.terminateBlockquote(data, beg, end) { + break + } + + // this line is part of the blockquote + raw.Write(data[beg:end]) + beg = end + } + + var cooked bytes.Buffer + p.block(&cooked, raw.Bytes()) + p.r.BlockQuote(out, cooked.Bytes()) + return end +} + +// returns prefix length for block code +func (p *parser) codePrefix(data []byte) int { + if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' { + return 4 + } + return 0 +} + +func (p *parser) code(out *bytes.Buffer, data []byte) int { + var work bytes.Buffer + + i := 0 + for i < len(data) { + beg := i + for data[i] != '\n' { + i++ + } + i++ + + blankline := p.isEmpty(data[beg:i]) > 0 + if pre := p.codePrefix(data[beg:i]); pre > 0 { + beg += pre + } else if !blankline { + // non-empty, non-prefixed line breaks the pre + i = beg + break + } + + // verbatim copy to the working buffeu + if blankline { + work.WriteByte('\n') + } else { + work.Write(data[beg:i]) + } + } + + // trim all the \n off the end of work + workbytes := work.Bytes() + eol := len(workbytes) + for eol > 0 && workbytes[eol-1] == '\n' { + eol-- + } + if eol != len(workbytes) { + work.Truncate(eol) + } + + work.WriteByte('\n') + + p.r.BlockCode(out, work.Bytes(), "") + + return i +} + +// returns unordered list item prefix +func (p *parser) uliPrefix(data []byte) int { + i := 0 + + // start with up to 3 spaces + for i < 3 && data[i] == ' ' { + i++ + } + + // need a *, +, or - followed by a space + if (data[i] != '*' && data[i] != '+' && data[i] != '-') || + data[i+1] != ' ' { + return 0 + } + return i + 2 +} + +// returns ordered list item prefix +func (p *parser) oliPrefix(data []byte) int { + i := 0 + + // start with up to 3 spaces + for i < 3 && data[i] == ' ' { + i++ + } + + // count the digits + start := i + for data[i] >= '0' && data[i] <= '9' { + i++ + } + + // we need >= 1 digits followed by a dot and a space + if start == i || data[i] != '.' || data[i+1] != ' ' { + return 0 + } + return i + 2 +} + +// returns definition list item prefix +func (p *parser) dliPrefix(data []byte) int { + i := 0 + + // need a : followed by a spaces + if data[i] != ':' || data[i+1] != ' ' { + return 0 + } + for data[i] == ' ' { + i++ + } + return i + 2 +} + +// parse ordered or unordered list block +func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int { + i := 0 + flags |= LIST_ITEM_BEGINNING_OF_LIST + work := func() bool { + for i < len(data) { + skip := p.listItem(out, data[i:], &flags) + i += skip + + if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 { + break + } + flags &= ^LIST_ITEM_BEGINNING_OF_LIST + } + return true + } + + p.r.List(out, work, flags) + return i +} + +// Parse a single list item. +// Assumes initial prefix is already removed if this is a sublist. +func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int { + // keep track of the indentation of the first line + itemIndent := 0 + for itemIndent < 3 && data[itemIndent] == ' ' { + itemIndent++ + } + + i := p.uliPrefix(data) + if i == 0 { + i = p.oliPrefix(data) + } + if i == 0 { + i = p.dliPrefix(data) + // reset definition term flag + if i > 0 { + *flags &= ^LIST_TYPE_TERM + } + } + if i == 0 { + // if in defnition list, set term flag and continue + if *flags&LIST_TYPE_DEFINITION != 0 { + *flags |= LIST_TYPE_TERM + } else { + return 0 + } + } + + // skip leading whitespace on first line + for data[i] == ' ' { + i++ + } + + // find the end of the line + line := i + for i > 0 && data[i-1] != '\n' { + i++ + } + + // process the following lines + containsBlankLine := false + sublist := 0 + codeBlockMarker := "" + if p.flags&EXTENSION_FENCED_CODE != 0 && i > line { + // determine if codeblock starts on the first line + _, codeBlockMarker = isFenceLine(data[line:i], nil, "", false) + } + + // get working buffer + var raw bytes.Buffer + + // put the first line into the working buffer + raw.Write(data[line:i]) + line = i + +gatherlines: + for line < len(data) { + i++ + + // find the end of this line + for data[i-1] != '\n' { + i++ + } + // if it is an empty line, guess that it is part of this item + // and move on to the next line + if p.isEmpty(data[line:i]) > 0 { + containsBlankLine = true + raw.Write(data[line:i]) + line = i + continue + } + + // calculate the indentation + indent := 0 + for indent < 4 && line+indent < i && data[line+indent] == ' ' { + indent++ + } + + chunk := data[line+indent : i] + + if p.flags&EXTENSION_FENCED_CODE != 0 { + // determine if in or out of codeblock + // if in codeblock, ignore normal list processing + _, marker := isFenceLine(chunk, nil, codeBlockMarker, false) + if marker != "" { + if codeBlockMarker == "" { + // start of codeblock + codeBlockMarker = marker + } else { + // end of codeblock. + *flags |= LIST_ITEM_CONTAINS_BLOCK + codeBlockMarker = "" + } + } + // we are in a codeblock, write line, and continue + if codeBlockMarker != "" || marker != "" { + raw.Write(data[line+indent : i]) + line = i + continue gatherlines + } + } + + // evaluate how this line fits in + switch { + // is this a nested list item? + case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) || + p.oliPrefix(chunk) > 0 || + p.dliPrefix(chunk) > 0: + + if containsBlankLine { + // end the list if the type changed after a blank line + if indent <= itemIndent && + ((*flags&LIST_TYPE_ORDERED != 0 && p.uliPrefix(chunk) > 0) || + (*flags&LIST_TYPE_ORDERED == 0 && p.oliPrefix(chunk) > 0)) { + + *flags |= LIST_ITEM_END_OF_LIST + break gatherlines + } + *flags |= LIST_ITEM_CONTAINS_BLOCK + } + + // to be a nested list, it must be indented more + // if not, it is the next item in the same list + if indent <= itemIndent { + break gatherlines + } + + // is this the first item in the nested list? + if sublist == 0 { + sublist = raw.Len() + } + + // is this a nested prefix header? + case p.isPrefixHeader(chunk): + // if the header is not indented, it is not nested in the list + // and thus ends the list + if containsBlankLine && indent < 4 { + *flags |= LIST_ITEM_END_OF_LIST + break gatherlines + } + *flags |= LIST_ITEM_CONTAINS_BLOCK + + // anything following an empty line is only part + // of this item if it is indented 4 spaces + // (regardless of the indentation of the beginning of the item) + case containsBlankLine && indent < 4: + if *flags&LIST_TYPE_DEFINITION != 0 && i < len(data)-1 { + // is the next item still a part of this list? + next := i + for data[next] != '\n' { + next++ + } + for next < len(data)-1 && data[next] == '\n' { + next++ + } + if i < len(data)-1 && data[i] != ':' && data[next] != ':' { + *flags |= LIST_ITEM_END_OF_LIST + } + } else { + *flags |= LIST_ITEM_END_OF_LIST + } + break gatherlines + + // a blank line means this should be parsed as a block + case containsBlankLine: + *flags |= LIST_ITEM_CONTAINS_BLOCK + } + + containsBlankLine = false + + // add the line into the working buffer without prefix + raw.Write(data[line+indent : i]) + + line = i + } + + // If reached end of data, the Renderer.ListItem call we're going to make below + // is definitely the last in the list. + if line >= len(data) { + *flags |= LIST_ITEM_END_OF_LIST + } + + rawBytes := raw.Bytes() + + // render the contents of the list item + var cooked bytes.Buffer + if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 && *flags&LIST_TYPE_TERM == 0 { + // intermediate render of block item, except for definition term + if sublist > 0 { + p.block(&cooked, rawBytes[:sublist]) + p.block(&cooked, rawBytes[sublist:]) + } else { + p.block(&cooked, rawBytes) + } + } else { + // intermediate render of inline item + if sublist > 0 { + p.inline(&cooked, rawBytes[:sublist]) + p.block(&cooked, rawBytes[sublist:]) + } else { + p.inline(&cooked, rawBytes) + } + } + + // render the actual list item + cookedBytes := cooked.Bytes() + parsedEnd := len(cookedBytes) + + // strip trailing newlines + for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' { + parsedEnd-- + } + p.r.ListItem(out, cookedBytes[:parsedEnd], *flags) + + return line +} + +// render a single paragraph that has already been parsed out +func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) { + if len(data) == 0 { + return + } + + // trim leading spaces + beg := 0 + for data[beg] == ' ' { + beg++ + } + + // trim trailing newline + end := len(data) - 1 + + // trim trailing spaces + for end > beg && data[end-1] == ' ' { + end-- + } + + work := func() bool { + p.inline(out, data[beg:end]) + return true + } + p.r.Paragraph(out, work) +} + +func (p *parser) paragraph(out *bytes.Buffer, data []byte) int { + // prev: index of 1st char of previous line + // line: index of 1st char of current line + // i: index of cursor/end of current line + var prev, line, i int + + // keep going until we find something to mark the end of the paragraph + for i < len(data) { + // mark the beginning of the current line + prev = line + current := data[i:] + line = i + + // did we find a blank line marking the end of the paragraph? + if n := p.isEmpty(current); n > 0 { + // did this blank line followed by a definition list item? + if p.flags&EXTENSION_DEFINITION_LISTS != 0 { + if i < len(data)-1 && data[i+1] == ':' { + return p.list(out, data[prev:], LIST_TYPE_DEFINITION) + } + } + + p.renderParagraph(out, data[:i]) + return i + n + } + + // an underline under some text marks a header, so our paragraph ended on prev line + if i > 0 { + if level := p.isUnderlinedHeader(current); level > 0 { + // render the paragraph + p.renderParagraph(out, data[:prev]) + + // ignore leading and trailing whitespace + eol := i - 1 + for prev < eol && data[prev] == ' ' { + prev++ + } + for eol > prev && data[eol-1] == ' ' { + eol-- + } + + // render the header + // this ugly double closure avoids forcing variables onto the heap + work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool { + return func() bool { + pp.inline(o, d) + return true + } + }(out, p, data[prev:eol]) + + id := "" + if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 { + id = SanitizedAnchorName(string(data[prev:eol])) + } + + p.r.Header(out, work, level, id) + + // find the end of the underline + for data[i] != '\n' { + i++ + } + return i + } + } + + // if the next line starts a block of HTML, then the paragraph ends here + if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 { + if data[i] == '<' && p.html(out, current, false) > 0 { + // rewind to before the HTML block + p.renderParagraph(out, data[:i]) + return i + } + } + + // if there's a prefixed header or a horizontal rule after this, paragraph is over + if p.isPrefixHeader(current) || p.isHRule(current) { + p.renderParagraph(out, data[:i]) + return i + } + + // if there's a fenced code block, paragraph is over + if p.flags&EXTENSION_FENCED_CODE != 0 { + if p.fencedCodeBlock(out, current, false) > 0 { + p.renderParagraph(out, data[:i]) + return i + } + } + + // if there's a definition list item, prev line is a definition term + if p.flags&EXTENSION_DEFINITION_LISTS != 0 { + if p.dliPrefix(current) != 0 { + return p.list(out, data[prev:], LIST_TYPE_DEFINITION) + } + } + + // if there's a list after this, paragraph is over + if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 { + if p.uliPrefix(current) != 0 || + p.oliPrefix(current) != 0 || + p.quotePrefix(current) != 0 || + p.codePrefix(current) != 0 { + p.renderParagraph(out, data[:i]) + return i + } + } + + // otherwise, scan to the beginning of the next line + for data[i] != '\n' { + i++ + } + i++ + } + + p.renderParagraph(out, data[:i]) + return i +} + +// SanitizedAnchorName returns a sanitized anchor name for the given text. +// +// It implements the algorithm specified in the package comment. +func SanitizedAnchorName(text string) string { + var anchorName []rune + futureDash := false + for _, r := range text { + switch { + case unicode.IsLetter(r) || unicode.IsNumber(r): + if futureDash && len(anchorName) > 0 { + anchorName = append(anchorName, '-') + } + futureDash = false + anchorName = append(anchorName, unicode.ToLower(r)) + default: + futureDash = true + } + } + return string(anchorName) +} diff --git a/vendor/github.com/russross/blackfriday/doc.go b/vendor/github.com/russross/blackfriday/doc.go new file mode 100644 index 000000000..9656c42a1 --- /dev/null +++ b/vendor/github.com/russross/blackfriday/doc.go @@ -0,0 +1,32 @@ +// Package blackfriday is a Markdown processor. +// +// It translates plain text with simple formatting rules into HTML or LaTeX. +// +// Sanitized Anchor Names +// +// Blackfriday includes an algorithm for creating sanitized anchor names +// corresponding to a given input text. This algorithm is used to create +// anchors for headings when EXTENSION_AUTO_HEADER_IDS is enabled. The +// algorithm is specified below, so that other packages can create +// compatible anchor names and links to those anchors. +// +// The algorithm iterates over the input text, interpreted as UTF-8, +// one Unicode code point (rune) at a time. All runes that are letters (category L) +// or numbers (category N) are considered valid characters. They are mapped to +// lower case, and included in the output. All other runes are considered +// invalid characters. Invalid characters that preceed the first valid character, +// as well as invalid character that follow the last valid character +// are dropped completely. All other sequences of invalid characters +// between two valid characters are replaced with a single dash character '-'. +// +// SanitizedAnchorName exposes this functionality, and can be used to +// create compatible links to the anchor names generated by blackfriday. +// This algorithm is also implemented in a small standalone package at +// github.com/shurcooL/sanitized_anchor_name. It can be useful for clients +// that want a small package and don't need full functionality of blackfriday. +package blackfriday + +// NOTE: Keep Sanitized Anchor Name algorithm in sync with package +// github.com/shurcooL/sanitized_anchor_name. +// Otherwise, users of sanitized_anchor_name will get anchor names +// that are incompatible with those generated by blackfriday. diff --git a/vendor/github.com/russross/blackfriday/go.mod b/vendor/github.com/russross/blackfriday/go.mod new file mode 100644 index 000000000..d0f058ae9 --- /dev/null +++ b/vendor/github.com/russross/blackfriday/go.mod @@ -0,0 +1,3 @@ +module github.com/russross/blackfriday + +go 1.13 diff --git a/vendor/github.com/russross/blackfriday/html.go b/vendor/github.com/russross/blackfriday/html.go new file mode 100644 index 000000000..fa044ca21 --- /dev/null +++ b/vendor/github.com/russross/blackfriday/html.go @@ -0,0 +1,945 @@ +// +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. +// + +// +// +// HTML rendering backend +// +// + +package blackfriday + +import ( + "bytes" + "fmt" + "regexp" + "strconv" + "strings" +) + +// Html renderer configuration options. +const ( + HTML_SKIP_HTML = 1 << iota // skip preformatted HTML blocks + HTML_SKIP_STYLE // skip embedded - -{%- endif %} -{% endblock %} - -{% block header %} -
    - -{% endblock %} - -{% block footer %} - -
    {# closes "outerwrapper" div #} -{% endblock %} - -{% block sidebarrel %} -{% endblock %} - -{% block sidebarsourcelink %} -{% endblock %} diff --git a/third_party/pygments/doc/_themes/pygments14/static/bodybg.png b/third_party/pygments/doc/_themes/pygments14/static/bodybg.png deleted file mode 100644 index 46892b801ac1088cdb7091f230bcb0eec1bfbe85..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 51903 zcmV)#K##wPP)7IfB;EEK~#9!P2D?|o5__eV64U@ z=)r-V9t@6x9@fe+$e;&9V}Q|?MgfB!{4~dA~S*i z5pm)?_G9z=%U}Nd+wFe;efRtOulxJ`x5NGZ@3-G~znt&K-*?~t=Wma{J$^a=zWdMX z{r;Cf|9biD@XznRod5cV-wuC!{QmOSKm30E%b)-D_|NO#|MbiDx7+X6e|*cQ{dV|u z|9^kXPv7rO8 z_>@om+vEAE@A>w>{Q39mKfmWw^Ns)SfB*95U$%ccJ-_4A^Gc7uobwxhd;Gfp>mPpE z=6iqN{q6LZKmYsV^Y?du{ll;Oe|&p>=RTkFe}DXC`|BmY`>zkVkLNX?zW+~tCRgx( zfBb#-+wE_s-){N5U(UJue}2wS=Z^pN;g{|68_s|K)4#slkG~y$-~Ihh|M>L0wq5S- zpWpAtT*I%I@Bfo0@ch5S^E-~uzdil!^!$`ZuHkUjF&{ z`FYQ$_4hyh`{VN&Typ*YdHv;_Z~lGvk59jB^UR)i^!Dri`IZjPzkTW5p6~bn_rK4l z_q^uccloyb&99gLeEoI*d@H-(cmMBy^G2Wl?UZNGtG?z_e!b-H|M4yF>@R=5AOHQf z`R(@ax4w$oU;prYh=*LxU;pr*ulfJE6DU|NU?NB@gZY z{`j}Y^LDmbKF`N=$>09|l5cw6{51>Ye$NAczLfKGsXVXZ_m@1d=h8U;=k>X4x6e1FXge`5Pw zNcU`E-kO{-^)EKCg411)lAkpZnWmlMDaP*Z%19fByOT zx!bSz<6r)qb>B7ji~_&zyT1?r{%9pWciy+WrmXRQe9I+f5C8uDTx<92-`vdKPFXB@ z*w4?q|9;Ib`}?2%^5?();rTdkS&8|!-ww}y*fq?UUD+XpxBUe5RkW5E7N1@1wtw1)OD(sP~`O zEQx&MKfmWy=NaUEWcmJb{@0h>b?!J3B#|!5EWg`G{{HKw@8$XY@<#vur%hf-ZZKcc zRr#I(nbrCGdmd6=%k$-3bD7T<@Ht^AU;6yl2F?5Nxvma*jJf^XX7)_JGHWxh+fw=M z@Vv--Zt-s?`#j(L`+GkBw_5^tmRXj-_y5U-WoJBJ<1Vl6Z;w3K{M~bLee9liKK6wA ztor9|z2uSPdlS~P<9<2kQ=X6FxxAkT#>E3j9LoC7HRq0=FYuDxn19PQ$d1bHeny&G zf_WZxf4PENea3(arkxn!qy|6cQHc`gb0`PW2-MA0mUXH>W+UOXexHFx`bI`4Vz zS+|bE%y37JfPBAkE)qAw8e+F_HSY7*2T$B4M8W^SQrd6Xd(|yIBI= z@p%T%WA0yH5}BUS_?VbzyFZ`(bF**q$g>unyYZG?^9<&ng?wM0OV7!f^_W-me}Bx{ z%nnL`%1im}_WajtURr{$*Ymu*mxSoNvVVOL!m~rOhI2d5(6<){et*f0WcTHDC%olB zWQEI1@^EstW@RTJ{=O5^vf%#tJ>Q-e`p@sr&)?^J^5XNF5(M+u^3ZZl=Mm>Fb1vr5 zW*_B6{_Ww&%EHMp*1i1PZ+V$nRs63>E8)tkLNM3Os&_6!q1?QD#on|feOukBdp7G$6bj58wE&DAH7OBV4w*}wM)zUIWvyT~)oHpqWw zC+FbE&t-AV`+CWe${Wn9&0@}S%y%`N{+wl-`0|fW*{r#Pe}CNk{ZC$5)@2@hZaW#H zSDRck>nD#%`j&sspR&*Ly0b5{EAsNPmvfPM#d77GZOv)l6P|KG$^Nq|^S$}EEV?|1 zpDCi_CSf@Ln(xSC=nMFqZ_A$f$G60-Jle*l9zl6M4R5FC)j!;cqpg2xrjW!aA<~K1 zrE=@tHTY(iWvS#vCA{W-5=y&(AGw2ne$Ri;-zLIkS*i#U)}QzG)=K1&EtK${SNnXr z`z#L!TJrGJA4y;HobwvJ+8mlHi=?%AzNwxPwDXP6C~)i{aZUVFnI#*M^yWTPaQWms z-(&!J@wu-2M$^XT5s3oNjriL7=edwJ*}u8z=LMe?Vp6Jv*SwTu&H0twMoO~m+3eZ| z*LxG7W6rnk{RZJ@g7G;!KA|tGJrCp=@V;ebCU)d^QvfDzWD%(~@@kVnR(^f6~EoG#%1ma@OgO&@VU~QwaE|UBgyI$VUp?R&T@Fj;PWUFeDe)G zS0C933DTZMuAndKoZl5K?#E=;J+iJnP9Dial2GN|vZQ(_9+J2^X`jpcwOio1>$CHc zXFThG@4ezg*7t<>1ooWg&k%h|p`8elD@e|eMWZ_DQ#hyO&XP%%k%J~rFj;;6Hk&ES z$9B$9nYfcru_cnL^f13?e zWpt_Rvm5gp-SN-WnUg8Uiie}qkd#CvpMt2b;+XU;CtQMW7M#;6uP_fciy^n1;G1xm zE6px*{w2?D?;&UCJvR`RS**<-jtQU+qVDNa7C~M>7EBI@@Bfp) zn@@l4t^S?!Qf=`4f3iIDkXP2y3gehpl0!~OmgVlN79>B&5tEmb<(Qm5%i|fE zzh%c}C#PU@R6UQoZA!L8<>ofKWDohhyqPTOTwRu4kIZXwpVkB0)Hrz;c{1Iw`yQb$ zdC&QGN$Mu2P##&n$P3M$mKoEOCi<}nCi26?=AaMV<=~t48E6p zYpQw9u8=hS>qCpBlN??Bo|x0je4kdyET7Mcx!-Pi*b=EMpM=dUTRHIG9+p%dK@PNp z{p>RPr0LPQMeQyRJ8>WpseAjF<(Rw9CnvW^4AIWY_dScuufk{Y`v&N%Q#Y@qcXSow za_mgv^_BxpWn($!I7v#EV=?(gHda!^MB3bCGnsuBdj2&}H!Y-;vw0p_TuI5(vB^eD z1ZlK5w$and#u1pG&hO;V%+}47`jljI`MWG;+a;fvC$vfU&uO8}lC_=PsGFC3vdxP_ zcjLoON=as^B-|t!%qni@@cAf`J>&~>)+UxDz&{`2B`+eUX-k%?-|eOE6NcL(dxlr( zVE&Zdl!ut0-}CSC{L?M_CofN#IH&j_;Vpk^n!4-xd(IwA-mcr1g_Pe;Y1AtEm;gGJ z$aCqf#!R{p3BPLW+@}YdKWPJrKUpeSQmF{?x)RvES_P#AkQyfkMy{saw^O!I7Jr`k z^T{+yh?^oWk)+8PI6s_Ro z*?CCW{R#Ei+sQYwq_SI*D{Jj0Ksl3j2lIlGduPXI53UnY8I;}svvr!*M)qQkqCDQb ztn8>PLiKd=j62si_{g_>*hmle% zdn&tDwV!8|Z*MyI+C_0o!z%Zm2$ZLh=ORIKWK0gS7p`rM?&(JZ`+NRVvD}5#c5iz) zk8Dm?l7pq~qHR8up5FU=9#d9mU(Z?U=Ru_5 zl2?+|+f?Y3Fqy+4Kc5@S`jQQ|dOzpIJJS+XEe0(k}jh+OXti*&MHD?}JZYtqbYd3)>H=GyXM9hV!qBo*Q-kBGl zwnH9vE;IuQ4V*l>EH7=+?6Cx2eaD`}TUm3`%av5-8&d1$W)w^b@E&JAFRv`i!UQ8} zSsr;7T(XfanqzX6?tzoXp4TC1%d*Zh$lghBu657F3s6ic3iCR$kMg;R0y!F5Hh-$rekXOn5I=aR)O{mt^s_2o)!v5dPC1+pa@E!t2UnF%(vv6&iC4(jUXLuwJml{Uee=hoAzv;U$Tdm-i>uWqlw%$ z-^)9s+8te(h2%s!LWO2@JnEZb+w zc~fma&*{sISzqinhgV+ecXLydi@eQzayL^uxOuku*EIX{ z1hSdLveaOkG%8kmCm$tvv>EacxRrR>N3G+}d3mkWFPfRHVvi}N^6}|{b+mCwYLyFb zt^ShNkVlXsAulZ6qxN{+~oM|5jwfw0m=|=2M<`^saVFUoXd4o<{bi zGEyy`m!EH&3CD{@b|(nw3AQ@Pb50~`bE=!JLArAi#a^ZAuF-R8fA?D!a-Q5qb)4X3M3Tjjy_o=SN~PA-ot6zJ%;h!xJoA)a z37d%sZI!fpEfL9uJpXh|M92koR?vebAvFt4KQTKuGx{v0&g~Cv@LV!^%zn>lp8(x# z{Yx$%BB1mAtuA8g-*bX~ZaX`wn~0WItj=B42u&9gN*u{vVqINTae^b6dH=)imj( z?XC`mrvYzBc*zOdjPj6&qur6ljGWqf&f`l!HciVXcOrGv;VYWuOZUbOC?qeX0qQik zf{zKv`5fb#Tx)x2mwaNvHH1rAG;I(c5(JfV$^OA9QV{7#G}2tf16R^V@_^J)oyZjW zsn?{ndKx*rjLGvU*%;Z4Ej$l-3R$*2s_yCO|CqR+vp+LVD#+#15$slTDv`A{!7hs- zznMi1xsaEfpq;FyaFfmebIskiGg5=A^0sD<*co4+)iJ+qu%7ESq0F1;anjjs`Z@RG zCIKz~n8zfrr|Rtv*}8DKqiR||u5pfyX#_bNTJvO87SWoGC~;gOoP1pjhRq)E`% zm`;|Vd7D>}SJrODMZ2~6_|>aW#wJP46=a*FN1-=igp;z=&dYOXd#vBAh|9Mn^T+~D z4$^7HF>@ElqeP#)3LTalqS>J$L+)LFa%DkT%uaDL5!-4twnRM$jYi=c=>J% ztRqxlE;m89=}Z>VPKwx3%CNO*6|OoUeTH*Br^hW zgHF`@mpvq6=IT@(IcoBEn}q)kH`-U0gSRi$>0r_x9l`t>2&MI`o2<{DP?j7x>0MrO z6Q)bf&^$_+g5FmyH;*B!(+myj#hf|`sbo;s9uT59w|ma+WYTSJoQ$G!Te*FuWu^d- zcsUzY8wugL{-m%uI#yp#vYST?{+f{6*PV&`3F zmj$PPnJ$SGvOBN&cn(8lb!T!{OHZknXWH!tm8hF{5&m-r1>K(Kg`PC3jHlXD{Ww|u z&9RuL&@%i1L(rk|ag~DNcu|kf?Y_y)q_yEBar(if6=%0k(PdGjf&}NtfzjFjA&;pc z_p}0(J|Rr8WsyJk94wqOdp{4hXZ5?mWpO+=o$@qrw4H)VoVMqS`F(;f7+MYo!7@9= zwZpx789C5^Q4)s+WKuXsQrq+t+P>|i5PT&ygwc)SvCzsFrCAP#BKXWDZ-6I>QWC?o zRN81c<@{~vz9pFF0Brp+ZQS-dj|JGgw2W*zSa|EhQ)@|kH~Jl%!f6J%AG-;z3H9&= zsdfqjxn|>ZZ=ZEU8d+NkHtL+jp=_ari_9}sB5%459@(K;*~TIHHNemOZBNMygbA2c z9z|Y!UZbL>QQ(mVtU+#8Y|q_OUZc}~0T(5A_DmW_fK0`{wd%+Y$g712P+2F1!&lv~v>O^RdI1~?`g)@jSn=B0H0c7r?2pNk|4+VJX#NwCd>O~#!U zn(ND1oS5@-j3p&?*5)ZBNwt5IB5GICdS`5KAOFmVC!B^^v=K_$Dz_NEwXTQEU znTr3r7&bQb>+8#Jcp1QqZIr%G2knunTqCkAm6P^K_W42$p(*5dTNB*m_epk)IP+Mv zY;zk0fb9DnFAIy)#oAYu@G56W-VPp8MB`Q_W5ksQVfdU{Lx-Sc=}t#o0L|H*%)C9p ztBz(f{ZDd?AH$}cvhUO6J!EuLDoY#P(&&c&W(e8)*})kOIkIv`233F}K&=V?=K8iv zdyE0V&4dF~ex@1c0heC0(bf=M$!H|+xfD>+j$x164(0Qd7vMD4_@A#Erv@x<_Cj7A zc!MM?E77Ba#Lo*XWV2}Eq-qIXS#=&0RE7zxvX6Z~>M{%nPmxF1YC4ota@ldl$imTyTLaZT#FHId-0%aUYiaaI&alAdb5+UkUr;rA6rFSj6MbMD0yP^lS`kMrtJ2Be zE8;p!$e{TJl&omJ$Fx~Knja+l$DqioH5tWI5HD%JFT5ZVe<8lPw!9LR=nAu{0 zpIiCqq=*N&AjqJOobQ@bW?6|AkbdTQ1CIQbPt7T5gp=FqOm138Fo}8bxyMd8UksXa zm$|;|v=XP<&BzM{qs-s6WPD_?;!8C7Y{b$y_oB3>+FZVAKb1DJ14%t@i6#^kq5IKXssoLOmdwHRWu6pIw`KYa{Fm*oLI1F)80|AnNWgt z+YX7g;B*>qMK0~Nl>qNB5VAxIE4$gNSw?0oFv(3w8+}B=LTNrKW7lM0n3ES2|2%sM zc%rh;+vGB3ss@p%dJ9qbs6Cqyo)DOtG=FDuKM23QSr&X?VhIQ)?78VbW~^qgx)=8! zVIdE&?AA|NGKQki0^r(8tr-~YfFJTH3EcUa96?U(?6iEFfo}jHIf+~HoZtx!hgQX+ z*VorwP_-s+JMJ$noYFUonnA}pIkBe)|2~baLpjh7nw;ayB<Pj4FBWhb*#7l7vmkhn(YN(MAg-A?XLoQn*ivb?VIJn@F6FMeN zb)^}$PIfG;rS_2>FK21ddL8U^B_{HTumRa5$(ArDN<2H|^O}6#6rrznc!8vVZuX(uX zk7qs0Ef6kB$?D`WeJN;Iltm0$NmO11R!r&&H;|eg(0eojE&$I+ok=QD!BSu)K;|(5 zO`&KOt#nNzrBKXWPVp@7JjiA(TMWFUQBK`*Z!XEM+hW}h(&+@+na9}#^aa2&d$1?& zwf&8o{2&Wcd%Ma22N7uvrSf#KbhF?RZxQEB6q8hfb6_TBTjq#f<8QrHJy4urjO)CS zEF{>+EDJIbkP=xy`8oMRFoAnLBVsJc%2y9BuL)tgSod3RwLpz@o(wh8Z-;5ak}PO#ikLT6cxCrB89Tk&XG znMGZM(zW1`qY;xdG*^YzlB^()Ca*j@1#%9N1I92rUzfcD@uHq_5y~~XfR>~|Otb=P zp$bKLwXH-FxXn$?SacC-EmU`52ziOXwoWRlEZck@g%Zqz)(v56@1d*#$Ffa!2jlAtOZ0dq(WQv7|nEm+CP6tc4OxKk0x5VE*r+@*VG zUU5l!G_8^k#-k93AfV~U5u(8yTHM@K(VGuye&;|*qS+x=_yOOIhH|BY(Yq!#X{l9z zWBQ4W7M++Fm9?pjRZ)2g#Mc~}o|ZmgmT7Sr+ct+9RVa@XUA#vW(?#r5;eZ#dhmvjO zuqoKB5LuvpEFmfJU;nUKfKF#)=W1=TWK3Dm_pJ;7t(Uv71SU@FBfkL`yavNMi%omZ zzP#z(@QUU{JZOOcM`qEr=XUPHcn4$79ISw_@)32t6G2SG@G)R=CU{)h8 z^xhRS4=x&J>nI(XX=$b-Y zu5UAK$qQ`~O(f?!^ZhL;8EvXc)7+9psgy`%v=4dJ4K?{INo5c2-iXrUc+iH|EQ^xI zPWcUy$Wh);uPWRom({HKJ-a05M<4cu-WM=*5--(s^5>pG+a-V^+`zvS_j(2YN{`!l zL=vLfR9}I>lFk_T<~2&F$^*LCdqu_Wo9ujZ#^*s8$8_{jUZB2r%bcACQ(if}uUx(Q zBg>{!iXv;|-jp-iQNICQn z9JootHTGUbE_O)S63CXSdmwUsN2&*T7nP{|G8N0I+`|G%C7;T<4(QHhTyJfOtGMxcTRy<_CkByehH z^fkJiPF0NIl_?|!A)_IhnwRAofG(<2x&@yyWgOw0b{nU;^10V^#v)eY5vvrg!82j~ z^7C1&N?&?kGIB*V;);k`9cs6`KftXN0P4;_p+10ArgYh2P#Zl z>SVT9hR*|WG#5|BGMCq&)s`t#Y+gr&RxhitgT-Hrf<~^B*ac>lWdRwdX#&?jG_6$Q zqbEqHaT+9}I0i(ieX~gNOC447InO0~+uTo7Nv1C{(BW%$zlUM&(^GTYnN*gPbA?X? z3MsB?nzwoOHlnyY{mzf#U%45_A+f$;A|)d;iAnMf2!euZVv&tw>{MF)ZPOXrg9ItL zfwXazWO{hHeFSV_snzFAP|e?z{B#EJ#;B*@l$!AZOlyx+MEtKo4MVNRc2~94)8bYbIA&4}cfWzB+c(m@>g0u+r zSvXzFdx+n>SZruwHtibRR!6Q+Y^NbKnj-J2ncUmL=@*aGrPQ>naI!TC!3`obQ%Q|V z#uBthY)f{NHv zI1?za`#Wc+(KB*qG;h~12S8Ls-`VQ>fo3zT}Qh2*@Hdp<>OF18DO++W7C7)s))a^stgq2h3vl z1ML{SImcKr6=zx?6>0cHjsYiWP3&}8+d_J1!@x4-lZqxdV;cj+<{&8g_(c3t7GlWN zG2IIt1i4f@sdqEJF2olDx+JdoQ=WBI9&Uhb#HOA{fB`6t0Qw+ift68dGs0^$4_F_H z#AW)0zl{=sXoTWr@JIgl3s4K_=)8wKLVl+Mc{XkXrDjSck0`MiRbq4tzMZSsa zu?6f2k2(L>Y3T(;Zt|hi>Z>f`Hz$VtTt)heLMn6eYt!YsrW4+AC~fqIGKO~a<~}eh zQ}&rKBwGSNSIISsy)V$pAStU4lC83V@Jljgoetf*vu|t@48b9T2gY;~8yFv8z>|e8 zQ)Oo?ktTAH|DDPQ&)hs zWgJ21g;@hJD#T3VAG$t-DVKtGbCoOdSe_OM+{6eic}*g~^0vaRwnkE7ebF2-D5iyq zUWh{|@6%+%2hZ{O>wW`}ot>eDSs28JkrS&@P05$rq#v3;orv9tJSrI%d%nfpI~3u6 zi$*5EgDR!b1D;VK=SPRiuO{Ecyr0P{^k$ADys{I{yMLQ!FL;-pes%+4XrzuR95jf- z_Dt`v^$e^%-67Izc{q@_376)G1nLu@t04MCTuYjV(4EB~2xAHmdr~5I^i>dBF_oj% zozp(siYlx2Y&JxXwoAcZH)7F2N)V5z8kl+GSGuKSt%>a*jpsAbX)65q8QPj~KR}Gk zL$REz)5}0rPXyU?VtfHQ%!6>6W{vAi6-==sj>xv5>CA%`2*D;|C(4|Rbn`fuz(W^T zm3}mB6W}#Vz{v|YdFx|6mpsw2QhL`Ia|z8#sj0;;uzA=n2B0$I(KEWH9j(=*$qRsn zrvzk@do$An7E5>)Qu8YEP_@Bn@99hcqhx{5JVXDq$g9mi(c?NX{spIJt0A z>N%a&yiynJVGcb-9ei6pMAF7Qa8lRpBz%J+bRQ~tay3XVxtlzUbmSJ{oE|tXo-3eM zR=#uP>=N3uDAH`T&WJRvLT}kEk_}sTH`n0oN@K&mc1ZSmIiu6PBEcm-~cI+2}ij` z=R(_$C?5&59j6Br}5q*>f~C)62y5d?7WRl%CU-g4Bav}nmG zVg(zSl3`epVW}1yZI#)3lA+-Dkg0RnEF%T5b8JB4)4b&B3+(j@&{T_Q8W|}OF3+Wm zg1f`8uloa-3&{#-;UaZTxIsdBDfDNFYYwG+Tcw~b^vFy%yFk7{UGWVfote11`YIaj zu*p2lhIQFI!e|<}ZwcQ%7XTd3QpL2(3W+>W!5a;nBc<7Qmae0S3=%aB70&Q-CZhaa@qt>fC{DQ%Mwo z<}1{;DBw1>(p+x-P=Z=xXQBmFZxV8J4VH|2*_2my5i{#JNP4q*bC)nt#9~$p82VCQ zMR%d&`BKU^Ik#YZ+L|o-y$IM-X9QdMWPV|#dDy6+-V?}9U<=YCNm1bluL$5NGS#=4 z@u4l*wLn@ep(^!&Tn>1mAyqw|6Xm`vN04kX5tUW{?qAdDWTeoB&_k!cVzVdRH%%pK zU`y1p^-8tSE7x?=En7pH2Fr`MQ6~R`N_YV(ABKfl_5X7 zDWC2;)>u{!iGlS0oSfY=cclq2(nX(y4@|9_OKg6B(Cj1+ztHbI{5lREX;!_#Whp}v zmdm2KYzemKdzF!dTj__1Bp{`5&kEGu?@KYl zS9Q;lp|8GKIna&jSRQ~-XKZqX%QZdJ znK0LLB(x>8)mu+C-^pIv#~GVYF)u6Nfz%1-Yi?jF$kZW!yY_wpJhUx7M5mSY^0WKv z%op6l0~xK6s|8^0E>FljG+ld5Cv9f<9IrSjBJ|FWrP8MHqI=gF=#IF8A3&am$zDgg zSAv-BKwNPY9j=Kv?Pr$uMPj1b1W|LlvchO7_*o;n$ga*|mo4CCVa7%xCV1Ny^*3Ek z)NaGX2FB5yai%C`tj@f~_OzO;__PULcM{GZZx=90rRzhSfB=8w%0=(DUGa3gIl_N?iemloMNF1qU?) zo~>4xB94w1osO9sG!d0M0zqX)x=B?z0+DY(6?NL!8CW73)3t9fdgNSH9wsaq zqvq8%Ss7_`Lr(NW;Sl~NSuWI^FuXEuUt&lKfbnOZsf42BS7j%&~i>&kY*ypoykoRlPid$oJWK3obf}f z`Qr6tnK@EZ`f@N3q=)8RqDkxa7sqYh$I3j?YiWDuY{UfUh479urQ^v3tvc%8hG-gf zq7mFh=*b;>Gp!F^HmO{}x6p+ZD|Xp-E8>0B-NauB-CMm3`et6Mh|>PdJ?#b zA3=|ft1ceP$O0X{vz^R>!yWJtSw!cP(X#1x)*J8>5SDaRE+62S@T#|&&+fxHK98x(C219UWqe(9E=f*w9t+`$p{u13)#A&t|uq03mn4VQ zCSSYI>MYKnT~wr{R(xN5DZ+7hM6}8z-(Sinre7 z;KIDQ=ELn97Fz<)v@?F!@Z33dMS47mp@;W|hl*9Ar+z z*}%6-qYpil<@^ct$H>JoTb+(KjTr{G8gJwu7(kNBU4}UIZ2Ddt@s6pS_APf69zkH` zxpT8fS_cH`GgVlAkcg)I+07xiB5rWWDBSCd=d6|KkJ-vL6|;d0!zlaBxD~~aZ#a~# zJq^WL=Fl4(h+3O=h9?yw!7@%3*U`*8p;pK!mPM<{9{u|ac&L#rh$^5u)ow!5AYVY$ zlm@aW#-MGAq#g<78EOU-t!nq+yhgu*G(ozOM7fzCFmrNmywvh7sq&d+CF*Is3jcW; zYxLWB{LMD00MB8xK#qn-)lfUI$^t+igu#)<2O+;~Qxqd(Elrz_{F?Vj?U#K^C*oE zJ+iDxbnlWszmYS^t6gVQ@)Ag7Xrbz9ARdYaSBb9oix z4aMvdK>t(dbL*8qtXh_SRRj-=Zc=t8Bt;7%n(6^fZqT$99mal@Y|Z`);vl)U%I zBRe(8ALV0y+klcDyTSIgUk zU=FD)lAJI_L+N-xPnfKbf?pV6q|+MOpIJkYo>^H20ci;4g?7k&g70O9byAkmRv)2!*T z;4eVJCO65}X<1eYwE`_S58$p8dt_aUAviH<9mvSzCqy+52ZXz1j00b=Ug=rfP$ke! z0m(2Qq)xslF=-OD9b5-B(Z>{kdfjq*8hKH>EedW>=6W zPS=HoX^s|R(N#SD*l9o&9TdaO`FlK7VrQ!{{f|$ZoE63Q-TcE03SKl+z!1x`;WKq# zv~cq@6S35`=J800Rv2IwE|2;*FO?f8lCnmQ1}srkr&(f z<(2Cp(|00r0O;c)Qkz#v5jR~rd}9Z9p@5K?+(Y?HA82n&G`#>S37(M2fS#cH z1!q_JlhnuN1~9_;C}88^+Yzt8aT3Jld#?8Q84**2I;tD)UAkb<#99u$4x>_(=k zdGvPU@(v~@ZA_WRk|j{(--ir&WT}pXleq740v-jQ;)Wr4Qfp{Yx60o!M9fW><@`!^ zwzz`583G|#J_8_AC9&R6vFLne$<^wvYDlGG7nMj1gG~jW;Pq;A&(-HjYIO*nKd+m7 zOBQG~R(D3zG}zk^f0v*U;We~v>AUAluuQzEujF$IF~72=gCokZ=(!N7MioP*Z+sy~ z36oIzxYCj=hC=r5f7I0u>2Ac)?Ugp^N72RcDIj)RTVuh~IK=oA! zY?5=Y=GmUDL?Qz{peIO%QR!Q>cNN<&%l%Z11GD&u*Z#ffT{+ zwAI7~vSv|8vjZe$0zCF>1})e!rERtgQ0=TXq(|>-OC=oXB$0;63X~823>o$+h~6Lo zm(_#?Y)>hNvqS4YSRSOfQBm42Jq`%ko~aenNBa45Ic$>Wh!=Fw5LPvgK)E1@i$ADi z5pY`7i9X1svXfzjV79S1lkmX+X+W004Q05i(M`R<4A(nK_=iN4MAI6|7TRb&jucrQ z=b472YFsO#UUXjxrPbByWW^#m&VXbl%mPlS1BcF z8r~el)O(tKqA9@3PfF)3;}6E=j53}FPrJx8T!_x=rv7JaOglfx*jP$`&W=`O=Cj~( zTY;3wORBZdf zx`OWD@=zTPR#Wyiejmft`V1_)VB%zU6JfRV6s4)MHZ4)MkiL?;*5}{p|E`m%Yv!f= z)U$IdkAa>qK|+J!Qj=cvtn>hQ>o7dZD#qpoen6tg_u?ZGQd@Fy{=`2I8H^@Tc3y_X z(>;7gp{j}eR%nETsW`-&{GH?i8r+yzl+QH0{D3^idw1~da z?!~DXS&TioYP*{Q$uhyDw@5F@KxttmlhP4ybic)ERTN4KSl6%EOET1lBz#6vIEA3Q zv{c$;DrUlf3_w&%uSe0Ll~;P8*A3{EVJAwZl!@S4g<)Q6-F%(1`-0k7l+I570048z z9_QSuV_mg&mlbn8f*wmA%BjX?+R)Z6V^T-EHy3W+4G2za!}3Yu1$H?&#=WrwyoX1_SV8#Pyki|UKh9>%bCm^WJ9 zNhM7uy7W5Y(d*Ng2A4I11OiR-4AITN2(r*bqIxL%aYlQgiN3lYt?u4e2~XZ*)75k@ z=B^%Ec{m+}9IJK_ALKMY8B3}s_F4_$cXk`L5|aqDd-k&$Tc9dx63ikbnkBo< zS0M`tn1|N*DrD)3j{wEU^)IlmgAY=BlkpEnYwgN%WIyWo6JM}~3NCm69y1}N?#ZR& zr`aPZ1WqUIe{e}U>nV(2#1Ur?MvkcYXpbFC_6pB@TheBRtYZ&(W9yKtS;>QE zNXo6JZyv^&$ivqy)$H~G?-Wkkd2I1$oK$ww)_Iwus9xP~62qnWZRn#)n1EbT2k>H{Jw3SaK1OX~6iHF=ek!vr$J zqTfCOG9{>OrbT#Mmhi)0d##)wx}eoCbdO$Fgkn}StpgnLel#{#39(7dpk;-e$; z)VP!cB23rD;D}uaGzCG-46fAuR<+S_Smm zDp2(VtJ7B6c&3MjS3zb1+uE?kZ21n1NKNBJ5SmVWTPO*e?c{|Mi%CrArt64(!;=dO zs58FN4DNv9zEzd!TzW^fV`0n_1Q?Tf0qSLOb3HKH z?Y`sS6I32A@e52Ktv#7}URFDDH${!45d=zh!KN`OpAMg?N88+W{ooi(1Cbac9lolS zy-Ia+m#rYKZPBn`>p;fmQ6>Whg^z$!&`;zBkX>6scS)y7rI28q8qf#jjAl0qZS`eEvLBBPqK z`I82SW+ow$aTMFjS(V4O2`_O&C^o!@9^lP1IY;lta7G@XJ*xyaLE+NAnJXYP~y?&+|NRqamhPJ z6Fw#*we;HL?pmJViNI^q!Ml@P@|%WG{&O6DN#)jFPHEi7d1M#ia~aYNZ0ijkn59-H zeB}^1(z00d6u{$f9;yLWj6?1Xa*6=$vYuhgCDW=>>n9~Lp)GXWl36Z>z}z5fazPTuNUoGlX?20V|Q@S)N!2jR6Qb6 zDw2}40a)i%D7rH5CIR0u>SbLYka-z>4V%RuT$`mAw%VZg&V8t2Z6myFNL{4yw?W75 zeu`k_j3;L!M+g4GZd`ub;uVZx9;a3prY#kP9L+Pj(yn~E1vcCD`#R=d%~}9l^+x{k=M7jxpaQaLLdj?uw7Uqv&xrQj zXu+b;chf|u?J%7nB@?!K`u;3**FYOGd0^E)tiUi^Zc``%IEdAKc(nRyu`=<|A0 zV5y_ENptWRnUZABH|aJ)5Ic2E(0^#1?u*jfGKtX4D#rh$xl%pQaVOMw$6tW0aV?G~ zUB4oou3XJ>1xWJ#PD!>R0|2^i3cT{tVKyVsh)OO%$&u0zkR4(T#57%iHleG3kVUPP zMBZ2blwfSZWABE4RVaCW|AsSQ3z$2;X&$WJF+6{%V4tiUge_y0f|5ph+^8fsQwf;E z%&l(hPn2PR4qknth2p5Ak78$7r5azbs7qnT45p9xJkm}r5BXyY?;MC3uT+fwM();3 zfsM22`V3@h%>)PdL-Tu-M;O`9RZRdbl=Y6kpOc5#g5x41?KWgbJK1-N*rV9lMnI!JJX$ zI=dOt0qN!-U=)eX!I1^#DS1r|sJfJj!6?3%J39Lqt}eCZxN$ptCV?7~)}1kB&ilNc z{_P3Rl{&r`VP66|Q>!2wV{V1ssYn9;T1r2yu`5=t2OmBTH-OSbFQ!!mpj_|_eV3Fz~ao=m<#5^uZ)sMjn)B zrY-MWkE-v(*XVBIX`zF7D4TP)O$QH>M5!cJBaVbY5L2o;khH^+>`RZpL7#2h8RVf7 zF^is!cgJ6H+&AvD_;rp)lx&B~lcU49M)t3x4g*v&#>HyW*DHbZtHo1f;SOSTi8ofH zVa%aiF8O-N7%?YoD z!;S&QVnC6F9HFSUWdb)2LJt5qvqG-o`FA}4Iwz=T%_FWGGDsz1ytr6m4s@rvObGf~ zIjRK4>2!6m{Jlme(h&5Apk>gbE0i;baak ztqrHTYbG;QqCFf+1P+Iz%bJQiyRK=V(Sr*GKWI} zNy`3R{pV7iZgOgsc-E<2J@S)LXi>JEZqPOMUW*6BVITwa+^ZT=9s~MbYEIQ#tlW6&~%a)d)l;nMI zmbXy}Lvg4x?pI(6?U-_XZuDfRiBra{GgW(ELJ;ubf^C&;Ty(Jn&21G4crm`9LqPOF z8L6N&^nuO81<>=7=IKmm(WD{NJid0Z2pAZ6^oZ#XX<(b4lein?&3hj2(g!Basuo}N zi+X$&rz;PF0|_aa8514QPsc8z2t?XSMm-u^`R2rz=0it^L&rp4kZxFGV-9g*pbMrI zCzzw|XD7Q-jz9Gm`UFqt%`6pAjNmLT?hBgGsO$uNs2ydZkybSn}&kXbfVq z-<;k6&$I(o>IFgXpaL`MF_Bop%ULvZJ~<&dVmh0+=J64(PDJnml8`p>I{ozdDVpHp z61U3LgQ92Gf?WcDzzGWaT#v93(!pTw##vpPDlax$jnpQ}3HJc%V)PG6DBCZqXo$x2 z5At4;`cWFn$=*_s95frhV@0JkiDqiq`r}lwXfE|yNYGq1DvBg#i5Q*KbP)Huht&*=BNvoGIf9^l2R7x-)B zQJLqVW15d^60Ih0nSZ=>c57ZHMj3Y*1j+sptTcds3dnFESwInl_ry+i@i}!(6qBU# zV4+araDWv`WLYl9hRT$YlZ+9X&H^@(1ro~=&a+YtLHDi+psD|g5xFa4-K)cw5VCU9Ae${R+vkT=B;!mslm>~#MFN-aVS9`>;C54e0##la&aI4G?n9K8Q@4c# zm9Jmt=m1Yiy6P@iJfeftc5lmKj{-<~eb7>gwg4lX{uoB!_L0wJ<~f+B12h#=48(6^ zBDo3_1LzmEMuPJ-qCJ|;iXYuBM``p%jg9L*gVF}%QjhM#0Ju=l7G$c<`k8^m}TJ1Z^XYyh7?-5P)8!=YJ!qcRv6dKm9QT>)%309VtC%8fCaQ1ZFze4pPaP|e1CG=BsPq42*+D&nxB*azqrHu@wkhbmc7?X%w zHNv(7hB^a5FFHD=fW`HbahM0uI^`xrW(g39TN6s-TcWf*bx+fT-qYBxdf{2aRH6pP ziCmT|MaXnIGoJ&BqY*IF&=30QiAbHnpJ|_Hn8Ph)r(+_?<>fh}Tw33cLALGR=i!;4_SY4i65P5}ceq4>2gdku>RE;Kc@3i!0Z!PPntLCM<(lo+F}+GBiM77|Iu*u^Go9Jtt5lzX2nlSxxMKbb=g z{A0A+PQ2Zrj7ZBf0p^DWC7@pdP)FuZ%S?}ULq-`LV<3ljhU^9+cxW`NNI~T*b^o+5 zK}74I+s2VTIy(ldx%{^=Qf1-9+PR3C9k8VfE)ID=52Az<;<-a8f^fapD-+8@(5p7{TSmcw=7fvwDwhMV1M=!>6M!FTKxYpVAv6YmIP5Z ztT$XE)hvMm_Ng$bZU)X5i!W^!MN)?wJIV!#Gy^?(G1E73=NdMz=U7#ND|)->zcCRn zT`#5QWQAqR^1FbZ>YfjF@TOr}zF)ly`^w(%33wezYddGZ8LxoTC0@b*B~EsDd*b@R z0f}tZpoZ=S(P-fvS-p{q=z(#dcD|fN@+8sW(_n`H%C}`R@mS(&ngA~&OLq_|5=IzX zLK2v($+R?Ycf)K<8a2eJ%bFiK^-&CqMBO7a`VHlVs=O!Xtv(k=r?{~MSefAl9$#`$ zm3m${*hhE&3u0H{7hC3%@QLbQl}9&Ed2%WsvQONTsRv^e zQ%0%6>33x(_fslNu#LI*j^fXGS}kd>o|P&AlbUyuwpRCA$O~aHShqlLbt41XgC3TE*+A;k~{9L`QPo(6t@*d=-j@zo9-iK zYdVV-WQn8KHIzaPE#d9ViHk@C8C$bJ4V;oSzbjQo!|$L)qi}1jaRlDfm~kx_iX`sD z3uawaA^SSc30tB(%&?4gR`H$R0)Z!GxlmWhEl~Js7~hDQJYp)A=ThGAsqPW*4s5wh zB53azku3j!eEf_#_T}9jCs}+2K``IS2#2I;n8PMzDvc`;k1eCQS!NW5dcxO% z_%O-S2hG{M6vFMvWOxN=;23P@&a38AQz|tOf_O{MchwQK6n(@T3F?J(=u36q6`(gU z5ofxZsN)zy5s04yY+%&}_XMmQW61Q5ay%fp%;E-R0<$4F?r{<(XITKw+0*6XoB>Rj za*3Jy(WnP2o{Cq=9T#D>8R&r#JOn}Vh}B5OlLG`F@#M!cdN4iYhexUfbdp~YYN$EI zqNwN9azC%~f2$PjqN4P#1MoiTUQ#YipO9Fj@ydd{0#+;`t1JPsiv(Ked`;STckC!k zd3`J$b>L2BIxL*1j{=hsukE5axO1we1-v}yD;md{GJ>IXhOq^usTjshN$Wcb<-eNx zFBMfxf!1El4#GP;~pm!`8vjbGym544hx{QLOI%QeW zQ#zyLB@@7RHaHnSzTJOe{I?7s$x^Ynl1gfzOa)Z%t1QTbgD`$#4q`n|A6XR^5M94H zyT2~LM)gIvWGfwf3TV>_l-Um8-#T~Mb!K=Yajjds@RQ7C`b<0RAobN&*k>F`vfDgQ z(`w4$xnYBp@Q@ggFy}0*9QlDsadxPcZ_nfdNK566A|ONEQ{9j?Zp;i*gxBUfemZSr zv6u{GN0O7pB&6es-Cuqo%ETT)LldaD!x>E%gIkB)Wcsx8JAk^>W8@1qAT53vVT5xO zFD>2_dlm@5B+>ZM^4XG#RK%4i`$J-z#Os*ZoykUH5)1<3Ua5!C2Few{S91131*EDPxBjVGAyD_( z{V8g|D)MTVZ@4LZ&)R7-=X*!_|BF#mj=N$VPAj~&QvXWIp_t>nRx&V(=z}L!jo*vq zP$o4wr&sk+%3)}00F@D%`Dnb8G7YJom<=kYS5`LQSBgbi<6>P7ND}ot(x5Cz?F`xV zKyX*9OHqg(W01BaFi=PT^ST+u{GKFgah!gPS38BKCglvLi!NN+J4!dJ4kF%Ts*l(= zBMpF!AJT9aj^)dfE8%Md%(p4$mhS%Y{$}%*Z|-cO0}qljq?Vurs$6;^bmi49TZBmi z-#r{~?R+BYC5|F}!Zuq!s^_I(ZQl+wwwT_R`i$>6^yKx(0LW(1{Uv^my z7-p2@At{nV7cEXJ^qobO2TPijM>tuBTwT6zK_duV>gO37a~FlPV~Sx+osI)2byW(c zN?2lxgS$BrfFiA31KepzQS8bi<~0oHRiz)3i=B!-FN#}ud#X2jf)&?odij&F#0`au ztDJ$cH$eN3H**p*jm5}k&)1_Ph5`MUMj@H zSHT0KMPUdML1!OQx?&xXUq8ar?bCngWpHnNbz7%EaK{ z3R**)hKyDuCE6_%QapohKngs8a}z|^Qk>D+Eyen?$sO&iu_n}C+a<_A*zo^VFYwpM ztub8i8u5@IVc>z?LWAY2&m*HuzfdEEyN^L`iZfo^DCK%-sT}MJvTf|u3&Xhc888mc zvhWaD+vm|$=BhG|h}HIay~BHR(JQ=k|&n+sWlXPx&h8}%1SLzFDv<+>f|wEpAU1><;?Q? zZi9~lvD$w2KBunrUsc=NGCdaL*p#uFWsz>$EY+dvGbYb3BN$blzvK_{hk*kEX~LX- zB0&avH`ptj{+LM>LUC~Z={tIPG6kpu28?oL8X73xC}_})^aRBrgIDh85Q=gEw2@pX zA=ts&LP%CJqA#zkL1c{NHAH05H;i@K%4R>+*qJ8-^W>Fgp=(?hnF;muo|g^}{L>jo z*Oa&}g_TYKZ~V%k4whm9H^JfnZgp3=n4`!ta@F9dmhz^uV@F@PTENB#s$;6V9r}D4 zMRmaAC^N zi|QQWU`R4L{#W5p*_GvuSS>%uLd!LqFc_Ii)hrq!%jOEGR)Qs)IU;e$p%8;~NKsOY zSv-{kus3BiRMuyJOoDGBsnH_yePl52Y5AyQQVJ@OL2k;){IImbypKGi#Era0UM~3^ zoQq!7U6Y(1qkgOcy6~EVg_#Amk?*d@KK#|w^45l!5st|a8Z#s_C%a_lEd{+&wok++ z^4nQ|7`fvw9xBsUuSXURtW^N|9uOQDHLn6t9WqG?S_7)fe8-W*-6F6fJ!hXxv*x}U zQO;P}S2h3VWPRTke{1L_#`cP(BCCg;{S7Q=gll#i#96 zHgpB4xqY#s8oh!$r6fyln96N>w=H}yMFD~>>-T~Ob}e3R#{~RNwl8(E@(u?I?~7N!35@Fpu~{61Ji#1KZLIB#_Ok`^$-kU8fI}wG zN|=^{?Z1H=GmO`L%L+r^q#i78z{ByQXLdjr3{S{-g=hg&iGVWKfTsd2m3YdI=c^I& zi7q@Hj5cydRt^>x0h)j%Bg@g(J5%1I&&BL2RSZG-A9nKHTZHN%dP)nwC_FnI9WO)% zcX$Lv;5?>fdt`V?1JNDvNd#ckPf^8mvNFLu?KUJ2HdZ2=NF&S8w$4&sw$L+?eXyKk zG?OTxpO~vcm`|gp4$pT6m07T>AFC}~U|x$tIaK20X0>B5$P6kMP${c(2^T`!)Kc}E zOPtc9hyXqV3D;V-wJUj3xgt^$F36HIE;Me_hAW1W)B zV-0+nLXxM2;vpW7q{;4C+Nfq%ZP$gbaIs2coJ1s={lKaV;+AV^jJRvU7y@e$gOQZI z+*-->KiLXPnbtNhq%6fSuzAMWrXD(xA~5$KvAC_TcTX>~)WnhEm^)vf$tJQ^mwm54 zQ)cItkqj2LC6JAkjZJzh%W;DgM%<;OtE*dR>2)3G)jn?y%T{R*la0}~3JqikYRQ1|suF@IEx(KIH3r@=rCsBpIHyS*8cmbV^=?Y#q zDod35nIG8k$>m$(?JZ!`T9opVJIL--<6O6IrPJfmR!L5V)11fHQcrvAu^{z8v>gVG zAj1ywwp2u-!&jYmydApY1$o}>98|e32eezOlD*`%ro^+N{+QyS5G+T|)f` zm3+Q;fk!xwt5e$UsC@!q8@tiG(fBD<%piWR%a)shA$V%5}p*Y zGip4k&;4&Ne0I^ZnKv4*&>gI%?hYveuV!`S_jlF?(t2}ZlAe#t(cr`JbSnL-GBwgxetV`9o2zVdLGopX^_M9;7Pkne7w|LDnBce9oDK zEF$TvebS~*$FhKv)v`En>==vcv+uww!lEm<`Hk*%XZa&luL)C#$Jc_ods_oK-;K6r zLGC#HjW2hyvy+;({2Eehyva{X#h1A?!EBYvQUI>Q$9R$Cu)(FyLMpAkhS-fXX9aJb zNAvNft8Mq5VFTJ8J{#r~T2~<#z}ianZ9#Kzt7<28LkwTD#l)e3>J10*XUdstwXw5x zWMrlzG!Yo;Zm{h0uopgdS)`Az$K6ZIDUR1u4$;nOicwf-;!QwA%b;V^_GO720N45l z1{h1EA>Ak}L}oP&r8kmMteu+yU-c-OkGI0Wu1QMAHnjp!`!%olQI%gUkS4Py2_Gae zDLhDMoW1NV!=~v+9F&=A11g|-m`%n$V-e&}CX`A>)k_P-9sKTM1QpJ4Ag@K`AJ1RM zb1gljFk`X4g{_VVd@&(EDK3Z`!JH{%_dE|ez4_kdd!gqhSKzVqbMfmHY?@had0kNi zXKSpRo$yLfej(^IIC<66)m>^I9c$i=dUVZAuX9NmjC5qNGf^aws&R_(>Sa*9&-b=z zQpx0LeB5ihvZY_R*vm`VL!$@Kk(S;M#jNAX03ef+9#xZTJi=3TEPE%S%0PAsVa)KOQ}yuwHb%80uP78V(c8sdCj zD26IDU4c-kspY^xOi9V@wKrQjFG~utw{ zm|PWV{5YcC9CCzZ5$8$eB?U8vF(y~}D|}h#AZq~2NXn@I@f1kj1muZ^N4SgnD9tc# z1;*ONF`BP_Tb;$FdFH)kIc&&@;E6DCgeL7Mw%=r5)iZjsrSwSO)TgT0uVegwW(I;^@9$p^lKMa~!z|6`OZAhFO9e z1-nhlcC2Tr*lRp4sz5+wd(l1a4E2{xhSy$KqDK5^n+sq z9fFP3$&q)?nSpJkzm}jqjM6=?tyNXx&&ZXte87#ILS2>bGj+Qz^?uc{8l2K7HiDqp z(duDo@l*0aSalK-TF7Zk7h4A$3NE3Zjt;j&UOC9>sN&|A3M^>3oP!>F6_84VXSJB` ztrg@loj6eS4)}`=`y$Z*(~dsUXC#np1F$T~opg)~5V;0BxzYCa1Il`B_v6UqrSP?P z+=0Y{++h#M4u+?-b{)On_tkz+6kS^grvXM-J3j|01?7(8j_XZtJZ$g*v})&mR(-y5 zjLaj6x)f(dLmf(u>;!wrd>`;D zsUWf?!Y$a%RX%(TmxZX*~hS1{8<1Fke#3_lpL5HHMC7$IVtJ3abHnamnbdT!x|CO z3nH|j#k({|Nxz_6<#ppJTS)oW;_F&3+m}DZJ(ybtJk-)8N##LCZtE^-acj-4#N;ki( zKjTr+s>9of?2d;jdfNTC(agjLN-m0L*5c=Zom*naBQc`q){i+DpcUQygix<6>$1At z)x>}UU{B9jO2T3iN2Waw(ri1s0wIO2(2{u`;^S$NxCq)V-9fk@FbG2vDWc;BpcBA? z{bDoohejH_+kU?%?M z`!|cP3*5YPt=jGw3->&n3a3BlhMIMmd1ZChTCI(nCXlBkYQ7Y$Er4Xrqz%R@^#I9> zB7#R>@#pOQ2H|$uPk>vMNPR#WW zN<_f5u}BjlYifM1cHohd#ZN{(zmCOtohHZkaq-GZJRu>ap*zNFpWG-Q_-fA@zOa!j zB=Tgw1qmbd^l)?4AJP(`NY+yxVh}8De>wyB5!MZ@fBoyfe^n&#MzC@1aoCAg!fDcs}xcvgp}r> zG<9m4EJ%I;?rAwD=Qq}-U%Zrv9901P)Dehr6w7(o;M-^QrD`?!45wWz42PhW;vXD9Z{4R)U8N*lMRXSLg z-UAUQpl=ectm2HPupT9Ri(iXMvc^;89$v?K^)uj@5g30YR(Gm|)tDilD^)`QNp9g! z+Cbt@mWp{nHj|dKSF500T7-pnJs_frkvcBbVxXGd&yVCiJ3W|1@-nF_+Eu6+Js&p2 z{%n9vR*bW!Ve^H&>rZe27`Ez^_=1;A>4HchPLNKy{Wc*tQ>}}K(vJ0&gRZ#&892;4 zKbNq%)I%VDma-tz>dM1Mcx}&4g+~u{z_w?^mZ%OIMWt96>T z7vs1@B+MPtk;S=%-?1>I&dS47Cu-~wx7s3d6e@pVN^eS`!7!Fb%9VHb~?eTSLNvCKTxz(TK#-f#m5fRFPy1tv*%T)%S^Jx?f&$5E{^uOCrezz&} zBd00mWTqKx=nAks4BP2KbXqdDL>_H6{XeF6u!svfZX&xB{$P4d@X6S=wt4_~C9a`` zr2zDN349r%6RxAVtW;(0v9MdeUN%r^tsog69O?6SlJ`P-h|G&Ls~x#B04A6NiBx3g zWo?kUVtm7EBdO*DTr_dl+Rf4%gxbI_>J|Eh!-wn@NFwJslrRl2a3}s{+N6XaDE2Oz zo2)tMX3>*HZTH`A;uE z?{179I!Ba6fUY%iT(zE6F*+30_-G%WEF=X4DV^s+5_@@;P$iV-l#ae9db!jL@}_AS zU}tXV{m&qyXA60#shGdh#$8hDq|p(m5H!5_@d~&Qg<@`yKbhEJ)F)rYuCZwFZPIX| z?z4h)7uXAULrzJfjkJqg6)87Y1&FzX_D zLo}j%7^Ak@{y?XwA-zy>$p_VtWvGTIhV=vaqZO7{&GvRp;_?ug zIzU3#Vel&%9A?$3ZG&~#D7($!h0T*}X`m&aafi`HXfhXm`w)wVUU#c$Rztm1wLvkF1 zto}2vtGxr0-?ZmV2P%PEiC4Tzc`A8%ba6B@iJGUFLi{f4sJK6v{MPC(3=%>#q1QJy z&Q;FM^g+E1BTPzF?~Qp2iK;4V?U+~L+c3HE0wz7WdhF(DS%ht%JV-?nwS+sQbKEU) zfhwjDrvE3=WL)#J-OFRWT&W+rYFR$ejkT0%8JVb}jD+UvgyTgc8w^bSW_m;FnkN_( zwK+*!L&qevs*`M9n5^G!8&HSRGU`lKg^gQwclBtyjtw`)eB?oHAbmY5cx>1gLJjiP zVqg(RVGsnWuFyp^uFE+XM~BG8B{$gFG{8Q+rEqV!Wnf9IEaAGu}?TU1Vc zI=-cO2AObZjoZIVdV}WxRkI4?eUIX6pcs#zQoO^x%0PESWlcu)^~^(HUD^$*Ona`8tMf zBf74G=25e01g9W+ZPt-JC?2>H0xgg_suP(4xHkBF`9jAvCeNp!v9Xv3^=h(R(YcY$ z-xWH3rWwL{jQN~nwhgO26OJr~rtA-*UtV&K=VUd7n{)<9oO4-qYz%>gSDoli1&?E6 z`qAuNJ#ApK%DFL!?uXXpu7gipL3ngj>z;H?0dWR|_+iIg*P2wswXLxOrKSp;eKb-J zMbYF+J3ZX59wR7vA!&!zqPA>;Wt#5bXQVH3iY9eL!YXfmDMv5^K67uLi~5H5g*YvFFoYKNY3b9 z+0&q|_*QvFo$DTTSgOCe=hX;Ltv|W4pe*LR!40(!c7!zXD@*!;00FF!SFr-4(|%ZL zUq@rJihQ}%F>>Ru@hUJs-NqJkC|Q*Hg<*6@baYJM8N+-4Qd=`LsFxO17q(6_@GUG#LW&;`I8lJb$tbF> z1|OV_#@dj0Z0&HMvs2kHaZ%UTlkB2ewE}--eBX)t3F@zYV?__<`Y5wwVHczHW|Wec|&7u%UvOu}=2!{%GGjmT- z$k^TZ0_P_gCSWDUi-a$oC*u&RVJzYj1#0zvW8~I)x}F7C3nD;eO{bTJ>2x8kyt_>Hpo(dWs86W%pq!XcVhnpm z8JZa?Lp|5M_zTY-I>#g;F(WD){Za3sAU2l0z!{8p$B8g6UImuXFYDILlgwk4+qE@Bdb=!Yfoz zHT&<*SUGh(9PM9#L^!vVlEAWePjAUT zEaj?>Op>m>7^NUnc^SZrxcbvUdz9;YL-_C#E84PC?J|l4SVL+7$TlQNm5|RiA(v6K ziM8){yeuqE7whnV7Dx=4YW{T9anDl0g(7#swOfavW$6yAE6piv%DR1VK6xFdp-xpx zdSAn)3oFg(4t_B8)998)d-kP_edC3k;gBP%TJ3jw204m=TG@3Xijkh-bG9ZNpz<@# zsGm}K0Z{VH*IB>fxppTt(>Kj0^-3Z^nA4tc6mZMPF_OJNl+oNOI~jDG`nO?;;tZOY zl9&#-2gjDJud%{xzPa^uBa&Hpn>rsCFHnjI4@Xk~RtP-2jnL~4d6c85vb0JvmQ{qZ zW-m>(k3FYxm4e$VNHsAX|1bQLu>!_b{Hv}(%`P6&#jp&Fcslcc5R4^7n|;o33%#AI zTJkUx1U54ayf6X8A<$Xk5NZg>M{ph8)g=OxCpk_?1;gKpK*{|4 z)jkGaUSN-`zY#{*n$F<|fOe`T}1v^Q)_(6S55M zOjb;EsHu^@lGk;T`AVzNz->wUpiL_t)DgiU<9g?MW?yqfIwHC;6+(V$=iIx{?@h>&XTJmH0>Kw}d#_k&@M z+#9^RGS538i8N7RdH^Eoukk^TGy4b+m#lhsz>&T{JN@s>BU$5&2H0yA4B8$uhT*Hq z#hg@qv-J-QHPjjfku}fJR;L`!tu%+&a{Z8&X?)!ScP3DlF5uWs#kOtRsMt=v*iI@{ zv2A^^ZQHhO+m%$3y6Nej>6v@i+~084S$mzc_kN!rZD2-q>qkHw4dy6|)qy;ts2hg~ zHFVn?MXz5eu+bWPtFIXyN%arqy6|Uhy^S+4yGM6h>@Yf?+!MJzdvgj8lLvEA%%(I4 z3@=UzP+23s))&wRJ?p%#E%zls3hM=rH3^)U3@b@xcAKGtkz$rCVK+uO;VNvp2)8a1 z`&KH0;Cd)#N>bAvQ#9*B|HYOJAF%ywpe%ej!YvPmNF1GkuhZFa@=>Y@dtxospjM`) z8Spq#2{(pQhZ7@B8E(UB@&Uy(!Ig0h-zP~f?)Z+&=;RUpQV1+yk_{sB$j8h#w@#s@ z(S*X%b%Oe{mE_?}`l9BQgeMT2$9RpB$5-feL|}pqnn)Xj1^WQiHqOERC-g9iOfnV8 zb-uPCAW^eSp*GBn9Ggf9lN>fVP?#!*4OE}#O;fbck^&%F2!e)A2C^;%adEt-bTjU( zW{mgO(zPHyK9ND+7Mc!%d*l6x9_{=aaV^_woz~ec0~uW4N{ZDGVoUw&G0%DXw;*ST zPP(_>nc#HF4o)f2z|_+29nPrSi!_-{eVU;m!7Opg41jF5W@2@0l3sydUZC66~TQF^dsiv=b4OMKNkt9(xVpDCWX zhPp&{3tdtNkyiF%O&KT=8RimaG@{bLxM-*?YQi(6%Nf3*qh$C)4AlDX5t(VGEG1n9 zMhjuk7tI8;xrW?X!@BWuKkO)a`Cw{vq}6teT(yQ*F5aY`x0V6f|VI= z7zeFsi0DR1F@&n@AtgZ}(D7r}jrd!4cnE6Um;}ugZL5E&BMLD2r|@s`^LmO7VA~mFzQK^<8+m-abi+8~g~pICEreIn|RtA4gs#0WwAA+zG=% zS#n31Al*=bQ_nz}(CO;^Wzpqw2v#z?!jFW6ySw{?E5k?yZ;QNo6Ndwi4a&g!*3k_M8LA}8J=`tN$fof47k|bICnOL=RQ0= zSy7>#5J&guV}n$ z@wK!~t?042@jJ@t=Ub@4r$3bYhnw!kcc>olnqfwLUcS{cooK5oQjG$_BQuVVkzk9) z>J_T=OV7501Y(s*3~F1Y9_D!IX(Kh2R@Fo*c_Jxe}q7c z8R%70L{jeAb%prQSTiJB^*9|kN_}g@pA?uaHkA|(0@PfvdFjVwl(b89fH%FTatML- zle3v2OdM$WDBDfo!MfH zj01m(E4T7(g(@5yEI_K7)avOvd}{^~Rd7)`EcOQVK~CIB z02S%4$%Slt=ZgL2e!$SoPi~nqZ#%n@Xj_|mYy>uT+vk4nSDys&BXy%8`af&&k$h`? zp5McX&(2KO&Y&LSyOe&@MeNm6XGqZLFG%kpO?v42kiSLvw*ZAwT~&EW*?&Tvxq@9) z`fQ9j`k(|e@gr>Pw2mRyGdHzVAULALFDpgp;6wnkY4{X6vQHok5S_euO@kce9hVGFnq78{fzIjPhs!dQfA>1GP9Sq_<5AYe$S0D{AA| zt+6~I{%Z2cC?!YFBFOv$6R98wN;8Aw|E*HyQR<>sJQwYML-y=ihAf&a3isAMzcnsr zmGRy;%NZH6jb(pbe#$Y;(enxfZAu}!-LjRBt?6`d6P?V z%*+m&aGnIr-+7G%jQ0x0F3p@3`~5c7W?*0J;Lhr*+&}D)D1xa>@IYIz;C)e%pdtF?4ucL-pkBU#`yUCLj(ZBJ$%%5}QK5|N*&#M2!4WYVk10Z{hAh$j1GqL+v zKr+NKC9s>7-D9ReK*fS}L%#Rf4(1hQCFBu@&TH-FftV*2`XmZh5J?fpl}l=DJ$he7 zkdC#am6RX49xg6Oq;HXc9{$4%AyZX{_Mwucw*X^vJIUCEzwFB*=bCCQD<|fVGH2H1 zym24YpO(~Ul(IJPT{#6Ms-nI}LdwQ3qBwW347$e<{|6Pq>iqi;fUvDL>>6lt6Sln= z4t`(KK1lSy>q3qaZu(mOC52psaVmCr$Xk4$c2U9Eob;kBm`HTNR&+db40=byxrLr$ zB3LOd*QZ_b1W(E15BU^*E$v^*x=X6)cFvI zk6c+F+ah+1g)Eq=y)@kJbANQte~l6B{@o#&`$H4HL^P0EqTih;Yb?FCA{JAqkIVU^GqIihksha@oBveQClAJhU*(? zXk$h_p}p?Ay{Kgw!^^mgbq#`4VfU#{7Uc^^|Sm8 zm?8-+89Mj8gX2%x7?-Murzuk$nz|v?i#Da}vFk z6;+pPC->+VXPAD)aLPAZv;lvAj!>^Y$lRcDhBcUGrRo|?YX)y*0@iwj74LZx_%0mOj5tn1}0RI)kgAIU&c zd&cGRk@OTYcOfU^AF)%0x?2ePG(V85m zRN+a!pWGRZ1FJ@#JQUF#yz^Z%gqv*U*xiTlFRD&c@H&`3kWj1l&)7-}Trn$YM!VNMh9LyPa-_&DG48M%&7l5mn-FV$LuNWLMBXEHDqEqW<} z{ZIw~k}Z5@aEr>c;LCnVk#qgQ2>k~g+-L?6ko+Rzim8Q@%t_Wce8j2OywP{h^3i{v z^UGaTb^mUH#x{QGA;%l?IEXmD(bHyoK4WN;u*Gk+6Y5e+lwg~KrivyRb8bw1&1ZFi`t$|CfEM}>PkotD|S;X{4BW6fLs#yof}pF;&t#(3DbVX) zTM?3Ep4X5cP+^=SJ2W4si;7T>++}b%mCs3uF#0$9iOMBz${OW_1T(OH zrm-|PUe}xH?sPn37$h8i=HkTF-rpeL+4Qc_r;wxhFYQMGd{Lbkx8o?@0Z*q#DF#f;(UqK9=1?EomUycipeu*v3V>(Ql!*I5qcY z)K)G0PAbXr3^-_|LHoEIn zj^d!bIAL;Bq(Bc)h{oaLTQt4qo_#mq7bC}1PjYL$m|rgU@W+g>x~2;E&8J;<*RHb|w2kje#K{8x2~-a9%=hKK=@R*4SkdicnG7Q5TRfZ8#oOL6Dw#EKFip-CAh#h-uZwNhfnZ{*; z!ZJQkLL(uAz$y?wWl?Fp)s{%g=NRu>-XEp0NN;JTO^*uIUphf9-n*@y)qXnKuhR}b zN_;Or(y)?hWsfd8u;9^43)P%eK}evsL>>ZVg7yU5!7VeUgJ8}1I0+1kS|PV+IJ)~^ z%j!|2Jxd(Y(u!UK19RNQA-Z_Aq3=bPcUTql)f5#)DRhOTn;&WzIFGWxVC*xXPV!Tg z=0#}eBD?f-CiNksx_@Y}TogR1ph%^9+;$Eh2url&<6H(P;=?9j6B$6my~MhFpu*@(<1)M7t$ zif{F<`tgN$WV38B?&Q{{(Fup68T2g0GfxlPpiT2TY3dQW@cJXjgW*9?RCd@c{e^*x zQ{5N1Iec_f>NHY;#nbG(WNRyo_-4>6Kxcm|+&Wp%$I5(T4x0E=e$Qc%-oR`~90iyd zbn3jV$|7rI$FQAMNRccN$F|7L=`z~-OVrAIJxUt_c!W8T-m6#MRefc`qr3EBzG-Q3DR35N0N!m_yg z-L~AwsU;SK)cE7FUX&DB?N$=}MEWcfqpJ{M(AjVG#@vTJZ0S>I^70vmM$I$I2(+_- z$Y08ty^yjFBtaE9^d-X^RNB_a-JZyP#MYSe|w$ zImzq`FBbn?F+^myely$=2NRJLYI`aQ&~AIaV{5g@w8FfKu% z>;v3bYoPacVm^Nc=~!|J3a=i($5rCd@Wzmm zw8so~T3;Hu4=UWue_8TMg=esSFTnhqkkj!F|ywB zv3d9tSRTaxF52^Od%^8ls4Y?PFTDeIuz!>PlCmyRDsC=Hxem0YDE%5bvO`?J@wZP6 ztBPwO5oLm3QojJ5(rXGPnUDGlJ^_Dn4v;6fZ?UJ{7A7jxCoW)kYyiO-k`>a{<#22JajKxai(STR_T$xL5p)dYTvm%ofHx@XRodNIEV z{tvTbgn34}`+b{XPH#ujrLnod!Dv!4RUN#`N4<{20zaz1iCrvw=IiaAbl6={WH zyFDcmJs?5_?Y~hSz|KZl;cUeICMyQUSU!n8Y{^EaAS1Y_WN(okp*v*4-2cKlEb{+> zbrg{(I@LW4zqfdF0I7Hlge{UO=2|@Y!^F;^LSe84UF1|&@Pf7G7+1;^h)`&>!K`f; zm3qVL0esGAt_$S0Os(Lywb5#>cD@aooEley7HCCVIL=GcC=sL}p;1W6vZ9|ZK$1=td|sQ5Ph z@l)!V<O>&(K0^1TJ6}ro%h|oK*)8;r6Ld=7{+%-cfAIQT_C-%fDm(q3hh`U42r3fWL=mDN@T_KtB6=OpzJ(C?#SA1R;ZlB%jL`_g(NU-Rwzoh zRr1Hm%|Dh2wK+3$xafacD-p7_w>HzSCFKNlJe$6r6}|?Z2RT-)fQGbzk-YeX?9KdaK_OW#$@0_g^goXGS;XQr=eE<00Gv| z8VA5m$>W6~>SOdcEXFW{sG+~wx_88-6O^ed(awasw|!ayEa;FOB#mHzkMBK=h%dCX ziIMd*GkOE=<(9!CaL5XN+pgeBFqeRz)tsV2)|DwnO^{LsmTs69vy8O!DsRDNlu@i$Lr(Lqw5qc_aU=qJp?cKa}f zb~xdZPf5(;VSCI#R+c|lW<_ttQsS{Wv~X$R1k-KZ(-Z*1r5`^*y3n4scAxid(O3vm zuk;hpv#8*B0vP2AWQDq0Z3oc0I!GdTV6H2E%9pj%1K}Tz-(_}sYa3dAD-QAQ#X+*u zL~vk#<;L%#+2Q|Gji@d&>en67a#3dwx!`Cu95qtqx{dU=P55d38PFRrQdwNHfA@3m zwV^<+a{D{YZ=5}#gjnd9g^8NF+8brD+KMZ2xplOt>=#Ah$az~ee=3Fy;PDmxKs|7p zT%Nj`8qEZ)9>#kORs7o%|KF(&y?tVl*XZ_4kx9>=why3WVV`hGw)OIeRDVWS3lkC+ zl7f*69c!4f8#IcA%;`3KvUkj|0X;Y^CYTS1q4iBAd0G?r-ehLlN^dx-IK#d)7Op$< z|F${|E<$wKvdjM`)`7N1AHiaI@&5ISwkXAsZ;VJf#{Gbshd7f(J2L-u`jWkRzi(u! z#X2Focrj-aAf(YH*%KVJW19$fi!TX(Xz8hj*aTid5ArC2jUSozDLl%w;aUK^pr;E~ zg${!fkwgLf-quDnDx|2h67H(@S&0Ozd`wG8aCc`)8lRsr=vFsd4=#AeA3=Ka9U|#U zTN#^c+l(ULa(^1VpE}*9@cmVwJ-J~fe3s+#C(unWP{xsa+$4b6Ph}Zg8mXTA-%f{L zIOBgh9ZxF%-RZFFyNV!h$6c}ptZbW?+~Se_2KT~Qmso&aqv-~H$s;i?u#Ak0(c-PH zypns{aQ<>S`cGC5jZYSdtp|xSIaJn@vrE8_K$28ynE@HkK5pDLs+_~Fb%9O3YxK~j3$rhVTfFhk1^d-sl1iaw0Y!CzU#^I|97TC zEvx}$qcCi74%_SqM;6TH{w3K|b$paV9ROjZCW+r4w=Q0nqBGNJ*Wj(gU-}uz@3g!{ zyMGm0Z1LeM7cM(3eA(r#UIIuIeJ@(`Wf1^e@RwSOR3zy<8~uao@J9Xz)q$~)0v`5i z{TvDn1zfJ)X}P}kww=e7Keh>jK(nHZH!DHBB=A5PP^G;0KK`XUX1NcGSV+U?bd(hw zJVprHrYP4!>y3Y4_I4h@@m7S(nc#rzn08*_GYhc%ehV_*Uqf9+25^C+jpB;y)b^gW z&iBm~)%}#`X#VK$AYTit^Uitp<)!@w{7dW5Qto`=Cg%NLv<^9cJgViU0<2G*s$wAzNx!{* z;P-!P9hJt8Id{QY2meFsz)Dx{3cy`Fd9`CjV)2BWRzhzHcN`n2ZgwMTUM8;;xXk3? zgdOnKE{499Wum@9uTHTeAqa1)CiGFiL54Wy%_vh*wlLrb!K+)_kmeQ{uYQFq5rqp!9P97E9QVm_b;=9^~>zQNU0fzq}X^Q-)8#m z;B62N)*j9SHnv#Y96-y7S>UWCyODlX@PDZtIuDxz)@T40Tm_rMrP3N44PO6^U>7<8 z+nc9o?M?j#V_QT+;$MlZ7?o~sR-1zxU%xwNyVcp%B_DZE=g8uTxD4u<0hE|$V-)L? zE}i4uIpG6hEvUhEKf84$8;j%AMjm+MN_De*ENpZc{md0ogM;PzDXEBcO90vwi*Svb z{I2{em+@{4A-jWxZp37j;e!?qBhgrpARRRlP3rK*-qMi%+T*E9@^+gECZ>og5BJ22mIw7 z3$mg91yf)9f1+SgKaVJ}M!*Rs}q@a#5o{P5FmKrAZ4AhewbKhB;<8ssdya1sn{3+&f?afV9!4E&DCo?u5bpGhUMaNxCmf#!{U}(RVGr& zb@C1#a!&J18mrZeSUhiS$%R-bTu6c(A?WB{;P09owr%NIYZxR;k8(v$qRz|u!__j{ zf3t7D++Y|d&e}-BLOOd9S7)*6-eY~&8yKYLw}Q?vi2~DikF&d|pE0TMt>_`0LbIZy zoFq9yUyYOnffK_gV5MS8z(N_z^@sEdMNQ_62PQR#MS&IWrCnGLdKpRoMq7VZ(M@*q z0P9_Gcft(K;QM$6qh_tPF{777zcH--oVhRDmYh!W)7Uz>g~y2qb5 zeG?3rbA^3eTMq@HCE9`C{LzdX;Y6f>uy$r3Dwm80@`k^#LW{C zG|Y$uy`CC^K-W}iU_N*-uBb$TyJlLprElGhlJRW?hhuTlx2A?#)r zBhJV^-rMjw$6N;Cc`acoaHW2VQeAcIBcE$Q05#n5k)6v1e`w|DeS~PyMrttcvj77fu`=6_ZW>9Q(I9=1>DV=#V>xjLL&56Tl&@gUMf8tkr?g#Cb({{_oFM?;(f#O~^Xr}T#3))RI_;hylH0VDeZ*;- zKaBK6JZ{q=0?^BTDdR_(%CuZqvGA1c5Wud0^2X_lJKKiW2R|lnS}`vC)u&SJFkm_= z$_(EdHc+I+)o``-nyt&o7e+~=e(wu}laZuiZ zq|^NXy3jGjE??K1R7=g8j*0Ost;*xAuLI=I>Cb~yA~yYY8#(E7HjB*M9ix7jQY9go z&C}!wHlH*HhV^?`t6FSAf=F0CM}l`MyI^>`p!7U~5o9onCN0!I3hUHACXG^}MY!Gp zB<~zLM{CoJzQ~S;EuEP#rzqxKI5Xb2v~W!s!HRD>1&unuzE1U|y2mSVP(35(s*G$e zpe?}bxzJb^scf9TM0uq;UY=3=*|5d<*9J){GQ2Wtu|h^3oI)lTevJ;MkZb)p;WGAJ z^LxkHZ;KbL%7GPuGvHEX@n$Z0vVFz?bX0=7(pL@>`{Q;OPz}i$`d%)AZEwAz*TY`X zW%-r^9^YY+;5*AKVlJ)#Nc?aoX|OvgXv;H81zx+Qp`A%tS?S&h~Rfuv(x+3ltzWTuZ{HvHB zEFMp@{i-8Xp_hh?e7pvMrB&-ia+9nBvMHQj{DSkjEt_X&cmfBWt#_?u<|`){M##{b z{$c9j>7z3n<+us4OHHCbD)|!o*Gc(h6kUUM2#bzHn4|=@M{Hkj_-xOMp5Gn`WBbC? z(q;ydNv@}f(aemC2rHFWmNNW0FrhEYUbW!}+F7$(m6a!*y~H$#zn$S3HHKyiYa=~PA-iy1c!c*bf( zQP$kRfJsgQJNdrrda(PIexER1!E;oYDRXRLw|;aBdUOh>HfItr;NK?>~D zJr2?0`tXutit-RoxSkWwcCmgr3u-ZPc;ln{46)1d8H^!z;OP4Twzml2bc0If_kF(6 zVzko*n|CfzKv>i0ZUN?7l!~>Lh;BEP2Qs=DxX`_V*z1jx9JB; z=lWNAs7ujY8W2(W*1 zBx)p}2Qe6?0AAvbG<98J`i=2fpqBZ+$PPnp_d5vC;Y!k3!Y4G}IxbHx0@KIxqpHe4 z*uo|%wwVcQscR@)N~@sJMEzPT`SFqgi*r!HMBzwniT_vZux+Y@8)&-~oooUL?3e1L zIi+$2AFWmh32-f!{@$%N*iR@cthPs#>$FXAn@cx+-+({3fN=g`7GePs%d6tda%V;zMQJD{O`{5y*dsj5pKUz)Q>HvMGevq?4|5s!h1OLtqGi;6W}Vz$EE6KU_&|={K+Rig4zOR(Q3dv8^Wl0d)VB z;y@3ojzca)5*0p-T;gQiA3Q})`}S+%E~5-$?f!OMec%m?=Rr02q*6MVHrZgF_|sw> zy%A2MT{!cox%$g&-dsqxv`xR(59OWUC}#sKIdJ%_9?TQFIb7QRG3jm+!51 zoO(omw!u+B#SK=Ty)m5Pb{T7jL_veaZ@|Q1Q!MJKw+#^0p?LB9H4{JA<;IL|4qN!b z%RtOpQW!F3)H=oMD$2V)E(M_Pj%*V{$idJDBn3KIqSo)hWr-P;3L`)ycJaL+)8JA9 zd+_f2`MwJ*e*6E)9lY!9rj*OP*44@bv*-DVep0!XOOBGxc>i7QDCPgZjsw%hB3N- z;<(Uk~*F-M7~eX0}>#*PVTW2 zq5JFh8;bK2DZJ4K(qtA^kI_lDhngoZn>_w}@0{+*U_6){L6rjB?-;3qnH%W>!FJ)Z zI7p#J#TOrqG;vFFj04~Pqyz?ki}Rd)Ccj_pm?MeRhVhD;)#hzr5%22`6lc@%6GrbhZ4RHNc{u~0W6jx}Ca_8CqpJ+#3rNudkyb3L;(}_o#5$u}M`C~k9uBP#% zT!O!itdzW=n^?55{2NXeC0KqRdjH(%SR*0QZRqg}bu4pzPDOcO&bCq636%;zWh{ts zT*8EgMrS$1^<2VvOO~+Y{fQYVP)c6JorXoHmemEBwIPVmsUBvA@?{)KIICmFK^XlxOn!KQp@Vt3kk z(2IQD+ zGt+D3a@FsCd+q)S)(nTqvl75pXMuq3RoYk;x(2M~l=vm5k3YUb;Oo>c6V$r%)s3;N z{%A_}fyAPdOjp3f^re%9@vL09<|ic{NYxVXG`0 ztbEXtI?{7fDu4FG|&4PcV~d3^SEqaK~?Ua)Y`CVmo+z$&~WX zK*J|#4O$uk*Pp$OVH{Uf5zU6Q{C}xmj7LCBS#sw=*H8WMa?L{T|B&MhHT93FA;*HF zd1ho!ga5y`wOjgdHN0bDc+ z8K~|O6_3lxB+M9brAJS&7h><9)Olc{0PggGNNbh{3TF=Q+#`CdpWjCzb5a>iL>ci5 z&b&+RjJJF8$E44OUk|}e>{PUPloWEx&2u{`+m!#IcjyHGX;xDPAr_(HrKIgrGNWnv zMidv8kkK}az-hw)6vt%*Mqrn2TFhRTv3*2gqO(9R!IF~g<}|R zcIh0hAb|8wmNFapJBzb%?xq%UT;5<=zB6}|UP21)Z7_C)_6$skxT9c$f+83}>&H_u ztFA|upcql?_V8Kpn0WH3G_khPh9+ug>@Di#yO7t(NT74jfWm5wtx2079t4bv`qV|BUs4)6P>IXJ&91z2 z)s{mglbUK1yfku7h&sKC(FAH70P3z`acG{#&9E-&h)gZQQdU8gPy&0$KN2)rzBln^Ci_n6=^b zaat*k*~!+WZ_-)MpBEF9E#nZ)mFr~S^V(Sj9A&?A7nCcnONyrFG$qL%)&F*AwKKFe zn1O)ARcXeWt*2vtVOu<;+J|mthpgU2OoJ*L_g>h$P%8ngqG}=Bs?e)EGd;M-NlE1hX>TMzxTQbu-3E{L^;6w4ltSXf>16OXiLk8zt=8`_*X zQDE_EVl^~idp%k!uygPX2QiU(AYo#>|LnbR*(fwHRY;@Skld%xt}BX=^X^lTy2~nu z9gk)}+WAsiSX-`?>Yu8I@%KzrdIk*`+y6!N;G`$PndecFvEvzOwih?ytR9)yGYB1U z0nH_vFIP3uN zyo3;;%jCOeb_fj|P49Y|_+~k3GXe7=4vhEQ91A3Ubxza(Ka9K-39Fo+^k#+(g6JKmrJ3Y(}m}R(E^ZhY9lU>kR=V$ zG(Ny{BM8%ZH^cEskz=*`T4SgL+yb!DrO0`bVj)8dcFsMr zz%L+l}%@y2Su*%&uSh)!TTS@!e4)-HTogZw$C3)w4=0_Mi-08@qZSddjHNC^u*zYn9wF zVL5(Wk;G_~6Mm`UUDib6ZuiwmBhH`blog87;RNNX%mx&;b4Mg6^Zm$^UC;jznk6M< zen~%$t>zYe0n=ws(IY`{%!RY9n1;)9#e#|E6T?Sncg9GssR~ZE-tS#IN|nU~l!RIwPF~P@6HRbPyb_s(e>X?q)ND}>~(LRtiPe>@VzBs`q@HpQv2Cx=?=WLjRJ*cJ)O z!~gCX97A&Wt|!Dz96yD-IJ>0=#n4Gs!R3r9z>Kswo!TIsP0s5RbH#rr2@<4ayJmd@ zbd=?@??TLef|^H28VtY}(37I+psvV5538Mi_+FEJw0C-PiHiFH)x)Un^?h3RCu5A_ zU2|-;5r7tzzuWAZ_K7sDo2-g1!F69{lQlKyyV~D;+m>rWu54>)cfW)m;2ZtBW%`3u z-ee$Iy>;W8^qEg#;byFbWf@9Vno*m(pX$$krbiI^eq3Ij--_!fj(hEyh8UjfU*-rW z`Bbr&AUKKl;3XU-o(de_^w-8dlHky7O|QEOez*4*7j7-O)=hyQn`N}XBw%+7SX_VQ z73H(S#~DuF?}$?Cl*Q(^0=E$y`eQ>#>jTx zscG4ge;?cS_wY)z0J*qCHp+{V_h<^GGNHK^-ft~*|GSoTmvLh|^IzG$5^HE15Pfv1 z{+(I-sF0?!5L9j;U01xzn<*hsY@F?@W3v+-e2VqI*DFmex|1iWn2*BYzUxr*JA_mM zM(i-sVTx;O#gh3~L0<)8wGwFILvKwj>Ue$R7FEE@66AjX0a_NJh;gltsXVsxeF5fR zcdM)!nE*-SQYs&bCuH`7L<8Jm%J&)n`+hoM@DU?EkLd=I%;^+y6o)e!uN_snIjPC` zT!T?igYrMsAYI|%(jZIX`Y|M@iH$VS1xQm|^9b-g!yyD*ty3A93-KAAZtmUHBQj|~ zfPbILGn33Pg|xsC8rw^OGO`9gMoj`AW4|?zIJ72+$QKF5k#Khi(kI3LS{Fqqk4&fY zgLDaucdQ16V-aYgy!c?3)0;T+${)yZJRHu)6`1$J zmL=hVA6jzT!sVFSGLaY&$z{43Em6y;?Ows8{>2yIW39|4>5eGFB^#sh((`G6NXR6y>U`FN1Q2-r zpK}arvd}qT>#kscX7JxF)B5gNID$21;Qd#@&4jJx)TGUYQ2uG}s!0hkPcrPXa!q1aIOh1R8n{n~b4Sa1GYW9ycOOM*`grbC1P zd|{ZO?9RsjMtkIYN6F!pzE|zj(Q)&jWdz^vV4L}GQ=O~-u#GC*F!f=Rwzu)=G0w2Q zdUo9gS<+!{q;W&PG0?dFPfidUwYIF7$^9fSLEv}3V z9~xCj_{`uJMI@bnwex3&Vq1!<-bmd$K>@Lxs~C^wSiyQV(-0S8811!fDgh9R@`ll@ zNUiJlb*@7DbPycS;n9sdwh8@fmxlBLxiiY8ZCTlXf3!iBiwW(S;cwOGCwjndof&?Q z=&+G8v&|_pR)MqjPL>S+?qvH9)h5y0>xMttmKIcBG{%mjs^@gs`sA?1*RUCjwd^JR z@?K-V4c${sA$|nUwhaY%L71SYO3{uXeJE?$7*AJutO}BtE_i9w?4;B|maS@`w+Uxe z3$}ZXrTJfK-4gRM-id6iczDsHfX4j6typnN>DAL zwp3F=sHI{rwMFdvZpf(EDV+ozDIKv*MQt6eLA6D#rIupsrMb?Xd+yA9m{0Gg=O1{_ zd7j^gu4Us*h~)TsYsuRx1(|FX;^5H>_nC^q=o(31lQEBNUuj|i_sXXkE2-a7&BM{l z3T5P^y~59s-62y>=eb1n58SF@VFBD!SN^<2(=BW&Dz0O}`g8Ig8^tK*l1fb1Pe zW%pvk{%MK+CLXY5bC*c+h%^M(C}*g^vqak`gNL2N9LI!3jq2+C6RYPG>nQQTQdw^& ziNjybO*%eAieV?~@06Un`7Q=8(}q1P=Z&naXqscD$Ta*hDKz$RNc_3&H{Sll8xd!X zhM;}M7`fnh=MxwdtFlx05(9ip$y@F}tvrn`aP*m_r<5;CUUYxjFv9wMSu5|%gjx=e7FX8(M;umMifjrd<-8rNZaMw)WL{V zc7nAuug1a7ux6G1R6dmJ%17?LUucMFm|@rBKGLt!SfNF8C2yb?rS#xd5C6t|3|IZd zeC${;{RK)jt}%s$b^U+U(i-SCcDqllwJECa*J7MYk-aVL>yqJS$1XKD(7X%vE1K+4_9zDrDqAl9&DGw*$23jjm`caXV$FTD!(gK+3?*W&r@ zl03UXsQgc=2eC)^k0c`syoPF;RR-dM=YVSr-7)c2lEu-78MqP)j?W~H3a3`>Bi$5D zK1#ZgrIqC6(1i@aGU!>ObA9o$jB^LCFW+nGV8d7W7Y5WEv93Y0_W&q@W|+=hsUb)^;i~v zuf!Jpy0UvSDRnxsHY50~&h~*iOVy*r9+lXDbT0NvYIJSMj9G~<9!bNShnMOXm``$= zT3P{NYh^m?q&|#7H)SQ)GAlOQP%Zf7$%-TU5~nG_zChEZ`3PWL5Gsv&YQ2Rq7!;B1 zwW@!zQX9Z*EP{w6O7bBB&K4;Vw(Y{n@9xMEM2VV3nVtoasVxr`#Ua~ zKfvbZVq(>Ii;+hm@8QlCYlHe~hHoamO1Uf76N@flw;v(tQN2l7CncUg*opxj-2Ca=E^(`>~W zxDeRjROtU>vVkA?=l!3V{RuSL;E;gb)@8FDzV*BuWhP$f+43Y~qf1o&OUMSm%`wz} zk?{`I64bGFu%RS3Hm~d7ed}SBVuk#n$$20#)y8N6n_=)xpXce?szKBJe2W9xOwKob z4?*brS0kuiYHUpH1>ZrzC3R!pY$ADtCv}#L`k(bN+OqO@>mxrdEx0msBKES3_zV>- z_CkoB7w0*N@-59morjzj8AP!bK1I;s`CkRu$r`m3G2bdb^pv!v|8L_vS(ODoI7WBx}<=OqW_{&Xv~+)FUZ#$F!@V22;ty z$M~pYXx)B)4>UXV4+O_`R6zy(L3NuMHFd(aPMo}DxH|vKGtj880LulQCYwKvJ=^(UWa4j7;98;B= e{*SLG9n%K6rv8|15+s4M2*qLObjoy5J?;qW_s%xsNr>pP1 z=Q+>kL@6mqA|ntWfPsM_OG}BVe2wG(9cU0=XXnbJ=&u3ZQA*q8Yn1xmAu(Yq^xs8y z#~+qoP0k28APV2fY zc&eR3XiB%0QIw2^uyRndy_q0Yt_GknM9KNPEQP=CQ}4}()2z>pOYgnD1Sh|`Q(T;| z)?UQxHtCJu?tR{U&WXSn_Ry>BXW5ch<9*)jpQy;lK^rZ2M&T<;v6(LD zHX>?k29z$h4Ojj*e)(Z1f-+=}WOpE-9k2ZGnX&Ea`tHPkq2-+*Pk4Gn;}`i0(z=qn zKo=S{P>YDkV`}pVyX~;9ld~5mKW+|9@<2*pA|TZk^nNSo(4O5qbaH6hf!ucHJ_xW1 zqZN|KGygU_=HlCWDdx`CHGDE=IpJ}~|FZ5}*R3g(U`ekzqW73OKr)SV z$d_zC>*C4tb-3etn)Erk=h1wTdXOl4k9DZ(Kz^DtrJ3W$)isVDiyJeH%Xq2ML9GA& ztnF#$*}LvFdoXb@>M`;}{sd3|+o^2e1yt);y}UhmIk?c@G1GT2o!*Azppi#V9YGBK z;dZJoN-E&IV_A3X@oy*l=FsEc>>cfM_$`F*J`1jnF#>fbrO2sa0nzmP*L6J$p7}S%oOoXt0hn?u1N69 zee%rborlx})z|Hm-GpWz;7RgA z--k$|-Y)t^pG8N+DpbC$w{QvcSb5PLlCj#?2zAl5Aj<*ghV13eO!obJb2ajIG#w3C zxrA`3^Y`opwRjGD5(n|_X)k!Sy7aopUc2uwwwu2YbMbmj0fxO`2C02vSQBMGDltQ1 zP{3;$GJTf(N83Q1R@~1XzI@G$Y-66#py*L~k6f;8l+B#NS4scFQ+_^0_cDG%mxw|J;iG=nhGjD!JbqnoA(c=n~vGyjyRVRJ}+7$(Szo;zxR<8`C2 z`9Q|(!_+*89QxVxWCN4z}f+O9l8<|$l8kCDDAWPJgLnLsUhYMF_tEye%R&JdtFDNghu#bA zTkbAb{S;&i{?721wI;w$kbuZi`_M7J@yB)g)8xrgm*YxTy#pz?Q7>$F8t3ri)!$pv zxQjqdF$V%mf*tn!jx#9|QZDtQ;*pBksiUvOphiGp(Ua&}>BQp1_FeHw`IA3}lqnt? z7ic6v;vn`t+L|ZrO}#CRv2#fqH6{l0HxY8%RI-zBUi6Uvl!K3XD1S|^O+$5+ zu~4&BszxLbW;>RjC-d1QuOJ8_tfigMVJtbGsDmSJJdvD#>r~<1&q5c!6g~)M!A`j= zYrYHQj;&=kTxC2dkJf>eB|q9gW>CI)%dLM$^MdIdcp$cRoFmYf#)>jZ5O?WzCf@gwTFW0Wj4NN=gsa`}#WcWA(jJ6#ZZN)YY zEiveq(EHAw+iPyk&Uc0TKaRi5HjTjY^_@t*NA?+dHCjgUsI40cdIIV=Sy*{Ec(%Ou zZ!sgD%-3Tr5Z9fF;>O4q=(cOQ7c8x!5NN~bOv7vV0~v!(sG>1C)T=&+C0#4`56bK2XE7XG z(NJh)aAx6;s=E%O09!UutN3gQyczrt>?dMQ`!~~{KCJ4@t{(&Ye(*svFeGS}KF{TITd$G?< z2!$hPsP~4DAJ&#|G5GHouE_|kJa7D&48b;h2JfBt?;kYNq|AN;-fE4O$^Hlx<2v{W zP~Hm2Vs^7Zh35}N+{k{RY)GHGS>f|OPz$u~?UvrCpno#a(-Pp)y+wb6J)yoiadT+d zgt?yi#v4z#0H`pwV==}NA0%vHYP;mUuwS~;0>d-JGtdWLJT~X}@!(8-+){`eWiiEM zgrvV9PyxM*Hos1`z;{Sz#&Wz_D-Z1+3>qZW16b8pud5sL$0Gq0Aa_adWONCJR-CD0 zt}6}cNf;H~?Dxi}GUqJk%$UP3j#}<2f^LwIQ2ftsTZWiPyRmO3VQe4mxCYwfSp?>o z{1I)w;X7b~8+AQwj5wTNFd4<%Z)AqMRFC0U)tcl(bCdMyZs{yndYxuwFIu_3Z@A(+ zz_(Wz2^hB__#!mZNpdClpR9p~+K4W1gcW=lA1hn8xVGbpokA7<)uWvZ@#eYvZ_Jrp zu@LGwo!@3h7z%i*?k>HPUI=eIb@Vd-eJ{~c3hW%&xt~o~`;l;qP)|pq@k}2O{4I8} z8nnK54u`6XSs`K`_|9-SsW~i7s|Yn;v8~HcQfcJozfO2fbtNUT@e5gwxrKkTh-{^U zKry9DJOgvOY83YzzT~HMH`C9`Zl59G$^CuGPpQ-e8u$xOA|$*yhlm->xvKM;ZMi;| z$6txeM9C@9@am0&R0b5b7TtKh-RCd>{=wVG{dbFp|DEgvmu#3xPUNX=?kONLODUg$~*+0w$rSgWWcsT8Ogof zcu1d%5!Ku$*WS@hgVF3^1Ft&IUalio?h|XQHX_Ma+##&&8mUC9Xw&fzOh3|#0H*vI zU633I01BFA+`@e8-2KZ|5KF|$M!7#~vNKx&TOyPAy%0Nng8M{gWzYi2q;ZyL-viyS zKs>8ZEF)2?k4)I`)F#okQi)iB`M?QE-QP3h&udz6y@wam13YbkUf2drGB zG#yE0lBpL}CDKW`RpYB56D}k0J8>JtQbUJX2djB;#2N;6X{;e^8p}Hh3i+pw(o4DJ zM!HXKJC}ARsVcmbI`@3tYQ$O?WAjC$H#gtB8&zHlHP#_!BejnETq3DU=y@}wkH6XZ z_Bf>HeQc#RdwM>)i;&xdU(W09@DD`lpUHA7EczpEKY-(^ar5dfTZq|NVuVD~23rFVgXq2E!e#+8w71NNgVxtiKqH5 z-&_B{&4LwCR1JWB^SIkLXEOcHy%(qa07;)lb1F5d+wkt{yadyU0mXE9oC#l1^|AHe z?&_!NdmRXIR8ro^&aMg6P$QlWJ;8uczYCNem<>$Rb%)H80|V$@1{#Lr4Mg!M48Z}4 zHIwGScT**Yw(*L+^N85ck=w+TamY$qq)md^g}-oc*Zg!jbIb`el!D{!x}O83K92O@-KH8Gni;!g<9mU0A8Fy}fFD zEAf~Vu$k{kVt&XY6u|j4&!o(YY{@r{#_Ipq~J%jiVBG;lxfSg*~^Fny&+|y6)>Pki4A{ z*_sTGb}+Io?cd^JUX^oKmDddu?$xN!*-#r>2(QRcLZ|&Lgt^_i@9OZQrmswHO%EXc z!+7`=51D-5tc6=e3hm5F51!gO==hAtvhEqsE$)_g-hFcG@9ENxlXoY(&b}TKkG%VE zr$d_`x_zhNM5!PlV@ylP%%yAmJvOxlFq?1MUkFssoy(grh%I)akRw(giYM+)&D49v z{8E)eFRuR74iPK!D6~QKhFkP`Plprbjtu4z4tzforhlGYmOFAO`9yy0O2ZG1tO{Wh zp3F%1a>th85J8WYTUwxTEHFyWa5bFw2Ax#CY0>qQrEsu z-Nd?Errw!B#cjCF{Lib8YJe=jc4*g?KT^vWf>6FNgIXvr1Oq_MW!+Xxoe>36$oR{d4a0TeJo+lso0l<1-G!R0<8GLIr}E=ha-Tg{Dd?mSH`KMoU)%t##)UhGT9A)4xWE39$XI=nm_~YZvd5{ z)nFd8WtD6;mUpry;XGgh`GUzk8IR{#70e-U=G=Jh@CeCl+Bt4^VHF`?a_CBUHdD;k zT{d0(2G6A(F8`ht?#EgQa=2P+yV$c+cRg$Kz%Nn@&JXoBez-QDKnxy-xbmU7_#goc zjc3|JkKelWRqz)~f3qe#7vbC=IMvMyZmgSff=?O$wHgw3bNoFcM+9)MMF3s%*V4S& z_R{g&fQoqbnqUy5){NR4J(|=?ESToFepuc zN!$82or0?=j=>`YXbu}`a{pofEwk#{Fc>CilLod5488sqG~)UlQi93mSX4@^#;m9)uJOmL1Wfb_>l}7gb@PfSWP&=?as1lKivHqoedlo zDhO1m;KG*;vMUViJ^C^zobssOYS}X~ADU7akx-8?b2MQcdOzhd zHo&NVyE~uPK{sh#M>W8^eZ*WvBBA;&v<-)mh5kj!7@@U0ix@@YyhL2cJJr~m;_HD+ z>-LaBZRI1}@S7!5hoFn-Du-wQL+NVT21lw0H_j0rO1!z+zQkZz^!hmu3f}PgqJ7RJ zKCbxOYHuLphEamtG*KEtW|5VQu8temK7dvCLZL470fiYF8S z=P8mwd~^659#}vcrab#B{?wvM_(LIwW_IV;H|7w>Z?kXl zsp8H1Gm{FKIY~?74$zh-55fyNVh9iqMI=(@3_{}OGsm!XEr`Gmy9Mu~p8&so&f>th z#Wydyr-%AOz|Opi+usjcu8^=t;M~}LZ@L!a`Xh8_qyW`otO-#xf%s)F@m_9kxPakj z0X50IiXV(P_OZuU8S)TES=3Jj8Fx*tYXLvr{_3bn6*DGDrk7Sj(+3n#tB~;RO5q&b z0G?c)eo?!1X<&~BF+Bk~D>z^SEhqdXFlNiUOW^p~0gNY*^VMu}BaT7C?I?n`z-ZHxe_^BAVt4vT~~Q%xqxHi;Uzm{vF0lR=Q$a z)nDDowuR={h*a9)k|YgZ?4=o07c*f88Oz<;{#Hi8YxR)uu^RV z6%?IrV7g6+&=$ra3bgH%%_1`)9GMF+EmoVWYlh|lE(5haXkUL_X;FPebtcYFF0@^mHK`ee+-{l=_r?0Hv$N9rNHYC+ljo2{`&iLtP~ zNe8mi@-zb;(u9UT&(LUyVp0ikfV;iYJoU{XIAKn~ti0)jXI^A{^;~^jhW^56lLaAR zfMwuZk=9;eXuVmvN>rRMXX7VqnBzJG`NsfOBRsDiSs=8Wpv|=r+d8_^et9A!5Za*y zGiBE}7V#6Vl{1BSj)|oXA%q9%sro#Vf$`W9^w+$v`bXGL_1jGL+p_kj71+Lyz0MJu ztLMGye$eFr$>51OA1n1Uve^6qB9-gU05Ns4{_Mt4xZU0rO%a!Ma(O6o90g_G0rMZvAM1mv za6)}(Cz*)JEk~{*tTo#{d}o17<8A*l6nE*(8@SlvC>h!>KJZJT=brm;N}|hTt_|5z z8;ZOu7YvZ6O0C2vGTr*!sQM_zzGiTeMyR05n|a_S>!I0wM1cD66mlU={zUQ})Ja93 z*X>9MH|xLE;(DSgXt|7J2zO2B)@K-VHFKC%>8NJn&ht0g>Z++_789!^3oHk}FTY;r zUk{0wx(&JYZ!Jn`76K^{cu9>Mbd`!^puq=~yu&Gw=SMgU8_tYKM%w5fqf(l4$tkUR|^|ZLA+Xzt5M5yD5#f)~9qzv&$-r5V#^9_H1H+sQlnU zA|91S*r0b-Ag(J`ZLx)FI*AO>Eyb74PYt#^bGj<#d!$EjCG(1DzWD}wsbpimYTs&p zXXM^0+x!s{w%PzIY|CUIrxn6SV$Z~%m_Lz6?-8SW zWL_<;Mj%Ip8KH_CQb%Rk9KbrU)$#91Ga(2lp5RkBqBn>a0 z3?}D7(6G^*+BI@@*SP7tdF}RAq`h!%jRG%9(U@C-ch26at2?Jh*oW#>FI__YVVUg&_DhOG zFK;S=1!JR!UPb2;#;-v&1W&@|B(LJY-kjgs>0OF6( zht~N`l`iB@$DRGsJDnE_re#;^^;m}kwqy81+^@~U1f4R+jHqaXq80(C|KuloC6RMG zEUWGW$I~+65PXnpDCux{(|F`}j()7Mu+TDuxG*7Z`7wWmBtUz-$@RW(Knl$mfS>Hl`h^9NUyayqNpm8p%5 zy=KfekOVO)0S1ZqDz=f42xD@d1qJmlv~4R|Ag<2@3SkCIbJprw)VjCNXBTYm6q`P* zu=jkQu$>2?p1*rrgFnJ;lsN`X!UR-d(h?NrsAkF;VhohLG-?!Q#;J4o|GtL2MqfBX z=yKYCJEe&>>Suwp{a_(1Z?w0Ug_+`A-bc~)SL6N_jt)C33%6kwsb*(CxacRVHDeut z-#+!dgqO|HnJe?vg>)st$%ep&5wtb$$vAlAHHM>#-7nSYhtlxPH^d#WftROSdy9(o zxn(rw2HX-QOA2vwNJ=R92~eEejL_-jsgP&bgWrL%xfXW6tFQ9!h5v=Sf z5G?yvLnMzXk$Tr6Eqwi_F%IwzpZ3S)gz74a%f3l!356uZI;rr6elxlSWGZ9dX&u$= zrQ?I+QNfDh`whvnQcmO&q#=FUWM=$#mq~kedG?K|yrf5(--d%u)jJm2&lDELx+RDFX>4B+;fkh$^(JT4Ev#~NbdXaiH4c+0 z0=nhIx+ueFvx;#diS0csF=R7Wdvoo~ve(0sAX3#JQAUuZeVQ_1N?|8>724AbU5drT z;=fjm{eNN{)o*%EtgQz+4VxX?FWx_h&wc&A8hRm;vo{VzTU(p^5Y|j!$CUa?KSrkf z7wVp|l2j*(__D7{@W>bL$%;HqI<7`l5D~v+vnaWnJT6(|N&brI* zTiOYj!*QmdDi}zVM2L9@%UHDenMSLecrfBLMP6<6Xw5f8-(>v_i`-yNXbo zk?e{TkYgjeKTl3yR@>dlR{55jM_CibX2d&$ny^kDo#FA3o$AQC7*}4Y5Nq<07Momq z!VfMnB;;r2sLd7v%_5!0YMS9cNAMJ3^RM>P$i)$qs>WQ^p|q0rONomRu;uB$Y6=bUbOi1e-rI--TAw_(klTuB;>VD= zaXhrN#%EX+b44U1zFc8TgdM z;tE)Oh31Iyh?u_n)P!;`>7$dUNH&z^Cz8q$?FfV?mtIR{s=Uc0-u#M^2y>~%Fjh*R zMe`hbS3^N>Mol=NqLaJ*gbJsf4l-CIBVnvph|AiPmJH8CcNkV!a}sncug#&snn8e2 zi6^%=1D~+0?!P^XYl&!>I9C8y1g5=ahW@=$3Vei!bORh41A=JS4)Wr<2!0cI91%QT`^D2)K}`)*9ZB;9>$k;0@$Ql=pz91$Cl1X`Y&_ zReKN#X^5>8Ie=HKCKya&k{dc7X3=`D7gLE@IijscvoP029H7O zln=i4>{hDQa*9cKVg7;pfQ=16J>s|0!{Db9&J|40np&+ywTfNKf&X|=`7&iODq>CU zw77}kLal=>R-i@#UUt^hSbtB$h@Yk-6Jt1mnt0KUoR2G}6bQ{7rc2|ne_rxzR2ZiS zYf8fmg%^&O0=$uUG3Ur6QC3NdcEs(Q& zRju$G2Doh{bKaJ0_%nH!O73pZNU*vD!X!Oo8l4YIkM*l7LQ|WY5WdvpT;d+UI&GfJuhegYo(F&N+&80@TV;xukIB&i!6@+k?K) zQ|TT|#H+G~*7x+ERqJ(USGQ3H{}+7Xdzeq7L!+4Hf#X(On<|Ww#UH(OI>VE7!YB<4 zA@z8TkLCN9D&8aMKYvR-8HJ*F#dNg}@@F;%h_KoJXJ|G zB2)92^_90I3N4A4#98DKzdnUOQc8Eee0@tE8YSSg_OO)aGvSNOFW7x)rjkEFCAAS> z(249n>%Lzt_-r1lgzR)YQ0c29Cf+(|N_;kdI=-}Px zxO-o`?YI{T zSQSAJ>x?)ClnvkPFczFKZMMmmBzX=}ZP$xzNBmyv1 zUj@ob(Zrt!=hR#6s>Zp^QW=Of&XqrVkEc$w{WY;v_vsqde{H%>HH+El3|$spe(o{e z<=)g>zmJBjq9OY|zzJsf+`>MUzXj(%o&1^yYm&{%Lpbnd+d&-SkTzAP#+w{(bISff zBvX=hly{&-gwiEWuQyBMLnZrx^4eW(+lk#q{|^G7$#&0s(7kukgGa_S=ET$r#9R;E zoDJX3*>qQx+TKfRe)0CF-Yxv<>_7dR08FEz`uU!QNY33Du5Sk1w)@N^N>puYT-}WS z(?_^!JZfva8qT4!m{QFpWHE^fo5L~Mm@(rA2G}jQv$+G?r_*YH2)Q0}YP&#NDN(Q^$AklcCkd6hkr^|T~9+&{{u1;`2%nL zPby}8_zaVMGlPU{Ah*;$Dz!AzWFH)*u=W0h)7H-3k_M?MtE%PoSPa(}Gu3yV(O3>x zbkIXubEi6K)%qsX#w!t-rgj7NrBuOLKD3tQ9zH~W=Lu3REpAt8ug%#B%S>$_EK*KW z00qef@d6|ji27_pJCE>@@2l?0D-T9WzLQjzM2pf31mQ73;GWVCNZd&g>=TqX31(KK zWI^}Yy42yPYpIy#;#GS#Jg}tcm(rObrK?8q7kwm3c{!?0{Pnu^P-<4&M%d!eAg+AO zETE*(vmqe}A%lAowAR^Ss*RL|KQH?tWdf={tz_CXEo6_-(7E@eN13&*o0xe0_2((M zzJJd++5EtM?fAv`wIUpugKK~{i8vBdlbS&BF@jNu8c4CMcxK)G1fs#bVgQqiTCoBK z!Fat5)^4B#QFz56GgVo_N>IHN+ITdP&6O=m3ag?a{v_UlAF5mesr{KkOUKuK=BjT3 z)ha5DcX7#&hdgHe>0j#we-9>YSN&V+{?qK>NjdWcTRrAf0&Hdp$&PprGq=qm0`zqaG^2!@Rf?))kmp3j!Gaz2j;uLN{+guBDkyw&3)AA}0t`z;SP z&rOCkF1@hg`-SMCe&no~{$4myIe%NZRM=e~7Brrr8s7@)MYWK~B2$0Cks7-V{gtaU ztwCALV0i&vF{mc%1E36kgA%FqmdSig1pBIf*}tyT%(`^BE9AeY{>XDJPRklva?Bq^Hb66GVgupZq*sxaW9|5i3TbQ+A7r&Q7rcsLMYG@|)2_ZP^|RliBtxK^ zl`m~7uo~GtSq_;jkW$lHP2+{<7hRGE!ZEg`GAg$+9DpG(1WxbdYOYEDTL?3>xO?mX5Y0pjt>WX7K=c|hwz{k2h|_z% zqet5%6Mgw#vp8BGTs@Fe`e0(>HGiomZxeqwSvuN$k^!s1X3* zNQUfX%t>cU)=*?YsT?!^J-M^jjBEq3Vki6;VY|qYTRX|)X)?1gBC-{%XAj2~Vq%z1 zq0oEg{(WHt!79H5#G_}xT!*d6!%lyDZLoi(U{Xv7$qjsv6 z(0l&@<}S?Z=B_C$D5&EDs}fI@Ja1L+29}_;_kzm50}LN4qxihXk?B6*<`rNLugnM*dx0r_$#R;OKlQIjKM+S?Mwst-k^`i)x9M zGItaH?iWA_HMLYtUUZVO3YRABA}MbF(78VfL^(-M1zXVTz%Xd5ywAbM61`P%s__gZ zDaDDZFsY0Ff`Y$rSB&+`pNOf9n8jn&J$%{Z}q9#zb9^z4+-)w5Aw8JbX9`LK7nX1S0 zOf(V`V43Ae@Oo{nKQ2@2X`1NDauI88LoY1~iu8M8KM#M=rPI4SViuaXMIgf^T8RJI zhN-~~iDeNI_EC(>B|TaPZymERk@_Rn8w=%XuBoBm1{vHhUvbtX9jw5MH(WRAt3BvLDW3e_!uBNUj zbN}m5`e{A2D6!9k-b*M+J~ie0x1gm0Pd5Zgc+ALji}E7gt>&79#pLEfRiSoT?H z`fr@ejt3TC0~|jI8ThmLz}#>h*Nn!}p4XzK=<|bBmaDs?ZFZ3{xK(L@vHN)86k3zT z2vZ>YxI+>ZN*0k;f=~DLszySFoa0gZHUE{Z!W9p3uN?32i$t{}r5q$yw*s7|CUe$P ze9nag<0d^HPp6C;?nC~=>duvou_8WK;^CFR*YrtPt%XUM{;ZMd0th=Ks1lx#agT_q za&^6XG&Ov*KN#N!ndkXS8W?3Egwv-W2~2#}Xwi8NM09){oY1gYsIvX4+P}Yo;XwY6 z*Qg#ZP3^3h*#s zx=JCY>zk03&T-0|$PUJB3}K8Iy7qrhuivJWjiCf0T+G zxpe!vyHaTjjsJ3SggS})x%YkSQ8<=FBd4H&hoPx7$j?G@bn^Sb`j&*g8I^Wl6oTa& zMLeTJ&>9TH7!dx}`%7KC8{RFEptEVu^uP@?d$0JQf5T7S;!~O;}xy~I|A@aT~q18)#{S+(`zK7ciM|}LA|9Fn1ku0rkcep3^uEh z+uE#SY=dpKCdY$ei6;5dV~x%Yy6WH9(VTwIT@Bc&GCEfXf$*x8t&YB^>|-}5uSkI| zZ=6>d~9t{T}QaNGYlI5 zzhhgSsd~)hON05G`ls~lIT@YpOd6Y0qlWj@_Zcx2w{hQQJr#W->8W8M)ZK@7pT$-O z7Di&0Q!K7o_}u3aOO9O^SEM9o{rc{gf=kWV1WU-o*<2q6a@6Uil&cZX63RmJgP2GafJD1;%_3-Y9VuE zxf@DX?fKvP(W9medm-WK*5?gSX-I-J^fa5X^ZbhM7e^KX69R}%5SBwS>q&jHi!Drs zNY0V|5Q~StE@}q!`FFbi5oXu_VSjvzbFLLw4W`0~q7xxJ+VR+$kw6PJ-xt2^iH$_y z$lr~_&ZhW#Hr(xr_mz;N9@MA4mQPR+^*_=p;gtZ<#hp{>nlYEuD@(M$rSk}iY-?w@ zXR#JzW-0j!oKMxLL1hS2%n;BBjK>>h_v;|JA78Nv3F`qzJHe?lt_AI|jv-YqE;Wc2 znPit`J9jsIvqB83K7x~jpKADmIt5-b;_MkMX2K}=SE%al>SXV(?gFwki!cWuPZcw} zH6rr2xqtr%UD;bReJEj2GF5$RetgB5s&mP(CTr@6SG9sAYGv`wWgg3O5T9hkU#o2} zxRZV3o}>C(F%8}R#I-la&5WXF4f^hWr1s48yiAt&df&F1c}H)S;!&lc4t5IXu{X<1 z{YBS*R7-zavbS0|l4k&=k|b5IR1+Nu-xiz-xY!F4lr$~ZG?KFX8kO6a@%g7VwQ#pWpk7V4yJqcE2rZRJE5 zsUcH`tk}$ch7d*5#hUHe4c+5sTx;F4SxjlXV8vmei`Vxq<{1sOY@_t$u@E?nm2ZU- zx_HrnOrXe)E!){mVIu(_frLsG5r`_7*TKL+aHW(N% zsBSi_i*STlP<~Oe^Rk@2-@jTsX~xD^6cmlou&nrFgN}M}xChd!{zWwC34a;EKry(A#Tn z*Z+^)74*Mt^*p3p&Mm{o(2LbLbKmCQs8Or#`NE_*R}}18h+=Bq#QdrIhMl>AsCka% z+uO5<5$qAD|MIUt*ZOTy-`MbXY+;Hk9Z8Pa}b)LzgPK2oX* zQ~lHBO}Lv+okyzv0Y9>VL~$cy9q@2<5b8VK*sVW4{RL3Q^gGp0=-gejES#M2O}-7XHiDQ6bkWH|>)U62B1tw!$Xu zbT$$1=T@HjN=T$MO_s%Zn2xLI;A+ZyD2=BKK#!;8o&z@Kp51qs{Q8yyporZ#m@qKz z;^Vp*3vi?LKC@9DpGecU@k9)z4H-IH4TsR=2027W#3-bihKjK0OO79&_0__qY<`o~ zgeVC{{E}+onDFtp>D672*RT+o}f#GBf`9-@BI|Mp1FR1lH^YK zSZE-H_`Q#P2!!|MyqYu5H@hLJSF<(>lHZ&UNqY^l5z;0Xc^GCOESpj@r~E655kUQe zW+iroeh}=i9cTvl&-1Fp7Yr1a34@Lolai#h1EX9+1Pfmff)k?gML4ugM2`_~vhf0o zj919TSR09UOmwM<&C-sz5tXby70!jq;N zQV%0Q7z!p+D5D~P&Sl zt>s2BZLwRi+Z<;k0Npw5+TVUwc$0D&At|KLJBhB%V#<>0RrxV71flfB?XgB``k!%# z*r&J!(BG|a*>BchaU0V2fodQ&A9a=P7K4i{R*kSEHjNReKe?g?*co)Lh-&!kwVeHZ z%Nq?MUB*Qd_`i?_G=kfHaX@e?qQR9~Z7frP^U6n^_wyX5LD+jn*4ND=d^Xm*{WjI?Ey z+Un~dN^ANoF}~)$WnMDGjk@d6Q%~uRq+Wi71jSR0FxmBT=wjQ?S6 z7frbi<`yj@xp6a4tDJt}1^GgcqOUibuN^&o*X8fjzS+mbiBel^1_z2}n;#g9SXGx= z{88kM7TrZW1Rrg?cXqq+UH0sBN}0-xAeZu}NTAr(F-lUNSZ#X8bJbA~TWX-vwpbG_ zDvi(v-^?@dXkeqbaB_`PMH3(D!4C$5Zi0<{BB4Z24%zis!-Lnv(0(%_#35SGOQu|> zCI8J9mq}V-Lf8X~ugzPC@bR^2+Q%N3Ac`jGbU^e(hBakLObjVV_Le6z?nRBgUlCbb zKP~9-aFerY=SzotR@%O{)F0~pP$3oMar!UrBcSE?<)!O}2n#oJ{N24~zG`{;@Zr*u z0zYy^zJEB)7W<2J&=I>Q75h`n9`>DF_5~$pcXyH|Xq9bOW%D5GTMI&JNN~VPR5cI! zXyAd6M%ZV+s_OC)aog2w=lVu$5i||;B*>YEKVLX`x3rW8gW1T5Ki9)D=Q$yj*(>~a zNpLh4GMrP2S82T~b~1zf>%aK5KPO$)@ zrz4*8o&VtCcRB7O_WN4T!;i$z%TxXg%`n;7w59^*5DU$fC_7!laA|KWlCzeoYzftzXU$dBCU&G`A_J6LeOZh#zn?}gOZN!AxeD9p<@<1zk{Qw&Gf#W+VJrVc< z67|rsAKi>#Y(lxsU(_YxE`&!YpXcs}>1#mlSit{>jq|+JHO>jngfxaLDyU6S@5*0l z&+pADC95wJO7YiI*NVSGYvyQ&NM+hMXH%fK^e5FLioVzDqSO+2^U?9znQ#88nO%c= zB}U8DSe($0F%0?}7^oIg=^Rc!?kI=rFl9;@QuIh<4-S?`l}*Q``zC`YV(v`#6$d6| zJD2hoE(=X}}ZH0`RjHa#oIL3qz;a)frbP1y@~s$6Lu5vXXj`Vhf~D zu(8*OApkDlEc{TMR{E{fK}V`di$+#N-OnB>TnYPqDZtx*_EbZVO19z zChxfxT{QIe1f576ox^Cy%X29r*s-g{)XnO;GIF8~6{dYMn-f|wQyHU16Mp<7P3{%bO< zDaZQFx+r!-qauyo0iANhHG)*V4vOTL-Hx@cgHFD(I&l_;{FJ_g%f#Y$hCj?N^WlDL zTun+btG~d|r5ko4QolE-e+WtyiqMKsK<`5QlTR~>+WD25BD%n{={V5q)UErMbm3Hs zSusvj2jB*Z&V={;Je}GT+w^{3bqMXE%rEac5ux7QR?dlCYyxMxD88%0GWIIUS z8ofG2PNGh$;ZCP*i-1i5#@OaVVB5EnH~3FTKmVKc?!BrLmlBEO>b%luPi2hW)#=Yv zMu(u0d|?MZZ?)k(J;%oRkAf*SW^lga3Bh2NE8ewm-W6 zRvoKL{c6w8k9X}s+l5oe>p6m=6+`z<{+{EvLRM9b!yk68Jlte{&)E`$6oX`oIA^2B?YXF!f|xf z9R?0m-D}8iho8Y$^m)MK$|6*3|IZl;nc-HMw#ZOnL7UzYBcqq(q(JI!Mfp1|t#EY8PAR(&pLo!X^qA?5U z8xGw;(&|*#Xnod3#iqrzyilcR|M>k{L(9mY==Jy?5Y_M)BCXD>?LWh{Ai}2x`!Dv{ zO>fM@m`I(?s%YcB|E&4m0tYAa2&;B`$8S}iRl8a26z(`M`s3N5h9*IWc3OBZ0mTvQ zsk??(2@!Srz!B|3iK(2nS>rgIcvB<6v<(xzcR#6qB=bN~M4_o7fH+|1#dVkYiP*f- zAo*e{4?DYQ$dSM3HS3>ZWdi1_x=8Vs_X5FYwt zeXYof^vlM&BlCHeh6JzV53$kE`;LBqc8W+Uz3Iz0J0_4)RU!~PGLGQCi1$4A7^U{0 zc(klyjyC}>{T{fVDJeAz62oA#y>m}B&pk~KW|o}~oW=lCAF!ga(9R-cZV34U_tw-> z`?RPSXl3>o(Dk!&XBQR?`8d;tojCcB^Dh{C?CRQ5Mi7mu9Zz~Iqy)J6Wi5yqzoqd9 zR;%Ue-Qr_kF>tkM_#&{Zr)=+jLTgSpPMd+aB?o|2Jw`TxCW=aoCx_8gn~aUX#;)M9 zCRw?1!)z#9dcA+5OjsnZL5Vb_e9K!B0fZsi#t+!b^bB!JXKQEa)&SUi`*I6Xa{L{e z>w>}sVNAe$*VL3IL5r`Ja@o5>mu0IG{^4Nd_eL+{SG z^u2WlW)#o5aR-8M90`n=Q@F*QOZ8aNu zUXvq=l#%T}ij%vRIx%^M%ZGFFB$F=;etduen)CzI7*L0wMm(T;TG z3zQMErC`~j<%=mFA58p90E~V1JI9jJ6pDy2#Zv|!EH-`zb%3>*z#X!js5(dRMCQu* zLyJU(BQJ)GSr+~SEhhhx{Q#GN6|4=E!`Lb^wIir3%@i+z4S%t6{Zq*sqEB_W(hl5% zR~ejgTt&=@>%MfHy%i+AP|AB!N#Mt}anU-J8-OYr+}&Bc$h6OP$>f!ZrBfxAUF+BL z)t|H`Tir~T!)lXe9NJq_0$xUe_hB&JC^@q*@&HM>45sH0;T^VKn|1;k*CrnWK)|%vQ8BDCym`JABw*np>;b;KBt?{+yRx2@0!sah3fMQHv}K+rYGwK zDL3$Klk~W6iE4F|=Z=f#=4}q-lV^a~M&QG6Vh%xEHl`O0m$D!`dCigLq#^T7V-C_w z#dO(&%NvraONPvl?LV7)W40n6U47qFXmO727xmLljZMx8~9 z19`y`!I$A?{9TXY1(8M{;;dOlmu9T8It8<`WR1!7-{;><{63_ru+HPPdLS6XE`h-h zb&KVKy=eAfi)(MIAiR0~!5;{9YvREuhyg#zSQ-stKSjKm=kGG6Zr;9Q*?KqguXF@u zw{47LZ>#r>ey111J@fjA{oNrN%Lqcw1o9^hjl*E7)N|Io_TYx>rAI-Il36i2KTa+I zOjj6Mv|(R0k!#%kcW?GqO*em93hooRzYN8E!f@mrot7V_a3=`_>g!4)YEG$3v6W+nqBwPCRB5;AZK74>@S|S(XaYuQu^zgf zVM&C5&d(G@ClOltMV!P(raXGx3XfWT_zSrlVC$GUwGNAWDi`=(UO)EzM(k1@$uuc^ z6}HTnNZw-2I4k9XAJq?bvYs$(YqVrT6*ZotR4TZ2b|)jA!srZ*#E~5{$A3GM!$eCR zI;y!p@}=&}QX5kC;uK1pIib~UmK9HDgreTxAwZRHAhQ*bBYsMuTz&P|iyC53O_zU< z$;4osg5s4Cr{*+MFr6?wJg^ZI%PDDig-9QUw|C>-QLwMOkE+fsTilv(rtBt?I;;r& zflH~#np+JS&4b|pyM{@?%BgMS;;<>-;2LWe)YP!j)DcoKUBj~5x~ecPdC0qcN=p9i z@b@Gzo~{S02D~j@p`nIxr@tQ|HFYBGwDt8+4_{8|{q&;MV79S2b=Cu7SN1c&4in0l zwEURRq$Av8%dH}R+V+dvL3YTu$;rA=P&B!Q=opXHy~_tID!%hA)|`hA+n-Iph^8md7@?ozw=k1vcL-qcSGZucvlk$a`pLzDEv~5TRIdJM#T_aJ z1vyt!=gyU>p}o?Ev~6c$4tXgWwl5H@N`fVbAM(|opkRZ~ zx4lF7q}(7;`eD6N9e##|cT9QkyVWw@o~yUP7(Yz7a*_hK<= z-gXlyn~U{~ss0Upu%b~NS*ezj2a)L5upMVs|0r=(kGt8E>h>u%a6#2td=~%)LgQmC zX9wP&i8tR_97oUX00tSo;E4$`l^i6qTKeU$dV6E*Kj+IMC|y1K*0 zbQaep)PZTsf)=#HLaKaA#RZEWY7}D7pE*9ZGwdeXq8aKG#ZF;tz|%8Za^zIfsM^F;iOauiuI3*>dQZ^x&sF`=KMr1Ke%`U-(>FU`$;x@&Ep0AN}VdM z&Jaxtl|(PWBW-_GK#HllU~O*KNyR`nHD;*@^LJ^nDFr)eEr>Go#}PL^04t0iBpeqD z`%vAYdQS3QzUIcU+x0Ub*-6d@p<_xy^DKERtvAXm_OU62@m#m5_TQH92%AsG5k#kE zr0(el97_ZP|M6CmZ3H0D%oi{7=K4-+OM@hzRfEfIw}}&rT7r2=1{i$E1Pxj=}5Cc55W%#uAnATgB^(*(Mj-*lq%icsf#gbr|9MaPh zH6gq1s29FRIjtvfh;H^3!bNe}SaT0I6-SU~Q_169;-i z!FhOFHt7ASqg=Lu7lq?sh z1PKSEdiB(%5xCds)`Y%L{H9VHMMNoiGc3lNwUotetCXXD60-;rps7Qhk$a8`6;~;J zd6%}Xcj(4^1YJ;qD+&1+a9BV1jmj&kYMY(|(fvchUq!s29!7e?V8~^n1^A4Xs#rKj z^N$wbd$%V~cLnZhl8FzssSYA4(N!UyDLjm%D%`>p>CkKWn>>2-_R<6gB3^TVstbNq z{GQ9GlNIi}V|iJ7CuPbZCiUBgju<9o{X&}x*wSThKh{qV`U^r?mn`ouxj@PV61UNI>B$9SN}I9cZcYi}Br2Syv> z<*VxEb9>jPtOpaHVU4NR_uIuMr!@t~N}_H{H5DBF4y=DLt}y0Hma|OgbfQUg_)6pc z2*|JVgsA=+q{NX9j9`$t7;jxUZuLd)*oA&HG`fBVud4QG|2PKr{v^*|lQ9v!tL+ST zb*-ump1mjvWIph5iTn%VPu=;$=EzbSJVs#~zQcHW!y70IhbKpT%Fe)@3G&$NpEDkS z9ZAbUi&kTzG~K;_A`IL|Lbj4Zd!bETAUlNR6SBchtTf}MH_?eunu;bNPL;iZ`9=S} zQfYBecbrm>c@Mp4MFX9N2m+!u`q}csRWzeiI7j#QCy)dWB|B6cFn%MSpo=ikbHe&iN?{XyKdP%F<0+76b@Xy82R%~%-1VnjuNJI-xDO|x+d506?P$Z%_o zh}*98BL5=}1Zj$v2K8#6!j%hZMM~mkjJpGl-$gb}{Pu}3d-sHmRt*S;?%B$VNCxoM zHi%>p_(w?ljO<%m1~fznuIM|9WW-BEK$AG@GsS-wr_=CZ!oA~e6KA&!_khXAx*caP z%h=c34T&w|i~31Cw!S(vz>Ips$#)0=w&0fcSZ`N%Vk-O)DC}4AW+XPcb+ZoKu;y$U z;Eo{$7lzn9+(Q>Un*7a?OXzM5Fza$7BUwP2&yQD`>$5wbT&uY{7FD4OK-9%*Zo+>z z_8{45pgzO{c&UqclC9kM>}HrdVdRgjxGpxp*I0GiT^+$DgKL7tg(ZE3YbnJ|gUmUi zS;B>mNr{=HOtWRybc9?r8XQn<(_df6v!(i6E_v9MvLN1S>Ko4yDE!6StQs*#)6I?a zcBw$M)#DvXD>&6{)QmOvqecKXzyr^G9^d&;8{@Oa`acU094UiZ6fq*Uwmf$AQO84B z-Ro-gj~a_5`Akt zL`iBibHVwWw_|uR+J+Y9w1oPqyycY`B6o2g-W-S-M{WD~wG8ICc%k6-%VFWP5$;?9 zr%F(u>0P3rLPt-xgY~Qwo~%|f3`%jeget#p-5KS|_2eJc7&e%XD(bsyoUyL`HPWU{ z;AD`y@Glk=Dp-48HQ}#{Ud&o*y*-Ul9KN6ANdcGfR8GFl;-ZP^z%djy9X=9#+M#HR zjg$Mc&pP)-CE?0((ZTo&7V0#3~eu;ZzuR}k>{LTtw>2WdGnMLg(TZTUV5 z70pWa7>r6`5V@3XmPypMdATkr3N55Qpsjx_|3Tbm`fVC8Du9x+NhQMOeHuUGsk1v@ zh-}rGF*L#!v++s{v`h4ZV*k5wk54CWZ4{L~#Kqgo`Yi1FjUw zsd?~l?kJe2OVb<=!Cq zz*d`aFi{B*c-Om;L!Fp_t$IB6r(PH~kT{ zO?@pwr}r~BM{-Q^9fIkY(XpFFX}TfXQ3O7-tu2D zP~t)A*eI5st==uTEYu%EMCerl5JhDCBhYAa;&@C~*6vxyhX$wWof;NBGY&R?Q%{@Ng6I;415w>I35fX^)rf^nukXf6 zgA&cjYdVEiJbG?`c(xPY6D$XcNNCb;A-~AF(|_Z0DCgIoCfVB=hlMQUiz3tX+^xZ> zes|ezAP{??&84{i#FrCk}uYz!tAa;18mJ)zCme#koyc;(63aZQRd8 zY?=S_)NjuS7ye;dtyKUzXg^d-bn7dItA}p(vkA#Z{K+ald=uZ|R-U}Q^b^Vov3gr+ z!*ZTUoOWztus@?C0`UEX6$gq8UT<-Q;5$|MyDL@FWVBG2y%cL6@$^qiY@SYwPk21| z5z_-_)lnFwXE`bk1lAi&t)Y=HFoF|&NgOQCqPk&K@wKZ+o?Ai_bc$JsAPB}ZLL*$> zNvl083VSNeLr8pJQkVr~PTf?P=`C_k<97&Fb5{&eG7b`rKoI0JYKezU0^5*-rk&3P zD6I=rsmz9Y;Elx+*q{}(kisl2WSd+27}U=%n+^-nsdD)>^h@=Iwx5#FJ$3{FTWfZO z`p1}a#Cusq{B4+3%BSc5aKj|}Z~d4`dbcHi{b=WY(zeu_n;dGH{~+!ZiRLu`9(AWZ zwnFU)+-|G=gfazFQI_$|L9BWW+2+hhBdEQE5>+%YZk!z4^T8;J!dV^iBer=}j-yZ# z#x;nySN-{eaKi|L0a#ComSALwuP}*WUW2$D%HG}tTQ04o_?{trw@&oo(?9-fCGG$m zJTMPQhm6$btPGk)15v4Nf>j18JqdzQg4o{1RvWJfc2*1p4g%O5zTc_pSvtsqKYut? zKdi^bTfP!dhM0G(u1orozyqpAag9FLB8mBYE**ivHM>d%$bs1^q8ed@hV}5c49L+H z(f~;fZ&f%LQy4pDxD!odHL(k5&I>#ng{+OnTb}y$K^2==f3ruBiKKVd_R5hub;pNr zE_&bNgM|Y%C-MMw7-C@Hw_{~RV~buat*t*>OKKH)i&;ZulSb&q65yPHNN+ruxaqpc zp!!sq{Q_^WrO%~qcetIlTl+VC23TO5N6Rg0F=(7}V$Z~fy-Pd4H*IOFFX=Pj-f-vB z-prSmCm7;su?ikN^U~OFAaptuFE0NxKdet2cU4}`Sln9pHk)?es?kX8EKb%slqFuh zPf1z&U`)!;)QTNF;dC(>vI2~u<`V-;c-T-vV)31-*Gz|~>n5ujfP3n#q)qoaO+*vg zce4(>(aHGwRyBXJO@){~gVFU9&kDn-V#%VrQtm^ksJgxRgi=poslL}^=ZzU|ct&?SdwB6^SeQ#cs zykhObKSvG0+0El&fhoEri{0esD-Yq)q!{HCWR)XOz_TGyQ^i-lPnBZt=8}}ZXTS0V zoc#lg0~~I0s1@^y+A<2=KXs+|uRO$-2NUhYij?H3K<4hcP6seL zRR)N%+cY$Z>&9SBF*T>Z?wn~)R#m7VlmpHh?!q;*f>6Rrdz$f;6z4s)o0R{9>Cnj+V!=0N#EgE)5rRm5 zblzSZS5_oSxAY|@DD@L_e6X@K>G){90AxUUMQ9=E1qCIH-lS7Uo`JG;P_l4XZUxS@13ZzK^lv$ z0__$$zpCFmU!NNgdZp$OvsL4{X-rq-IqO~C6?NevqgrAaHl1HeC8=TZyS`oc4Pi}e z5^X;V_UMGRZn7}@#|jOk)RUrv4INHTRf{?kx^Rh;VwOq^t8n*6tkV%0OIg zw|2#VangMJYJVkRCRc<5@me9R-QZQ8+W|G&EqWp58i6pk<&aFxQ7EyYP$iDeOp&sf z|E8wpR?smyc8hlPt_Q@f`6uaOt_en=3`ZHG8AgG3YQvZkPtKtQ*lhpfMY`IJ5aS4{ z(oxU`7w>B?p$>-{TLFKhknv5<7E~nhW8atYo^r8K$=pQk#w1QAU!e@#3#HPMJRk9r zrg6MC>A=b^VsD2dEZG0bLS9Wwu17^cg@$E~Cf+4C(`6i+OaoGouZ#8W)qjxC+G!3F z0utiGRn;}SAh~M=g6oN|!%jXb4W&bS$ai_!Jk=m#KH&YEWWi9pGbh-%@Wk@UuP|}u zKE4B*cb`?coMH?xU;6Hr@&GB>?qm9OY38MCgZ`S=?gC8Wl*OtFX>D+4sbpK3adu4y z-{Lz_+X%1*eG?A1t+rgLr@~Bn+ePqeB{W~ryX?o;)9&5<(<1YJVbk+G8|df^US$DK zbK4LVkeQJDIC}AJhF{#>`Pz`mtWqQ+x4inU45jT!W7q}&Cmj~WXH4oZA#H)W?WLngkGQYx`d+H0Kjt?FgkKc%PyC4 z7TczEQDSNWAa>Q`6rI{Axc6JP^|Q(#lN2Cr;QzddDG|8j`n-AG+iw)e%LtF<*s2G< z*cAw`hwn~rY<*Gb0!bPVmJ==dZ6=o4-(9a+A)D2hUwH_}OtM$jli_8=u@4H3>ax}4 z;UVdkZqScBc?r0;wB!V5!#7>|-hJNbeddt;{ZFgJ@_7ruH%{ECxwn8}QNAr&Xj0$1 zG8%HBl762ZHtti4t%=p9nM(>FXi^^qGl0P_pqWQ~Yn-O&GB`9e8pNUlIXtRJM|t4L z{z1*PtfW4?Nk@`+a`o=lTfM-B8npG&HL865AW6Y6hM#cgL$-`Ct1UVM9;6Am6@xietG`Y%!UL*bg%sL}ie{2tL?hmW``xQKFAMJ~o`wirpUx}T&6Q8ueFsyn8L$$0Y*>;8uBw7lE)we}g2IyEDC)%hx=A4dm4#@Sd?ZWt{e zahr3RN+V66wU*QsWV=s)vtaX|!W|qZW};Ut4A|$|F&I`zGHtME14&benpib7ia-0I zIaTw%qNk4$nD}nl-`ba4ktIi7)m1fEHAlJB`f1*3@H>-F2$2^$)%9mvyCjHxwosMg z?ovqAB@z_XLmwm65l|B68OniRDp(K*Oe?WjY`=3R{+Brw;bnSAitd`Wr?2JyHZ`%n z?R$4G302&36?F+(o73)^@p8JSi15$%fOjFg&pG13zakf@dj>X)lpEihW5zWs3uc3T z<#kFYbAA;pD`c-q3x90!*8NEA=F;RjU zvoA);^<;haZI;p2fKmv?AlA?Dk{*^HSobQ7N)3ErL!> zR2H`VQ60)O32|+>{@wxo;QS;Juu^ASK2BEB6x1RVD6f0g=d zf9SsScnW>Kzs{Y_E$N~}BLz@9Hcs3VM_9Uma(whdtT(sycDAiq(tn-t(h6Z1;qpF1a+U(&Wv_g64r z`OA!lXa~nXeU91Tmi*4k8(b(6!my8kc)0K2ll_I4d*Ef%^0=yt*h6UlbMDb&YwYY$ z&?DxPx~a~*FZrY6wr=qE5Li#XpfIufm*WfO%lqWjSIuRvcEw+W4|$Iu!AZ-=KD-^A zxkIm4heOM=u-7VnHrJ$2*}KOd&KwWk&t|tdt^fG-jn4$SWB*xY35jpn*I<6jACOFCLz8?Nis$U7`VbJ2FCl zlx4u)F4q1^^Gv#Ml1tkOJ&G7>CK$T`&-H~R5#U%%SoTy3N)r*28%dc48lHBw(yW8r zFD2p2LBnMSQABQ&W@eOTw%dMkH#%0b#V~c?r{F5n#k8`dW-{+Zle=tOf3PwMo-;5?zj2NRg2xaqg}maVyiM?ay1wW)Rji74g2-VZApohk{`?JV4tq`R zH4QROG!#YziZ%|>sN6H4pfzEFD^73}Y4CKfqCv*_@lilHVz zac0L2XF`*uCs2DU2-^^^M`qG$UECsgTtn{6tNJUkU>x>8w0gu5gpMlK4Z(+HoMT!W zN~}+U&avryV5Y#qK{uUMs0fx&-#*Ly7N5I=T*W`r1x%Q(&wM&>fDd(;;6$-7LANm& zA9C-R%R6*@iMa}R2=|_WzO({S-mn5-VSI|kT+RDBZ^a3i^+xbj@Ov`{?1iXOYRiLb zGOdvB2>0&rT4h<7lB7txc!d_87UH>R@C21kp!%2q7$-6-^5`b`7Tn>jeu5@MLOX2Y zZkL?7$dvVkp^o9Pg4JMel^u-yb0FM|Qz1!fTL7LM<`D_Q)lM%dvS^7zwI_D_UZ*_= zZ9=>_Lw-Dys9ormJj776^_%LAnb%xISiPP?ctax*)#QfUpTl59&|;~W!~?SqjM~!I z%nAo5?w!?kmDW?s#ugUT(IJ+!z{yYEeN&W!Uj z8r$?L*A}_8bsH-nah=uHa!Brdm=M+wXD|Ucu$WcbN$9(nX!FZ1B}^RDv-4?Y!5$k- z`Dbq7RVolx!Qun9n^>^@O^sVuhK^6@Jf>1*hTXF)nqN5;cSF`gKKvH)9~IwTUW+1_ z2^@&7Q5M|qLr}yO;TPLJ=$(MKe>O=KlOD|0D*cp)z>D<`K!-^!&Q13vFxlVn4Vie( z05hchlk<*a%#}XbxoQjR*-&7+P5L9UBh%G%`Th^LUv^YF2X<7cN})d7;GFqH7pas& ztbPVEd@6Ijf;e9=qJ3z#d5n;<3j!w*fo7lC&%8A!6Fan= z?4Yzo1IUXyDG+_@Hk_>e+v2-D_lGZ$Y-A2rO*%-t{xu4)0#Nug2(k-Ok2Np3_a0AN zN@em*Br zNShV;VwIs`oimR3Chq~7YoFQyJ}yK&8Gq6!6ne&jUaD0gDvuY9vG~1A*ijHNo`0WW z9tZfbYGdKsfXD+qIn#D_+*fV-y6VYyi`zd;l^^NM0t_a(ADVy}vI;7jSoIPG>Md)J z^qW=_wC$pO6X0V^j%%|2bW29p)|bs!ZjjVp;*$7=D+?tp>#Z(_H2~4InadP3R zScB}b{_V5EGrMNJMaX$N=h{eJgmUzpelP$|iX?ke@~7s2;6WKD^4dk`YE@zSBTNl~ zh3wAh>9_g8ZxJ>=B;P@|WxIc9oS`^+r$nY~NNq7PORktgwaIlbF?;SHMYU$D3co2R zcqJKG{QRWbUcG_Dq)pHnK8G*-#U_99{j84t#9+1eRjE1$bM&y|0C>Sw@VT`I*NiYQ z-sRPu<7$HMj+*QPfFJgANnJ-zBSZU1x7Iw%teu?u{AZX{k4yr^pjAcbz{qzl%c)89 z-tr54Yi%BMT~Rm+Bj}s^J84Tit?p%ODH|RN8rgMVCQmk!CIQX#2F1i7&_oyGVjX0Z zP;KstU==O1wLZ_MmW2!EK0FAPq(=JKzq;R!{NQD0liyHt30y$_?tAth@yNcipPg!9 zEHY+L0rSvOs^)xKMvSCw3`bt-!e{Mtf@9CxG3uF*+eG#vBnAE6-{1*p7Gaazj=Vn9 z%X)AW)}gxdwxK5qbC+O=X$1 z@=L<5lsZVVQX3mTKZ;85M-`!ciHSqhFv_Kob%Ox7N~D@4ZB86A zCf;z{x+#!Z$&o9Th-Td7K6z}vVYb(uipma$PN%Z|Plc3;NyEv4xa?$X$4Y*a{&m~O z=Y1E5UXqmb6?Q-2O!6KDC~NAQvmP0!Lk0lm5f$jzwS$&2lTA#S@GQSwg_<8pyrB5&MKP{V*efgINUp=L%`^W(&`%GoL>RD;%fE>0jl8=^GCTSRe z`18{G?xAAn_W=sFE8Q9PKasO}cJ~^eBg&<`myjLG`06)AFK5R5_CAdE$1oJM< za~O!y{=^RfvtN{g@!c7HC-Hv+&Trms-iXoLA2o;Y554r9MW0?TKCwUG(boKjzUsG;%}+!=N<2~?hQM(wqYW)AOG(4vk(#eXz$`{qkP^P2yJNC5gwX9rYawDiEJM#NZE{Ts}yBD5ib=0u0>;pxlGjq58-3dlQ5KY`r(O#k`?+kptQQ zRr~qr0k*fNdnXZ4F?=ImWe`)<*ca^6=#Xjp)F$8P5#>b?odhVnQ71)flxuu$Ff5 z)46AfNzHK75#C4N))%%+tG>O3VsjaZRXT7S+1NrA8V4N$60e|TycodYvrYDSruf(> zO;*+RvkuCzD6lQ+D7|PDuqwNURv3K@teeSoW)#Osx}~vcB`*| zR3h#oILL+JhO_BqFqDkN2+6YYPGKT*^P+dhEtt;=yRt8mp=hBSPkSL#V+zy%jU`#` zH<#d;IJ{Xz2$c;>l3VEHN|HzehmwEsF1oAeY+PC2@Je(%I6@J|kcXW?R}sw8)p;~P z>Z2g(xB;wyW|Sw^fMGt)v_^+ZdJSKS3>~M3tO3bSIdgClkaJ+#-_!03J2wh$kae-C z66=4b_%%&hima2d^z!)F$1!^6+L#GDqiGgWW*tPg9w=y;R;|Jdzn{k3d9B?XM=R5g zc?G0dO;bzM1TptR!lIKJtJEL`I^P2Ht;Kzvu!)Xxb`%Clc6*)(FXhemF8ihN6VpJrEEVRty@~ zr1*6{8*r#6`9rx?66xtKTL+R#LO^%?p5M~jmuY9;V>>3V8T*yNV06}i0CR>4choR~ ztHcs?EQaf}wtkDrC9P~asfT$T*fB8cDj*X;5>p(kI{i%qo=t6C$|Up&ePPKii6iJB zk6ili>b6|!3tOGRze5F1T6fl&*=4+k0{q|Q(20mMP<`t?0Ynza(^&)_^-tjEW4v>=eJQ3B_a z?~EHiRt#6R5+Z8^k-b~k>XP(4S87F-<*0xPU6<$juNvTvqMM5HWu#Al=N)>N2e1(G z8Dc&1H^|z)13%-3gpt-&e)|^=3$kBa#0@4^Qge59sf&&T#T1_Eq~RVnsbrvm3bGzZ zH^qBwMrGSOa+c7HVv!+}?&1L2aHj!2v?LV+;~C5$i{*i?G_-8wCBa82t@z%G;h}!a>b(--?0^LN2EPgGOH>_M=3{ zI4m&{+?FG#t@2{SW&N{Gh=i)Qp0Yo$NN2%!lT3c^5&^bUplkr-LGWKX7CsnX; zN^SSJsQsT!81wm!7zrnh_5af~mNJhQL+n%*<{KO0x?H^eF7;o)2`rx*Xw=z)cp)yC zu&<|XVHXpwyeC0{qn#&QPPsK~nc^g27HHIDnO~C+brWo;R`ZX@os6cX`<|34YOI== z$c;+|AfyhGP)yR0dI4)XqSEkX3X=dD%)+mU-x7;%PWjg}uYDPPIQy1fc7T!dB@Zla zkgA5DmUk|xRk0^)wBq~zivhxHDP2bDwUq`>9LscvDGd$$NvcRY^PuWn8PKRG<|@eeQi7xKD~b^mMMom@r%SkD5Ew%_QeiPJ$YMT5Nfhzgy2u+f zP7v_`6rMX@M&+Mh$NSjGJAaT2d~RQDh329c{^#E4DMJ3-`{cf*Tn}GZZGTMQ<;pR= zR9#&@oP&GfY*4Fi7jT#T(=`(0fYyIC;MGuxP_A$6E8Q|KuT_S>)H!pk@B?eBC8^yi z@@n&J;D}WgwazNUW0N6yZp)P-9yz=69vBfgIbwU8<=$4OdIGeaYKsu~ zEK(NrORysnvdnDN{}M+QOfgp0Hts9Ui}%&E;g5qT$TgK`RQAqbX+q?V*3&^XTO(P3 z?LV}y0jtH(BiGpKP9GK9*65vpIe_7a`?0j47KO2e_sfxXihkTKWrPceZn)}M=`rjJ z_y4L=sJ$r!=j@ip^W)h8f$?uAN0H?yWS=xKP_r>5nH>!%hz)XMyTAX{qKzYW_Fl zEFc0zTAO=+H20pc{hI%JER{#Ds#o5&5+-woAbIt_R@Gq2il6))w07LON+Rk_Mbe72 zKMJJI)E3Lr7PJbhI>Umxmsi@+bZK8_=n4b7Uu)V4=bTh&iMUyHUDoCM&`Zfn7PWyG zb4KiVte0qf2Ov@=87Rno@8X)$==l5K#523}U9J~l8GI4;o4jQg-0X>1Ox44>+J8ND zjwR}3HgErYPD7#u$S2>HJJ#QHzLxx!zh)02VoXQEcyQv!fQZHTP+MtZpK zOAr54h&mW5sa`{C2e}WYP9d~gfLE8q(-L80`A5<5MA=OuTi%Q-P$$-2MW*ex{|I+= zMuEcJu+x9S-Dt}!{@=jbKCI@(EqB%NO&~`}sJgZk@^OdwmTw~geg0h8LuU6C)V5Q4 zWG>LPn}TaHmT$@F-H6kv6CuWh=3ohJt0zr_JUWvhdaT{~J$PEfqwB!E_^bc_iFMP% z+ph;Sdp!WF9wlOIuE)U0z`yAduhH-aR#$gnJ=Xcgo~tHE-UsNO(w1laQJP#}f_pNI zkT+I)^4@`?P20k?^;>?_VSg7`ZIcVQ+C0k^ULMm#z+=Cu*>#ZU#4WRMhlo3 zrzMyo-l4t&gl0WP{0-Bpl*<0>#9fUHXP@-GmpX@liV8mb6Yu()46wksq-Hd?Ak9Vc zc6J78HCGMz2`!J2elFDxDTD9;?l+Q=gAwDf9bXNXp0N}*&4#&PX0**8n|gCYb9OF~ zzzZA>%|P%#Eyb&=yl&Xa+A$x0qt_$f*iYjBYObtJId8B4|7;_!+&@QA!6qesZ3xsu zARg*jwc7blX4O+Mx_7}Gohz*^gakptL)HB(2;Jrf?sc>=+1D(p3%!t+0!hnArOPwd z|0!o167|i&B!QlYdQ7Up*CA>K;>S`!NR@TNx0=hXiYP& z-`=ivlf~Xch#}!$gdG~^Qnk|2NQE^4P-u8V@M{pPkUh=WWHfk^KP{xc*YkGQ+$c*2 zNMWt04;IyVrCj{Yj`q|k%!Hqmf!KU(lo20EE+Kp;@WRbS#46s39~?t(Nv1~9)J!d? z;HVRc*G_xe@tN2Bag8#eou0jUrLNoz!*4%o)2a_2y>d)W)&5d6(y+sTl4{kODI&;j z%Ai$9p3JXIuw|r7gj8+9fyx>yhlBfBzNSr+t%)nUwoAd48$Z)&5t?;5xpQK|YA52R zf@M|RiDzf41|P#Ak8tUs$Q-({LPAW-6X50rWq=(N6KB)mLW7S!Y)+K;9ol7Gzm@O+ ziLSI+1r4scp(d(1ARrF;(&8d&5wa0iA#F%Kwx_02;lvoo{wJUE4T%{}y7x8p7BAA7 z!MgsNF^}nRKm@d(Zhh3h>&h!m^(jq~kMmN!Va<}9O!^{C+`M$J23IcOoXXh{KjXaf z8uE+iIoX&egvUov`!E4j`7Hi$?HF90z&G zpFI1HFLrkVzo94CGvCZyb0+(dW?un*s@cDP+d`uDSgV zvYIHiU_HKhsk{Nbwm!G5;y-7XTcY*|zE~{2t;?_O-;fc>!~kus5m7BDdQ;BRPfswVNS*n7oIbd-AbK1%|RkHS}nk#MR_) zd^d9I)c>Fu6T|*z#yaApZnGZQj>B&tEamsQx9ycu)Is4#-`D}VI^Qt5?xgO?h5TI! zLbCqsq5ic}r^Fa-7}pnt)+*^yckZ;9gsZj^RghRQ{epy(!Bhyv099&iyE+TYruSHj z3yxB5ooN9UPeI*ydZpCr7FUD^`~7g9>c3mTg zd*|a>7t*J`2dq+s8-BkSQ?Qsr2&p6{UMjlr_V7E*M1Dc{~5lhKBsR*(As{ZcrEO7#~>3f;aUgh zz*9UG27}zE1*p(Hw9!M@=3p4FhWHcc_}C+~aZ?%gG`Y%GZ@e=clId$@n0rPUUk zIu$^Xj97_lyG`>7mMVQZ+H`#PtuoorxEy*4QV~(N=J#M0{SaKx!HA-xi+P+0HReOj zA$!&&Ii_RMn|dK`yw}Z<;qaHo;Av)cKbJj;j(iBC#V~0*j$w%&nQ9juaA=^tbC(JVeaeAj}j3?~t`eB}8omAdPyecWrSdgjTYlbQ9a(yYoV zNzr>DVJVD0yEeh5g3i!v8zTcOp1vumCGCE#>V#$WyqX4`16%XEykXjR;Msm=h35|` z|AVuPIk3q&ZXFs=4i066@(|7t%N?5TL?C^6w0xxvgz9c2m;Yo3)m(Mi!h>$QcczSa zBZqFW(I&7s!$Kn*{wGu_g!ej`7emzX1hg5+6Y$OAR_Aw>+APpudq2^()Em+xkJYbI+9AzRHWHFt#(i#*>CZh#ml+Ctg*yVJ-&P?L4q%c7OU}Ls z(WnMl4)=-1J!!Rpva6qM66Km}{JutN5ASeSP{E0ibb`B>O}vFYfh64*`nfNj&^~Cp)w1kwd{hP(UiF}5{25nR( zBXrHCMLeJK2Pbgn>HQi1)>@+|LRo0dyH?@LCH7l~Zh~HHcjJz28=+`LtX+VmkP0L5 zGzn}!N%4Br;Y5!sR4`O`!^gqfTjy{qwx|o)+7#1Qvo8nD>rJ`^z%nGcHuW~B{7pms zF}g!^z(=KyT$0=ly%?PgEIIH3qqmnyKfqjCpnqfNo~z#h*Xfu6CY%&g>@Ljj96;S! zMl_ZTnJdNFR?VO3$+hXu^Rp9`z)%L{R&nIA2Ykr1H#2K;oEm1GyyNK8!Uny|y?3{Uw`!x|eitF+!cK z@#!dLAfK3$w1yjMcP7^=WWnUy)#n|6B|dWR8d;Z$gVeqRJKjNaj4XY17VdefMLRBR zM(ioF#}uJtYSuvVbaEbNwZs=yCI2n9y0`FiG}Km%yx^8YP4`EOoel>Ory8wkDtAw= z3lhrlBzs}y$YY*7Rb&mdCwdAe7=If0^J($b_VoBY=8kyK5Ca_k6^VVzNTw|Vk0gSS zlN8cQBrVR$qeUw!IK2o+Rxhb(!y{_J4V+gnbMX+VPlC(v z{RNwtTijG<_MDUqJ^?2hGK+CTz}xoYcT6;)X;a$>MJ90ME9HNAu;C%f8`QdIKxE+i zWv`utPYT;t+G+oC@8#RNGa@#!PPk8P$8j9&5i+M z5(G>W1~zf=xn`kCmCC~pDKdXSa41JQp03SFyubi>!ha7XVF#tiS!EMTdR(v9i zlJSTx>W+VpdO4xflEXH_aU5ZAM`cz{JOM}yGAG~ZIMp=aHXe)>ONf~vHiU&;`62(lBG5R7vE1-{aQ=5hfC27Pm{-UNT;QPJ0B=WF!oUdV(q@DRvTOaWqAWUIZ~UEgh=>}v=1`G6t&$dxc&sH zLAL~H9x3HsS#$tJD)x(Pk305n+R@8U;w*E@2d$1&;qOMHjs;XhO>TQi`JE^hI|S0^ zcj?F3qUDxx#Dm5Gxc<^GDQ#Ki%dn(ntuMf8%$GQfnF8mR&+U?Hm>~xWT@g6wfwwK! zoUM>ISc2-k_qd`4D8g)|r@l_an50odac=Rb=l|*@`#1ZlyzA2(P96mD#)Byg%^cxj z_bX<4gQrOC`?7st3Da6@Fu;ZmBf@n18_u6%(tww(8WsVh-=4M!c>(|u#q~;rWGuG4k+c-dLF1{sxZb_K;+a%sMbvJ5YuyV@oRH8e8rRjVYTzE zF2t)zLM`yajvWDNZp29yo@`aQyhP>s!VaovZSW9xEcy_8nK_J{JZ3GwUE}x}d^+M^ zwrdML7OCbPk?cxxQiDzWwPNKmNl!y1-5H?PbWW@i3Dern0=^!j&lo;Zk8;UYJ|q*X zr3ZJdKy0}}oB$Nl8;?7;S6U>8NJCGSt%Deo3fEL(kx9ZYzlFrFJW)H3xurp2c19Iq=@3t=?j8LyiIO2!UWhCq3Yd zQBMue9{?2uMqEThaIOE3emVjiFPjb7Wt~3~f%TIUZdr!kvkiL!4>v~?pONf<%h0d^ zr}!`ERr*664kqW?rxF9jFxLuD^Uw}*HM1;y;RviuU`V{b01E}a5`W>Sa1J(rd#Ih6 z>_H6r)!bCL2-Gql)C2{>*n4?z1EbNs3MZ74^hpZVGYqk#`qGRUzey3gW<)T{h2U12 z7;3!S85FmqF3JbzV(sKj#uH08Fr)AFKKeJLDi{BryHEwnG0Ryv8VJC@)Bb|uAR`#_ zn-0oA$HRlzZqK2%#O@y~n?huS6e$SHqkd5|pvHgwf`pcakoOdD7vGdEtkK|;3*1q5=|32^Acas!Q%g;6r{;xo zY>BG3?rY~EnsIB;>1VKi{shiT1ZUZQ#HN;>^G5fLkPnLFT)ZVI?arXVz{0jH^S66! zg0kE`F`u1CPOYRbVou*T(SH=viKv)1HUOX`*_gK5)OPKiC}%i~{WSrkYUQu&y`)CA{*ENcJ$PfKj8}t0=>( z1&oddloB@0igZ7S$RSf6 z3086Qj}dVA$H%p}-x~_Z%jDwG)0{!jUtTV-CS1l!^LRPz@_Bnuo&N)xvT2F#JKS+g z?cT-+HCB8ky?jEL=9G*e2k+J9Z^H&;!JT|Z{HCvOWeHaCo1eHpm#Lffk7YVO_HWCS zvSd7E%yK`$Q+07z6rqny#nYtf`IihL^Z1h5{MWHcgtVS_J$#taOAyMSt{7uIbqoYA z7Ikkd-i!!rx>~(Ytnr%~KX_}MAJG@rgl*x))rf*`3z?FZ#;EM`ig`y(Jn>Ul@KL*u zfK4?K)H}tYS>dR+3foYRT4rLHz90`ICh#hO3-I;z*rp@>UOW-MXobO3zpg*dD&;vE znzA2&LYi^@#@i1{6J{$EglQiqePlaxXZS(3mG=75nI5Ym!T_UQmYRF>3DP{(DR2?M0AR(MX$fR ze|JUpOfiN;_WqsgJ$4=#Yc%AxLYA|DcPj?UP}nTbH4&%*hA&e zw<>%@$#izx2$53y(tB7N$@e>td3R^JwVT}iv}q@sT@y>Hj>iD7f+#O$jm9LWqd+sa z+FT!H#o8{fkQ-m~71PBf;SGzX7`w<3QQ&W>pI=vbYEIqlIa-|j2N+6&KYZ-i z0$$SPwxV2JXghew6PGiUy@x9JiDF>mpX(We65zMV(ym1Zjs`t?VV#>GsPiwF40@yU z7M$v#9SJra(DQQpqD1q+$CTGD(Q_^W6JUk>&9DE`L&G)gd4rNe{YRI-J==FDTN}ZT zN{n{Kl~fP{Z$iVBgrX(t7Q7qU%|1;)(Q10n>dNYU?40b336=E-L5*~WZVHD;S8K|uC3|pk->3S;qlkK zh_(yXyw_#pt#$y#xt+4+> zviB34WDKaYj=QI_kM`YII&hUUhA!9Zd-vBN)r8)=g1-Ule};U_$uS_{ya zQZs_Fj$U!;Q9Tv$UAijPQe9{muD%f!0k`w*@fX{u{_El0NZpa9dThcX_vbogOQN`g zM90z=jjEa}%a9 zm(G*QQBr+QyF^l4ABvoCw`Qy#inuVp5|JD~J(W3028yc#cSw5NW8&Z-_w(I4mtQrB!?*5f0& zUIjcDU8pmKWb0zIbyI-pyc}9*c2}!&o(xW6-XF2%QRsxPdEh$CT>_G^Z0Y}h$XF+d zP<$Kui<-Jrx2|6!Wt(v``@YVyg|I}3b2M3Xp{Mqw7t7oH@>;M4S#?ooS}sDu!UHz+ z62YAlR`)`(UV<*^YTLAAki+pY!(VW*AR1|uozxk219Is0-N3yyokae4rx?rJhbd9w zC$!x*dl4;A|9Gb;U}{&GsBne82GPiGc$jFyZiCh>ffXRjSU%0;Tq=hZ;$O1Tx+7xw zc8%-i{Z>Li{O`Jf*V5$hYJS4ieu2KL8oByZ)6|rXS8p{j{f2Agv2Ug{B%5H|+$R0X z<#lW1#p?w{_5liXyGdiZ;BHds@*}crjYsD4eM3{VW?!x#)uf2tF&o*gcmBgTWdZjO zU@if^#~4$D?sYxCDN3S;y$IG*Z>gJyCQ(do)|c%YQ8TUz^R(z^vNrQ2$?2 zs~22o<3b!5U;^&9oyyQ)toaOJxrqkA+l&hA**$jq0m8u_oEi3(yg!oHrXpQjz~Is= zCg}O20Bs}S6k>{eiTv|Oh=>Vva|i-FhRzk0)hhW%9dcCt3adfk8Ss+x`g1z1AIEuB zp9OS{c#%QwCPi;*m5TeCS_b8vB~WVrjA!5puZC_aiwUqHaf&L2kcDFO;2@62hKd;i zI}FtZ=upZq`O+B(A>;FsQ(RHS=L-?Tt>&r~s|f~#N+Ag!%$63jw{SUh}O*$94T+f4gOK2~C*%Qdex6W%dsd&kI#sBrazg<=TUH2tAu@Z*c zjs@MmIkxCPJ~D0LXV8B0m*hOiyVxbwx;(0=Ns9djZ^c6XIdpgY@TUthsSAO11Bc2& z#B}C^o@5Q?7O(|(^kHX||4^f$Uym>DlSQp(N?;U_y2Ma+2)?RKNC%i3NRJ9`Sg0{- z+LK1Al803~w0mX;A92OOEb;OGmKL941@)h$Tanw;HI%Vuj2@&J{6^+FS7yY#g^#*X z-ZJuQB(5(QM@knNdoPh{>mGm@7l;PZMN8o4l|a#k7qVy5kyR&b5P2}B^29?0K{hMZ zS28v`mgD}#hrNXFIK2y_dXNhE(Fkw(TCdKlOjxs>_9$L&Po5n~wR_AJ`5a}>W@CXI z4}W^0PIs<#Op55B4Nc?$GslDqMnS@H|)4VMYF#0(io^i)Bsa!ypgL z9Mf+M_wczgV6e9R8s-O{%hl&=$rE0DUtQqbh+cDih|f9X!310 z@=v2Ab9@j|_=c;Uc+~J-Wiql3p2)hERF*{Xv7EM6rT6U8bVx*D{Grno@?9Wa z_XY)P7^}%qW)-Bhy`o^H z_1u48*=t5rN0T;z4#1RH9^ipk`0k7)E%~B}XWiT8rCps7Aw)P;a==5Zjqp910Nwiy z#+gdBHRDP7NpayC=yey$If(g&>5=$$p5ov?EOoJLSCI6O2? z6FjJJ&i*@UF`AO*6ot5)F?NS}I_6MDlnn+3ldmtWV)__U=qvwMZM_Ps1M5F21}~P4 z9@S36&{AAU+aG&4I)NGVR2dz|YWuOK{MGL?RS?pF#^pM}3w)i=$STh!&)OcK6kc-~ zfjX?WH~6Zd)5Blt8t+r~k5!6tOCD_XS>+Lr#4<){>i+nQ8|Qh6WguY}%5a34a`-kk zkg>1xXfkh`ehXQE#!$JBDMwaHa}ZOx3L&29E?GYGcN7L~eH!@OCo>F*t`TmQtzl0( zF@j|yl6FFV_TQF*9}XC)jV;>ulntS9DlXaa5oN%GH!Zlv2EGFt(vc?G$Mn3+q_165kE8^@#J}h z81`C$u2N5&;s~bL$Xv1|`BdWR*epoVtutFSmltZsFpt{~?o!q_qr*TbSti50mP95H zI_)nj47No47O4F11J;2I)V#T$2J)x4Z{Hb+Br&;E@+m$h1DJ?9!lcV?RqJ`ZOs_l3CkT(? zcC5^$Ku4Ped4jjP+%627XmR(K?4!#tP^_Z3+TCnKfTeVP2i~b*V{{T}dUJ&;DlFsF z_KekesauqbzZ~aiqbAX%xW_JwzgNZL)KEvsvfkEIj3rev$D27Kw{5dO3d#Bmg7*2& zy3F)%@rMH$>hPK|)9ucA^tUMlrVEBiB1}Gh7_@ zJ~cRZ%L05&@4;Xht)Kir%3zOT*nYxKxq>gNnT8k$!Dd$p-^#k_-=A53LmfKmnctAW0FgFI3H=XqzL~utFIIS zI3c&2Day9*%i!!Eq5VHeN7NcGEV7k;$&j}OEPD!q^f4sJCdFbR2#i-bjgEqG<4O-_ zC=py`KB{`ccJ`p-t{@7U#{)^aogyH7AV_P&&HX-T*<-&8kw@pb7&q^oO1 z@-rpEHn6*onixutrz1x8myGFxxC++kCXmBK#slya-)_8pH5gpxQ3d)aqJp7LD`yBu z`WC>WetPId-CVi)r6tMOAudFypuzx1TS2dx*c6gggO=)yCuj#mno{z@zO47`gpRi0 zI!3A{Zo4w-ASh}jjA-k`(gki}*_dP5*7dPBjigP)NP+HTfSu6bl?}nEESsfO^l)Wa z>)66(nt{&nu}6_ti5r>I(9l-Ut?%7jZlZC@{)Bz)a`>v7SpunXpyQmG{UCjzbz{c& z6bJAb3bt$~ETbY@4L-)P`-r7iRH?rTL8g-FqU-Hrkr&+k&EM>5^g#8={I$wgbb!*klDC3uW}Yu?-FAJ z`SNG5#+u0SRySHLp-C|fpobY>Ap2?jSyBO6R;kQzIcfFo|0ic-oW zaiMA2ll-S?p?FRi7kX=fKpSCzVPv0%gq8Zse7qhTFos9orUrVRz(y1@e!Abd3ug)i zq^s@|8~a7oXf)ZRKCMO+-inH9T?3AaM^8Is2YxJcZoKV7t8y_vw7<;VI~&;G?;KR z?_u9A!~E*566ms@EE+BewuBVtsT5gNe52f) zY;g8mjpJR%)bFwsPixIZdEWQ^ACJ_<6<1!Vhg@En;=oi(vSV;l%T&`X5O5-8P9!+z zl%pM6@`|ZBdK+g2D8zt;&4e24M=2I|X?a;o6HThnyBS+!C~{?tqUugXObbi^`C3p0 z@Ia-?0p<}Zk_Rum0EOMhE=sB9PL|4+Ts=)F_6c#&Ogbn$FcRPE#9;TXMnGJ3SJm|X zVObH_JeQIwSb|6LCjgH=f8Hj$UI8ZpQ#l_EG$cwYJ@d(JBK0Txn@TMjuJ{e#u|M}c zzJlShJ9`J>`rm^(tJqV{JJxlO*+p5~gh$oS4O*DHFBluunY5J)`I*2`vs8#`3gY{h6j!m**&^vooK>#>=j4$-fwU1T09P1-?bIbc;wpU%F1LUJR} z(N6kdh}~h42PZ+#zzo&J&&>5mA(=7n`9P&qzxh!}Lz4Z35VL%)(ga7(2i75Jeno55 zY=aWe8CsJ979L{=ixjTd&#!t?;mn;|nRdPdvhh*f_2TMtnPqmK&eN{mg4&A4m8)Xb z^1Y!uPYEsWi?W+JS`m)NnhneA%`(N%F&dQ_J<=f+uw~p)_Ka0?%ECDA+RCPYaW%GL zOBA!&2W>cc6z;E0s`%J+oD3OL3Dq6`Dg-vtH;siU{2LUN?s^X)GbV?63Zqc!F>LvF zZf#8kipohbhmR>bZ&PCDpIAeRF;t(4 zd7AD>`3dNBzg7|lN~Z5_PViLZ@|u>j23t~Cs)2&h_d-`Na$V~X?VPnS_1~9v&dbS+ zQt4@!;u$b{O?d?i2IAXk)|C`N8uk7vTgkWu=JkZ~L{)KSS(->_EJ+!~CbqulQ5c&^ zN$axJC0%XCCOe}4(4;OanuB1!{L9n7yl#{dDgi|9euAMF*LnYoCUtJ_Rih5sS{I4w zGj{`ivd8wI(7spN0Pql{b^ds(>p*WcH*M&2H|sFxq%;LIbl5hg?e&jX2oL1Qy zZY2Ek>W?4;kE5VoxFj+kdQ~ygeDlV9^;#|I@+SZCvJevgQEm-z(@Rlq2>y7F&UON7 zjQ|u^@Nk40a8x4lk7<6nC8yMidPtMhoC{wUK1wDKAYSy`Pc$7t z_X@D_|LjHv>nXn6jlFIRY=-=aJ4R(eeOk*)^rc#lfOjLwOrN8v58al_<806NmC~|& zJQQ~n8#cukB6q&vC&USyoRy9o!%eU-E*t2wIaEY>x{>wyf(LV7Wa~g}AKhx1Rgmjb zbzeW&4_y4@-R1jj3tVEjNtX9z2jY44#-G7&w#06K5D@9z<_SL{C@&cC+~z^nz+Q;2 zNj;025?sEXyFG`{-8_#m$lcD5MFGw1kTw>|9KKY^$U%$|`^ux4A-M{Y*Leb#JkqW) zj<;T`vGR625&Ao5%F#tEa;Ywj2uS4&L3J)1ZVl;QlK077A=6co%}m2Q7v~+UpMfxD z&RRw@0yeXpVpB?3DpkOjWvfqAgWTYuLa_@`!T|=@XzpsjX~b6aE8gX!WxIH6hI9}% zizDbA77pJ!QAIY~k%_u_m4SJ8h^FFaxg?SP7WF|_Toz{Kqh6W=JRD;JYqlA4%K2eB zB>tLTZtc6R_E%W))T~KfW96Uipf_P{iX`BS^+5HVfrH={;E|B`E&de`MoYFa90uDo zn$L6ssP{oiR?dc|Mp<~8`USNFvPpc)f1S{ff1FSyR^_lg>q$>WEYVLMpeA!Mwp5C*spD+ z*%PHVryI|iN3%-OHoV=U1=m`9lA;+4mchoE-Rau0k#+|%G(M(@q10<*)ZI!|Da{dd z6Wk}+73yoeycDx*px!2R%$eg zDwfGr&QAsr7XaM^f?bGQlMcPo4wWzaz$*Sa>QK=l zjKP_(Grn~EZ7~{ysn}YqiuW{C-*q-?U6)^N^TqB%^M#n$EgwiUE530C76)X{yYs0& z0WuqY&@}WVWM*DRIEmFieIApeibBcu=$QTTcoHDc;zQ^dswD3tj4b#-HZ z#Ao{){F3PP=UeTI&&A6JW5(V2S&~Cli#D1f1O;=U9ZQ!&Rq+1JCxqhUzZ|I079v9% zaF^EA@=?qsZg_2vwQxvD2XNHZ)1w-1ybnHHBlh_`dMw4!CVp zFAf`X{Wg<^(NqJ*lmG2=YwvmsI(xI`I}fUAd`$l&p&1KGoTd}2H^X=Svhy-6#7bI6 zalbx{Q#<>1P=Rwf({qC=E9Vo4do==+XFBUv)A*R7p{cCgIUDiNTmji;AL`9|>&^)Gl30ad!A8z?MZ!MA4JomB>BP*xicY0R>4Sy^2)lqxJ5csOfb~~mvCQ2ug z=cDEsi@Feg?fN!8z_2iqvRsL*<`pN6#6#EX>J+((c!Td*eApXC>p?XZ^3zd&gFuQ` zysLB%WuYIW!kwLX{EI$%kJno=37g(LRGk%!fFYmUjIQWw7Dl{P8xi|8KZwJ+-oM3B z2wkZKkZ7d^{n7@%{nIne>qfUJlHy``AsbB9UvBp?CL(k)EatvZ>4*=38AILR&P`}s zfD0)IPjpUTz)TWy>6MYo-M2(>{AVSF3nBswlB$WpA@T}kCL z2u~^A7c~TxL8Vtpt`aQcszJ3mOBaxb=O$f4KIuTqo?oMvf~ZE-a8$%0$qL{w!J`)m z{CFt_Df}ePe(GoJ&tY!KN(NU}14PGnDv1c7Fa%3?*(Jc9zz&d3beffW zM+{M^KPId3Uz4>-0Vq2l%9zkYWTR0=;GTTL7(P@RWGJHzw~2^7XCoaWM;?EW*5^3*Y@ zmI^0bw9FzI0>~>+rqaigL!dZ8f8j|FkU|GA8bT$Yf_#M6$a{dC2Ztq7!o`vX*8y>5 zbv<(ki%monso91ySuh9dT?#*YrA=dzcDQ%Zi^ARrq3IDnD9;orugSIDS&($g$swXVC?96rDiL~xXz({MnW`B6q$&pH!Lrc zlFR@`%YS&(YJv*s0+?^*O{LIRSC;G2u0H|ByRWN(>@d7^7bb+%Sue|q9jEzW@1KQa z%V2YH^Jjprk6jibmVzMeyAeiYm!zm1%a=Zw=(8u$UoJBObr@qkPj!`%Xl4vdyp5=p zxC-U++|-Y%hzP@B%uoamwPRUO+3ERU7cJJVi<67R5Nkmxf659ov!-)KFMlc!gkjgT zWKFfRUVQz{6?%m5T@n&A96YLc;C?TT?-S^uWwJy$%#7K3WY`Ulc%>8z*aZjv-C-R^ z^X0z3C)5;fl$4IX3uA!;dt_3jpgwCMl1Lf6sdLD#<|L3`uMC=p*86{3ul-~ae|F6D z&`xhuP*Vs9b0tSu+QsM>7)2(f?fTqt!Z9{PZ@+7a4SaOP^fpn$$T|1M-$k3wnMf*1_RDXb1ni<87-_8F8 zyf!#szsWQW6-}M+Me5csKUp|(u)M5tKU{py zP`nthGdUjVg`(wFoaUB*TSp<<;)Hn%Uk$T~n2pP?vgTejn$dLTLqNxe59MXHe$FfG z19vI!&1pzc4<`JrEY7p`65i|5sEsBkt0Ng|nVK_4CX z&>E#lXZpLdYjPd%$SK?{_0kf}Ni1i|h4PM{=O_#pPB~F?e~%UtEHbvXq_z*hT&m@o z)W$84U8!2vA0j}#8#hmQnm62ozM&C0O8WX^ARMEBF2asCgI268^`p+!_`{YjRdo&n zQd$1@ir}E^HwW5F`MckhqFSP>(A4AMPwMv8+b5nJ1}-HyL=I)Ilh0ieZj!{U+A=4Bz}B6y3A@85qx zoqTp?W0ObBUyXxB)Z|9LQxwGgz)OassOezr`X0p{d7vFb4lc1zNYG2uy!0Y<-6h|z;^X>Ga zcx|P-?!giHpi?Ntin|t(yY{9^oCPjcqLvLpeWS@}0IdHpVB(Uf2&ZP=T2qTA3-n(Y zDIq4fx42pp$@x-eSJNoa^q}8($h5%AQ6PcFqi=HM$)C3ClnSf- z;)WN|zc0+KlRZvd@@j=S(-?oLlIEMNs$YQUsiZ%7=fJwdJx7YB^#6! zM*=m`4DALPn(#sC6V_J0JV$)iFQlaG(y!-MRJMm0RVhkn**Phl@dc#JD-+=c^f7O; zXbBDKqXbN?j^0uB$qqs{#~jVQR0_)e^V1DN=3sM`Ts(kUpo zfe}2su@+V5&I<6`+PXo8n#TmcO9TW&?=VYg=p3Tg<(ZAC1gAE~vP}A6q+mL*!$D?> z%1)C#7+6D8*+{tGp;g5?nKErn#h|d|fTBU09}HRt3#xv6x89RcZKx>_sG=|l2L)Aj zzo2T%Z3g)-m%P?4b4k%%_4{I8*iGEA+6T{f9XR5mObC;TsN}c>)9BH_{r4eJS4b^bQuFRUwdbma|OkGk$?^oUdGG;9kP#xr)A6GwTN@D11 znu}&AM5C?Pi%>^vF?Cdggu+S@mSC;;knt*tPwz)?(z6zyMgOp*DDQe{wRcPOltF75 z$`G|j*ih$Z`qB>ApWrhk*fAh2@Ag@b)-LVYO z{occPw3JyY|TAsVhUVg*;3A=X~@DI0Oi4#JA1^-+=9du66OM!+=7O>&7X@Z`<* z6gX~S%YxwZSlQ1++%YLUi$lIDiw!rgqY~Q`S6%A`zVKu`H7`^&*q+hjfxmla_73JC zLxzl~It&3;Jh=W~^ZFw2z9GHr(%UrJ1leP;f^Q2s>34n(8gSP}Y6>SG!j1Hbg~xu% zSw>i#2TFUOF8>_{zfp=<5dX^vj1%XVo-i|PG(7r2O7RK^#XCN{n!t+Ban@`vcDiA{ zx7OGtpHpT?KrD$+{S*}M^JvZ8KCnL9-YmuL6ip!?Oy}nVv~b(4S7)KngQwSEPB=&Q zMif&y=*$WS5IQ?QHo&*`oucGr1VxlBIP$hTE*-tffvXLZ49-VszxnUIbd@M}2w8*7 zrn_qEi->X}ptY*LcCKg-t5=bZH*Da=Snb|Qr<5_YPP}|4F0X=95B?bT6Ef(SdJz?B z-ep&@=~dL5#{)?>40CxdPxg($7>XKofMYFYam&0UT(+7{n8!W82Jl*6&nn`$ z_-5$4fX-yp*k75|Uk!MDH}ERwnF9VBEt)e+Eu^V?G9M4$`Mj6sdIr|_Rsf~ za{>-ykza0h;+69ib&H4srQeO$==8@GlFmQxx;*m2WsD>+wv~HFJ%}lFTkImPaF~sF z3+Ig7xLa{@?$7CSEH*eO6mLQJ0_-*(=`9S{VaC~2E(dI@Pg`f}UvVyu{pN>nRJgYK8nKG~@OmAC*J zN5h~a{MgS6Wb2_P{Fy|(ig2~GYdzZE=3@<-=jCy8!nm+PxS<2J&ue-^{5=pCz`b(7 z{0IJrTB>j2iG5T_J%mfI^x{H)-UG1NML7P;ufi%>|BGKG6U^gscaruINenUpOMAVgdOo<)r@kbb4{J>u58X>i_VoLk4PZ zI&8g1V=zCX6wory1}KHiPeA+wKI^$5K*X;*M(wN5Enq^OO^`~8 z3wZ&~gFQK_Z<^&5c|xZ^x6FJ_QuSKvR+zx7^pEyFJenrromK>R>b5BBjE=+WV#6~$dg2s&9vLAQjQK@D;n`t5}or-u|g4si%Zh+EU=i(ApO!z%R5+OOG;NC?`@6V3fibW$5gHse8Oe4R37Y(&>?gj?k z&p(z~iuN*TJ}KQS;`#J{@vp1o9Ivv?{d)nF@dsqz$<`T-&t=lMHHwmqEb5QXoE8tR zcUTeL?|Z5dE6+YA-rqN6w2Jn*CLpkjwA%1g#|8j7h_6oA8_w!kX6#r{FALEu@ZK!uV%)9!2NS>ZB~lcQR7`bw=8 zQlyT5vhcn2M|l1@CpB6A*XFc#B8^-qC+uddemagg64Cyg0vH62@w%zj6Ss-|3QzKg z9KJu#bkATe*3e%s*mZA)gugoHnnyL%gI$ji(sy0qXRRWqV&6+cmfmCgh*!1WCLn4} zz7jn`A{I{P-yG@EVpm2kA3-z)Muo88l{R#LK#J*r6>0-U{|pXASRr;c4NY~S38PpM znXTgtZ2`1vXgZ=)JJ_qrD2T)M{bWBdR3N!P1fm+<>%3McL&JY{D_lJUi20TFiiUkr zGtr!>8+2}*HHX31_DuyQ+n9%Fj5dK@A2F3=j&O-x6C^@w4RO@X>#Iw|+P?8IrNV=VcTmjm_7wGx zDp!-kA`-z{OS$52Kki$p-KoiOp<@;0v1|hfp}C z$8boHwh)9yZN@k|vn-QIPb9LJD2%IPg(3`)$wW;)w)alsX(WpW=|PFzy`(iA8;26L zO41n=l^s@o@ZDiHW6lM3sW2#mH7=lx85aa=VC-J!{RD@*yuOYlh-LBfBopxP9e}Yg zv4fKT$*$)P#%4E2CH&^CSUQ`iV@v6-rd5XdC5cT>epwmba)gM<#qFGer|*{hDVERDj}fJ1oFSkuL{N zuZDd}7C1V125BSwn!6gy?|+{(O+t#_b58GG@>lr`lj*`jVsz7qDXk-Q*;rXfREfhh zd*;FCUBncY0bPrhVywQwi;qM5R{y;zegmy6QcDR`Q7WyTq51rRsKfRHC_u6{8B4_-PH{6`5hV@XMu6&jC?aqsgVGiq%dKyCeuQNv=a6z zxQ8UCYYy?Ja*kHMfbJkYrMu?+dJDK!aYhEsV3A3u$o;15JXbcK9-qSC1rkGV=O1(l zCtYF3D++W`zp=zb{&i8a8~(be1QZgKaq5p+5vEs6$6tHia`Za4bt?xDqqEg@Bfc(t@wy;VX&-3;2F-P zdr9*5Z2(BkQPS71$)iE0Jzsn!nyf5(XXej(TpmtmcR@YFEqqR4%N!nij2F-%1E5I< zz_cV{&->`4j-d0@V~{veMnXRzD#BJ@5<2#2}sJhFx9ZDySMSIzr+--8jY7Jx-5rD`AJy0GYg_yHh-6HC(WkdpIzpo zq4>FaD<$82DqJjIu9(&eix(00I#f&7^BU%gKD^7Etvlu_?*pw9@O!ZLpbUq)Hn?rp zq|dzYxlV5u^BnoD+M&h# zvhT5lg*{+^eo3#4?j_n+OUW(2l5CKUreimckB@){9SKbk^UC=L zsoO$Y)9R=x6k6%F8%OAhb6{<@X*=u+_F=BXh`d9_KPN@fr=Z$}jx8Bj!CTeHl>GyG z!ihn;XJ2U{sN@se&_-#8W%`B^3Im+8I&Dmhf5=he^)D}O|D{R8HIi|xZf@!+S4RaPiYEfb1_K`{eN)&USvY_dL99THdu&Dl7co6JZfddD=Gy%c94X9 zazx`(fn|+S3B+j}3r%6@A_E4`1xx(_z(-d{mC@hbGU+PY4m>cw6*QmiBchGqY6VRs zS7Wx!hZo*on484lDC{5b)WuRsx35?%ucd@ENt(q#merMxEpN&MCjVx6S-aJbKV~s2 zB&?cF4f6_+?vM0!itSvOcr$XY39PZtfnO?DmY*=$UN1Hjs;>)zZocHkrnr{N+duOY z<~K5A_zT30`BmfK1f4#*k+C9#A4>#hReaW&j`L27LDS4y^dq^yB(4X1;BypI|N}Ret8Q z(oF__vJeh|8O)b4uEuLP4|*8P!9i-6!G^nzwdTyozO{5>BdM@M|1)Jw%`>M-J_r_c3r#Pl+|Hv|B3r-tt5*w>yg-trpG2MmzZ^x9TKbdL1XyXP5 z$*2-nd9@4IRxzm}g@FlIBUfg9QSVaAtVdELCh1XFyzA@E!feu#fb(1i8~D~1yh zu$qn%W?Qxu>l2)^sfikfNiIPW9ZY>;byiTUSRA2^UQjs3V(vuRdWfo$I z35cpuieP1vi99&_KXu(zP}^bmCvY5!7cExY-QC^Y9fAcbUZl9YySsaFFTvf47K*!; z5`5G5-JSXG?Ce#po=I|(oacAW`F@riIUFF9^!G{aVbIxB6-5|mEX>QgBbbCszmUvR ziCZv__V{@)t64w3{He?gfsfK>6GE7+nt>up;OI!C)jsE8Tl-2CFNqO4=7}4w!XIrN z^oK+(Cd~jI9g3VOtuXDQDgwbk;a9T0LVEFB^c#*;)FJ&)&WLxy=@nbwN2(Gv-t(R5 z1aH-2`WS|)!KhH>8SBXTO0=3IXgT+3h5i^C1QN18dm12%+GJ;$lLsdsNc+lET$B3Y z2N2D6d@j2fmY$soEQK+5(xsAmTMr%Pu#mn{BOt8SK0$1p>BC7lOe(w~d=zxNMNLS2 zFr57k(O)%4LmT~3?ab1kV4fjz&v*2CExZQL&#ae$Mb~M;D@{LW$X}*n%9?q;T^ieR zFoNd0#hq7;Ix)1*u+A5~a?(R$3pxZFMx_k9k8j&= z7&-5E5tyP9VB$`7IwZ>MxgCMsI?A31nyF@k!R9_EhL`|nCIeS$#5e?)iO4E-@ zak@NIht=`&YG^&MIAJrlx8!kJ%A>l7Al#lZO!S{Q(wv*tzM{P4|4o(RaSi;VN;Q(s z|4Ws2@PVUn!Kq~G)Pc~LxPr(Y0b?^_W5n_Lnp5;`Nk+PSM25dVkOzu81<%?kr!5f& zRqcL*I?40Is7*hE^!vzg=B5X;f8q)C-=fuJ1uBR=!Yy~S(mW459uxR`&C`1ouiY~Rr8xZ(q zqp=22Xj@HZ0WOQOndka(umSxWf}z=}wN)EQpkwV)DSmu+8QMzfUxHSYllfxgzzd)t zf1YtO1UHSJH)$UQb5+{Yb57^;xkH%|SKJN#rbWLpTxRy$8*^wDgLb0rNHd5MVZ^S4 zkw^VRPB?JWw2^rVYdaFO|Zs75Z@N6GC%}jfd7A z$6PzdkC3^$QYjizh4tvw7=~w!EhD%p{eh~i@;my&>cEXDvzO#T?)MMA!MzN>UgwT? z>cbZCX`_`}V=#s^p*s%gyzD_h9D_mb*Vy}k1q}%3*`+1t?Wt51MjshxS?46a7>e!I zvk%!gRFur5E|?HBQxfx$j(Ti1#|>!gMp#T{*6b_COH5KzN$jrO9p3ZR8ls83xlbfL z5kdGN1_(mw4R6RVynIqg{70UCd?5Hoo_<0D^nE5osbM3}q?zEl)pHz3A1I0Dt}t31 z?kF`6H4ox_QV>!N-HJz|pJHb!kQsMiN*UsC^|R+AlvkWt1|RBlW%vpP zcyai*6VNU21jtk-<4kd(#hpz3VEF|(2C>Ry5X}(SEdED$kygG*1mXv`l7%bG8>jS|z zu?GG|cnoJoqO9=`=3GXbuTvM^jg+tB>y2W1ebkza2Q$7=S)2#ViKylLxlf6;b zXk*gNZ{B=oW5?m5xX?VOIC|r;UA#crA4&N@aOxK>I@Q1ZK;Bjxy$KahY6E0*Y!H|> z6M}dN_ZTZH_p_xd0YxR!M~_jSpzek({pmofTKoI0`jCAWvcl3; zBCmtPY#5X09;^a5(Bb~yGgJMv5Bj%lF}WOYa(_b_<9n%4CrX$6+Ix&mlK9E|E$Rdr zR#yZd2&G8K0w4Sm>UM(@JTgpTp)qyQvDp^(7^GWtX3DPJFAVOMWUO5MSj3qKj>X=h zhyTDih?w+9L)0cNA?~l5ANC_4WP(4$t{n7X+BBleD#i*INkq^0Siv9hg#-7`O|`s% zv+)UK7RG=AH>QSJMGB9+ppFj6HgotfFq1A$TY8Zqc{SzOek#THE&6P2CF zfxEL!#0HTia@>vR`4)E59OY{Ai}yQDwxEJ8nW`o$`X8q&QDGTz*jv2&CqAifZ&jgM zS$dOlam=KSK;ppb&YBiEUI$o}jgpODw60ZO#4Y+hNXl(UY36PBXrgj9Jzz1!n}ULg?ev7*8U&cbH9zu zTYtqJu52v6nbWrVD-uosp_GUEh}4PjjlV_dEx?Cd@2vt$Y_|}ZvaA_WSBN$c8wouH_o^JX0atsQkkjRxn+)ojeEP z0!;G}mF3Xf002J?It#1Xg8MwCl`0Xb8Qz=AoCkQPt#1q$1w&-6UmJ}Y+eP5(7d+1; z#TWTWTMm1$IU&V31O6h+x>CEEYjPR5Z`=_p`6w z4{C;OJ!{nW>Pg|4^;x;{mCZle?u@nXG&jEux8|t3MYm~SknAuinQ1t5!0l&#+ngLt zW?n!_qZ8(H;0R;--8-LDVmq8(O!3ek^;BGs%D8P4eP{uiq4-#E5t0ft^%#6c-#(2| zk0`5^f(-R+_3642l%Z0p#3%oGzmPXvIG0tbQMJtdsL5f8jZcHX@`v}ues7kjAiq>T zd*?4S;&dSanTwaL6??a)`BZM8WZgvsZQV0j@PnE{6*NQCS^7U&y?dXIe%hh zLY$Btetodv*io{61s{J;TdFlZe|$oA&yJ34wf=7@v;N%N{M<&zAn6_L>xHIGd3=Vh z1`0C`hu50=vqE+zFU|@wHHOG&F6`Khfm`*hY#K<@w`x{Rn`gZ~E5{*h-mKd-W_bpu*o-wT^@-V+H%xNM3&OYrh|l8 zB7BIK2nhc#~WoH%VMaRBYg2r^{7P<$cuwPnCsQ;K4(B`wf&Zp)$g5a&X|6 zTN{*wc&id7sYbyfS{gH^Q1)|dY@M4T?Sh@U8n=Ez=aY@14P;+%%rS{GidysGPRWup zWW&eK)NAqmOa}Q_+o>O_hEM1G?B_Jif%a_YsSJVPQ7dEz`+zgoD8k5*VA!h58sck; z!P+c^xRyjji$qp#D;_j%{q1JB(nzQb@KUhM0j>)U?w8f z2w3`%n%23DoW>xIF#(_ns}ei&vHNZR4^)GCMyMz=Q51`+pw7h?x1#xp_4^hiT9^B! zI?agA^N`LuA~_HGxlwyzm!1v|f2WFZni#k$Ua#om zB_`;@Rw@J}XNdMdV_b;rCuRrr45_oR@{*NYqXQ?;K~u_nZA ze%GzoxK7OL_+DLI3?I}aXcD*^h6kIeG3|I3h%5g)kN%KEfd^LMGw2#7o~TsI{tJ(` zJP{f%f`f26;k7ZnrtOJ&*~oZ5D4hFZ{YkXpJ?@$SmrN`_8{Vy<%E-i9e57Y0BR8fV z84`JSNTTL8{CKP0v<{%UKpprp7zGeIQN3EjyGZmi0a>jgeYSyC1b3WED_|x+1W6xs z&`#$KAAUSm!xRf4D*a_UuVZz?NJWN+oj4m=fxOh%P-?Vv?{7s$T)O|Q@jS4L1o{Ox z<^vGB?xWq`wLEJ%!gyiL2aPR{W@%`zPx(&~`u+@OKhJ7j4%KtPbJ?;3hhx0$66hyxJOU2Bw}?=U+2K@>~V4? zPSMBkyT1ew-a6x!Ft5a-JwBF&gx)?@BpO}bHwj}xG$*&=2;EUKfhcB`y9FyC+pTo?0!g<5FU-sFvUHZ3~%l3#DH2*A9+x00|w~GFV%RiI0tjvYR zZ~d>`Z&vSA_s_KF&@IEC54^Sv#|t_mN`A}>&Rbm?Ka`&(*}vh|6?t6ZJ{0@1t&scF@c@dF7TZ@af_dGayA%JAmD3b-)cd)zfW@+x7KRV?YRE6{%T`*AaVMiao*G$CSbvx>h(>7UX) z{W|<@{M+c;O8Nyw8@2x5*+mhb_4p06zra4XyWCfNx3Sz}C%1IjDA|!|&-=?tz=6!x z*`>L^3Bx?nMMi*kr_PJbn=(N}Z)>3EntPRrRhKk~3hTMed)v?U^R?GAd;iq?chL(c4pVN$^Nkl)N6w8%u<_}w z^P@E69g1iK&C*xfzh(4qnVwyh3%+t>mojrD0lRcT04XlTVBW|!IJE}O_iyF45qgHk z=z*sWOue4sj#$gnO$qtsLqLE+p-Vn2O6~kANimO7?Su-9EzKiLqC*JkM}*~TV~7%w z2PJY16CU~CO_BtEgMTUjr9x;ae=ZSAN!CB3pb@vsgk{kIs30j%Cdhd?9KOeX;C68G zYi^SL%kG2%)A5%qJUG6OkScbF%&uUV!JouX^h1S(CT>z_|IGUlNzN5!!U!E1p_3Oj9fWTOV@W58vdei zG;5YFUeOe?4)>P;a2K{Ij@icmDsxxYCaOJy;jzxsz~O7$ATuO?q@2PQCsOB^YHUGp zM1Vw;K7~9~b%S^E_JZI!t$hA~@tgAS8HnLjCuG`uPFJda7*Wj&=ya_zRe1%vTkK)+ znX}UvhR8;-z<tI^ALzWU8|@oWPn9v@k(HU&*|wB*v@QbjF@i}; za#a&oPNguoDT4qqdMQ~71xv$4TNP`ygnwl+rY&Q+)_79MZPM*5jjGjt{z?=O%|%En zHH}(1723s$hyTo-%77@Z82xmLCxLU^sohvA+8~lnjK}4j1}8#W0uS#gNd7*5=PFJS~E2St|azMFAa@3 zvHO!U>+YW)JCixb#b~;=#Pf>4+#CD*BjZs~X-4}^H5YZBGTy44TAwXN3(Yl-ZC*Z_ z{t>^%u}K9N*NXmk> zhTYZ$vm4&>n?|lGzM|ucb?@Zml7tkr@2>*+mFL1y)NHa#GYb=`l1KXGuT159X=c{3 zZ)AB$M-bJsQEL{Wddkm<8{-@|a320jB**^Kawl9r?WL^#c;nh+F8=yc<5=w9ea(qS z;W6XgjQC%90QQXfncr|;f1UDoqtCX2Bs#*;M(A)nB|t}kabFHoj}hFR+-xlDVgJ}j zTB>6zM%WYkd7IPV;|A)KgjHj6Uos3mkAN#9=p>O=^?YJY*b2AFf{@+36w^a0FUg_6 zZ@RFIaR3ES^J_m!N28mx!kVy@hhouIv79IcR{Q{6pq%Bd?@7ph%WafFx%?FzsA}6Z{$g131nj2bd5hgQ-{?D*ERn*M)8IL zSV~h3!)?G>y-4g<#t-t!Ng5xm>Riz1?BSSYYOgCFFp9AoEzheh5WFDti9}cNSM#@Y z4HMn_`E0!|2QN#E0DoHYt(=?k;m_muzP0iMbr0>XA84*0I<4q+fed0G)Un)Eks96- z`GRWl77Rq>{lybCA-Y|O1pZFKpE+#Nzk`J}zGzRQ=i$5VdaR(fXa(VLoCiVIrT(yX zn$L&f^U5ZlYCPTpLauJ#Z1>e*A^GG(qo(2&vE4PqbYeCz#uyCL*Wtt8JGo}cfHO%) zaz6Sx_I`xrbgH~bv9zyM4u;$ezcXXJ%+6sWTOeay#E4NQH9k-<*@LjYPLhaHqAuqj zIO*(==`JXT;kqeK*;Ds`l%Ff1SF3gep%IX4rmFUDq5u&yZehWPWKGj+>?R?|t+l^N zpqUWR&ofc51w$=aKWl|pGbVa0t5MB3N{{ZQ+*CioFZP+dn*-bRC#W&A21TPT304wC zJhd?i28(l{EE{1$ZbGo=&-pux?Y}H??|4V=6f3s$qtJ=>*EEfFQ8oz)4$~MY>6k(* z-ilY?b=;PPA7!OFha2(B0?@amGm%Oh_#X2RK{&&Bsbx(E zbu^dPpE$-PwZzyF;U?u%rtYAAWZMRh5^UB7&+D}0{sf*c2nXHnWIuI(eK$CO@ii^c zE`i^*fvKzrURpB4FN}_YfjUX2CY&zV@JAbAW-S=g#mjyoRWZo~KP~0oil)wT`Y9A@ z^?Fv2EbN}oA1-1%U5SuWkI1h}U?*n4!eWzP>WU- zQEc)18TSSz@BdSa-COD3a-W@}c5^*)J<>e}1!DZF;I=k8Op;CTx__{XBar?259;LY z{Lz~(WE5cdgO%tl6dDs%t?{h5ziIaF(>m!o>Bdjv!L2JNoUt3byC!}{>c=aZ2b%l& zWbnwbuODrks8ffzPrxJofoNVXly^7jOCtR##KkijHg20fml%+4KO6t& zzE5oAV$k9CY)UqD0SW8i8TetSL>T>3qqg@t<_&2WsZ2Z87Ty~VK$Ymf3izT!*uEkC z7Ck|T4?oDqZ==4&ci+r+=@-fL-WkeH_(eedmFiWHIQjUW(qti$4&Tq_ZDlUqgC^4j zfQ=Lv|NOrYr|=QxO3!9i=9voCxBsLZO-Ki8Ps1a4-3vdpDWnN$ENPB>hHO0qFYIq1i##ajtFt!=$YoKQ58|eNW)|HEt^6dEkXo{_2~SeD%#R?eoe+rN ze5C%stxSuboL3?++3-aou%vFHSF>G(L}tu~48#KcLerkFI$5Ox+s(jJMK)Xfbg+9n zVwsA=hdW7}0r!40@cY{Qj8^E-%!zKtyzF}dL$PepfQtn{AZViGquweGiiZN|hJGT< zQ(Ld(cSZUXQf3l@H(Vx@mUo2d&*Mk25|S3t7k7u@L_~2)NjX^)8B{ldT2ja;OX3Qp z_iQ!YPBcy@wl)ZUQ2V#Ugh8lvr7+VJBChbvyxA+Gme^!HrhDtkR@B!I;ylQM*qIqi zDwszkZox<*NdD4}RN_Zp$b#U*vQf0Vus)wr`69{khgy+2NYffNbAY7RddVW-BRS{4 z9cZJT1qXa=$>I}S{mNYFF(e?Nhb0MI<@p3PsD|KaSXpUK?F`CCHNy23?5(jk`cSOC zUoPmNt2I1afhx?P!N@5si+#@4Lm9*lBJ-^E`t0s4t^-4XB1L|JF@Swp4uQXwC zl}=VXI4qPyHW3(jC%yPHmwPiJBni4rxJwj`3$ze{rzk#S5NH~*Br;;*M-tzi#U4$- zxN58#vvg~gtPUue{gU`Tq%SF$)Pd1a43?KC8CW!4GOtv46-Qu1;zcw>k49oq7!k!0)P6 zZv~1~7IFy`V}9^B_|@c~n43xJtmJH>#8Cva+`I+yfoL8l2JZd3-}qLcZeMG=&NNJT zM|wn5KRp7UNB2bQm3!U^HMXu}z0<1-6d$l9#%c1z23!`Skhae576@@2j6Lkjg}EFB zcu7;9ZnO5Kth%jqLC;k9X-OJ^V7nLm5baW*W0lV1J$7Q;PtY=kg`S0!=zk_w^PwKZ zn7R;0vvBBB2wd14k%w0tMO_4lu%qRudVA6{;;1o-D8bR9Z){R-Gec&Y zB?PN;002=FwB&qJOWi^|yhR#?a5A|$o{QERX5^^)67Ce_Et_}?p~d8!z_B=RUeSbL zNx=c~g%r*51;t%8x#+oKpNvA9d2#SY{$2yB_X}a{5kktn9X3NaB|;-YqzjCedxWrE z4C;NU$cBO>YIrLAxY^L3lj@RnBZ4v4;1Kr#j2k-kDOM;5SDa!UdvlYOQ&@StF`ee$ z68lm}dL3qFZJyg{tmpl;nTwxiFNL6B>ZNB}N%bi|%2_4Wq=QxL_4;T$)|x5IT-VhS z^)gOyxBe?r5kQFCJx07|7Cqi!9?!U&QkU^*z_#f}JfS!5Wn}hl@rGQU%1->CIzA=3 zN-K7roCb>dkzD;g9Z3ODk{{1Sg|4WyKz$EYBMrn_Sl;~ZOmz+A=!6j$kag{t#_-MZ=cV>s!WsM3Czza7Xk8^qE+pi}R@&!U} z9_gtJ2N|<78}0+ v7l!~hFEbmT02^CnuENs)b->XXU}x?9|39!ccxwwe03|Q2B2_P87W}^ev|o0l diff --git a/third_party/pygments/doc/_themes/pygments14/static/listitem.png b/third_party/pygments/doc/_themes/pygments14/static/listitem.png deleted file mode 100644 index e45715f914df0b9ce5650cd81f826565d794bc6f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 207 zcmeAS@N?(olHy`uVBq!ia0vp^oIuRO!3HEZ#7tid5-9M9ECz~A24Tjhjus6-LG}_) zUsv|KjDqY+yxD&zFaw41JY5_^BrYc>NGv&UGh(5%v^3ic2_Tqf;9+ScrKuZn^uU2H zQyfn*9&-yU`CQ%jRM<_jbEVs=+4%-On`#az=vrO%C^ha<()jUzeq*EHImaYp10cwd vh@M+!5EQwitFh7Z?ulO_J-(9;uViOPP?5c=x_{|>pv?@Pu6{1-oD!M<&SgTz diff --git a/third_party/pygments/doc/_themes/pygments14/static/logo.png b/third_party/pygments/doc/_themes/pygments14/static/logo.png deleted file mode 100644 index 2c1a24dc7dc7e8d989ff3c98eee2c233074e3c0e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 26933 zcmb4L5DQ2> z#H8W}i39izii@0{I|PD;_um&BB;z{~_$88uyplB1DjY6072L^-x=aX!0wOOZuIaP* z*T~x+zwbWK>RSK931vjMsw5WuIbs1XOb!o5jVhObD-I`(NFYUtZ7UiR?zAVBk$X** zOBXICcXFi8*4%J$|JHlMZ9i9TVfSKTZ1rgMXtYC+bF9sB70%~$y*msE>y6O=`^Dzf zOW)UMuRWPbKHvLws9UzAc;Pu7Eopslx>>E97kqdiHA$~D>10L5#I({)t(bdefU$FP zOBX3;j@MeN&`^fMcRk);ZyX(sG-`vlPyA4y;Klp;U&UVtWTMF2PgLNwweyD6ld_tV zyihQjaHsDzBV<_wJAy}&wDa;@4SEFs{McSwk>L0$u2jl`$LXPdG}{(elm@b2y&}mCxdpKKhdA!nU zO0*+wQ_RlAr70*VSoNLDcJgm_%+$JAZ~Wrmy@1%2xO9CC^@tR znx7{9cjfktVTCq=Ej2n9H9D^aQc`Pa>!E~1N6U9zuLV65taruIqDNRn7S%7*M2oWIWH%tD`TO+} zDsi4V#oMM_j0|uy$q`cv_8&i~e&*?;d?#AdA2am+SY)tm@t@(a)opJa>6&Jue!Ig$ zjX^z0^44}jc{%gW-bB8s9w8{0?81Tqhk=oi3NcMRJw20$e@o8&*GEg<7V|&M{F!#T z^GVu{cg}R;3KHXmBB#1!YwbYvtTT>5xo$VHOMB%zbXC_1HTIGBB< z-;HyzQhQ|zGwaY4(02@yUgFUz(%%cc{}tQuTEL^J*L9o4kC>R4$9nYpZ44d#8==zv zosn;8Tie@L8YP;lj45(Z=$%@HHm~1n% zW%75Tk!yAHJlH))&m`HDe-Wc{cS+NGwwmEEQmp2;rn;Xg>O~kn(`s4mOkpQmjfK9D zq$f&#sfEwL@!gr`M2RDbuVMR}hBTR=SFB;H*HOUx_nT6W?sJt!_hb-O!=^5@7^HYc zQzxfY$qMbX03F7Z--Ck(k1fg1DHJ8e7{hPT6wT9jc$!kUWz5SPe)>GNU`*iYVpHhu?#`nC41V3kgTJ4`vD~>+Y zRFPl9gh5YUvCmfW#fMnmgze+KX&jTfZ>4p-4fm6B76@WSJ7J;PpC-Q$GF-^oevEM; zQ7TPt)9n$j9DWxgx8f&RGV0vdSQ10T<1lY>hv&-x<8xULCT4s6MrhUWp@=%Ajt8CP z+CTh0`;DCre!6GO4pSF4wst=EyB0s2x{?|t*`&#@@X;CS2~s&+^_-WK;RU~p6#_TL z*4JE*2jVkgN$e@#1qp=cD2R~!G3PEQxRSM13S^$J(F>OlqeqQ-FFi0hl%^sbxWan# z!MnrD&Shtqcz$6)*u~pBs?s?IyXWh-Z=F9CKK|E0vjjOBRw6Ev|9!l_{WI5xRr^!5 zJP!fCoEBR`L9=|8ybq39I^85@VxpjKF*!FyTs!RFzql}+ODH_#+WWiljXU*D-$wh( zl?LAWvp0<92oaVEfdw8@xLU-%IQ73CidZvm(71Jr6}XvtLh_|$9HN-5h>UBC+tKF2zlj`b59}-yc$&U)9i_~^_q}L z`EMRGWWhx-=`c%;)^R1Uo4>jfrn>%GUrKt2NgZkTM z199CLpx_|wWS?LUVjy+mxd_Vj( z!zhQ8*NGXeN;KfEPRqli?s2xlV1(CUetqZ9AC7SK(t_mDO5=7C3rEKaMtb^>_m@*D zXv@pX1rTg9vRJiznVII{D9qPA0Gw6(URVvCp1Oohk!h?( zH8$WD2a475Yd{10#Gp~Q{yX6<5uXbM#PsT5#tXciQYxDX>-}za(2fRFfgWb4sW~kI zQ%|?Gv&)z(*Q*_7HEJnH9C{qaf%x+71G1G4tf3ks;U1#h#|QStEbnwp!d85kJicR?4g7}3+$Y3|S@jKAN4EPG)}Px2Od$zzG$ zeRYF*hNnKJF z)I`Swc@=etW@4)fV$OR#W{T96rdlA&4skM*CK*x65|?Ck8AQZ3VEK9k(W1Nhk55LOzQ^E(^`Z?7ZZ zKEuk&>ScdlpB@MLdnJaHVok<9S=JaSs$$JjhiY9z2YY)zv)^ARO#}o5cc;@_RKD}Q zJJ}jY;-rW5PET{aWnd^d3Wj^3Nkc5+Jwt7^lNHpKMXfC4+%jEFy&84c|d z=TwnOHZ9?&i$eiDLzp^0vvJ#vc3_~$ds9=2y2i#64$p&Wm!k|DGc&VHaH|5cv`L=W zs1g6bM@UJHz^1Y$qMhsNT3+_Zs@gHt`&+uQpZl9rXVN-ZF; zsJg_X#YoWNb(B${UB>Cb7tDd~?zK0bTYG)Hq7aEiZoCFMce%f$*Q+_Q}+^8Y?y*k50v-MH6+k;`qq z7r|a;vbm}s!L}E~lVGf0velSGKtx>F-r6c3`Td)yRFm;A`D5B9A2I?wpMb#A*70$N z)p(BhzUKg;7=!2C&Nt`8I&nI({#@x#gh6+=w*ehC6I7&}oV7o~!^8EfUdS*Y_Pe@x zcxZyAa`{Fy@L|Cu=#hXb0r~0ai7)WM=ft4V>1b?pl&5mYeR6U&1B}r=di)sUwZMBv z!+;A;D@)6Fg5Jk})l^koBp6dtXVMl$$cJiN+}#bvo85P3SPUA5D~2j0n2veB}Xu4gX5~}UzDtXe=)1QC+`h|)B zFP?c&9UYCr%)(Lx-Y0O$@1$KvcWNEeM_#0)>DiH$rdULLg<8NdavWlnK>v$ge@5|zx!oU1o?&q)4jCwSiV%u<Jcm^@04Xs>~yubJvh4l?As_;c{tU9Cb<=({eKF>{JB5rs@glAP;&eP3iJf^Fw z>ltXEk~4OmnVfx`=r7_nzkL1Lv_6_Ccnt>E;?UF-9Wa z#r?mdW4Go9H7x|#TJ(P0KfP3GefHcIf5hWh5dZ;bK|%4PqIYa(Vq}ysH~*9I-$sWe>(5B3vVAYu!Xbu0=FmF+G+jR}=fw^` zB&)e^@9+taP^;Y;rRB_X^n8G-GQ-&GcrlN>Y;-#X-ACo%y4n)9nHHKwhK2A}#_W}y z-zJ>BPIbYyQ3_N|OHfTGR+UuLf5vA(s~j&^LFC^$Zz3OE{+D&xNw|x?#uGH1D;XuT z$7>O3w!XVdHzRCiVd0^7-71kA4Cs^$fF>lkxaueOoQ}#n*GSh zvyZ^cDLEw%3JO9%K=6PnDYYBx>e5f1eCI06G*6JDPLZQdhvcE7qt`@8n8k@vsA|ue zZSU?b0TP$R=Y4Fb0)k5$=EJ3cfx4+*6AdsC!H(P;9p=hZ@25jU!uod#@VOSXG z=x*Q=I72lAiW;C}?(gqUX;&KFZUVVMc4vFr@ypQmcuImQJ;G1+1*!!46f>eDPx9!# zKj^8J?pK0p63Ekb^=1GXlaq%qF)@E>t&9y0LVvNN z)59zcv|dCE@&L3!Oi67hI!;4D0lB|Exfbv}-@-zT2rVgR{nTd;`E9AEjY?qvCWHZD z06rmMgGr5ryuQ{plQnK&!s|~>%`9M6mXM#c_S0;0Q=>B&S%txCCZVUkfRlt9gyg`8 zN5$cKAY?kw{N#L!a5$|})5XQ7lLo<;7%f~rYy#x|^_-?yHau7mK4{6PXomZm7 z!+T%w^RJZlGj5PsI3I1N7~d^McWWXxQ=L6K$p#6)iQUVhTtuf0ncvYSX~@YTr?Z>E zCnY6u%7{KJ&(87yBr5a((8%f8SvL^r5>isGyg|J?KqMSD<>lpXgVpV%kQqv^TgliV zAt50qc2#98l3_0~0wJp1CGECTw29f-&WYc?`Ke9m;jTOrlaluH3ktGnGp5YxH#!-e z9=D#PVoOZoqe_RNy<%m@!NJi6O*DV=&mY=B3l2OZJZo`rIOS}Sc4q)-S-^VWAz_ec z?h16({FN%v9K@CAVn+wnRiz5u{qW&KAv!6Kq71V9%o7hCUH{|F*=A&PbTkHW$hzpB~1dC@5 zz)QpcPr-^mf6NWrKX_hb3HyzHCVH3m>r?{DQ0sqt-l?Ik{`V3WSCSrokc8W=j-QUs z+CGU^iNo*epiiDUQ3_fjZDCQckj`n1K0GplB=X_X#z9R@4b8~62nJhVHfZ?E46D-! z7>);by6J(kG%|7o?s4KnweExI&FRK%_!ka$b1$!kDFCT#O&uK{1MTb%R2CK%wzFv7 zzLoR`pd<*6tBkqJ;_rO*Gs4T4$^^&=ouoj-fETl}q6PIng!~OmzWsgqa0xShcs0fp zwaUs$@)yOX2N$3L_e7vsyOGh&@{%qtE{b4BOLc;ug+l%}?6Wg7DQH+&I-m_#tNHlw z)i*X?tH{aiv84?WAJt+@e96pY(e3c}wej(}=^|v&r#C58DRmhOAc{YY6cSotyxzUI zw%GkcMnRa2xr+=}v|=AoxS5nk;I9smC2~PGon1MyNJ<`I-VaiVE5}ZhQ-|pPV+TOD2}qlfXna z=*blHCfSQ;m5n8O2a}A#B#4{`3&w-9~89(1-%k} z!_(9FVDiU-{alj5KlkFri=;oBo0%R%BkbtkGc&^qRkDwflCikPBb>IDPdc9inclw5 z|Lhc%=UaF&Rj72Rt--ZC@{M;15edm8KUrIV-qXY5VPS18D1@gepH{D2x7ys<&CRX; ztyF>>0x9XYz*?)3yQ0EFL<9tE&~96NFLt)E$VD#aRA?QXoyi6KZ%*OB+8i8I;t>(e za|;VUewWClm(58{O+9|ErnJNA_m%dtM*?2^!OI>s*}mCC&`u#NtVL&0MI$y&Ep&H#eVKUtd?g z!kDundO4E8ZE$dM(g}gsNvguZ!CB0f>-_``>ssep5G*~;e@jnCL6P&z4QS{ZkkgBc z`@yB9d%6G(bzn_gBcc(0DaA#xKS{{Wer_~mWutrh>Q$NsShp)sLD0#xGS<3`7nD-m zmV?P6JUl#Tp4)&TQKk)D+ah6mlC7&MC@2sS5&3u>FW*Wip(J>YG=aZ8vVZ?Rsc^13 z>F?jaD4^>QECyKOxRdo)-}PH?q>Ec#SH|Q3YeqzbiK%RvVqkGm;15{!%y#Fs4#sRt z0Oz@=sS(1zTXRu-;=V+I8yOJ?8GyehmuFT(7q+~f=7RoepP?owc%+p_d z3~R<4w4Eds9;ql2ByMC53m=s-mXS2o57G>C7RdaE{+E+$qv(^(gWuTPY+H&3eo0{G zKq-!s_R1KCl=x66{l}K!YfTx$ag@^W^oKH~vR>Sm5z@SiD=~XFO43fxf5PMLN^#vQnGSAbL&raGD;!xaXa^BeB*FUq$OIGzux85Z?-YYM!fd3iy?Rco$I3%OcQ zKM77%^(JbNCU;A*$>Oee_5X8eviUi{f8ZGrFGdtVF?AGUKZ*6AA z^9<+*Dq63qElo{NNq@4F))l@T@lW1{JQZcusv966A>BttM2NGQQn?>Ym(VdC+VDCq zT8z0G^5=Jyl$5vuaSLx}EZf9d+^&vg8>WyZ!UslgtQRKUPxjxxe`6ydA~xUN-Tj(z z^}qtv9|jP7xw}oEiwk>;_er3AUkrf?E*_q+haj7zq$JR?l%^A9jdErv6qS^&U%h(e zJxTL%et!NP1XJ^jIT6fe--ag&^YyL}_sq;pf~%4?T3Xt308<}a?=JTt6*AJu-P=QH zod`dQSm!u6IsNw5*Ik-LlBxkQaRpT96VPkUK(ne8co93h7I6Lg+Jwch_)JoyWGD#8 zBw_XTbAK+zL_0CMNFarZ>7f~mo9+_@sA-vOuf;K!?b0VW*s~Ny?KKbfcC*y+W>#`8 z()~zQkdh-ZYvCoRj|qh{gHE^wFX9hN;2JcCuZBm1^4(!P`C z$RYYEv;Tg*K14#5{=fv*>vzH%e}Xp&aHnv=XWWkA*lRsKJx}22D&eC>cn1as>Pe2% z(JLqnWfv)?*O&q*GBX?Hb+njiNmMA;sMgop>%mG-Z=?SzRKR@)9rVi&Vq-x|l}4?7 zTAp=radD5^Zq2Ik1%Wi-$wHsR02L!UTwhmJ{${Q>t5~Ax<#TgtW~8LLH&?aRcb6== zG||%1qWzT`C}LE3`T2NR+x+cqZBH|7Ou^kLk39VR#6W5FNEootZn^3k7}!?>4s*jC z@9Qb>;NQ8dcM*WLxqV<_WmU)on=XhWIgB=L|4?#}#L^2WELg#2DmJ#0;^VW22Y)Fk zsmmZe1WRjcS*B(nF#Pgg__}wQOcO-1kGoJx3t3EzKq5M>r=^t>q>URPM zp~fAsUD*Uo+ywxR9nYE^UA;`d+3VwtjqbfDduwa!&bo+cus3Q=sBu&L=m1_}0XTnU zwZ9)pT%4`4)0Z}J(8PrdqS|)t#J0bC{{-Xky{HNQ09y%_v7ZdruoG1I4i zQ*FN!6Qllw_p&(?;u|~Ky+8Ui-*i@0A6vIE@#f8&*2jm3VL*8sru$-nZdMMv3qeya zxeNmcKwz5d4h;n*q^gQ-1?XgdLPJB(dE7$QyLi|9-%edC*~lI-rj#1+x6%zU%EXbS zUkMRfGcz!tq{&g=EhVGW%2~ernukEx;@?W~FC=SNYp-)=k&IK<5V;J^?{{T?85i z1_oYvdHEmD_!3RV+A^K0)%oi8vKMEYCWa;#iqw{O8lw1>&0OU!+kL7TCc{EB#W717 zQ*U$x)Kc68Lh$gVV1*Ly?_wi)NGGMm>H^Ax*5px-vo&A^NME5pr$nm|ox&90n zj`rbSB`7qbNK~{84BA!@k5GlufZ@0Opaay0TY%f+v!Ya4SXj21ht%6~JOe(irwb~- zfB$|jt`d%djg2iGJMY7rxylhK6^NX?eD%zQ>;Ry&9NAHAc(}Njd&UM8+HXPkSFVf# zHm|7rV#D6v9_RBFDg?A|(S!TP0(AxqEG#UOYV*DlVZVRqv(*wpjrSrN>r&m5Q;%qA zStyZ-Z+!%Us&-yVc#4cquAvzYN1y3ruJMxW2Vg=RQm^}#f+LkpUO-6ZRSdjO)Sll) zM5N&sw_sC@+bGgcrRLBXJ&qwj%*2vQHO-8>&qxOt)_6VL3@=YbKX7qFI(O4e8(7CP zd=(WH8@9H#&?n-0`QzUD`ud_lrul-bAMdU@fcnoW%LhdD=YM+>o0?kB&E6-gF7^5t z6}6e0d|VFmr_I7Ty1Kfw!J3e`mQ3kPnL_k1FanRp^a%kkSz&in(#!gUCZ7FJ8rIzG z%eyjA3LgRiW=a67aEm76$ao>FG`@}7_VclbJwFErN5QkF$yMJg69>I!x9v2bggJWB zZsVpvBY-sW1^_VOR2Bnm;AcIK00KVuuuDzzy79fsS>-pRT+IWI1pU0pBZ>N5n+V}t z1kDlgJzK=EYDZb(&zB-Pb@w8%G9NY_e~x_gvf1}!e#hh5AglfFA1R|{3#@@<51M!Y z)wG_$eY~*K!cxlP=mB`T4A*Vge`Fs^^?(*y^$GX16<SNJ$+&S zV5W@qzt)(7`2-YCPVeJo;=DE22Ac_UHP7oQ8g3R!YC1Y+r1)2nZEfe!Ttn7IWMt%z zMl}`#oF)b^b#dAxE%uG}im&|cR;{4XegU5oi)jj~uA%W6eCeTqsN7f{Fv;3Rk-;{8_lo-u^IDQ?1k4PT#8 z@%@WObhKT$$X!35SOxrh=j2~}U+Y+&E>N!vE1LAleVUOd-!dUbzEr{^;a)y+a+v2R ziuL(urS$t;N^@el=s6VS%UAYpws&TODiH8$yCSKqs_G;jNO={KJRf6Y>qI>dG$TB) zu20rvfipG^JSxZL=4~CD9}Nv6{O^CE_XWe%kNHS2M5Lv?8l!fG*f5;;nx9oPp54|j zsDZA{?)7(`8-SQqfD4vJhKKPNyTxfJ0679R{0OvwDrS?82M0O1-%(?k1<4yQ^bA3o zc@u(fo*xN^uDGZ@2^JIeqlyQ!-;?TFD16}Ysu8)D&Kv18IcE`jVPJ1!VTIWJyV%IE z)~azaJ^dg3TgoG}x1P&lDZhtx?~S16%Q-Ju?bjH6SDRd4gnxM`RQmR2f^%vfh~Wbo zYu$%OM;OqO5is0EX0IAu$fB@BZcHr$UTT1w^Y05BSm!%#b|xew?46vf*##`TX4Pup z?(U9CK!D^k2{-EV-CFDT0c$sR4*bu#BOhEBr475?fygv!64SuHHjRt-4C?4j_(THOI87cg~1an5_qFf~X2t)grffA>;kQhO8p z0jDs^P(H}ks&G^i)Y5JYRWf-nl10lf37bOrXznaNPk_dkyQ5~^Ov;_h_RZO^p-C{- zU$GieG=kePrpCnpGA*+z3Cz;YuBCf!uCe+lrU)>0^5WLvF#QS{p!Jda`S?)J)~T0S zHNyw!Uew?9iHrLD?CPR$pU9IA1g75Lt|wNAm?{-M>X^OYY>U;D&s0v*;TJSa%+z=w z#0dvq0o-$y0EImPVeJj`(B0PVu8!{5r%gT{;PH8H^h8Jlr-|E+ekL)Q`No7O?jU#> zWhuK0lv1b z3oLUMNsGXaWOoR)D)7}+&S&>ctHyveLOm}KfPrtiUh!TN)~3f-s{2gK%{_Ct+U|#8 z(BMFv|9Av6K`CH}f6H4cM#sR&Ri*cbOgAMrm6b6$t+Z&xtqTbW`NKW@o;!H;0*o}9 zSG?2z>?0x~u9XxO|CsbXu6l(|MjiLw0aCXHIXwdx?gMIND*Dd{GE&k*(D92qO&L&8 zQ41^d>j&L{`t`ol03N3Ap1o0w`Q;9gB`rIa2rH%1xuixc`k=!-7>a0i|8juPK*TY( z?M?oUiR01Po*M6D(^<;D!a^gJeKr%F?m8VrSK$?UXpD1we2mQ-IR@?z-?rv!EQgd@ zyxik9U4TF0_D=+e{NJ*(*Pzb$0WZbG9gin~A!pNGCoLx@hkaUq(-wo`Qh*U zyFrDW&Y!0nKexd~EZOXje|7*X)7#f)30w!pXw=+922{i9VXI2{#09sd21m=!)FL8J zuVCsW+1}32z|J<#w-o?;EBs3t5aYIw6TW@3S65YCAD!EJ^&&#zEdH3@hyq(z9eQh% zqJ#XORc&T%y=(dYy+--<@jNK)_$p5M^vavBTmD2h-xvh~(5LN^P=qePsxwl><;`A9k-rC76HDdr0b3aVRZQKF^bgMyv|>QTOqFYZ^Am!Esam(AF1 zG&n9XA0~dRWwhZE5ByT}0@!YTEo<9u{J6Nd%RU2b0u{vH=gaH#IP23jOWrrKO}0 z5)%{Sfb9xfMSf(;@zBG0Q<~3vwEr37! zddD1}i{4hcV|Wg8NBx*qZf-Y*kw9VBC`bSUdm5deO5Gdtk6JS`r# z*$P^#p{6Pf7|~B^u^WlW#rCwVTfY0-77yui*tY557MAtlZVfAFISnV8xEXG1dO(pfx-_)su1amp>v@D;PghzFWc500O4Ow>2-4I@e zuK#U7+-DHY30eBr*_&91Wi@0iSFd&Tpc1*n<<_y5{KXkm0egG?P*ICbvDb;~rk z(L6K#@zX#t47D1`SeY{t3B?Wtl%NDeuQr0 zccx6|L>UTQEK~R(G&mH4ow!hEI|aMTbOp-v1>j{Xg06phgBN!`UtC`Hf_wA>lJb+f zjLa{uW<$(+{m(ZyH*6A;lJ`P~d2wu{fd4I)byn)j$jCIl7WCqRgKC6mAwf&(kAvLZ z-9^D9Z1>#yoj|;}nZ{;P`Hw_061{sMiSAw~@Zn|`T288QD5V~1HA?mlXHGq-)Lf&? zNcw2G1E;}d!(bdu!fx5;tHC`Lr{x5;@7ZJOSfKRI=n}Ok(9-?PtD7dbjZr9jK~gq7 zkqlP?ACQ7$YYDSv8!!44=me07cB}O356mPaLgzrdp@IRn{r5G>%%kxvfe*qW=U_PsQn~EWeo0;W4mS_~kIV?Aw{d;=6Uo&X& zD3Jyk%jm3s7FV0`qWZv4+swou
      iqU(V_fBwX^d}2|D=Bk$roABOZOF$hQ9i8_E zrD5vP`FVM))n!@{2yc=C-S+zTcOhjcl|?}W z=v;NDr>Bt$sm$*>ea`awz>2asEjO9D?u}D^5`DV)$x1=dLOxjwi6)*EcuaJ;07Ab6Rb?g^5wn&$<5U>*EIfUG4VvmO=F4RPx~A z_JR{MT{$(i1XGYNe8Z7G%>4H4&&16p4wiUzC=D)(T8XAK(3(Cvqo{y`Bp8qgFkn{5 zL86s{iD}5N^L+r2678d<+~i^EeH8|cl@{QEosm>euCJRqrz;i$pUi^|gx)+x=ruH^ zGGDwzpMMk>?4O);Q?|0&v5ngtd@0!1*Ov+)?2Q67?skc0=`y%?nbGh3wQB&z$$<(f z(N;KGX}x9xzN6K^z(DO45(FUaI9prWGH`kAl;q^zERleWiLC#E?+AC~> z@!vxac76>ABtfn&23!4- zdF~%@@j+08-D>#jK8Q{% zWm=ZJqnX)+dWE*aZK^6iXqS^2-1a->Ae@<_!WE8fqv-7fkf##l5^g*VdysI3$NCa>LNjaFkj1hpB@jZe9oTG%NtDt5J1rt)R&Q_m*38x_*V%=lJ*&KQJG% z>k(ix>cDUo2bmQ9A`pM&l%`6MFe!wnYHA|X>mPw+%HDq(nLfZ?`i6#oOI7L1JugfT zo~q=NXzzh&w=;(ytA1;-y1h9YBfz7NK{)e8-Ls=)a!nP6dXCq)YvuXqg#@vN<;deA2K*LA9UTSXMYK0feDR|lx2-{;0gfSGob>k)$i@?%ckoyRH0@L4iCd683^!jm-5EUgrcu%3qa21 zaImC-=}I|EC>@i8tJoBr0;&M1;}$40VZKN=ZL+!x84{@0ATUailt4rRi88#5!8yC~ zmtmUQ96$w3+H0L4K&yYag&d9z>+B3t(b1V>k;uiaON9PrM+Z&XSX>vJd=Lko2d(mV zqP?S|$GFVQ70kz(7<;r7C?dE7Fg`wKg0nwAK(HzyqYyg(dbo9Jy&IGmH$V;bE zZ6>iB1;ULqvze^Ip+BN)=jle7{j)slOJP;8!qk$Yp;S_co#la*3(dIR^N&Rx)frlR ze(M&Vjzt=lRo)Z5AwYmyA=SF&M>e(~H&R2ZlI8!Xm0}HuA~qr6EE^?d?(&uqhz*wG zyp{PrJreW8e6t>gW#i_?A@X=Rg$F`|^^QR3@8IU)88su4smyLS==@0$o=ikaN(T~c z`6t8aoPwYUvgL|U14A>+51jaFt&jHXGkr7kMkxi9+sP}`oCHb)pOrLKs~P^r8Vj{Spq2xJ67 zsP?`9K%jt*=coHP;3o;GFWsjmC$}--qYe$O0Ob91O!5stgzc7QW|VKkLA3S1oAfwd z_B}gVs&5SZ&gU8$c)Oj}0b0wknWd!`vRL738*B+v8=H?{0_x}+vn1&1>#t^UT8|Qe z`~Vg>9>YYHAO{X^=~yL1W{9Dc~z0ePvvp&63pnL$PSXW6d@#xO}B zgIc-`&8$5I5bDUI9VwQiEthh@+7dOwCFF!?4;N!^kttD+a49tk6{~sJ*_))18HRXmY;Ao#o*r&r*!vi70J9Vcgwei% zgB5G(LcZrmcg))r@x#N4Vc;+$W*QVGVPLSt4pOhJ0JZi3qInoF0?ah?!DNP;!>Z2J z_)nkQxw*MVz6*FBOn_;e2*CAROR4=s=;CgpUYk#KCJbiT|Me@;=+cs(BCu2RG{Zwe z#PvZBE0FW0Wn?*mD+@E0(V^bC%*!!$oo(83@^Li#l$!wNXNSGq<+6<9}pA0BS1 z`v4m7<3xWy4s`G#@MeLAb5|qaJU|p!UHhS>Ucgy2piop<2AHz4^4zbu*Q8n+?f)^J z7LR>+h@6s==TftK(Pt3Cwlgz3!-S~R>nm~V(*Vm$hd46&9WQS@091cpOUMNpWp^&p zO}`Y{8o6_qJrt%ZX&u$m}ngv>58N6W_4rHAOH0^Y#& z^!hIpd3&p}^ubXMoJ@KyWff(z(=E;CTJPrSaxTAlB;<_#vOVY>GUIr+LW78`>b7OF zRDQfhOIY#TFS488_pns)k|Dk&VKN~8t?z!2$8;r)R*)$Ei?>r9yoMR!%{UUP(9p>Y zR^Z7*x{>V`*dKrivIMsd!^RJ`BlWc01sErUP9=+e+s(Im6A+I!;>`Y_m{-!O+=pbdOx*%0wb7psDg29V;RU@%xHPaCZGI+}O6U z%)F^z&9@sy!cDJvVRWxY@9<-|Li*B0LN05IIPYc^!C|p(|9Nt9a`5{SS%3G!!tEJw zcJhs9IFJxiDo4J4|1M-Oht*xfOcO3eLq~Uk5!Fu`{b2--MYrWSKTj0%1g`&GioM#5 zt?qU=PhC{szbXMV5&^>TDY?-$?f6#iBVceb#eVrl)%MWbV{K4nL z4*4BA)|tYVN8RbsPE`**$iSVr>CjIY57}!gICxMh{=*0N;>8r}&}))RqHpKLq$W#n zQnIqnvo!P&aKK8`31nXHeOdd&7zm8oeBRLj^~_RAs+SG;qiun}5oqvikK^ff1Wrgk za6h=iztlwbx{`qvBtJvw3!`HY-Wpj!OZ%VV1I|NBMGgG+{DMOk;?oU{l~}} zi!jR2Z_GtgXKTdpdbS-odjCErS-?X2`jbYARDH4S?RCbe8tT`Dk>x*tTzd`XJAsnA zp4C1dA6Hd{rgwF9)q=?6_I!rfS9oxoFTLx+^9j&icNcZ_#0W3U7)9EP|5{Sz@mgmm z-RZQy4xYci|9@FPYA&wJ21Q!V$=7Kg`^-UZ#DZ$=^VzyQ6w9hJ?gfMh{e;ZC!&BSO zoZdr^XUjnp`)v05J}{Y&+RM zKF-R?4iKx*{sf}C-sk<~LFimuT;;CkBVfv9yhK1?#zaSt9UdL6{8Bdd^XGewpOF~O z!ts{-;2f{knc@&9ekC8mre0WrU_g8QpPolPR_=aeMa#7EfwH`$R2gc>()?}EEFGwe zCI_}yYpkG6lTc>AGReTfQ2ctTT+|Xx<%^WSqF~t2qEcal2CW5+Vo3eaVq+nP^HKu_ zV2tlt!A!CSd|VM6&?tk#GLqBN<@w^uunUjY*MDr6RdswYbG`ZWiY*I-Q(FsbF5iV? z*XuH;Ha9oZD8MEufImIRjt(@jXHGn3R8z*A6oy|-~+BBrXEO&UGN1x`9IYv ze&6oi{7hTomf!nTv-Z21f^!)j=Zd|Ga*9V^vN{zZ?!fqHXGX3#1+Y>Wm_a>73n$Y^iU>Nh*hr>1qlTY1&4mJa#@ zO?*c-{tX5gY1`_r_lq(SQ)>U01#rks?g4>^fqSrFl>s!J1)@ZjpB_9s{QAjByh-4# zrK_6SMB5;4n%%`Yj>O>kt*xlN29efFLBZDFV4|h9#A@E)h6@p!to1CM zS%6`L8yQe1XFMLrtL8wqRd0skL?+J^ywe{A;P}Y{o@L6(m=sLlAoOxiUO7}JC-j2^ zYI(fo6!kad_nBrR_>tQAOM?I1=3UN}fxIfj)Ydk=!kJ`hMjM2DGyrW8`Nr>FxCX$Z z392~gtoZ=k^@E_Rg}J5W)h8*cXh2dew@aDdw(z`Y)JC(=;{oRK!*6hKYB3fdxFnEh zc7gbW{^_tP--4e(3zcySCt3+F?Ikt0@c~}B@g@-gFR-@0>fT7ZYDLxAXbq&y?{f4&PPQXD6 zw~VZk5{B}MiWw-(%?}`OFW@6w|H2Y|P?ZA*muNN^{`*%5Gr`0EG`veS++@OLr!jP9 zwGO}QlyvcU%)fVke3pR^<`8<>Lx^F*B>w8x=dkJ}ZG2kAGnN6&#bMVzPpaaR1e*BBITc`?UG3E`0hrDmB_(C)CR84I^W#!UWpK*<# zDe@{tT{R(uci4!x-P-2%>?p51r!h4Lgt>-9yg^iKajhc`0Wp}a__@hxf42ISmbdQ% z61C;U3FDT39kzB58wtbyZf$E`d}&Q|$Bd0;xR~p0N5E)~ZvstG4;duKM)Efk+j`rn z3?%rW`1zKgi0wHl2sdF;=Kd~sGqOJgdZ#l&)rDpZ58+Kc8yiynuO|Gw`dB(JxK@QOfP zaQtW-Vp09>-8&0#Ff$Jr`B|zZnzSho)PKXUM38@g*l?5M5>M>w`-e&7Qq9r^plu#~ z0OFcGuq89$if^qR58jH3KD)WPzEf35`w1AxI4Gx@fPfrLMrYvKRYMwPcdo&|D(LU| z`G0L)cQ}^s+rN>m%urTJlB`6i?3rYR%#4)mC?(=iM3NOHB;;#l6`5s3kx`PAk(Cfa zDSQ1s&-?e=anv8J=N{K}o#**kPs7nNm#)dfK|0mmF(@NnU0w9-?T4e$Gzj$IbhtoV zr&-<9jr&x;`@*(4F1H&NbzB)IIU@(P->8{9md^FN`KdpTzcJCNjGrrIb<~@dcsIE` zdSJh`Zm!7Y;|zh*-nCj=b-C`R>>|HVc4@*p*-An8}`eSTwKnK4;1otx>|36Eh-TFE=sy-0t;F zZ@x{^t;w+)rlA!T6`XMCTVkGD6|>xGmEaHGWx@VzLnjqsFtN1{ni?Cw^j&F_x_iU2 zAXGO~y3nA1Frm`1L#Q6lLnr^Z|9kk%N>W&`Wm z1i7n`iSxOpMe&BF%TB8M&pAGC_;9Huers3a!i&|GHRE&s40KGEjodw?E(*e}dgM%H z^ZR(?PYTEM%Kx-_Pj z58=mqSf-BtHaSIFgB#f#%Qpn)$d%k8tvTDYii)K`v<8b%QqL*7_lcU0!0NKvIyz@1 zIYk~!-^`7+(();IJ5D^aZ$OxfkyMgAVWH^MF!}KbmD`^2O;&Z*+#=!3{?1ow2bPCh zEp8py@M9(z9=KiG8`6?=nVq9)+hE4M8B!SGc5;hpim)a@7uleV<-CjE>z+9`t`x(W%5fjDt{e`uYMz@ZMzpE+oBf(2r1b%Vqg9mk zy=i%+w~hl#n`M8RB55<@_XqwPQ1F>~9qp2#YMOW4E9hN5=|$pHDj!kzY3iG60>AE* z_63N>zYMOlmHoi|~s7`EYdhSQ1`M4Tja+sg=!@ZzZBK z?!6`lNgHc6Fu_GCKp9(k37$A1AEe^k%KC7CPVlMAMWscWu4cPKIJ|gi z@9TD5fu|rkNzQZNp8dnl`?m>*@K_<}Ug!on79JDBGWGA@Wmm$^;)^$$)U7CBjLNIO z4&{1~tuM~kF_L-!gstAXQCoc=+I6yf!^yjZrI?kDJ|yU7kO*hQ_bGL1RSK>bBFfh} z%eAe1eQfVI9QdM3oth(3SXyvr_ian-+$U+Qj+e5J$uY3?2!<-sJJ!}J>$+)J_v+dP zykGqLCpfjT^6G~ag{w7}09LAJvXN1H;k|qLsEJA?yNsM1x?_rp=`}Tv*?4$P)WRp9 zRa`8c2@$1bUKjt5i}It;A4spOL#@3Pdajbk(B@36%ul()x^rrBYKjUb;?VZ-O%ro- zUlyVldbM5B(sP*}Ws)^Zl+Yc$hg)CH#KhzR_FweW{mCdKhl0jsN_aa{~SH z;rQt{;q1S{m<1e;q-=x17hKu&12Imt4UDe&xw#ZpR#xxY+8pn^b>%%@Njoe=@BmMe`-NMJsO$V?@h6h|!JVeLwIHR*y&?9c|Y>F1>>zw%a3^@x) zP*Tc5{r5C2EzRe1j?vC_{~eS~UiE-e!de}Rr4sc*p>cYKkJGN!R|bOjWC8+uj0Weu z?d;OSCK!4;Q$7Flnq5V|P*tk^3jRXyYwYE1O&OSMLB!zUw$}E!Vxl>K;>2=wqTHUR8PM!Yn zB7pnQpx8ufH7O^eRe|;*ueQx1pX8KDbhT~5!!sPCVN?|FmfhEHAFni1d_*?sP}=EkPNo^#mK-gGbHcPKJq86q=X%YBV}|I;p?ca*=?{6 za}q(>+53j%^#>tRrHE^W=juK6wlJ#9%*>BHJ(VH4nF9t8vK^L{6^EpUCWHkkIO1{3#yA%{e?zXN!^QHuRp z^Z?f(C@#JgMC%Payz0vn_w0aoj}vKop^WdiAae%brIwRZHf^FF4NWk`>7p~#(uurg zCMNM=BTJ4UhT6;yL9j-D13un?+f)%^6O@zVG8Z#@gPHz2xY&)#nhyg~E}uoR$<89L zOP5x+5CdE3=_z=dnjx7vkk&cD4|x)%D0*;ZX~wx@XSuJO6k-$ix_Hrd=Gc8KC0VFc zwc(krgYoW8LXVO( z1NVLnTeY2&;g;RGbJVDR!Eg}J!F;ePAGNtv@H0J;*5#rIV}NHAufm*RVBiKzqTXR% z!7VssvWVa5vH$ti{R@7cCRV{1Z#3)Z;+ncveXcjjwYPWQ@9(^fzrCNR5f!i4IV?26 z!ET&rtDKw8{SsZXW#Ps{C4btJQ~P%nXW#ff?EhaO+lS-UeZSUwh1VFxMJersrb@-e zTc^&+8mW+4=YG$RMUj1#?RcAeK|VTyw&@{=EtK}EpkL&m9@-qAm{^t(G8f^vsh0js zLQIU;U>D0%DoRSxO6x*sVP;=KKNO}QFaKZV%a?;g7v&Sspsl~y26wf+6t^aT0G_PD zq>B@u_J%>_ZT6z9Y(VBARUH;%NnT!FzqO4GBY57CY%@6~ z5;zTn*y!=_-}@dLs0K}?7@!YFX$-2!AX~&+|Mo`;r&u^RgeD43UJnQuhAes(Mpex} z%WI!-28Yw7>k>h@wZ}z;g$o8JPxceU0R+S?wv5ijV!DZ<36k{R(JcptHcV#cbkod& z7AiuUqcp8P#GJs;S91mSNl4&TSFMm~(J3JN&2xYLSbXZ~v3Pj@ekoVOvtyuHW-F~{ zqH)QcFY`WGSz7)A%WxI$#&h(93OKVKkeEVPV*;aNV_9$_j+~d7G zH~J47)|7$>1k+vtK4ck}XnW=A)pkFN3VAiUme$rAZygl$lVqCDgCm+>aRtj?+SS$N zh1&ZS{+cJus*Y#5Y2>3akgohE0(P(GrB z-ogCxr%xFk>Se70DWh3M&G?+q)YO#l_4DWJWPbiAS<12~DQI>VK`2op=U0lc+u}n* zX_%E#NutnIo7)D$@Ou|eQGcM8L|TKOb*;L(y3|ijF4R5-KI)P2aXDwOqy`Ni;dL_k zh)q-sR)a*;kp*^ITpS$lAot@uF2puNPC0o97dsY%Clzshb-Mh-)4V(<#w|DRK-F_( zqPCXoC#?Xh_Z>&xC{>*lLFAfDA}3}T>uB@y1sQ2@ChuV{jr#O*?|kuk=GXuHZc0z` z84j{j2oIf+qu=RnVAnaNnio89$atveS-6d4}Rx?g2ERn zOFm}i=oG*R*H(PkQA!%WewEWOFvR~@cfO=g>n``On}fp>5V)&mo{_L$Y@W#Ir~{A{ zeU-gzF=>&7~^Z!ju4+I4f zBK!CM@tgY*o~p8|J8NGK8d(*(E(qW2n(FJHAV4!(84{q|kKJVfW(-5h$qaQ91!33z zSh3DdN=b-?E~%xZ#kp2%Fz(*HZs|m^?zXmkA*}f&bVmdMXA$+Kv9`qe@xKOBmyZm> zi2QP1h=M=5{2G>fVyJ82fzySLKA*gqzH+<|4Wit4`GJs;iZQfV{Zo^ZRW`Mpy&WCT zqwtzh1us8)oQ9%r2YJ&8d0zc86VU)UadGz;`)Wt&9l%5z^&THn5S5fBXmI^o+k9YtzBE%C&F0bjCY!X2|Tb|?0H`XpVF znfdm0SC=U-KmSHKsO;M>NqLa6d%+=m^Y3_jSZGK{9jM22|Hkr8>}x!XL$H^ z%lw0V5pP>0BqdMdFZ=qM&~3SSh#11i9%%khP)oLN*+lTKuE zJG^?0dRD34rZ&9u{d;$q{Ui__p_IK!K2>qYE-28Vcvj`ZX%GeZ6@YbE@O$<|aBgm{ zuDN;t0YO3gGIKF~!MJ9IbVJ{3=t(9Jh;Y>2(^K-ep5B(~K5;3jizh*nU)~*C!A=On zZm`3B;8l-Vu1T+@r6t3j-Me@C)%X`l_?+r=8d%@{fS=s#A`5{xE+$3_6|#G{pV3S{ ziXF~EMKzs%cP}+4K9T^3{y^0{O1?cD*F%WVYi(-UcUnO2_mO}FtI;bLFE0H8$zFix zFp&HfZS2CHaE+T|W9MIG@11{ggfvZamLRa?WKry;V00AlJ9A+FehPp8)nt%GhNn(t zOeq)*UG$Tyq2E&P+H7QP&0Aocn^syXYlp5vIFwzUx5)=G2lW@0;>d$_G%pGcrdl{0 ziMJgm#pyJX?*5vSe&5lKvgP%ho%8Q$ZziytNSeiO6zS7eJy4+EsF0QYL)f_x= z^5iI$N(zjGXR>q9@=tv~6Qw&Y) zu!e5jSFYnxo!2+MhG%BC)V#|2Y`%_HWf_W?APp`L&HdNvVDs|d)hVHC!dOKn{r}CK zYIg-T9x&Foq`2P61Ls{7%T0vAq;mtST^83BVv{;}(7C+4+;i&qO|5$?d{TWSl)cKU zJ9F&WL!0G<28|y{zEBt1{c59wzjjT3&tzXU;rmswuCze1H2#d1`IgGP*4M*;E(C~@?|V8Hr7i)S$VLft?gGc@Jr3wMUK7!m2|_M1Ti@|>9eo7bva_=rK(Xy4>d4yfM}Sk5E3G#)vGJB6z|au0D0UR6Yfm3zxaD8~`N=Bi znPK^;B3npbO^~l!djaJfP>gngQY*X}AG#XJ!aICU$;1&6^P*n$f*M8T%`dS>T@EKUjJTc`ny z+Wh!P6Z1wFen$zSsd<>+qL*#?_H4w*xAe*jypvd9yE2!s{_f1|nGmOVep28M5``D5 z`?Ua91;arKjUTVfA0@=IN^u(In@MIfl;u+g)e50sBa2!nI*pg|gDoNol{N z4e0fa-*Bmu-Mp5VSM*i-X6{a%!%7?j+2Kha9G3DLU|kK;5u)4{cIm!;wkybuQ~n#F z4Z|`Mmye*a)35#8PzWdNNmEl(K}>Ue-4U7h)pxP%5)t`Xm+V&ys4E7OzMtLSvG=wk z@*8bxdNwwE6ac7@j`eG-DJ6fvTyEjZJ%7BRK4`@)s|N)OK57kZL{%>tVQb>2DHJekw8TDEUR? z6+Htu$q~ZB68`4y@l1U4EmwzOhwuE^~oXLc7uAvvc6;_5_AiJ*9io60*CQyZcI9{;_qi zG#au@>y7Wkn%yFmLrRVZ$m#E3B<$ljbGT*JlH#l-VjRWZ&8 zvAE{C`ugt=(XDjyEEhg(6ARan7K3Gi{Le=yh>hiTlE)K65ko60|3E~d4l>@VZ$}RH z`Z93e2;7H~oOQ!dL>3pBi)|}?_Us+mdhF`qv5hXh5F-4(gWOCNICr=6Hc^MVN_(;a zlnY{U5s>Q3l#C(>y2s@22(YWGT3EO;j>$v@bNgH5HC}&w@1D1ixcGE-RMfWCK`Z7+ ztrN%rG_n1m}-wMzB^Zzs$7ZNJMG{z4?h*eyn` zK-dojrKDKU4WRyMWOO{5EZuDWaTHiN(3KOHTEs11{5%Vf)jKT5W0=$aU|&2xlHyTq zSx|Vcq$dKgwB<#oQv_LxF?u6);#Yv`%WRc}_CKl*e(j$(C6slQbo}Y!) z6SiRNB!XrrBxFn2=?O+6zD8w6cW306^CIP18O^)mnp0d#EipjSqm3jd(~A$ zJg55l`m_;C5b$MS-~+G(J{;bkUFMGyL5SvksOW!X?KbNkrLKv~S6^0DZ3F-u=?3a( zUTSG02iv-9$b(GYf0+>227Xk{AT=RQ8U zHTeG0r8(Oxlc!T3hMwG^yJK@v-@1V2<0NspcCEowbXWB1%Lio_vv>}jA094y%d>LD zZbpnIB<9YAa=F_oe;IZe(yZMxHf&FpC+f{r9NYDTtqMksraMDYMmIK3eZlty+&qyW z!8h(*`2x<3$4jM)`-Fvi!3i9K)5Z!A_LBj%J1Fb4&AF%J+!dffc97)+ z(5!lKsQq-#3c)de@7XBDA9ngHS&4AegODx!yL=t2$q3`6)UMB;@j-`>+F3w(!!G~+ z{q1r3*@v)lxN&@5yb~2QaEry5$1-~5PzYK}%5JwSqAB{D$7}z5ViCRHlB%(L>%_^j z!1a|b3v+WiUOv9F^P`Bp0)^bRftA8U!PoPs8<4^@zU#z(V_*SD>=H;I*nC1$Z$>2zM# zS+wOJx!&2FwYPtL_44I!Pb7<;K23Uy+iz`cJxA332!?-p!fzi^_#_fq9iN-)Z3}Av zd!I?d5WGk2XJP@BbfQ}l8nOmP>kn*)lc#_D{8_<5?2?h;0K!b~?(TjG3wVc~@Fnhu zx08T9adu-uD_6O@s;+=o1FMUak(Ofamiat^Q zl>$Jr8+~Y9nFLJ`DET-}695UXl%2}M^qD;&FVF=h0qN+$tx^j9hmW`cJpDC_Q?#$2 z-%4L^ue7-sXXm$XkDQ&HnjXPk_Jf{XI9_<)K6ML=9d_JTqT9zycJlCitqp%uPU0Bo zeUo{oRW8M(o`*H*j>`#@@rp5N@47*QQ&iQGn;peDE&GU`iTZW{TlHVoDRa-63k%g$ ziudli`#}47e<|}_-)(4#!boc)0?$xey78`m0-v~>s1&f$RqOZiXWSEyp5oDqa2mKB zPIgz%?&RT=u)fVxI>yC&%=e=o6g4)`1iPQs3ov?E#HpwF?wcE(N*B z+MD1uB1sU^^MxubtWaXA{14@x3q5=}Fw$csxwF6$DbR!70q_3-M^dM)e|`k3XXV~= zZ~7u8CtZ4B-@1n}H6Mpt0wOW0Rd#Ws(;0=Sh~(^Q5A}MOsHo^eV0@yX_CBa|!`zr4 z8OT?HZv^qP0Euz9z>HCdZ9@8%T5RV9ncAeJou_DmI}SrAtL*7H+ZQ0Njp29=Fr&LF zT_V8q5^D*r%STcotR=2CO6e)t)df)_$-23b|Iod7R!{oRF0$irRI_u=oYYZ zSyJ?AEepz`-a1TY7>dxt{1-E6(-J_>+tdNXIUg?PF*t18;&n6Y9HoJGsbwRB$|_UxjnvpsX)B9~Y$+aKrq#@m_0vYb78b`P9qX6Jp+ zdwJg9`+c9w_j!K5g|d{TEG-}vt#x1#(E)f9I1{Lpw4o)()20=F#PfmUfzyG-2CfWL z4tWjO2h;<5fP2cWcVPE>2Y3)z3d{yRDQRWdqV@w+5fNtsoq+z5<^T(Umm;Fg5pPiu z(H^)87zhkWox0Fg^(L^%;H^C(fr^OF0lx>TJg#SeWx(fw(|}`vF2HJ_4meHHsw2wv zBBDRA2xtpT0*(W22aW+cdYrQ)tpR!f8-bM(@wFqyq9URn@RWZJ2Hpc61J>Ks&IV5O z`2muijEHLBRiHcYxTK2@YoH>c7x1!wUIu&wxE{D0*bVHEv@jxu0#kqvz;Ti`M??ki z1aJ}X2VjV#&4;V&%?8>5qk*2lw}A(M$-q3|8USa#ub5BG@UeOyyUlTINkkmqDl94@ zMgr4-b0odgL~EJ~i~?pFkiP-FfER(2fi;p&%DQK|v*BkXy`DP$UEp4z7UCV=!MV5BqH*MR_j1?&Jm0L%i;&2j5!puOGgeb4(NviekkR0b818x9nfJF}YEe6yAU;=QR zzy2E$ap@si)5$=8;66$7eYhIHcHfmeVr5g|$cD7Hmy z0#*T)CW(U`6Q%$k1%3#;;LJ7EAk_lj@XK~K`<{@)Qu{{4l?^=mE;sQ2eti(DTH!EJ z?fZ&rQIhsV#8PLZ4Zs$lO479vafhwqbTj5t9LIV|+GZ6;10yBv%ToPUgZ*ekbOh#G ze+S?!;3mhldSF+Iq&6hq0fqv@BH|%Q&lJ=30N(Pp3-ChXLXy@2-?!zQZL7L2i!HC0 zG&9Es*b7`65i8w)n&{wOWx9~ou^}~vhCb@s5%CBx!a7eaHZyRRnL zS%cqqke8bXbak?L8klQK`fZ9JZqW#8;1iNMK-_YEllyEL~izWMS)ALEq1YmE}+{v`@NeQ({4%6N*ZX3d)0MeA9p4C8Kipu zB}Dh~##94MX|p8!q<=&tU$C#YeAhCd;gocb zONAvV;0rpHB1Tz0 zepLZ=C04YH%p?HK0M?omN6L1=JIPFK^>2=6w`m5Tjxo(|PJR z!P_y7nR1GVL8b!RfZ@&Q-h~9}-Bb`C(L|ssf$0&^y#bKgyGX7F?w7QuRDjxSpz6uA zgY%JHsr?IpFE?;)KXa%$moAhFQ12M1rj$jivP!FS8n`wA=aoXtvJ?}j)wYOwyGBhO zI<{t&9>WgccGm-)vsyc)0hFXV;PsR>T%L!T9qwf%J)?FJad8$%m1Nc}0IZYrTuA|C znUUHb6%mIz9kw%7Tql4JH$WXD;wUnU%1-gQDa9hSg$61;71b@zpq|VYCq?ZQUV?a& zvtoDitvWI*Yf29&Pb0mSDrJV{*-}ZYsy-FC$5`i(6mMHvsul&H)c*JK)NyH6_DiG( znbmbkw%c0DKt0F)f6b_J8#kXWLADD*W|2k`pXO3TX%3)j`Tr^K8}fAH5o8v#rmdIb!cWUSNvlg5D7QyurYxZ?nPt)W%3Wz9oA4)!EX}oi z`bVi?oUBO6S6(&|t;nh?OCKoHgdeBCYSRQ=yT~*Jw*#Ltm-=O~fvRdo-D80-nslyj zqOKKWCKfh&uI_=u#r2T%KA9=@6KVPsd$r@#UdnP{iHNr%Vtz}Gp{hi%`V;VzvdNUC gEM+N6S(+sO1^9v8ds1+#WB>pF07*qoM6N<$f?9#*$^ZZW diff --git a/third_party/pygments/doc/_themes/pygments14/static/pygments14.css_t b/third_party/pygments/doc/_themes/pygments14/static/pygments14.css_t deleted file mode 100644 index 5c37aaf9c..000000000 --- a/third_party/pygments/doc/_themes/pygments14/static/pygments14.css_t +++ /dev/null @@ -1,401 +0,0 @@ -/* - * pygments14.css - * ~~~~~~~~~~~~~~ - * - * Sphinx stylesheet -- pygments14 theme. Heavily copied from sphinx13. - * - * :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -body { - font-family: {{ theme_font }}, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', - 'Verdana', sans-serif; - font-size: 14px; - text-align: center; - background-image: url(bodybg.png); - background-color: {{ theme_background }}; - color: black; - padding: 0; - /* - border-right: 1px solid {{ theme_border }}; - border-left: 1px solid {{ theme_border }}; - */ - - margin: 0 auto; - min-width: 780px; - max-width: 1080px; -} - -.outerwrapper { - background-image: url(docbg.png); - background-attachment: fixed; -} - -.pageheader { - text-align: left; - padding: 10px 15px; -} - -.pageheader ul { - float: right; - color: white; - list-style-type: none; - padding-left: 0; - margin-top: 40px; - margin-right: 10px; -} - -.pageheader li { - float: left; - margin: 0 0 0 10px; -} - -.pageheader li a { - border-radius: 3px; - padding: 8px 12px; - color: {{ theme_darkgray }}; - text-shadow: 0 0 5px rgba(0, 0, 0, 0.2); -} - -.pageheader li a:hover { - background-color: {{ theme_yellow }}; - color: black; - text-shadow: none; -} - -div.document { - text-align: left; - /*border-left: 1em solid {{ theme_lightyellow }};*/ -} - -div.bodywrapper { - margin: 0 12px 0 240px; - background-color: white; -/* border-right: 1px solid {{ theme_border }}; */ -} - -div.body { - margin: 0; - padding: 0.5em 20px 20px 20px; -} - -div.related { - font-size: 1em; - color: {{ theme_darkgray }}; -} - -div.related ul { - background-image: url(relbg.png); - background-repeat: repeat-y; - background-color: {{ theme_yellow }}; - height: 1.9em; - /* - border-top: 1px solid {{ theme_border }}; - border-bottom: 1px solid {{ theme_border }}; - */ -} - -div.related ul li { - margin: 0 5px 0 0; - padding: 0; - float: left; -} - -div.related ul li.right { - float: right; - margin-right: 5px; -} - -div.related ul li a { - margin: 0; - padding: 0 5px 0 5px; - line-height: 1.75em; - color: {{ theme_darkgray }}; - /*text-shadow: 0px 0px 1px rgba(0, 0, 0, 0.5);*/ -} - -div.related ul li a:hover { - text-decoration: underline; - text-shadow: 0px 0px 1px rgba(255, 255, 255, 0.5); -} - -div.sphinxsidebarwrapper { - position: relative; - top: 0px; - padding: 0; -} - -div.sphinxsidebar { - margin: 0; - padding: 0 0px 15px 15px; - width: 210px; - float: left; - font-size: 1em; - text-align: left; -} - -div.sphinxsidebar .logo { - font-size: 1.8em; - color: #666; - font-weight: 300; - text-align: center; -} - -div.sphinxsidebar .logo img { - vertical-align: middle; -} - -div.sphinxsidebar input { - border: 1px solid #aaa; - font-family: {{ theme_font }}, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', - 'Verdana', sans-serif; - font-size: 1em; -} - -div.sphinxsidebar h3 { - font-size: 1.5em; - /* border-top: 1px solid {{ theme_border }}; */ - margin-top: 1em; - margin-bottom: 0.5em; - padding-top: 0.5em; -} - -div.sphinxsidebar h4 { - font-size: 1.2em; - margin-bottom: 0; -} - -div.sphinxsidebar h3, div.sphinxsidebar h4 { - margin-right: -15px; - margin-left: -15px; - padding-right: 14px; - padding-left: 14px; - color: #333; - font-weight: 300; - /*text-shadow: 0px 0px 0.5px rgba(0, 0, 0, 0.4);*/ -} - -div.sphinxsidebarwrapper > h3:first-child { - margin-top: 0.5em; - border: none; -} - -div.sphinxsidebar h3 a { - color: #333; -} - -div.sphinxsidebar ul { - color: #444; - margin-top: 7px; - padding: 0; - line-height: 130%; -} - -div.sphinxsidebar ul ul { - margin-left: 20px; - list-style-image: url(listitem.png); -} - -div.footer { - color: {{ theme_darkgray }}; - text-shadow: 0 0 .2px rgba(255, 255, 255, 0.8); - padding: 2em; - text-align: center; - clear: both; - font-size: 0.8em; -} - -/* -- body styles ----------------------------------------------------------- */ - -p { - margin: 0.8em 0 0.5em 0; -} - -a { - color: {{ theme_darkgreen }}; - text-decoration: none; -} - -a:hover { - color: {{ theme_darkyellow }}; -} - -div.body a { - text-decoration: underline; -} - -h1 { - margin: 10px 0 0 0; - font-size: 2.4em; - color: {{ theme_darkgray }}; - font-weight: 300; -} - -h2 { - margin: 1.em 0 0.2em 0; - font-size: 1.5em; - font-weight: 300; - padding: 0; - color: {{ theme_darkgreen }}; -} - -h3 { - margin: 1em 0 -0.3em 0; - font-size: 1.3em; - font-weight: 300; -} - -div.body h1 a, div.body h2 a, div.body h3 a, div.body h4 a, div.body h5 a, div.body h6 a { - text-decoration: none; -} - -div.body h1 a tt, div.body h2 a tt, div.body h3 a tt, div.body h4 a tt, div.body h5 a tt, div.body h6 a tt { - color: {{ theme_darkgreen }} !important; - font-size: inherit !important; -} - -a.headerlink { - color: {{ theme_green }} !important; - font-size: 12px; - margin-left: 6px; - padding: 0 4px 0 4px; - text-decoration: none !important; - float: right; -} - -a.headerlink:hover { - background-color: #ccc; - color: white!important; -} - -cite, code, tt { - font-family: 'Consolas', 'DejaVu Sans Mono', - 'Bitstream Vera Sans Mono', monospace; - font-size: 14px; - letter-spacing: -0.02em; -} - -tt { - background-color: #f2f2f2; - border: 1px solid #ddd; - border-radius: 2px; - color: #333; - padding: 1px; -} - -tt.descname, tt.descclassname, tt.xref { - border: 0; -} - -hr { - border: 1px solid #abc; - margin: 2em; -} - -a tt { - border: 0; - color: {{ theme_darkgreen }}; -} - -a tt:hover { - color: {{ theme_darkyellow }}; -} - -pre { - font-family: 'Consolas', 'DejaVu Sans Mono', - 'Bitstream Vera Sans Mono', monospace; - font-size: 13px; - letter-spacing: 0.015em; - line-height: 120%; - padding: 0.5em; - border: 1px solid #ccc; - border-radius: 2px; - background-color: #f8f8f8; -} - -pre a { - color: inherit; - text-decoration: underline; -} - -td.linenos pre { - padding: 0.5em 0; -} - -div.quotebar { - background-color: #f8f8f8; - max-width: 250px; - float: right; - padding: 0px 7px; - border: 1px solid #ccc; - margin-left: 1em; -} - -div.topic { - background-color: #f8f8f8; -} - -table { - border-collapse: collapse; - margin: 0 -0.5em 0 -0.5em; -} - -table td, table th { - padding: 0.2em 0.5em 0.2em 0.5em; -} - -div.admonition, div.warning { - font-size: 0.9em; - margin: 1em 0 1em 0; - border: 1px solid #86989B; - border-radius: 2px; - background-color: #f7f7f7; - padding: 0; -} - -div.admonition p, div.warning p { - margin: 0.5em 1em 0.5em 1em; - padding: 0; -} - -div.admonition pre, div.warning pre { - margin: 0.4em 1em 0.4em 1em; -} - -div.admonition p.admonition-title, -div.warning p.admonition-title { - margin-top: 1em; - padding-top: 0.5em; - font-weight: bold; -} - -div.warning { - border: 1px solid #940000; -/* background-color: #FFCCCF;*/ -} - -div.warning p.admonition-title { -} - -div.admonition ul, div.admonition ol, -div.warning ul, div.warning ol { - margin: 0.1em 0.5em 0.5em 3em; - padding: 0; -} - -.viewcode-back { - font-family: {{ theme_font }}, 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', - 'Verdana', sans-serif; -} - -div.viewcode-block:target { - background-color: #f4debf; - border-top: 1px solid #ac9; - border-bottom: 1px solid #ac9; -} diff --git a/third_party/pygments/doc/_themes/pygments14/theme.conf b/third_party/pygments/doc/_themes/pygments14/theme.conf deleted file mode 100644 index fffe66d62..000000000 --- a/third_party/pygments/doc/_themes/pygments14/theme.conf +++ /dev/null @@ -1,15 +0,0 @@ -[theme] -inherit = basic -stylesheet = pygments14.css -pygments_style = friendly - -[options] -green = #66b55e -darkgreen = #36852e -darkgray = #666666 -border = #66b55e -yellow = #f4cd00 -darkyellow = #d4ad00 -lightyellow = #fffbe3 -background = #f9f9f9 -font = PT Sans diff --git a/third_party/pygments/doc/conf.py b/third_party/pygments/doc/conf.py deleted file mode 100644 index 51a916177..000000000 --- a/third_party/pygments/doc/conf.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Pygments documentation build configuration file -# - -import sys, os - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) - -import pygments - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'pygments.sphinxext'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'Pygments' -copyright = u'2015, Georg Brandl' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = pygments.__version__ -# The full version, including alpha/beta/rc tags. -release = version - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -#pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'pygments14' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ['_themes'] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -html_favicon = '_static/favicon.ico' - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -html_sidebars = {'index': 'indexsidebar.html', - 'docs/*': 'docssidebar.html'} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'Pygmentsdoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'Pygments.tex', u'Pygments Documentation', - u'Georg Brandl', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'pygments', u'Pygments Documentation', - [u'Georg Brandl'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'Pygments', u'Pygments Documentation', - u'Georg Brandl', 'Pygments', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - - -# Example configuration for intersphinx: refer to the Python standard library. -#intersphinx_mapping = {'http://docs.python.org/': None} diff --git a/third_party/pygments/doc/docs/api.rst b/third_party/pygments/doc/docs/api.rst deleted file mode 100644 index 123a46431..000000000 --- a/third_party/pygments/doc/docs/api.rst +++ /dev/null @@ -1,316 +0,0 @@ -.. -*- mode: rst -*- - -===================== -The full Pygments API -===================== - -This page describes the Pygments API. - -High-level API -============== - -.. module:: pygments - -Functions from the :mod:`pygments` module: - -.. function:: lex(code, lexer) - - Lex `code` with the `lexer` (must be a `Lexer` instance) - and return an iterable of tokens. Currently, this only calls - `lexer.get_tokens()`. - -.. function:: format(tokens, formatter, outfile=None) - - Format a token stream (iterable of tokens) `tokens` with the - `formatter` (must be a `Formatter` instance). The result is - written to `outfile`, or if that is ``None``, returned as a - string. - -.. function:: highlight(code, lexer, formatter, outfile=None) - - This is the most high-level highlighting function. - It combines `lex` and `format` in one function. - - -.. module:: pygments.lexers - -Functions from :mod:`pygments.lexers`: - -.. function:: get_lexer_by_name(alias, **options) - - Return an instance of a `Lexer` subclass that has `alias` in its - aliases list. The lexer is given the `options` at its - instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is - found. - -.. function:: get_lexer_for_filename(fn, **options) - - Return a `Lexer` subclass instance that has a filename pattern - matching `fn`. The lexer is given the `options` at its - instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no lexer for that filename - is found. - -.. function:: get_lexer_for_mimetype(mime, **options) - - Return a `Lexer` subclass instance that has `mime` in its mimetype - list. The lexer is given the `options` at its instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if not lexer for that mimetype - is found. - -.. function:: guess_lexer(text, **options) - - Return a `Lexer` subclass instance that's guessed from the text in - `text`. For that, the :meth:`.analyse_text()` method of every known lexer - class is called with the text as argument, and the lexer which returned the - highest value will be instantiated and returned. - - :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can - handle the content. - -.. function:: guess_lexer_for_filename(filename, text, **options) - - As :func:`guess_lexer()`, but only lexers which have a pattern in `filenames` - or `alias_filenames` that matches `filename` are taken into consideration. - - :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can - handle the content. - -.. function:: get_all_lexers() - - Return an iterable over all registered lexers, yielding tuples in the - format:: - - (longname, tuple of aliases, tuple of filename patterns, tuple of mimetypes) - - .. versionadded:: 0.6 - - -.. module:: pygments.formatters - -Functions from :mod:`pygments.formatters`: - -.. function:: get_formatter_by_name(alias, **options) - - Return an instance of a :class:`.Formatter` subclass that has `alias` in its - aliases list. The formatter is given the `options` at its instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that - alias is found. - -.. function:: get_formatter_for_filename(fn, **options) - - Return a :class:`.Formatter` subclass instance that has a filename pattern - matching `fn`. The formatter is given the `options` at its instantiation. - - Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename - is found. - - -.. module:: pygments.styles - -Functions from :mod:`pygments.styles`: - -.. function:: get_style_by_name(name) - - Return a style class by its short name. The names of the builtin styles - are listed in :data:`pygments.styles.STYLE_MAP`. - - Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is - found. - -.. function:: get_all_styles() - - Return an iterable over all registered styles, yielding their names. - - .. versionadded:: 0.6 - - -.. module:: pygments.lexer - -Lexers -====== - -The base lexer class from which all lexers are derived is: - -.. class:: Lexer(**options) - - The constructor takes a \*\*keywords dictionary of options. - Every subclass must first process its own options and then call - the `Lexer` constructor, since it processes the `stripnl`, - `stripall` and `tabsize` options. - - An example looks like this: - - .. sourcecode:: python - - def __init__(self, **options): - self.compress = options.get('compress', '') - Lexer.__init__(self, **options) - - As these options must all be specifiable as strings (due to the - command line usage), there are various utility functions - available to help with that, see `Option processing`_. - - .. method:: get_tokens(text) - - This method is the basic interface of a lexer. It is called by - the `highlight()` function. It must process the text and return an - iterable of ``(tokentype, value)`` pairs from `text`. - - Normally, you don't need to override this method. The default - implementation processes the `stripnl`, `stripall` and `tabsize` - options and then yields all tokens from `get_tokens_unprocessed()`, - with the ``index`` dropped. - - .. method:: get_tokens_unprocessed(text) - - This method should process the text and return an iterable of - ``(index, tokentype, value)`` tuples where ``index`` is the starting - position of the token within the input text. - - This method must be overridden by subclasses. - - .. staticmethod:: analyse_text(text) - - A static method which is called for lexer guessing. It should analyse - the text and return a float in the range from ``0.0`` to ``1.0``. - If it returns ``0.0``, the lexer will not be selected as the most - probable one, if it returns ``1.0``, it will be selected immediately. - - .. note:: You don't have to add ``@staticmethod`` to the definition of - this method, this will be taken care of by the Lexer's metaclass. - - For a list of known tokens have a look at the :doc:`tokens` page. - - A lexer also can have the following attributes (in fact, they are mandatory - except `alias_filenames`) that are used by the builtin lookup mechanism. - - .. attribute:: name - - Full name for the lexer, in human-readable form. - - .. attribute:: aliases - - A list of short, unique identifiers that can be used to lookup - the lexer from a list, e.g. using `get_lexer_by_name()`. - - .. attribute:: filenames - - A list of `fnmatch` patterns that match filenames which contain - content for this lexer. The patterns in this list should be unique among - all lexers. - - .. attribute:: alias_filenames - - A list of `fnmatch` patterns that match filenames which may or may not - contain content for this lexer. This list is used by the - :func:`.guess_lexer_for_filename()` function, to determine which lexers - are then included in guessing the correct one. That means that - e.g. every lexer for HTML and a template language should include - ``\*.html`` in this list. - - .. attribute:: mimetypes - - A list of MIME types for content that can be lexed with this - lexer. - - -.. module:: pygments.formatter - -Formatters -========== - -A formatter is derived from this class: - - -.. class:: Formatter(**options) - - As with lexers, this constructor processes options and then must call the - base class :meth:`__init__`. - - The :class:`Formatter` class recognizes the options `style`, `full` and - `title`. It is up to the formatter class whether it uses them. - - .. method:: get_style_defs(arg='') - - This method must return statements or declarations suitable to define - the current style for subsequent highlighted text (e.g. CSS classes - in the `HTMLFormatter`). - - The optional argument `arg` can be used to modify the generation and - is formatter dependent (it is standardized because it can be given on - the command line). - - This method is called by the ``-S`` :doc:`command-line option `, - the `arg` is then given by the ``-a`` option. - - .. method:: format(tokensource, outfile) - - This method must format the tokens from the `tokensource` iterable and - write the formatted version to the file object `outfile`. - - Formatter options can control how exactly the tokens are converted. - - .. versionadded:: 0.7 - A formatter must have the following attributes that are used by the - builtin lookup mechanism. - - .. attribute:: name - - Full name for the formatter, in human-readable form. - - .. attribute:: aliases - - A list of short, unique identifiers that can be used to lookup - the formatter from a list, e.g. using :func:`.get_formatter_by_name()`. - - .. attribute:: filenames - - A list of :mod:`fnmatch` patterns that match filenames for which this - formatter can produce output. The patterns in this list should be unique - among all formatters. - - -.. module:: pygments.util - -Option processing -================= - -The :mod:`pygments.util` module has some utility functions usable for option -processing: - -.. exception:: OptionError - - This exception will be raised by all option processing functions if - the type or value of the argument is not correct. - -.. function:: get_bool_opt(options, optname, default=None) - - Interpret the key `optname` from the dictionary `options` as a boolean and - return it. Return `default` if `optname` is not in `options`. - - The valid string values for ``True`` are ``1``, ``yes``, ``true`` and - ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off`` - (matched case-insensitively). - -.. function:: get_int_opt(options, optname, default=None) - - As :func:`get_bool_opt`, but interpret the value as an integer. - -.. function:: get_list_opt(options, optname, default=None) - - If the key `optname` from the dictionary `options` is a string, - split it at whitespace and return it. If it is already a list - or a tuple, it is returned as a list. - -.. function:: get_choice_opt(options, optname, allowed, default=None) - - If the key `optname` from the dictionary is not in the sequence - `allowed`, raise an error, otherwise return it. - - .. versionadded:: 0.8 diff --git a/third_party/pygments/doc/docs/authors.rst b/third_party/pygments/doc/docs/authors.rst deleted file mode 100644 index f8373f0a4..000000000 --- a/third_party/pygments/doc/docs/authors.rst +++ /dev/null @@ -1,4 +0,0 @@ -Full contributor list -===================== - -.. include:: ../../AUTHORS diff --git a/third_party/pygments/doc/docs/changelog.rst b/third_party/pygments/doc/docs/changelog.rst deleted file mode 100644 index f264cab0b..000000000 --- a/third_party/pygments/doc/docs/changelog.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../../CHANGES diff --git a/third_party/pygments/doc/docs/cmdline.rst b/third_party/pygments/doc/docs/cmdline.rst deleted file mode 100644 index 165af9690..000000000 --- a/third_party/pygments/doc/docs/cmdline.rst +++ /dev/null @@ -1,149 +0,0 @@ -.. -*- mode: rst -*- - -====================== -Command Line Interface -====================== - -You can use Pygments from the shell, provided you installed the -:program:`pygmentize` script:: - - $ pygmentize test.py - print "Hello World" - -will print the file test.py to standard output, using the Python lexer -(inferred from the file name extension) and the terminal formatter (because -you didn't give an explicit formatter name). - -If you want HTML output:: - - $ pygmentize -f html -l python -o test.html test.py - -As you can see, the -l option explicitly selects a lexer. As seen above, if you -give an input file name and it has an extension that Pygments recognizes, you can -omit this option. - -The ``-o`` option gives an output file name. If it is not given, output is -written to stdout. - -The ``-f`` option selects a formatter (as with ``-l``, it can also be omitted -if an output file name is given and has a supported extension). -If no output file name is given and ``-f`` is omitted, the -:class:`.TerminalFormatter` is used. - -The above command could therefore also be given as:: - - $ pygmentize -o test.html test.py - -To create a full HTML document, including line numbers and stylesheet (using the -"emacs" style), highlighting the Python file ``test.py`` to ``test.html``:: - - $ pygmentize -O full,style=emacs -o test.html test.py - - -Options and filters -------------------- - -Lexer and formatter options can be given using the ``-O`` option:: - - $ pygmentize -f html -O style=colorful,linenos=1 -l python test.py - -Be sure to enclose the option string in quotes if it contains any special shell -characters, such as spaces or expansion wildcards like ``*``. If an option -expects a list value, separate the list entries with spaces (you'll have to -quote the option value in this case too, so that the shell doesn't split it). - -Since the ``-O`` option argument is split at commas and expects the split values -to be of the form ``name=value``, you can't give an option value that contains -commas or equals signs. Therefore, an option ``-P`` is provided (as of Pygments -0.9) that works like ``-O`` but can only pass one option per ``-P``. Its value -can then contain all characters:: - - $ pygmentize -P "heading=Pygments, the Python highlighter" ... - -Filters are added to the token stream using the ``-F`` option:: - - $ pygmentize -f html -l pascal -F keywordcase:case=upper main.pas - -As you see, options for the filter are given after a colon. As for ``-O``, the -filter name and options must be one shell word, so there may not be any spaces -around the colon. - - -Generating styles ------------------ - -Formatters normally don't output full style information. For example, the HTML -formatter by default only outputs ```` tags with ``class`` attributes. -Therefore, there's a special ``-S`` option for generating style definitions. -Usage is as follows:: - - $ pygmentize -f html -S colorful -a .syntax - -generates a CSS style sheet (because you selected the HTML formatter) for -the "colorful" style prepending a ".syntax" selector to all style rules. - -For an explanation what ``-a`` means for :doc:`a particular formatter -`, look for the `arg` argument for the formatter's -:meth:`.get_style_defs()` method. - - -Getting lexer names -------------------- - -.. versionadded:: 1.0 - -The ``-N`` option guesses a lexer name for a given filename, so that :: - - $ pygmentize -N setup.py - -will print out ``python``. It won't highlight anything yet. If no specific -lexer is known for that filename, ``text`` is printed. - - -Getting help ------------- - -The ``-L`` option lists lexers, formatters, along with their short -names and supported file name extensions, styles and filters. If you want to see -only one category, give it as an argument:: - - $ pygmentize -L filters - -will list only all installed filters. - -The ``-H`` option will give you detailed information (the same that can be found -in this documentation) about a lexer, formatter or filter. Usage is as follows:: - - $ pygmentize -H formatter html - -will print the help for the HTML formatter, while :: - - $ pygmentize -H lexer python - -will print the help for the Python lexer, etc. - - -A note on encodings -------------------- - -.. versionadded:: 0.9 - -Pygments tries to be smart regarding encodings in the formatting process: - -* If you give an ``encoding`` option, it will be used as the input and - output encoding. - -* If you give an ``outencoding`` option, it will override ``encoding`` - as the output encoding. - -* If you give an ``inencoding`` option, it will override ``encoding`` - as the input encoding. - -* If you don't give an encoding and have given an output file, the default - encoding for lexer and formatter is the terminal encoding or the default - locale encoding of the system. As a last resort, ``latin1`` is used (which - will pass through all non-ASCII characters). - -* If you don't give an encoding and haven't given an output file (that means - output is written to the console), the default encoding for lexer and - formatter is the terminal encoding (``sys.stdout.encoding``). diff --git a/third_party/pygments/doc/docs/filterdevelopment.rst b/third_party/pygments/doc/docs/filterdevelopment.rst deleted file mode 100644 index fbcd0a09e..000000000 --- a/third_party/pygments/doc/docs/filterdevelopment.rst +++ /dev/null @@ -1,71 +0,0 @@ -.. -*- mode: rst -*- - -===================== -Write your own filter -===================== - -.. versionadded:: 0.7 - -Writing own filters is very easy. All you have to do is to subclass -the `Filter` class and override the `filter` method. Additionally a -filter is instantiated with some keyword arguments you can use to -adjust the behavior of your filter. - - -Subclassing Filters -=================== - -As an example, we write a filter that converts all `Name.Function` tokens -to normal `Name` tokens to make the output less colorful. - -.. sourcecode:: python - - from pygments.util import get_bool_opt - from pygments.token import Name - from pygments.filter import Filter - - class UncolorFilter(Filter): - - def __init__(self, **options): - Filter.__init__(self, **options) - self.class_too = get_bool_opt(options, 'classtoo') - - def filter(self, lexer, stream): - for ttype, value in stream: - if ttype is Name.Function or (self.class_too and - ttype is Name.Class): - ttype = Name - yield ttype, value - -Some notes on the `lexer` argument: that can be quite confusing since it doesn't -need to be a lexer instance. If a filter was added by using the `add_filter()` -function of lexers, that lexer is registered for the filter. In that case -`lexer` will refer to the lexer that has registered the filter. It *can* be used -to access options passed to a lexer. Because it could be `None` you always have -to check for that case if you access it. - - -Using a decorator -================= - -You can also use the `simplefilter` decorator from the `pygments.filter` module: - -.. sourcecode:: python - - from pygments.util import get_bool_opt - from pygments.token import Name - from pygments.filter import simplefilter - - - @simplefilter - def uncolor(self, lexer, stream, options): - class_too = get_bool_opt(options, 'classtoo') - for ttype, value in stream: - if ttype is Name.Function or (class_too and - ttype is Name.Class): - ttype = Name - yield ttype, value - -The decorator automatically subclasses an internal filter class and uses the -decorated function as a method for filtering. (That's why there is a `self` -argument that you probably won't end up using in the method.) diff --git a/third_party/pygments/doc/docs/filters.rst b/third_party/pygments/doc/docs/filters.rst deleted file mode 100644 index ff2519a3e..000000000 --- a/third_party/pygments/doc/docs/filters.rst +++ /dev/null @@ -1,41 +0,0 @@ -.. -*- mode: rst -*- - -======= -Filters -======= - -.. versionadded:: 0.7 - -You can filter token streams coming from lexers to improve or annotate the -output. For example, you can highlight special words in comments, convert -keywords to upper or lowercase to enforce a style guide etc. - -To apply a filter, you can use the `add_filter()` method of a lexer: - -.. sourcecode:: pycon - - >>> from pygments.lexers import PythonLexer - >>> l = PythonLexer() - >>> # add a filter given by a string and options - >>> l.add_filter('codetagify', case='lower') - >>> l.filters - [] - >>> from pygments.filters import KeywordCaseFilter - >>> # or give an instance - >>> l.add_filter(KeywordCaseFilter(case='lower')) - -The `add_filter()` method takes keyword arguments which are forwarded to -the constructor of the filter. - -To get a list of all registered filters by name, you can use the -`get_all_filters()` function from the `pygments.filters` module that returns an -iterable for all known filters. - -If you want to write your own filter, have a look at :doc:`Write your own filter -`. - - -Builtin Filters -=============== - -.. pygmentsdoc:: filters diff --git a/third_party/pygments/doc/docs/formatterdevelopment.rst b/third_party/pygments/doc/docs/formatterdevelopment.rst deleted file mode 100644 index 2bfac05c6..000000000 --- a/third_party/pygments/doc/docs/formatterdevelopment.rst +++ /dev/null @@ -1,169 +0,0 @@ -.. -*- mode: rst -*- - -======================== -Write your own formatter -======================== - -As well as creating :doc:`your own lexer `, writing a new -formatter for Pygments is easy and straightforward. - -A formatter is a class that is initialized with some keyword arguments (the -formatter options) and that must provides a `format()` method. -Additionally a formatter should provide a `get_style_defs()` method that -returns the style definitions from the style in a form usable for the -formatter's output format. - - -Quickstart -========== - -The most basic formatter shipped with Pygments is the `NullFormatter`. It just -sends the value of a token to the output stream: - -.. sourcecode:: python - - from pygments.formatter import Formatter - - class NullFormatter(Formatter): - def format(self, tokensource, outfile): - for ttype, value in tokensource: - outfile.write(value) - -As you can see, the `format()` method is passed two parameters: `tokensource` -and `outfile`. The first is an iterable of ``(token_type, value)`` tuples, -the latter a file like object with a `write()` method. - -Because the formatter is that basic it doesn't overwrite the `get_style_defs()` -method. - - -Styles -====== - -Styles aren't instantiated but their metaclass provides some class functions -so that you can access the style definitions easily. - -Styles are iterable and yield tuples in the form ``(ttype, d)`` where `ttype` -is a token and `d` is a dict with the following keys: - -``'color'`` - Hexadecimal color value (eg: ``'ff0000'`` for red) or `None` if not - defined. - -``'bold'`` - `True` if the value should be bold - -``'italic'`` - `True` if the value should be italic - -``'underline'`` - `True` if the value should be underlined - -``'bgcolor'`` - Hexadecimal color value for the background (eg: ``'eeeeeee'`` for light - gray) or `None` if not defined. - -``'border'`` - Hexadecimal color value for the border (eg: ``'0000aa'`` for a dark - blue) or `None` for no border. - -Additional keys might appear in the future, formatters should ignore all keys -they don't support. - - -HTML 3.2 Formatter -================== - -For an more complex example, let's implement a HTML 3.2 Formatter. We don't -use CSS but inline markup (````, ````, etc). Because this isn't good -style this formatter isn't in the standard library ;-) - -.. sourcecode:: python - - from pygments.formatter import Formatter - - class OldHtmlFormatter(Formatter): - - def __init__(self, **options): - Formatter.__init__(self, **options) - - # create a dict of (start, end) tuples that wrap the - # value of a token so that we can use it in the format - # method later - self.styles = {} - - # we iterate over the `_styles` attribute of a style item - # that contains the parsed style values. - for token, style in self.style: - start = end = '' - # a style item is a tuple in the following form: - # colors are readily specified in hex: 'RRGGBB' - if style['color']: - start += '' % style['color'] - end = '' + end - if style['bold']: - start += '' - end = '' + end - if style['italic']: - start += '' - end = '' + end - if style['underline']: - start += '' - end = '' + end - self.styles[token] = (start, end) - - def format(self, tokensource, outfile): - # lastval is a string we use for caching - # because it's possible that an lexer yields a number - # of consecutive tokens with the same token type. - # to minimize the size of the generated html markup we - # try to join the values of same-type tokens here - lastval = '' - lasttype = None - - # wrap the whole output with
      -            outfile.write('
      ')
      -
      -            for ttype, value in tokensource:
      -                # if the token type doesn't exist in the stylemap
      -                # we try it with the parent of the token type
      -                # eg: parent of Token.Literal.String.Double is
      -                # Token.Literal.String
      -                while ttype not in self.styles:
      -                    ttype = ttype.parent
      -                if ttype == lasttype:
      -                    # the current token type is the same of the last
      -                    # iteration. cache it
      -                    lastval += value
      -                else:
      -                    # not the same token as last iteration, but we
      -                    # have some data in the buffer. wrap it with the
      -                    # defined style and write it to the output file
      -                    if lastval:
      -                        stylebegin, styleend = self.styles[lasttype]
      -                        outfile.write(stylebegin + lastval + styleend)
      -                    # set lastval/lasttype to current values
      -                    lastval = value
      -                    lasttype = ttype
      -
      -            # if something is left in the buffer, write it to the
      -            # output file, then close the opened 
       tag
      -            if lastval:
      -                stylebegin, styleend = self.styles[lasttype]
      -                outfile.write(stylebegin + lastval + styleend)
      -            outfile.write('
      \n') - -The comments should explain it. Again, this formatter doesn't override the -`get_style_defs()` method. If we would have used CSS classes instead of -inline HTML markup, we would need to generate the CSS first. For that -purpose the `get_style_defs()` method exists: - - -Generating Style Definitions -============================ - -Some formatters like the `LatexFormatter` and the `HtmlFormatter` don't -output inline markup but reference either macros or css classes. Because -the definitions of those are not part of the output, the `get_style_defs()` -method exists. It is passed one parameter (if it's used and how it's used -is up to the formatter) and has to return a string or ``None``. diff --git a/third_party/pygments/doc/docs/formatters.rst b/third_party/pygments/doc/docs/formatters.rst deleted file mode 100644 index 9e7074e81..000000000 --- a/third_party/pygments/doc/docs/formatters.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. -*- mode: rst -*- - -==================== -Available formatters -==================== - -This page lists all builtin formatters. - -Common options -============== - -All formatters support these options: - -`encoding` - If given, must be an encoding name (such as ``"utf-8"``). This will - be used to convert the token strings (which are Unicode strings) - to byte strings in the output (default: ``None``). - It will also be written in an encoding declaration suitable for the - document format if the `full` option is given (e.g. a ``meta - content-type`` directive in HTML or an invocation of the `inputenc` - package in LaTeX). - - If this is ``""`` or ``None``, Unicode strings will be written - to the output file, which most file-like objects do not support. - For example, `pygments.highlight()` will return a Unicode string if - called with no `outfile` argument and a formatter that has `encoding` - set to ``None`` because it uses a `StringIO.StringIO` object that - supports Unicode arguments to `write()`. Using a regular file object - wouldn't work. - - .. versionadded:: 0.6 - -`outencoding` - When using Pygments from the command line, any `encoding` option given is - passed to the lexer and the formatter. This is sometimes not desirable, - for example if you want to set the input encoding to ``"guess"``. - Therefore, `outencoding` has been introduced which overrides `encoding` - for the formatter if given. - - .. versionadded:: 0.7 - - -Formatter classes -================= - -All these classes are importable from :mod:`pygments.formatters`. - -.. pygmentsdoc:: formatters diff --git a/third_party/pygments/doc/docs/index.rst b/third_party/pygments/doc/docs/index.rst deleted file mode 100644 index 30d5c0851..000000000 --- a/third_party/pygments/doc/docs/index.rst +++ /dev/null @@ -1,66 +0,0 @@ -Pygments documentation -====================== - -**Starting with Pygments** - -.. toctree:: - :maxdepth: 1 - - ../download - quickstart - cmdline - -**Builtin components** - -.. toctree:: - :maxdepth: 1 - - lexers - filters - formatters - styles - -**Reference** - -.. toctree:: - :maxdepth: 1 - - unicode - tokens - api - -**Hacking for Pygments** - -.. toctree:: - :maxdepth: 1 - - lexerdevelopment - formatterdevelopment - filterdevelopment - plugins - -**Hints and tricks** - -.. toctree:: - :maxdepth: 1 - - rstdirective - moinmoin - java - integrate - -**About Pygments** - -.. toctree:: - :maxdepth: 1 - - changelog - authors - - -If you find bugs or have suggestions for the documentation, please look -:ref:`here ` for info on how to contact the team. - -.. XXX You can download an offline version of this documentation from the - :doc:`download page `. - diff --git a/third_party/pygments/doc/docs/integrate.rst b/third_party/pygments/doc/docs/integrate.rst deleted file mode 100644 index 77daaa43c..000000000 --- a/third_party/pygments/doc/docs/integrate.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. -*- mode: rst -*- - -=================================== -Using Pygments in various scenarios -=================================== - -Markdown --------- - -Since Pygments 0.9, the distribution ships Markdown_ preprocessor sample code -that uses Pygments to render source code in -:file:`external/markdown-processor.py`. You can copy and adapt it to your -liking. - -.. _Markdown: http://www.freewisdom.org/projects/python-markdown/ - -TextMate --------- - -Antonio Cangiano has created a Pygments bundle for TextMate that allows to -colorize code via a simple menu option. It can be found here_. - -.. _here: http://antoniocangiano.com/2008/10/28/pygments-textmate-bundle/ - -Bash completion ---------------- - -The source distribution contains a file ``external/pygments.bashcomp`` that -sets up completion for the ``pygmentize`` command in bash. - -Wrappers for other languages ----------------------------- - -These libraries provide Pygments highlighting for users of other languages -than Python: - -* `pygments.rb `_, a pygments wrapper for Ruby -* `Clygments `_, a pygments wrapper for - Clojure -* `PHPygments `_, a pygments wrapper for PHP diff --git a/third_party/pygments/doc/docs/java.rst b/third_party/pygments/doc/docs/java.rst deleted file mode 100644 index f553463cd..000000000 --- a/third_party/pygments/doc/docs/java.rst +++ /dev/null @@ -1,70 +0,0 @@ -===================== -Use Pygments in Java -===================== - -Thanks to `Jython `_ it is possible to use Pygments in -Java. - -This page is a simple tutorial to get an idea of how this works. You can -then look at the `Jython documentation `_ for more -advanced uses. - -Since version 1.5, Pygments is deployed on `Maven Central -`_ as a JAR, as is Jython -which makes it a lot easier to create a Java project. - -Here is an example of a `Maven `_ ``pom.xml`` file for a -project running Pygments: - -.. sourcecode:: xml - - - - - 4.0.0 - example - example - 1.0-SNAPSHOT - - - org.python - jython-standalone - 2.5.3 - - - org.pygments - pygments - 1.5 - runtime - - - - -The following Java example: - -.. sourcecode:: java - - PythonInterpreter interpreter = new PythonInterpreter(); - - // Set a variable with the content you want to work with - interpreter.set("code", code); - - // Simple use Pygments as you would in Python - interpreter.exec("from pygments import highlight\n" - + "from pygments.lexers import PythonLexer\n" - + "from pygments.formatters import HtmlFormatter\n" - + "\nresult = highlight(code, PythonLexer(), HtmlFormatter())"); - - // Get the result that has been set in a variable - System.out.println(interpreter.get("result", String.class)); - -will print something like: - -.. sourcecode:: html - -
      -
      print "Hello World"
      -
      diff --git a/third_party/pygments/doc/docs/lexerdevelopment.rst b/third_party/pygments/doc/docs/lexerdevelopment.rst deleted file mode 100644 index 2c8684407..000000000 --- a/third_party/pygments/doc/docs/lexerdevelopment.rst +++ /dev/null @@ -1,681 +0,0 @@ -.. -*- mode: rst -*- - -.. highlight:: python - -==================== -Write your own lexer -==================== - -If a lexer for your favorite language is missing in the Pygments package, you -can easily write your own and extend Pygments. - -All you need can be found inside the :mod:`pygments.lexer` module. As you can -read in the :doc:`API documentation `, a lexer is a class that is -initialized with some keyword arguments (the lexer options) and that provides a -:meth:`.get_tokens_unprocessed()` method which is given a string or unicode -object with the data to lex. - -The :meth:`.get_tokens_unprocessed()` method must return an iterator or iterable -containing tuples in the form ``(index, token, value)``. Normally you don't -need to do this since there are base lexers that do most of the work and that -you can subclass. - - -RegexLexer -========== - -The lexer base class used by almost all of Pygments' lexers is the -:class:`RegexLexer`. This class allows you to define lexing rules in terms of -*regular expressions* for different *states*. - -States are groups of regular expressions that are matched against the input -string at the *current position*. If one of these expressions matches, a -corresponding action is performed (such as yielding a token with a specific -type, or changing state), the current position is set to where the last match -ended and the matching process continues with the first regex of the current -state. - -Lexer states are kept on a stack: each time a new state is entered, the new -state is pushed onto the stack. The most basic lexers (like the `DiffLexer`) -just need one state. - -Each state is defined as a list of tuples in the form (`regex`, `action`, -`new_state`) where the last item is optional. In the most basic form, `action` -is a token type (like `Name.Builtin`). That means: When `regex` matches, emit a -token with the match text and type `tokentype` and push `new_state` on the state -stack. If the new state is ``'#pop'``, the topmost state is popped from the -stack instead. To pop more than one state, use ``'#pop:2'`` and so on. -``'#push'`` is a synonym for pushing the current state on the stack. - -The following example shows the `DiffLexer` from the builtin lexers. Note that -it contains some additional attributes `name`, `aliases` and `filenames` which -aren't required for a lexer. They are used by the builtin lexer lookup -functions. :: - - from pygments.lexer import RegexLexer - from pygments.token import * - - class DiffLexer(RegexLexer): - name = 'Diff' - aliases = ['diff'] - filenames = ['*.diff'] - - tokens = { - 'root': [ - (r' .*\n', Text), - (r'\+.*\n', Generic.Inserted), - (r'-.*\n', Generic.Deleted), - (r'@.*\n', Generic.Subheading), - (r'Index.*\n', Generic.Heading), - (r'=.*\n', Generic.Heading), - (r'.*\n', Text), - ] - } - -As you can see this lexer only uses one state. When the lexer starts scanning -the text, it first checks if the current character is a space. If this is true -it scans everything until newline and returns the data as a `Text` token (which -is the "no special highlighting" token). - -If this rule doesn't match, it checks if the current char is a plus sign. And -so on. - -If no rule matches at the current position, the current char is emitted as an -`Error` token that indicates a lexing error, and the position is increased by -one. - - -Adding and testing a new lexer -============================== - -To make Pygments aware of your new lexer, you have to perform the following -steps: - -First, change to the current directory containing the Pygments source code: - -.. code-block:: console - - $ cd .../pygments-main - -Select a matching module under ``pygments/lexers``, or create a new module for -your lexer class. - -Next, make sure the lexer is known from outside of the module. All modules in -the ``pygments.lexers`` specify ``__all__``. For example, ``esoteric.py`` sets:: - - __all__ = ['BrainfuckLexer', 'BefungeLexer', ...] - -Simply add the name of your lexer class to this list. - -Finally the lexer can be made publicly known by rebuilding the lexer mapping: - -.. code-block:: console - - $ make mapfiles - -To test the new lexer, store an example file with the proper extension in -``tests/examplefiles``. For example, to test your ``DiffLexer``, add a -``tests/examplefiles/example.diff`` containing a sample diff output. - -Now you can use pygmentize to render your example to HTML: - -.. code-block:: console - - $ ./pygmentize -O full -f html -o /tmp/example.html tests/examplefiles/example.diff - -Note that this explicitly calls the ``pygmentize`` in the current directory -by preceding it with ``./``. This ensures your modifications are used. -Otherwise a possibly already installed, unmodified version without your new -lexer would have been called from the system search path (``$PATH``). - -To view the result, open ``/tmp/example.html`` in your browser. - -Once the example renders as expected, you should run the complete test suite: - -.. code-block:: console - - $ make test - -It also tests that your lexer fulfills the lexer API and certain invariants, -such as that the concatenation of all token text is the same as the input text. - - -Regex Flags -=========== - -You can either define regex flags locally in the regex (``r'(?x)foo bar'``) or -globally by adding a `flags` attribute to your lexer class. If no attribute is -defined, it defaults to `re.MULTILINE`. For more information about regular -expression flags see the page about `regular expressions`_ in the Python -documentation. - -.. _regular expressions: http://docs.python.org/library/re.html#regular-expression-syntax - - -Scanning multiple tokens at once -================================ - -So far, the `action` element in the rule tuple of regex, action and state has -been a single token type. Now we look at the first of several other possible -values. - -Here is a more complex lexer that highlights INI files. INI files consist of -sections, comments and ``key = value`` pairs:: - - from pygments.lexer import RegexLexer, bygroups - from pygments.token import * - - class IniLexer(RegexLexer): - name = 'INI' - aliases = ['ini', 'cfg'] - filenames = ['*.ini', '*.cfg'] - - tokens = { - 'root': [ - (r'\s+', Text), - (r';.*?$', Comment), - (r'\[.*?\]$', Keyword), - (r'(.*?)(\s*)(=)(\s*)(.*?)$', - bygroups(Name.Attribute, Text, Operator, Text, String)) - ] - } - -The lexer first looks for whitespace, comments and section names. Later it -looks for a line that looks like a key, value pair, separated by an ``'='`` -sign, and optional whitespace. - -The `bygroups` helper yields each capturing group in the regex with a different -token type. First the `Name.Attribute` token, then a `Text` token for the -optional whitespace, after that a `Operator` token for the equals sign. Then a -`Text` token for the whitespace again. The rest of the line is returned as -`String`. - -Note that for this to work, every part of the match must be inside a capturing -group (a ``(...)``), and there must not be any nested capturing groups. If you -nevertheless need a group, use a non-capturing group defined using this syntax: -``(?:some|words|here)`` (note the ``?:`` after the beginning parenthesis). - -If you find yourself needing a capturing group inside the regex which shouldn't -be part of the output but is used in the regular expressions for backreferencing -(eg: ``r'(<(foo|bar)>)(.*?)()'``), you can pass `None` to the bygroups -function and that group will be skipped in the output. - - -Changing states -=============== - -Many lexers need multiple states to work as expected. For example, some -languages allow multiline comments to be nested. Since this is a recursive -pattern it's impossible to lex just using regular expressions. - -Here is a lexer that recognizes C++ style comments (multi-line with ``/* */`` -and single-line with ``//`` until end of line):: - - from pygments.lexer import RegexLexer - from pygments.token import * - - class CppCommentLexer(RegexLexer): - name = 'Example Lexer with states' - - tokens = { - 'root': [ - (r'[^/]+', Text), - (r'/\*', Comment.Multiline, 'comment'), - (r'//.*?$', Comment.Singleline), - (r'/', Text) - ], - 'comment': [ - (r'[^*/]', Comment.Multiline), - (r'/\*', Comment.Multiline, '#push'), - (r'\*/', Comment.Multiline, '#pop'), - (r'[*/]', Comment.Multiline) - ] - } - -This lexer starts lexing in the ``'root'`` state. It tries to match as much as -possible until it finds a slash (``'/'``). If the next character after the slash -is an asterisk (``'*'``) the `RegexLexer` sends those two characters to the -output stream marked as `Comment.Multiline` and continues lexing with the rules -defined in the ``'comment'`` state. - -If there wasn't an asterisk after the slash, the `RegexLexer` checks if it's a -Singleline comment (i.e. followed by a second slash). If this also wasn't the -case it must be a single slash, which is not a comment starter (the separate -regex for a single slash must also be given, else the slash would be marked as -an error token). - -Inside the ``'comment'`` state, we do the same thing again. Scan until the -lexer finds a star or slash. If it's the opening of a multiline comment, push -the ``'comment'`` state on the stack and continue scanning, again in the -``'comment'`` state. Else, check if it's the end of the multiline comment. If -yes, pop one state from the stack. - -Note: If you pop from an empty stack you'll get an `IndexError`. (There is an -easy way to prevent this from happening: don't ``'#pop'`` in the root state). - -If the `RegexLexer` encounters a newline that is flagged as an error token, the -stack is emptied and the lexer continues scanning in the ``'root'`` state. This -can help producing error-tolerant highlighting for erroneous input, e.g. when a -single-line string is not closed. - - -Advanced state tricks -===================== - -There are a few more things you can do with states: - -- You can push multiple states onto the stack if you give a tuple instead of a - simple string as the third item in a rule tuple. For example, if you want to - match a comment containing a directive, something like: - - .. code-block:: text - - /* rest of comment */ - - you can use this rule:: - - tokens = { - 'root': [ - (r'/\* <', Comment, ('comment', 'directive')), - ... - ], - 'directive': [ - (r'[^>]*', Comment.Directive), - (r'>', Comment, '#pop'), - ], - 'comment': [ - (r'[^*]+', Comment), - (r'\*/', Comment, '#pop'), - (r'\*', Comment), - ] - } - - When this encounters the above sample, first ``'comment'`` and ``'directive'`` - are pushed onto the stack, then the lexer continues in the directive state - until it finds the closing ``>``, then it continues in the comment state until - the closing ``*/``. Then, both states are popped from the stack again and - lexing continues in the root state. - - .. versionadded:: 0.9 - The tuple can contain the special ``'#push'`` and ``'#pop'`` (but not - ``'#pop:n'``) directives. - - -- You can include the rules of a state in the definition of another. This is - done by using `include` from `pygments.lexer`:: - - from pygments.lexer import RegexLexer, bygroups, include - from pygments.token import * - - class ExampleLexer(RegexLexer): - tokens = { - 'comments': [ - (r'/\*.*?\*/', Comment), - (r'//.*?\n', Comment), - ], - 'root': [ - include('comments'), - (r'(function )(\w+)( {)', - bygroups(Keyword, Name, Keyword), 'function'), - (r'.', Text), - ], - 'function': [ - (r'[^}/]+', Text), - include('comments'), - (r'/', Text), - (r'\}', Keyword, '#pop'), - ] - } - - This is a hypothetical lexer for a language that consist of functions and - comments. Because comments can occur at toplevel and in functions, we need - rules for comments in both states. As you can see, the `include` helper saves - repeating rules that occur more than once (in this example, the state - ``'comment'`` will never be entered by the lexer, as it's only there to be - included in ``'root'`` and ``'function'``). - -- Sometimes, you may want to "combine" a state from existing ones. This is - possible with the `combined` helper from `pygments.lexer`. - - If you, instead of a new state, write ``combined('state1', 'state2')`` as the - third item of a rule tuple, a new anonymous state will be formed from state1 - and state2 and if the rule matches, the lexer will enter this state. - - This is not used very often, but can be helpful in some cases, such as the - `PythonLexer`'s string literal processing. - -- If you want your lexer to start lexing in a different state you can modify the - stack by overriding the `get_tokens_unprocessed()` method:: - - from pygments.lexer import RegexLexer - - class ExampleLexer(RegexLexer): - tokens = {...} - - def get_tokens_unprocessed(self, text, stack=('root', 'otherstate')): - for item in RegexLexer.get_tokens_unprocessed(text, stack): - yield item - - Some lexers like the `PhpLexer` use this to make the leading ``', Name.Tag), - ], - 'script-content': [ - (r'(.+?)(<\s*/\s*script\s*>)', - bygroups(using(JavascriptLexer), Name.Tag), - '#pop'), - ] - } - -Here the content of a ```` end tag is processed by the `JavascriptLexer`, -while the end tag is yielded as a normal token with the `Name.Tag` type. - -Also note the ``(r'<\s*script\s*', Name.Tag, ('script-content', 'tag'))`` rule. -Here, two states are pushed onto the state stack, ``'script-content'`` and -``'tag'``. That means that first ``'tag'`` is processed, which will lex -attributes and the closing ``>``, then the ``'tag'`` state is popped and the -next state on top of the stack will be ``'script-content'``. - -Since you cannot refer to the class currently being defined, use `this` -(imported from `pygments.lexer`) to refer to the current lexer class, i.e. -``using(this)``. This construct may seem unnecessary, but this is often the -most obvious way of lexing arbitrary syntax between fixed delimiters without -introducing deeply nested states. - -The `using()` helper has a special keyword argument, `state`, which works as -follows: if given, the lexer to use initially is not in the ``"root"`` state, -but in the state given by this argument. This does not work with advanced -`RegexLexer` subclasses such as `ExtendedRegexLexer` (see below). - -Any other keywords arguments passed to `using()` are added to the keyword -arguments used to create the lexer. - - -Delegating Lexer -================ - -Another approach for nested lexers is the `DelegatingLexer` which is for example -used for the template engine lexers. It takes two lexers as arguments on -initialisation: a `root_lexer` and a `language_lexer`. - -The input is processed as follows: First, the whole text is lexed with the -`language_lexer`. All tokens yielded with the special type of ``Other`` are -then concatenated and given to the `root_lexer`. The language tokens of the -`language_lexer` are then inserted into the `root_lexer`'s token stream at the -appropriate positions. :: - - from pygments.lexer import DelegatingLexer - from pygments.lexers.web import HtmlLexer, PhpLexer - - class HtmlPhpLexer(DelegatingLexer): - def __init__(self, **options): - super(HtmlPhpLexer, self).__init__(HtmlLexer, PhpLexer, **options) - -This procedure ensures that e.g. HTML with template tags in it is highlighted -correctly even if the template tags are put into HTML tags or attributes. - -If you want to change the needle token ``Other`` to something else, you can give -the lexer another token type as the third parameter:: - - DelegatingLexer.__init__(MyLexer, OtherLexer, Text, **options) - - -Callbacks -========= - -Sometimes the grammar of a language is so complex that a lexer would be unable -to process it just by using regular expressions and stacks. - -For this, the `RegexLexer` allows callbacks to be given in rule tuples, instead -of token types (`bygroups` and `using` are nothing else but preimplemented -callbacks). The callback must be a function taking two arguments: - -* the lexer itself -* the match object for the last matched rule - -The callback must then return an iterable of (or simply yield) ``(index, -tokentype, value)`` tuples, which are then just passed through by -`get_tokens_unprocessed()`. The ``index`` here is the position of the token in -the input string, ``tokentype`` is the normal token type (like `Name.Builtin`), -and ``value`` the associated part of the input string. - -You can see an example here:: - - from pygments.lexer import RegexLexer - from pygments.token import Generic - - class HypotheticLexer(RegexLexer): - - def headline_callback(lexer, match): - equal_signs = match.group(1) - text = match.group(2) - yield match.start(), Generic.Headline, equal_signs + text + equal_signs - - tokens = { - 'root': [ - (r'(=+)(.*?)(\1)', headline_callback) - ] - } - -If the regex for the `headline_callback` matches, the function is called with -the match object. Note that after the callback is done, processing continues -normally, that is, after the end of the previous match. The callback has no -possibility to influence the position. - -There are not really any simple examples for lexer callbacks, but you can see -them in action e.g. in the `SMLLexer` class in `ml.py`_. - -.. _ml.py: http://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/ml.py - - -The ExtendedRegexLexer class -============================ - -The `RegexLexer`, even with callbacks, unfortunately isn't powerful enough for -the funky syntax rules of languages such as Ruby. - -But fear not; even then you don't have to abandon the regular expression -approach: Pygments has a subclass of `RegexLexer`, the `ExtendedRegexLexer`. -All features known from RegexLexers are available here too, and the tokens are -specified in exactly the same way, *except* for one detail: - -The `get_tokens_unprocessed()` method holds its internal state data not as local -variables, but in an instance of the `pygments.lexer.LexerContext` class, and -that instance is passed to callbacks as a third argument. This means that you -can modify the lexer state in callbacks. - -The `LexerContext` class has the following members: - -* `text` -- the input text -* `pos` -- the current starting position that is used for matching regexes -* `stack` -- a list containing the state stack -* `end` -- the maximum position to which regexes are matched, this defaults to - the length of `text` - -Additionally, the `get_tokens_unprocessed()` method can be given a -`LexerContext` instead of a string and will then process this context instead of -creating a new one for the string argument. - -Note that because you can set the current position to anything in the callback, -it won't be automatically be set by the caller after the callback is finished. -For example, this is how the hypothetical lexer above would be written with the -`ExtendedRegexLexer`:: - - from pygments.lexer import ExtendedRegexLexer - from pygments.token import Generic - - class ExHypotheticLexer(ExtendedRegexLexer): - - def headline_callback(lexer, match, ctx): - equal_signs = match.group(1) - text = match.group(2) - yield match.start(), Generic.Headline, equal_signs + text + equal_signs - ctx.pos = match.end() - - tokens = { - 'root': [ - (r'(=+)(.*?)(\1)', headline_callback) - ] - } - -This might sound confusing (and it can really be). But it is needed, and for an -example look at the Ruby lexer in `ruby.py`_. - -.. _ruby.py: https://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/ruby.py - - -Handling Lists of Keywords -========================== - -For a relatively short list (hundreds) you can construct an optimized regular -expression directly using ``words()`` (longer lists, see next section). This -function handles a few things for you automatically, including escaping -metacharacters and Python's first-match rather than longest-match in -alternations. Feel free to put the lists themselves in -``pygments/lexers/_$lang_builtins.py`` (see examples there), and generated by -code if possible. - -An example of using ``words()`` is something like:: - - from pygments.lexer import RegexLexer, words, Name - - class MyLexer(RegexLexer): - - tokens = { - 'root': [ - (words(('else', 'elseif'), suffix=r'\b'), Name.Builtin), - (r'\w+', Name), - ], - } - -As you can see, you can add ``prefix`` and ``suffix`` parts to the constructed -regex. - - -Modifying Token Streams -======================= - -Some languages ship a lot of builtin functions (for example PHP). The total -amount of those functions differs from system to system because not everybody -has every extension installed. In the case of PHP there are over 3000 builtin -functions. That's an incredibly huge amount of functions, much more than you -want to put into a regular expression. - -But because only `Name` tokens can be function names this is solvable by -overriding the ``get_tokens_unprocessed()`` method. The following lexer -subclasses the `PythonLexer` so that it highlights some additional names as -pseudo keywords:: - - from pygments.lexers.python import PythonLexer - from pygments.token import Name, Keyword - - class MyPythonLexer(PythonLexer): - EXTRA_KEYWORDS = set(('foo', 'bar', 'foobar', 'barfoo', 'spam', 'eggs')) - - def get_tokens_unprocessed(self, text): - for index, token, value in PythonLexer.get_tokens_unprocessed(self, text): - if token is Name and value in self.EXTRA_KEYWORDS: - yield index, Keyword.Pseudo, value - else: - yield index, token, value - -The `PhpLexer` and `LuaLexer` use this method to resolve builtin functions. diff --git a/third_party/pygments/doc/docs/lexers.rst b/third_party/pygments/doc/docs/lexers.rst deleted file mode 100644 index 9262efb04..000000000 --- a/third_party/pygments/doc/docs/lexers.rst +++ /dev/null @@ -1,69 +0,0 @@ -.. -*- mode: rst -*- - -================ -Available lexers -================ - -This page lists all available builtin lexers and the options they take. - -Currently, **all lexers** support these options: - -`stripnl` - Strip leading and trailing newlines from the input (default: ``True``) - -`stripall` - Strip all leading and trailing whitespace from the input (default: - ``False``). - -`ensurenl` - Make sure that the input ends with a newline (default: ``True``). This - is required for some lexers that consume input linewise. - - .. versionadded:: 1.3 - -`tabsize` - If given and greater than 0, expand tabs in the input (default: ``0``). - -`encoding` - If given, must be an encoding name (such as ``"utf-8"``). This encoding - will be used to convert the input string to Unicode (if it is not already - a Unicode string). The default is ``"guess"``. - - If this option is set to ``"guess"``, a simple UTF-8 vs. Latin-1 - detection is used, if it is set to ``"chardet"``, the - `chardet library `_ is used to - guess the encoding of the input. - - .. versionadded:: 0.6 - - -The "Short Names" field lists the identifiers that can be used with the -`get_lexer_by_name()` function. - -These lexers are builtin and can be imported from `pygments.lexers`: - -.. pygmentsdoc:: lexers - - -Iterating over all lexers -------------------------- - -.. versionadded:: 0.6 - -To get all lexers (both the builtin and the plugin ones), you can -use the `get_all_lexers()` function from the `pygments.lexers` -module: - -.. sourcecode:: pycon - - >>> from pygments.lexers import get_all_lexers - >>> i = get_all_lexers() - >>> i.next() - ('Diff', ('diff',), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')) - >>> i.next() - ('Delphi', ('delphi', 'objectpascal', 'pas', 'pascal'), ('*.pas',), ('text/x-pascal',)) - >>> i.next() - ('XML+Ruby', ('xml+erb', 'xml+ruby'), (), ()) - -As you can see, the return value is an iterator which yields tuples -in the form ``(name, aliases, filetypes, mimetypes)``. diff --git a/third_party/pygments/doc/docs/moinmoin.rst b/third_party/pygments/doc/docs/moinmoin.rst deleted file mode 100644 index 8b2216b3c..000000000 --- a/third_party/pygments/doc/docs/moinmoin.rst +++ /dev/null @@ -1,39 +0,0 @@ -.. -*- mode: rst -*- - -============================ -Using Pygments with MoinMoin -============================ - -From Pygments 0.7, the source distribution ships a `Moin`_ parser plugin that -can be used to get Pygments highlighting in Moin wiki pages. - -To use it, copy the file `external/moin-parser.py` from the Pygments -distribution to the `data/plugin/parser` subdirectory of your Moin instance. -Edit the options at the top of the file (currently ``ATTACHMENTS`` and -``INLINESTYLES``) and rename the file to the name that the parser directive -should have. For example, if you name the file ``code.py``, you can get a -highlighted Python code sample with this Wiki markup:: - - {{{ - #!code python - [...] - }}} - -where ``python`` is the Pygments name of the lexer to use. - -Additionally, if you set the ``ATTACHMENTS`` option to True, Pygments will also -be called for all attachments for whose filenames there is no other parser -registered. - -You are responsible for including CSS rules that will map the Pygments CSS -classes to colors. You can output a stylesheet file with `pygmentize`, put it -into the `htdocs` directory of your Moin instance and then include it in the -`stylesheets` configuration option in the Moin config, e.g.:: - - stylesheets = [('screen', '/htdocs/pygments.css')] - -If you do not want to do that and are willing to accept larger HTML output, you -can set the ``INLINESTYLES`` option to True. - - -.. _Moin: http://moinmoin.wikiwikiweb.de/ diff --git a/third_party/pygments/doc/docs/plugins.rst b/third_party/pygments/doc/docs/plugins.rst deleted file mode 100644 index a6f8d7b00..000000000 --- a/third_party/pygments/doc/docs/plugins.rst +++ /dev/null @@ -1,93 +0,0 @@ -================ -Register Plugins -================ - -If you want to extend Pygments without hacking the sources, but want to -use the lexer/formatter/style/filter lookup functions (`lexers.get_lexer_by_name` -et al.), you can use `setuptools`_ entrypoints to add new lexers, formatters -or styles as if they were in the Pygments core. - -.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools - -That means you can use your highlighter modules with the `pygmentize` script, -which relies on the mentioned functions. - - -Entrypoints -=========== - -Here is a list of setuptools entrypoints that Pygments understands: - -`pygments.lexers` - - This entrypoint is used for adding new lexers to the Pygments core. - The name of the entrypoint values doesn't really matter, Pygments extracts - required metadata from the class definition: - - .. sourcecode:: ini - - [pygments.lexers] - yourlexer = yourmodule:YourLexer - - Note that you have to define ``name``, ``aliases`` and ``filename`` - attributes so that you can use the highlighter from the command line: - - .. sourcecode:: python - - class YourLexer(...): - name = 'Name Of Your Lexer' - aliases = ['alias'] - filenames = ['*.ext'] - - -`pygments.formatters` - - You can use this entrypoint to add new formatters to Pygments. The - name of an entrypoint item is the name of the formatter. If you - prefix the name with a slash it's used as a filename pattern: - - .. sourcecode:: ini - - [pygments.formatters] - yourformatter = yourmodule:YourFormatter - /.ext = yourmodule:YourFormatter - - -`pygments.styles` - - To add a new style you can use this entrypoint. The name of the entrypoint - is the name of the style: - - .. sourcecode:: ini - - [pygments.styles] - yourstyle = yourmodule:YourStyle - - -`pygments.filters` - - Use this entrypoint to register a new filter. The name of the - entrypoint is the name of the filter: - - .. sourcecode:: ini - - [pygments.filters] - yourfilter = yourmodule:YourFilter - - -How To Use Entrypoints -====================== - -This documentation doesn't explain how to use those entrypoints because this is -covered in the `setuptools documentation`_. That page should cover everything -you need to write a plugin. - -.. _setuptools documentation: http://peak.telecommunity.com/DevCenter/setuptools - - -Extending The Core -================== - -If you have written a Pygments plugin that is open source, please inform us -about that. There is a high chance that we'll add it to the Pygments -distribution. diff --git a/third_party/pygments/doc/docs/quickstart.rst b/third_party/pygments/doc/docs/quickstart.rst deleted file mode 100644 index dba7698a7..000000000 --- a/third_party/pygments/doc/docs/quickstart.rst +++ /dev/null @@ -1,205 +0,0 @@ -.. -*- mode: rst -*- - -=========================== -Introduction and Quickstart -=========================== - - -Welcome to Pygments! This document explains the basic concepts and terms and -gives a few examples of how to use the library. - - -Architecture -============ - -There are four types of components that work together highlighting a piece of -code: - -* A **lexer** splits the source into tokens, fragments of the source that - have a token type that determines what the text represents semantically - (e.g., keyword, string, or comment). There is a lexer for every language - or markup format that Pygments supports. -* The token stream can be piped through **filters**, which usually modify - the token types or text fragments, e.g. uppercasing all keywords. -* A **formatter** then takes the token stream and writes it to an output - file, in a format such as HTML, LaTeX or RTF. -* While writing the output, a **style** determines how to highlight all the - different token types. It maps them to attributes like "red and bold". - - -Example -======= - -Here is a small example for highlighting Python code: - -.. sourcecode:: python - - from pygments import highlight - from pygments.lexers import PythonLexer - from pygments.formatters import HtmlFormatter - - code = 'print "Hello World"' - print highlight(code, PythonLexer(), HtmlFormatter()) - -which prints something like this: - -.. sourcecode:: html - -
      -
      print "Hello World"
      -
      - -As you can see, Pygments uses CSS classes (by default, but you can change that) -instead of inline styles in order to avoid outputting redundant style information over -and over. A CSS stylesheet that contains all CSS classes possibly used in the output -can be produced by: - -.. sourcecode:: python - - print HtmlFormatter().get_style_defs('.highlight') - -The argument to :func:`get_style_defs` is used as an additional CSS selector: -the output may look like this: - -.. sourcecode:: css - - .highlight .k { color: #AA22FF; font-weight: bold } - .highlight .s { color: #BB4444 } - ... - - -Options -======= - -The :func:`highlight()` function supports a fourth argument called *outfile*, it -must be a file object if given. The formatted output will then be written to -this file instead of being returned as a string. - -Lexers and formatters both support options. They are given to them as keyword -arguments either to the class or to the lookup method: - -.. sourcecode:: python - - from pygments import highlight - from pygments.lexers import get_lexer_by_name - from pygments.formatters import HtmlFormatter - - lexer = get_lexer_by_name("python", stripall=True) - formatter = HtmlFormatter(linenos=True, cssclass="source") - result = highlight(code, lexer, formatter) - -This makes the lexer strip all leading and trailing whitespace from the input -(`stripall` option), lets the formatter output line numbers (`linenos` option), -and sets the wrapping ``
      ``'s class to ``source`` (instead of -``highlight``). - -Important options include: - -`encoding` : for lexers and formatters - Since Pygments uses Unicode strings internally, this determines which - encoding will be used to convert to or from byte strings. -`style` : for formatters - The name of the style to use when writing the output. - - -For an overview of builtin lexers and formatters and their options, visit the -:doc:`lexer ` and :doc:`formatters ` lists. - -For a documentation on filters, see :doc:`this page `. - - -Lexer and formatter lookup -========================== - -If you want to lookup a built-in lexer by its alias or a filename, you can use -one of the following methods: - -.. sourcecode:: pycon - - >>> from pygments.lexers import (get_lexer_by_name, - ... get_lexer_for_filename, get_lexer_for_mimetype) - - >>> get_lexer_by_name('python') - - - >>> get_lexer_for_filename('spam.rb') - - - >>> get_lexer_for_mimetype('text/x-perl') - - -All these functions accept keyword arguments; they will be passed to the lexer -as options. - -A similar API is available for formatters: use :func:`.get_formatter_by_name()` -and :func:`.get_formatter_for_filename()` from the :mod:`pygments.formatters` -module for this purpose. - - -Guessing lexers -=============== - -If you don't know the content of the file, or you want to highlight a file -whose extension is ambiguous, such as ``.html`` (which could contain plain HTML -or some template tags), use these functions: - -.. sourcecode:: pycon - - >>> from pygments.lexers import guess_lexer, guess_lexer_for_filename - - >>> guess_lexer('#!/usr/bin/python\nprint "Hello World!"') - - - >>> guess_lexer_for_filename('test.py', 'print "Hello World!"') - - -:func:`.guess_lexer()` passes the given content to the lexer classes' -:meth:`analyse_text()` method and returns the one for which it returns the -highest number. - -All lexers have two different filename pattern lists: the primary and the -secondary one. The :func:`.get_lexer_for_filename()` function only uses the -primary list, whose entries are supposed to be unique among all lexers. -:func:`.guess_lexer_for_filename()`, however, will first loop through all lexers -and look at the primary and secondary filename patterns if the filename matches. -If only one lexer matches, it is returned, else the guessing mechanism of -:func:`.guess_lexer()` is used with the matching lexers. - -As usual, keyword arguments to these functions are given to the created lexer -as options. - - -Command line usage -================== - -You can use Pygments from the command line, using the :program:`pygmentize` -script:: - - $ pygmentize test.py - -will highlight the Python file test.py using ANSI escape sequences -(a.k.a. terminal colors) and print the result to standard output. - -To output HTML, use the ``-f`` option:: - - $ pygmentize -f html -o test.html test.py - -to write an HTML-highlighted version of test.py to the file test.html. -Note that it will only be a snippet of HTML, if you want a full HTML document, -use the "full" option:: - - $ pygmentize -f html -O full -o test.html test.py - -This will produce a full HTML document with included stylesheet. - -A style can be selected with ``-O style=``. - -If you need a stylesheet for an existing HTML file using Pygments CSS classes, -it can be created with:: - - $ pygmentize -S default -f html > style.css - -where ``default`` is the style name. - -More options and tricks and be found in the :doc:`command line reference -`. diff --git a/third_party/pygments/doc/docs/rstdirective.rst b/third_party/pygments/doc/docs/rstdirective.rst deleted file mode 100644 index c0d503b3d..000000000 --- a/third_party/pygments/doc/docs/rstdirective.rst +++ /dev/null @@ -1,22 +0,0 @@ -.. -*- mode: rst -*- - -================================ -Using Pygments in ReST documents -================================ - -Many Python people use `ReST`_ for documentation their sourcecode, programs, -scripts et cetera. This also means that documentation often includes sourcecode -samples or snippets. - -You can easily enable Pygments support for your ReST texts using a custom -directive -- this is also how this documentation displays source code. - -From Pygments 0.9, the directive is shipped in the distribution as -`external/rst-directive.py`. You can copy and adapt this code to your liking. - -.. removed -- too confusing - *Loosely related note:* The ReST lexer now recognizes ``.. sourcecode::`` and - ``.. code::`` directives and highlights the contents in the specified language - if the `handlecodeblocks` option is true. - -.. _ReST: http://docutils.sf.net/rst.html diff --git a/third_party/pygments/doc/docs/styles.rst b/third_party/pygments/doc/docs/styles.rst deleted file mode 100644 index d56db0db4..000000000 --- a/third_party/pygments/doc/docs/styles.rst +++ /dev/null @@ -1,145 +0,0 @@ -.. -*- mode: rst -*- - -====== -Styles -====== - -Pygments comes with some builtin styles that work for both the HTML and -LaTeX formatter. - -The builtin styles can be looked up with the `get_style_by_name` function: - -.. sourcecode:: pycon - - >>> from pygments.styles import get_style_by_name - >>> get_style_by_name('colorful') - - -You can pass a instance of a `Style` class to a formatter as the `style` -option in form of a string: - -.. sourcecode:: pycon - - >>> from pygments.styles import get_style_by_name - >>> from pygments.formatters import HtmlFormatter - >>> HtmlFormatter(style='colorful').style - - -Or you can also import your own style (which must be a subclass of -`pygments.style.Style`) and pass it to the formatter: - -.. sourcecode:: pycon - - >>> from yourapp.yourmodule import YourStyle - >>> from pygments.formatters import HtmlFormatter - >>> HtmlFormatter(style=YourStyle).style - - - -Creating Own Styles -=================== - -So, how to create a style? All you have to do is to subclass `Style` and -define some styles: - -.. sourcecode:: python - - from pygments.style import Style - from pygments.token import Keyword, Name, Comment, String, Error, \ - Number, Operator, Generic - - class YourStyle(Style): - default_style = "" - styles = { - Comment: 'italic #888', - Keyword: 'bold #005', - Name: '#f00', - Name.Function: '#0f0', - Name.Class: 'bold #0f0', - String: 'bg:#eee #111' - } - -That's it. There are just a few rules. When you define a style for `Name` -the style automatically also affects `Name.Function` and so on. If you -defined ``'bold'`` and you don't want boldface for a subtoken use ``'nobold'``. - -(Philosophy: the styles aren't written in CSS syntax since this way -they can be used for a variety of formatters.) - -`default_style` is the style inherited by all token types. - -To make the style usable for Pygments, you must - -* either register it as a plugin (see :doc:`the plugin docs `) -* or drop it into the `styles` subpackage of your Pygments distribution one style - class per style, where the file name is the style name and the class name is - `StylenameClass`. For example, if your style should be called - ``"mondrian"``, name the class `MondrianStyle`, put it into the file - ``mondrian.py`` and this file into the ``pygments.styles`` subpackage - directory. - - -Style Rules -=========== - -Here a small overview of all allowed styles: - -``bold`` - render text as bold -``nobold`` - don't render text as bold (to prevent subtokens being highlighted bold) -``italic`` - render text italic -``noitalic`` - don't render text as italic -``underline`` - render text underlined -``nounderline`` - don't render text underlined -``bg:`` - transparent background -``bg:#000000`` - background color (black) -``border:`` - no border -``border:#ffffff`` - border color (white) -``#ff0000`` - text color (red) -``noinherit`` - don't inherit styles from supertoken - -Note that there may not be a space between ``bg:`` and the color value -since the style definition string is split at whitespace. -Also, using named colors is not allowed since the supported color names -vary for different formatters. - -Furthermore, not all lexers might support every style. - - -Builtin Styles -============== - -Pygments ships some builtin styles which are maintained by the Pygments team. - -To get a list of known styles you can use this snippet: - -.. sourcecode:: pycon - - >>> from pygments.styles import STYLE_MAP - >>> STYLE_MAP.keys() - ['default', 'emacs', 'friendly', 'colorful'] - - -Getting a list of available styles -================================== - -.. versionadded:: 0.6 - -Because it could be that a plugin registered a style, there is -a way to iterate over all styles: - -.. sourcecode:: pycon - - >>> from pygments.styles import get_all_styles - >>> styles = list(get_all_styles()) diff --git a/third_party/pygments/doc/docs/tokens.rst b/third_party/pygments/doc/docs/tokens.rst deleted file mode 100644 index 6455a5012..000000000 --- a/third_party/pygments/doc/docs/tokens.rst +++ /dev/null @@ -1,356 +0,0 @@ -.. -*- mode: rst -*- - -============== -Builtin Tokens -============== - -.. module:: pygments.token - -In the :mod:`pygments.token` module, there is a special object called `Token` -that is used to create token types. - -You can create a new token type by accessing an attribute of `Token`: - -.. sourcecode:: pycon - - >>> from pygments.token import Token - >>> Token.String - Token.String - >>> Token.String is Token.String - True - -Note that tokens are singletons so you can use the ``is`` operator for comparing -token types. - -As of Pygments 0.7 you can also use the ``in`` operator to perform set tests: - -.. sourcecode:: pycon - - >>> from pygments.token import Comment - >>> Comment.Single in Comment - True - >>> Comment in Comment.Multi - False - -This can be useful in :doc:`filters ` and if you write lexers on your -own without using the base lexers. - -You can also split a token type into a hierarchy, and get the parent of it: - -.. sourcecode:: pycon - - >>> String.split() - [Token, Token.Literal, Token.Literal.String] - >>> String.parent - Token.Literal - -In principle, you can create an unlimited number of token types but nobody can -guarantee that a style would define style rules for a token type. Because of -that, Pygments proposes some global token types defined in the -`pygments.token.STANDARD_TYPES` dict. - -For some tokens aliases are already defined: - -.. sourcecode:: pycon - - >>> from pygments.token import String - >>> String - Token.Literal.String - -Inside the :mod:`pygments.token` module the following aliases are defined: - -============= ============================ ==================================== -`Text` `Token.Text` for any type of text data -`Whitespace` `Token.Text.Whitespace` for specially highlighted whitespace -`Error` `Token.Error` represents lexer errors -`Other` `Token.Other` special token for data not - matched by a parser (e.g. HTML - markup in PHP code) -`Keyword` `Token.Keyword` any kind of keywords -`Name` `Token.Name` variable/function names -`Literal` `Token.Literal` Any literals -`String` `Token.Literal.String` string literals -`Number` `Token.Literal.Number` number literals -`Operator` `Token.Operator` operators (``+``, ``not``...) -`Punctuation` `Token.Punctuation` punctuation (``[``, ``(``...) -`Comment` `Token.Comment` any kind of comments -`Generic` `Token.Generic` generic tokens (have a look at - the explanation below) -============= ============================ ==================================== - -The `Whitespace` token type is new in Pygments 0.8. It is used only by the -`VisibleWhitespaceFilter` currently. - -Normally you just create token types using the already defined aliases. For each -of those token aliases, a number of subtypes exists (excluding the special tokens -`Token.Text`, `Token.Error` and `Token.Other`) - -The `is_token_subtype()` function in the `pygments.token` module can be used to -test if a token type is a subtype of another (such as `Name.Tag` and `Name`). -(This is the same as ``Name.Tag in Name``. The overloaded `in` operator was newly -introduced in Pygments 0.7, the function still exists for backwards -compatibility.) - -With Pygments 0.7, it's also possible to convert strings to token types (for example -if you want to supply a token from the command line): - -.. sourcecode:: pycon - - >>> from pygments.token import String, string_to_tokentype - >>> string_to_tokentype("String") - Token.Literal.String - >>> string_to_tokentype("Token.Literal.String") - Token.Literal.String - >>> string_to_tokentype(String) - Token.Literal.String - - -Keyword Tokens -============== - -`Keyword` - For any kind of keyword (especially if it doesn't match any of the - subtypes of course). - -`Keyword.Constant` - For keywords that are constants (e.g. ``None`` in future Python versions). - -`Keyword.Declaration` - For keywords used for variable declaration (e.g. ``var`` in some programming - languages like JavaScript). - -`Keyword.Namespace` - For keywords used for namespace declarations (e.g. ``import`` in Python and - Java and ``package`` in Java). - -`Keyword.Pseudo` - For keywords that aren't really keywords (e.g. ``None`` in old Python - versions). - -`Keyword.Reserved` - For reserved keywords. - -`Keyword.Type` - For builtin types that can't be used as identifiers (e.g. ``int``, - ``char`` etc. in C). - - -Name Tokens -=========== - -`Name` - For any name (variable names, function names, classes). - -`Name.Attribute` - For all attributes (e.g. in HTML tags). - -`Name.Builtin` - Builtin names; names that are available in the global namespace. - -`Name.Builtin.Pseudo` - Builtin names that are implicit (e.g. ``self`` in Ruby, ``this`` in Java). - -`Name.Class` - Class names. Because no lexer can know if a name is a class or a function - or something else this token is meant for class declarations. - -`Name.Constant` - Token type for constants. In some languages you can recognise a token by the - way it's defined (the value after a ``const`` keyword for example). In - other languages constants are uppercase by definition (Ruby). - -`Name.Decorator` - Token type for decorators. Decorators are syntactic elements in the Python - language. Similar syntax elements exist in C# and Java. - -`Name.Entity` - Token type for special entities. (e.g. `` `` in HTML). - -`Name.Exception` - Token type for exception names (e.g. ``RuntimeError`` in Python). Some languages - define exceptions in the function signature (Java). You can highlight - the name of that exception using this token then. - -`Name.Function` - Token type for function names. - -`Name.Label` - Token type for label names (e.g. in languages that support ``goto``). - -`Name.Namespace` - Token type for namespaces. (e.g. import paths in Java/Python), names following - the ``module``/``namespace`` keyword in other languages. - -`Name.Other` - Other names. Normally unused. - -`Name.Tag` - Tag names (in HTML/XML markup or configuration files). - -`Name.Variable` - Token type for variables. Some languages have prefixes for variable names - (PHP, Ruby, Perl). You can highlight them using this token. - -`Name.Variable.Class` - same as `Name.Variable` but for class variables (also static variables). - -`Name.Variable.Global` - same as `Name.Variable` but for global variables (used in Ruby, for - example). - -`Name.Variable.Instance` - same as `Name.Variable` but for instance variables. - - -Literals -======== - -`Literal` - For any literal (if not further defined). - -`Literal.Date` - for date literals (e.g. ``42d`` in Boo). - - -`String` - For any string literal. - -`String.Backtick` - Token type for strings enclosed in backticks. - -`String.Char` - Token type for single characters (e.g. Java, C). - -`String.Doc` - Token type for documentation strings (for example Python). - -`String.Double` - Double quoted strings. - -`String.Escape` - Token type for escape sequences in strings. - -`String.Heredoc` - Token type for "heredoc" strings (e.g. in Ruby or Perl). - -`String.Interpol` - Token type for interpolated parts in strings (e.g. ``#{foo}`` in Ruby). - -`String.Other` - Token type for any other strings (for example ``%q{foo}`` string constructs - in Ruby). - -`String.Regex` - Token type for regular expression literals (e.g. ``/foo/`` in JavaScript). - -`String.Single` - Token type for single quoted strings. - -`String.Symbol` - Token type for symbols (e.g. ``:foo`` in LISP or Ruby). - - -`Number` - Token type for any number literal. - -`Number.Bin` - Token type for binary literals (e.g. ``0b101010``). - -`Number.Float` - Token type for float literals (e.g. ``42.0``). - -`Number.Hex` - Token type for hexadecimal number literals (e.g. ``0xdeadbeef``). - -`Number.Integer` - Token type for integer literals (e.g. ``42``). - -`Number.Integer.Long` - Token type for long integer literals (e.g. ``42L`` in Python). - -`Number.Oct` - Token type for octal literals. - - -Operators -========= - -`Operator` - For any punctuation operator (e.g. ``+``, ``-``). - -`Operator.Word` - For any operator that is a word (e.g. ``not``). - - -Punctuation -=========== - -.. versionadded:: 0.7 - -`Punctuation` - For any punctuation which is not an operator (e.g. ``[``, ``(``...) - - -Comments -======== - -`Comment` - Token type for any comment. - -`Comment.Hashbang` - Token type for hashbang comments (i.e. first lines of files that start with - ``#!``). - -`Comment.Multiline` - Token type for multiline comments. - -`Comment.Preproc` - Token type for preprocessor comments (also ```. - -.. versionadded:: 0.7 - The formatters now also accept an `outencoding` option which will override - the `encoding` option if given. This makes it possible to use a single - options dict with lexers and formatters, and still have different input and - output encodings. - -.. _chardet: http://chardet.feedparser.org/ diff --git a/third_party/pygments/doc/download.rst b/third_party/pygments/doc/download.rst deleted file mode 100644 index cf32f481a..000000000 --- a/third_party/pygments/doc/download.rst +++ /dev/null @@ -1,41 +0,0 @@ -Download and installation -========================= - -The current release is version |version|. - -Packaged versions ------------------ - -You can download it `from the Python Package Index -`_. For installation of packages from -PyPI, we recommend `Pip `_, which works on all -major platforms. - -Under Linux, most distributions include a package for Pygments, usually called -``pygments`` or ``python-pygments``. You can install it with the package -manager as usual. - -Development sources -------------------- - -We're using the `Mercurial `_ version control -system. You can get the development source using this command:: - - hg clone http://bitbucket.org/birkenfeld/pygments-main pygments - -Development takes place at `Bitbucket -`_, you can browse the source -online `here `_. - -The latest changes in the development source code are listed in the `changelog -`_. - -.. Documentation - ------------- - -.. XXX todo - - You can download the documentation either as - a bunch of rst files from the Mercurial repository, see above, or - as a tar.gz containing rendered HTML files:

      -

      pygmentsdocs.tar.gz

      diff --git a/third_party/pygments/doc/faq.rst b/third_party/pygments/doc/faq.rst deleted file mode 100644 index f375828ba..000000000 --- a/third_party/pygments/doc/faq.rst +++ /dev/null @@ -1,139 +0,0 @@ -:orphan: - -Pygments FAQ -============= - -What is Pygments? ------------------ - -Pygments is a syntax highlighting engine written in Python. That means, it will -take source code (or other markup) in a supported language and output a -processed version (in different formats) containing syntax highlighting markup. - -Its features include: - -* a wide range of common :doc:`languages and markup formats ` is supported -* new languages and formats are added easily -* a number of output formats is available, including: - - - HTML - - ANSI sequences (console output) - - LaTeX - - RTF - -* it is usable as a command-line tool and as a library -* parsing and formatting is fast - -Pygments is licensed under the BSD license. - -Where does the name Pygments come from? ---------------------------------------- - -*Py* of course stands for Python, while *pigments* are used for coloring paint, -and in this case, source code! - -What are the system requirements? ---------------------------------- - -Pygments only needs a standard Python install, version 2.6 or higher or version -3.3 or higher for Python 3. No additional libraries are needed. - -How can I use Pygments? ------------------------ - -Pygments is usable as a command-line tool as well as a library. - -From the command-line, usage looks like this (assuming the pygmentize script is -properly installed):: - - pygmentize -f html /path/to/file.py - -This will print a HTML-highlighted version of /path/to/file.py to standard output. - -For a complete help, please run ``pygmentize -h``. - -Usage as a library is thoroughly demonstrated in the Documentation section. - -How do I make a new style? --------------------------- - -Please see the :doc:`documentation on styles `. - -How can I report a bug or suggest a feature? --------------------------------------------- - -Please report bugs and feature wishes in the tracker at Bitbucket. - -You can also e-mail the author or use IRC, see the contact details. - -I want this support for this language! --------------------------------------- - -Instead of waiting for others to include language support, why not write it -yourself? All you have to know is :doc:`outlined in the docs -`. - -Can I use Pygments for programming language processing? -------------------------------------------------------- - -The Pygments lexing machinery is quite powerful can be used to build lexers for -basically all languages. However, parsing them is not possible, though some -lexers go some steps in this direction in order to e.g. highlight function names -differently. - -Also, error reporting is not the scope of Pygments. It focuses on correctly -highlighting syntactically valid documents, not finding and compensating errors. - -Who uses Pygments? ------------------- - -This is an (incomplete) list of projects and sites known to use the Pygments highlighter. - -* `Wikipedia `_ -* `BitBucket `_, a Mercurial and Git hosting site -* `The Sphinx documentation builder `_, for embedded source examples -* `rst2pdf `_, a reStructuredText to PDF converter -* `Codecov `_, a code coverage CI service -* `Trac `_, the universal project management tool -* `AsciiDoc `_, a text-based documentation generator -* `ActiveState Code `_, the Python Cookbook successor -* `ViewVC `_, a web-based version control repository browser -* `BzrFruit `_, a Bazaar branch viewer -* `QBzr `_, a cross-platform Qt-based GUI front end for Bazaar -* `Review Board `_, a collaborative code reviewing tool -* `Diamanda `_, a Django powered wiki system with support for Pygments -* `Progopedia `_ (`English `_), - an encyclopedia of programming languages -* `Bruce `_, a reStructuredText presentation tool -* `PIDA `_, a universal IDE written in Python -* `BPython `_, a curses-based intelligent Python shell -* `PuDB `_, a console Python debugger -* `XWiki `_, a wiki-based development framework in Java, using Jython -* `roux `_, a script for running R scripts - and creating beautiful output including graphs -* `hurl `_, a web service for making HTTP requests -* `wxHTMLPygmentizer `_ is - a GUI utility, used to make code-colorization easier -* `Postmarkup `_, a BBCode to XHTML generator -* `WpPygments `_, and `WPygments - `_, highlighter plugins for WordPress -* `Siafoo `_, a tool for sharing and storing useful code and programming experience -* `D source `_, a community for the D programming language -* `dpaste.com `_, another Django pastebin -* `Django snippets `_, a pastebin for Django code -* `Fayaa `_, a Chinese pastebin -* `Incollo.com `_, a free collaborative debugging tool -* `PasteBox `_, a pastebin focused on privacy -* `hilite.me `_, a site to highlight code snippets -* `patx.me `_, a pastebin -* `Fluidic `_, an experiment in - integrating shells with a GUI -* `pygments.rb `_, a pygments wrapper for Ruby -* `Clygments `_, a pygments wrapper for - Clojure -* `PHPygments `_, a pygments wrapper for PHP - - -If you have a project or web site using Pygments, drop me a line, and I'll add a -link here. - diff --git a/third_party/pygments/doc/index.rst b/third_party/pygments/doc/index.rst deleted file mode 100644 index 261140459..000000000 --- a/third_party/pygments/doc/index.rst +++ /dev/null @@ -1,54 +0,0 @@ -Welcome! -======== - -This is the home of Pygments. It is a generic syntax highlighter suitable for -use in code hosting, forums, wikis or other applications that need to prettify -source code. Highlights are: - -* a wide range of over 300 languages and other text formats is supported -* special attention is paid to details that increase highlighting quality -* support for new languages and formats are added easily; most languages use a - simple regex-based lexing mechanism -* a number of output formats is available, among them HTML, RTF, LaTeX and ANSI - sequences -* it is usable as a command-line tool and as a library -* ... and it highlights even Perl 6! - -Read more in the :doc:`FAQ list ` or the :doc:`documentation `, -or `download the latest release `_. - -.. _contribute: - -Contribute ----------- - -Like every open-source project, we are always looking for volunteers to help us -with programming. Python knowledge is required, but don't fear: Python is a very -clear and easy to learn language. - -Development takes place on `Bitbucket -`_, where the Mercurial -repository, tickets and pull requests can be viewed. - -Our primary communication instrument is the IRC channel **#pocoo** on the -Freenode network. To join it, let your IRC client connect to -``irc.freenode.net`` and do ``/join #pocoo``. - -If you found a bug, just open a ticket in the Bitbucket tracker. Be sure to log -in to be notified when the issue is fixed -- development is not fast-paced as -the library is quite stable. You can also send an e-mail to the developers, see -below. - -The authors ------------ - -Pygments is maintained by **Georg Brandl**, e-mail address *georg*\ *@*\ *python.org*. - -Many lexers and fixes have been contributed by **Armin Ronacher**, the rest of -the `Pocoo `_ team and **Tim Hatch**. - -.. toctree:: - :maxdepth: 1 - :hidden: - - docs/index diff --git a/third_party/pygments/doc/languages.rst b/third_party/pygments/doc/languages.rst deleted file mode 100644 index a495d15c4..000000000 --- a/third_party/pygments/doc/languages.rst +++ /dev/null @@ -1,152 +0,0 @@ -:orphan: - -Supported languages -=================== - -Pygments supports an ever-growing range of languages. Watch this space... - -Programming languages ---------------------- - -* ActionScript -* Ada -* ANTLR -* AppleScript -* Assembly (various) -* Asymptote -* Awk -* Befunge -* Boo -* BrainFuck -* C, C++ -* C# -* Clojure -* CoffeeScript -* ColdFusion -* Common Lisp -* Coq -* Cryptol (incl. Literate Cryptol) -* `Cython `_ -* `D `_ -* Dart -* Delphi -* Dylan -* Erlang -* `Ezhil `_ Ezhil - A Tamil programming language -* Factor -* Fancy -* Fortran -* F# -* GAP -* Gherkin (Cucumber) -* GL shaders -* Groovy -* `Haskell `_ (incl. Literate Haskell) -* IDL -* Io -* Java -* JavaScript -* Lasso -* LLVM -* Logtalk -* `Lua `_ -* Matlab -* MiniD -* Modelica -* Modula-2 -* MuPad -* Nemerle -* Nimrod -* Objective-C -* Objective-J -* Octave -* OCaml -* PHP -* `Perl `_ -* PovRay -* PostScript -* PowerShell -* Prolog -* `Python `_ 2.x and 3.x (incl. console sessions and tracebacks) -* `REBOL `_ -* `Red `_ -* Redcode -* `Ruby `_ (incl. irb sessions) -* Rust -* S, S-Plus, R -* Scala -* Scheme -* Scilab -* Smalltalk -* SNOBOL -* Tcl -* Vala -* Verilog -* VHDL -* Visual Basic.NET -* Visual FoxPro -* XQuery -* Zephir - -Template languages ------------------- - -* Cheetah templates -* `Django `_ / `Jinja - `_ templates -* ERB (Ruby templating) -* `Genshi `_ (the Trac template language) -* JSP (Java Server Pages) -* `Myghty `_ (the HTML::Mason based framework) -* `Mako `_ (the Myghty successor) -* `Smarty `_ templates (PHP templating) -* Tea - -Other markup ------------- - -* Apache config files -* Bash shell scripts -* BBCode -* CMake -* CSS -* Debian control files -* Diff files -* DTD -* Gettext catalogs -* Gnuplot script -* Groff markup -* HTML -* HTTP sessions -* INI-style config files -* IRC logs (irssi style) -* Lighttpd config files -* Makefiles -* MoinMoin/Trac Wiki markup -* MySQL -* Nginx config files -* POV-Ray scenes -* Ragel -* Redcode -* ReST -* Robot Framework -* RPM spec files -* SQL, also MySQL, SQLite -* Squid configuration -* TeX -* tcsh -* Vim Script -* Windows batch files -* XML -* XSLT -* YAML - -... that's all? ---------------- - -Well, why not write your own? Contributing to Pygments is easy and fun. Take a look at the -:doc:`docs on lexer development ` and -:ref:`contact details `. - -Note: the languages listed here are supported in the development version. The -latest release may lack a few of them. diff --git a/third_party/pygments/doc/make.bat b/third_party/pygments/doc/make.bat deleted file mode 100644 index 8803c9859..000000000 --- a/third_party/pygments/doc/make.bat +++ /dev/null @@ -1,190 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=_build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -set I18NSPHINXOPTS=%SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Pygments.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Pygments.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -:end diff --git a/third_party/pygments/doc/pygmentize.1 b/third_party/pygments/doc/pygmentize.1 deleted file mode 100644 index 71bb6f9ce..000000000 --- a/third_party/pygments/doc/pygmentize.1 +++ /dev/null @@ -1,94 +0,0 @@ -.TH PYGMENTIZE 1 "February 15, 2007" - -.SH NAME -pygmentize \- highlights the input file - -.SH SYNOPSIS -.B \fBpygmentize\fP -.RI [-l\ \fI\fP]\ [-F\ \fI\fP[:\fI\fP]]\ [-f\ \fI\fP] -.RI [-O\ \fI\fP]\ [-P\ \fI\fP]\ [-o\ \fI\fP]\ [\fI\fP] -.br -.B \fBpygmentize\fP -.RI -S\ \fI - - -

      %(title)s

      - -''' - -DOC_HEADER_EXTERNALCSS = '''\ - - - - - %(title)s - - - - -

      %(title)s

      - -''' - -DOC_FOOTER = '''\ - - -''' - - -class HtmlFormatter(Formatter): - r""" - Format tokens as HTML 4 ```` tags within a ``
      `` tag, wrapped
      -    in a ``
      `` tag. The ``
      ``'s CSS class can be set by the `cssclass` - option. - - If the `linenos` option is set to ``"table"``, the ``
      `` is
      -    additionally wrapped inside a ``
    - +
    package main
     
    @@ -98,7 +98,7 @@ the work and return as soon as possible.

        select {
    -    case <-time.After(3 * time.Second):
    +    case <-time.After(10 * time.Second):
             fmt.Fprintf(w, "hello\n")
         case <-ctx.Done():
             err := ctx.Err()
    @@ -184,12 +184,12 @@ cancellation.

    diff --git a/public/http-servers b/public/http-servers index ee3c14632..fdf740b88 100644 --- a/public/http-servers +++ b/public/http-servers @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'context-in-http-servers'; + window.location.href = 'context'; } } @@ -201,7 +201,7 @@ router we’ve just set up.

    - Next example: Context in HTTP Servers. + Next example: Context.

    Go by Example

  • HTTP Servers
  • -
  • Context in HTTP Servers
  • +
  • Context
  • Spawning Processes
  • diff --git a/public/spawning-processes b/public/spawning-processes index 748398aa6..ce76f92bf 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'context-in-http-servers'; + window.location.href = 'context'; } From cb8bf44eca8e2b271586d2ab3f292d653ca9a192 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sat, 4 Jan 2020 09:59:11 -0800 Subject: [PATCH 023/283] Regen hash for Context --- examples/context/context.hash | 4 ++-- public/context | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/context/context.hash b/examples/context/context.hash index 311c608b4..7cdacf5e8 100644 --- a/examples/context/context.hash +++ b/examples/context/context.hash @@ -1,2 +1,2 @@ -a899a68d131b0f8cf3ae846ef728877d2407d219 -9fUzFC2uyFk +5893bc5d4537db64f263a6be8efa9f2cda8ca7d8 +Elok_mfA6GV diff --git a/public/context b/public/context index 52712e4dd..a7bc320fd 100644 --- a/public/context +++ b/public/context @@ -34,7 +34,7 @@ controlling cancellation.

    - +
    package main
     
    From b32972d2e452801406d6408d86bf92c664885925 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sat, 4 Jan 2020 10:17:11 -0800 Subject: [PATCH 024/283] Clarify in Timers that we give timer2 a real chance to fire Closes #304 --- examples/timers/timers.go | 12 ++++++++---- examples/timers/timers.hash | 4 ++-- examples/timers/timers.sh | 6 +++--- public/timers | 34 ++++++++++++++++++++++++---------- 4 files changed, 37 insertions(+), 19 deletions(-) diff --git a/examples/timers/timers.go b/examples/timers/timers.go index d0256e672..693d9c224 100644 --- a/examples/timers/timers.go +++ b/examples/timers/timers.go @@ -21,21 +21,25 @@ func main() { // The `<-timer1.C` blocks on the timer's channel `C` // until it sends a value indicating that the timer - // expired. + // fired. <-timer1.C - fmt.Println("Timer 1 expired") + fmt.Println("Timer 1 fired") // If you just wanted to wait, you could have used // `time.Sleep`. One reason a timer may be useful is - // that you can cancel the timer before it expires. + // that you can cancel the timer before it fires. // Here's an example of that. timer2 := time.NewTimer(time.Second) go func() { <-timer2.C - fmt.Println("Timer 2 expired") + fmt.Println("Timer 2 fired") }() stop2 := timer2.Stop() if stop2 { fmt.Println("Timer 2 stopped") } + + // Give the `timer2` enough time to fire, if it ever + // was going to, to show it is in fact stopped. + time.Sleep(2 * time.Second) } diff --git a/examples/timers/timers.hash b/examples/timers/timers.hash index aa71908b7..17f311590 100644 --- a/examples/timers/timers.hash +++ b/examples/timers/timers.hash @@ -1,2 +1,2 @@ -fb413c9b1152a30107c53bf0a739a22c0056976b -_cLT2ewHYO8 +36cae12a3ca529e473d7839e9573c3e0a202c2de +gF7VLRz3URM diff --git a/examples/timers/timers.sh b/examples/timers/timers.sh index b4963a9a8..4f62fbdb6 100644 --- a/examples/timers/timers.sh +++ b/examples/timers/timers.sh @@ -1,6 +1,6 @@ -// The first timer will expire ~2s after we start the +// The first timer will fire ~2s after we start the // program, but the second should be stopped before it has -// a chance to expire. +// a chance to fire. $ go run timers.go -Timer 1 expired +Timer 1 fired Timer 2 stopped diff --git a/public/timers b/public/timers index 082fb4033..6f79311e9 100644 --- a/public/timers +++ b/public/timers @@ -45,7 +45,7 @@ at tickers.

    - +
    package main
     
    @@ -99,13 +99,13 @@ time. This timer will wait 2 seconds.

    The <-timer1.C blocks on the timer’s channel C until it sends a value indicating that the timer -expired.

    +fired.

        <-timer1.C
    -    fmt.Println("Timer 1 expired")
    +    fmt.Println("Timer 1 fired")
     

    If you just wanted to wait, you could have used time.Sleep. One reason a timer may be useful is -that you can cancel the timer before it expires. +that you can cancel the timer before it fires. Here’s an example of that.

    +
        timer2 := time.NewTimer(time.Second)
         go func() {
             <-timer2.C
    -        fmt.Println("Timer 2 expired")
    +        fmt.Println("Timer 2 fired")
         }()
         stop2 := timer2.Stop()
         if stop2 {
             fmt.Println("Timer 2 stopped")
         }
    +
    + +
    +

    Give the timer2 enough time to fire, if it ever +was going to, to show it is in fact stopped.

    + +
    + +
        time.Sleep(2 * time.Second)
     }
     
    @@ -142,15 +156,15 @@ Here’s an example of that.

    -

    The first timer will expire ~2s after we start the +

    The first timer will fire ~2s after we start the program, but the second should be stopped before it has -a chance to expire.

    +a chance to fire.

    $ go run timers.go
    -Timer 1 expired
    +Timer 1 fired
     Timer 2 stopped
     
    @@ -170,7 +184,7 @@ a chance to expire.

    From 0fbbc70ba5dc7a1a900f527f90da96d63da481dc Mon Sep 17 00:00:00 2001 From: Richard Morrison Date: Mon, 28 Oct 2019 09:01:20 +0000 Subject: [PATCH 025/283] Remove magic numbers from code --- examples/worker-pools/worker-pools.go | 9 +++++---- examples/worker-pools/worker-pools.hash | 4 ++-- public/worker-pools | 13 +++++++------ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/examples/worker-pools/worker-pools.go b/examples/worker-pools/worker-pools.go index 1584d5950..b3c88922c 100644 --- a/examples/worker-pools/worker-pools.go +++ b/examples/worker-pools/worker-pools.go @@ -27,8 +27,9 @@ func main() { // In order to use our pool of workers we need to send // them work and collect their results. We make 2 // channels for this. - jobs := make(chan int, 100) - results := make(chan int, 100) + const numJobs = 5 + jobs := make(chan int, numJobs) + results := make(chan int, numJobs) // This starts up 3 workers, initially blocked // because there are no jobs yet. @@ -38,7 +39,7 @@ func main() { // Here we send 5 `jobs` and then `close` that // channel to indicate that's all the work we have. - for j := 1; j <= 5; j++ { + for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) @@ -47,7 +48,7 @@ func main() { // This also ensures that the worker goroutines have // finished. An alternative way to wait for multiple // goroutines is to use a [WaitGroup](waitgroups). - for a := 1; a <= 5; a++ { + for a := 1; a <= numJobs; a++ { <-results } } diff --git a/examples/worker-pools/worker-pools.hash b/examples/worker-pools/worker-pools.hash index 97b94fde8..4f1f1588a 100644 --- a/examples/worker-pools/worker-pools.hash +++ b/examples/worker-pools/worker-pools.hash @@ -1,2 +1,2 @@ -dbe5adf9aad6828387231e477e22c5f0cd550b74 -WXYS5_KpNvq +f6fd187061dfd0ae5ae8243efa3a6fcfa0777c84 +hiSJJsYZJKL diff --git a/public/worker-pools b/public/worker-pools index 97ea215eb..0b7c7d1b0 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -42,7 +42,7 @@ a worker pool using goroutines and channels.

    - +
    package main
     
    @@ -109,8 +109,9 @@ channels for this.

    -
        jobs := make(chan int, 100)
    -    results := make(chan int, 100)
    +          
        const numJobs = 5
    +    jobs := make(chan int, numJobs)
    +    results := make(chan int, numJobs)
     
    -
        for j := 1; j <= 5; j++ {
    +          
        for j := 1; j <= numJobs; j++ {
             jobs <- j
         }
         close(jobs)
    @@ -159,7 +160,7 @@ goroutines is to use a WaitGroup.

    -
        for a := 1; a <= 5; a++ {
    +          
        for a := 1; a <= numJobs; a++ {
             <-results
         }
     }
    @@ -223,7 +224,7 @@ there are 3 workers operating concurrently.

    From d6b866d2a1fafd33307b91daa1d641d9bc7c93dc Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sat, 4 Jan 2020 10:43:39 -0800 Subject: [PATCH 026/283] Show how to use tools/serve --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 386bf716a..04dd98b97 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,6 @@ To build the site you'll need Go and Python installed. Run: ```console $ go get github.com/russross/blackfriday $ tools/build -$ open public/index.html ``` To build continuously in a loop: @@ -34,6 +33,12 @@ To build continuously in a loop: $ tools/build-loop ``` +To see the site locally: + +``` +$ tools/serve +$ open http://127.0.0.1:8000/ + ### Publishing To upload the site: From 5d8d89d24640107bac8f9597f177377821525898 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 4 Jan 2020 14:05:02 -0800 Subject: [PATCH 027/283] Provide some more background on Context And add a comment about the `Err()` method. Followup on #301 --- examples/context/context.go | 7 ++++++- examples/context/context.hash | 4 ++-- public/context | 24 ++++++++++++++++++++---- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/examples/context/context.go b/examples/context/context.go index 0ad734cca..3971e190a 100644 --- a/examples/context/context.go +++ b/examples/context/context.go @@ -1,7 +1,9 @@ // In the previous example we looked at setting up a simple // [HTTP server](http-servers). HTTP servers are useful for // demonstrating the usage of `context.Context` for -// controlling cancellation. +// controlling cancellation. A `Context` carries deadlines, +// cancellation signals, and other request-scoped values +// across API boundaries and goroutines. package main import ( @@ -28,6 +30,9 @@ func hello(w http.ResponseWriter, req *http.Request) { case <-time.After(10 * time.Second): fmt.Fprintf(w, "hello\n") case <-ctx.Done(): + // The context's `Err()` method returns an error + // that explains why the `Done()` channel was + // closed. err := ctx.Err() fmt.Println("server:", err) internalError := http.StatusInternalServerError diff --git a/examples/context/context.hash b/examples/context/context.hash index 7cdacf5e8..5f6b83ccc 100644 --- a/examples/context/context.hash +++ b/examples/context/context.hash @@ -1,2 +1,2 @@ -5893bc5d4537db64f263a6be8efa9f2cda8ca7d8 -Elok_mfA6GV +e338acce5d0f64d6478be4b886bd24a0fd1a3afa +Lun5aFco3pX diff --git a/public/context b/public/context index a7bc320fd..f182bbe64 100644 --- a/public/context +++ b/public/context @@ -30,11 +30,13 @@

    In the previous example we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of context.Context for -controlling cancellation.

    +controlling cancellation. A Context carries deadlines, +cancellation signals, and other request-scoped values +across API boundaries and goroutines.

    - +
    package main
     
    @@ -101,7 +103,21 @@ the work and return as soon as possible.

    case <-time.After(10 * time.Second): fmt.Fprintf(w, "hello\n") case <-ctx.Done(): - err := ctx.Err() + + +
    +

    The context’s Err() method returns an error +that explains why the Done() channel was +closed.

    + +
    + +
            err := ctx.Err()
             fmt.Println("server:", err)
             internalError := http.StatusInternalServerError
             http.Error(w, err.Error(), internalError)
    @@ -189,7 +205,7 @@ cancellation.

    From bf18f092fe8e2d93001a67753fe92c3267f1cdab Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 6 Jan 2020 10:27:31 -0800 Subject: [PATCH 028/283] Fix formatting in README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 04dd98b97..b125821f9 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ To see the site locally: ``` $ tools/serve $ open http://127.0.0.1:8000/ +``` ### Publishing From ec08fcd2cace13706cec02a48bd42fa2ed7cc38a Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Mon, 6 Jan 2020 10:34:57 -0800 Subject: [PATCH 029/283] More portable local instructions Ref #305. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b125821f9..143ee76f3 100644 --- a/README.md +++ b/README.md @@ -37,9 +37,10 @@ To see the site locally: ``` $ tools/serve -$ open http://127.0.0.1:8000/ ``` +and open http://127.0.0.1:8000/ in your browser. + ### Publishing To upload the site: From 6f7aa08f846db0d11c2694f8f3322d91ce7b2290 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Mon, 6 Jan 2020 10:35:25 -0800 Subject: [PATCH 030/283] Use backpacks so GitHub doesn't auto-link this --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 143ee76f3..b05eb65c6 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ To see the site locally: $ tools/serve ``` -and open http://127.0.0.1:8000/ in your browser. +and open `http://127.0.0.1:8000/` in your browser. ### Publishing From bd25cd7ee9ee9cbe1b7e9375dfcf2b91cf98b20c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 7 Jan 2020 06:05:34 -0800 Subject: [PATCH 031/283] Move wg.Done in waitgroup worker to defer Fixes #310 --- examples/waitgroups/waitgroups.go | 6 +++--- examples/waitgroups/waitgroups.hash | 4 ++-- public/waitgroups | 27 +++++++++++++++++++-------- 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index 2cf16a308..c3c85801c 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -13,14 +13,14 @@ import ( // Note that a WaitGroup must be passed to functions by // pointer. func worker(id int, wg *sync.WaitGroup) { + // On return, notify the WaitGroup that we're done. + defer wg.Done() + fmt.Printf("Worker %d starting\n", id) // Sleep to simulate an expensive task. time.Sleep(time.Second) fmt.Printf("Worker %d done\n", id) - - // Notify the WaitGroup that this worker is done. - wg.Done() } func main() { diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index f944ca9bd..ab9311b42 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -39bbc00ecd87888761d480666e95d8b2c2a2a589 -oBOGrV0n2Y2 +fd77f5122e6df1669c0a2e0d2c4dfbd30631c21f +7mWXl0yVe6I diff --git a/public/waitgroups b/public/waitgroups index e9d39c70c..e47765d57 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    - +
    package main
     
    @@ -75,7 +75,6 @@ pointer.

    func worker(id int, wg *sync.WaitGroup) {
    -    fmt.Printf("Worker %d starting\n", id)
     
    -

    Sleep to simulate an expensive task.

    +

    On return, notify the WaitGroup that we’re done.

    -
        time.Sleep(time.Second)
    -    fmt.Printf("Worker %d done\n", id)
    +          
        defer wg.Done()
     
    -

    Notify the WaitGroup that this worker is done.

    + +
    + +
        fmt.Printf("Worker %d starting\n", id)
    +
    + +
    +

    Sleep to simulate an expensive task.

    -
        wg.Done()
    +          
        time.Sleep(time.Second)
    +    fmt.Printf("Worker %d done\n", id)
     }
     
    @@ -218,7 +229,7 @@ is likely to be different for each invocation.

    From 77651fdd3a0bd45b8cee6d3ee6621fbde8869185 Mon Sep 17 00:00:00 2001 From: badkaktus Date: Thu, 9 Jan 2020 12:33:44 +0300 Subject: [PATCH 032/283] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b05eb65c6..411313bc7 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ Contributor translations of the Go by Example site are available in: * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) +* [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Ukrainian](http://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) ### Thanks From 1315f3803e285fee9457a84fd64da1dfd990e4ac Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Thu, 9 Jan 2020 11:37:27 -0800 Subject: [PATCH 033/283] Alphabetize --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 411313bc7..a990d285b 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,8 @@ Contributor translations of the Go by Example site are available in: * [Italian](http://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) -* [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) +* [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) * [Ukrainian](http://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) ### Thanks From a41bd206c983c0ccca4e71a5f9a071c5b23ce0b4 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 13 Jan 2020 13:55:24 -0800 Subject: [PATCH 034/283] Fix typo in a comment of the context example Fixes #317 --- examples/context/context.go | 2 +- examples/context/context.hash | 4 ++-- public/context | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/context/context.go b/examples/context/context.go index 3971e190a..ae519804e 100644 --- a/examples/context/context.go +++ b/examples/context/context.go @@ -21,7 +21,7 @@ func hello(w http.ResponseWriter, req *http.Request) { fmt.Println("server: hello handler started") defer fmt.Println("server: hello handler ended") - // Wait for 3 seconds before sending a reply to the + // Wait for a few seconds before sending a reply to the // client. This could simulate some work the server is // doing. While working, keep an eye on the context's // `Done()` channel for a signal that we should cancel diff --git a/examples/context/context.hash b/examples/context/context.hash index 5f6b83ccc..c4604b666 100644 --- a/examples/context/context.hash +++ b/examples/context/context.hash @@ -1,2 +1,2 @@ -e338acce5d0f64d6478be4b886bd24a0fd1a3afa -Lun5aFco3pX +a9537bfea55bca15d8db1c453e2d9852f9d447e1 +0_bu1o8rIBO diff --git a/public/context b/public/context index f182bbe64..3a3a40664 100644 --- a/public/context +++ b/public/context @@ -36,7 +36,7 @@ across API boundaries and goroutines.

    - +
    package main
     
    @@ -90,7 +90,7 @@ the Context() method.

    -

    Wait for 3 seconds before sending a reply to the +

    Wait for a few seconds before sending a reply to the client. This could simulate some work the server is doing. While working, keep an eye on the context’s Done() channel for a signal that we should cancel From 6f312cbf646103823a1961b785b90fdbd53b916f Mon Sep 17 00:00:00 2001 From: Grant Regimbal Date: Fri, 31 Jan 2020 23:51:23 -0600 Subject: [PATCH 035/283] Fix number of examples Four examples are given but the comments refer to 3 --- examples/for/for.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/for/for.go b/examples/for/for.go index 7c4aa04f7..c1e8b2e87 100644 --- a/examples/for/for.go +++ b/examples/for/for.go @@ -1,5 +1,5 @@ // `for` is Go's only looping construct. Here are -// three basic types of `for` loops. +// four basic types of `for` loops. package main From dd99be41c0b3cd46ff0673049993d6b5f77dd1cd Mon Sep 17 00:00:00 2001 From: Grant Regimbal Date: Thu, 13 Feb 2020 19:19:20 -0600 Subject: [PATCH 036/283] Update based on feedback --- examples/for/for.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/for/for.go b/examples/for/for.go index c1e8b2e87..9a4df3055 100644 --- a/examples/for/for.go +++ b/examples/for/for.go @@ -1,5 +1,5 @@ // `for` is Go's only looping construct. Here are -// four basic types of `for` loops. +// some basic types of `for` loops. package main From 526be69307818bee024675482277ee6322c9c24b Mon Sep 17 00:00:00 2001 From: Egor Rudkov Date: Wed, 26 Feb 2020 23:23:33 +0300 Subject: [PATCH 037/283] Fix MustCompile comment error --- examples/regular-expressions/regular-expressions.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/regular-expressions/regular-expressions.go b/examples/regular-expressions/regular-expressions.go index 52ec06d3e..95d425a6a 100644 --- a/examples/regular-expressions/regular-expressions.go +++ b/examples/regular-expressions/regular-expressions.go @@ -64,10 +64,11 @@ func main() { // function name. fmt.Println(r.Match([]byte("peach"))) - // When creating constants with regular expressions - // you can use the `MustCompile` variation of - // `Compile`. A plain `Compile` won't work for - // constants because it has 2 return values. + // When creating global variables with regular + // expressions you can use the `MustCompile` variation + // of `Compile`. `MustCompile` panics instead of + // returning error, which makes it safer to use for + // global variables. r = regexp.MustCompile("p([a-z]+)ch") fmt.Println(r) From beeb2315622e9b282b2bbec1d68fee5c87ed79cc Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:14:31 +0200 Subject: [PATCH 038/283] Couple of suggestions --- examples/testing/main_test.go | 3 +-- examples/xml/xml.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index 3bcdd6ec0..c91540f10 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -21,9 +21,8 @@ import ( func IntMin(a, b int) int { if a < b { return a - } else { - return b } + return b } // A test is created by writing a function with a name diff --git a/examples/xml/xml.go b/examples/xml/xml.go index e54510667..9870377bd 100644 --- a/examples/xml/xml.go +++ b/examples/xml/xml.go @@ -8,7 +8,7 @@ import ( "fmt" ) -// This type will be mapped to XML. Similarly to the +// Plant will be mapped to XML. Similarly to the // JSON examples, field tags contain directives for the // encoder and decoder. Here we use some special features // of the XML package: the `XMLName` field name dictates From b66993dc19e0f62c3dccc522656d981b86da674a Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:20:13 +0200 Subject: [PATCH 039/283] Spelling --- examples/spawning-processes/spawning-processes.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/spawning-processes/spawning-processes.go b/examples/spawning-processes/spawning-processes.go index 58fdae8e0..261a2d02b 100644 --- a/examples/spawning-processes/spawning-processes.go +++ b/examples/spawning-processes/spawning-processes.go @@ -49,7 +49,7 @@ func main() { grepBytes, _ := ioutil.ReadAll(grepOut) grepCmd.Wait() - // We ommited error checks in the above example, but + // We omitted error checks in the above example, but // you could use the usual `if err != nil` pattern for // all of them. We also only collect the `StdoutPipe` // results, but you could collect the `StderrPipe` in From 904c01a09867b3253517e1543fe58796de473634 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:30:21 +0200 Subject: [PATCH 040/283] Add error check to time-parsing --- .../time-formatting-parsing.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/examples/time-formatting-parsing/time-formatting-parsing.go b/examples/time-formatting-parsing/time-formatting-parsing.go index 2968c3c68..34da49bf3 100644 --- a/examples/time-formatting-parsing/time-formatting-parsing.go +++ b/examples/time-formatting-parsing/time-formatting-parsing.go @@ -18,9 +18,12 @@ func main() { p(t.Format(time.RFC3339)) // Time parsing uses the same layout values as `Format`. - t1, e := time.Parse( + t1, err := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") + if err != nil { + panic(err) + } p(t1) // `Format` and `Parse` use example-based layouts. Usually @@ -34,7 +37,10 @@ func main() { p(t.Format("Mon Jan _2 15:04:05 2006")) p(t.Format("2006-01-02T15:04:05.999999-07:00")) form := "3 04 PM" - t2, e := time.Parse(form, "8 41 PM") + t2, err := time.Parse(form, "8 41 PM") + if err != nil { + panic(err) + } p(t2) // For purely numeric representations you can also @@ -47,6 +53,6 @@ func main() { // `Parse` will return an error on malformed input // explaining the parsing problem. ansic := "Mon Jan _2 15:04:05 2006" - _, e = time.Parse(ansic, "8:41PM") + _, e := time.Parse(ansic, "8:41PM") p(e) } From 7311e83283c382d4c8f935c7de0d3a751c261633 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:32:57 +0200 Subject: [PATCH 041/283] Add error check to writing file --- examples/writing-files/writing-files.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/writing-files/writing-files.go b/examples/writing-files/writing-files.go index 82275ce3c..ef8bd065f 100644 --- a/examples/writing-files/writing-files.go +++ b/examples/writing-files/writing-files.go @@ -40,6 +40,7 @@ func main() { // A `WriteString` is also available. n3, err := f.WriteString("writes\n") + check(err) fmt.Printf("wrote %d bytes\n", n3) // Issue a `Sync` to flush writes to stable storage. @@ -49,6 +50,7 @@ func main() { // to the buffered readers we saw earlier. w := bufio.NewWriter(f) n4, err := w.WriteString("buffered\n") + check(err) fmt.Printf("wrote %d bytes\n", n4) // Use `Flush` to ensure all buffered operations have From 5f6871027fadcdb94132439edd7afe00ee00df12 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:35:41 +0200 Subject: [PATCH 042/283] Add error check to generate go --- tools/generate.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tools/generate.go b/tools/generate.go index 04d2e920e..ad6af0f5e 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -153,11 +153,10 @@ func resetURLHashFile(codehash, code, sourcePath string) string { } payload := strings.NewReader(code) resp, err := http.Post("https://play.golang.org/share", "text/plain", payload) - if err != nil { - panic(err) - } + check(err) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) + check(err) urlkey := string(body) data := fmt.Sprintf("%s\n%s\n", codehash, urlkey) ioutil.WriteFile(sourcePath, []byte(data), 0644) From 6c1f33628b2231ee7d8d6058cacbd2f464f0d311 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:36:29 +0200 Subject: [PATCH 043/283] Add error check to temporary files --- .../temporary-files-and-directories.go | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/temporary-files-and-directories/temporary-files-and-directories.go b/examples/temporary-files-and-directories/temporary-files-and-directories.go index abed14e57..c41d23043 100644 --- a/examples/temporary-files-and-directories/temporary-files-and-directories.go +++ b/examples/temporary-files-and-directories/temporary-files-and-directories.go @@ -53,6 +53,7 @@ func main() { // `TempFile`'s, but it returns a directory *name* // rather than an open file. dname, err := ioutil.TempDir("", "sampledir") + check(err) fmt.Println("Temp dir name:", dname) defer os.RemoveAll(dname) From 5afa5faf66a55818b517081a4f9a5ca1e84a0db1 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:43:20 +0200 Subject: [PATCH 044/283] Change xml --- public/xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/xml b/public/xml index 85a2d15db..fb37a006e 100644 --- a/public/xml +++ b/public/xml @@ -66,7 +66,7 @@ formats with the encoding.xml package.

    -

    This type will be mapped to XML. Similarly to the +

    Plant will be mapped to XML. Similarly to the JSON examples, field tags contain directives for the encoder and decoder. Here we use some special features of the XML package: the XMLName field name dictates From 678cfab8931d31134260c663b5c7b5c0d8eef483 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:55:17 +0200 Subject: [PATCH 045/283] html changes --- public/spawning-processes | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/public/spawning-processes b/public/spawning-processes index 22aaecd43..568b7f212 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -46,7 +46,7 @@ of spawning processes from Go.

    - +
    package main
     
    @@ -157,7 +157,7 @@ to exit.

    -

    We ommited error checks in the above example, but +

    We omitted error checks in the above example, but you could use the usual if err != nil pattern for all of them. We also only collect the StdoutPipe results, but you could collect the StderrPipe in @@ -259,7 +259,7 @@ as if we had run them directly from the command-line.

    From 746d2d5abbda38d2753fe6f54ba242a689404d55 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 12:59:19 +0200 Subject: [PATCH 046/283] change html --- public/testing | 7 +++---- public/xml | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/public/testing b/public/testing index e8a3bc291..385028c03 100644 --- a/public/testing +++ b/public/testing @@ -47,7 +47,7 @@ typically lives in the same package as the code it tests.

    - +
    package main
     
    @@ -83,9 +83,8 @@ be named intutils_test.go.

    func IntMin(a, b int) int {
         if a < b {
             return a
    -    } else {
    -        return b
         }
    +    return b
     }
     
    @@ -232,7 +231,7 @@ when executing go test -v.

    diff --git a/public/xml b/public/xml index fb37a006e..4c7e04815 100644 --- a/public/xml +++ b/public/xml @@ -42,7 +42,7 @@ formats with the encoding.xml package.

    - +
    package main
     
    @@ -281,7 +281,7 @@ to nest all plants under <parent><child>... From 0e720eec21c93092cbd4e630b615d300147d815b Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 13:04:48 +0200 Subject: [PATCH 047/283] Revert "html changes" This reverts commit 678cfab8931d31134260c663b5c7b5c0d8eef483. --- public/spawning-processes | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/public/spawning-processes b/public/spawning-processes index 568b7f212..22aaecd43 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -46,7 +46,7 @@ of spawning processes from Go.

    - +
    package main
     
    @@ -157,7 +157,7 @@ to exit.

    -

    We omitted error checks in the above example, but +

    We ommited error checks in the above example, but you could use the usual if err != nil pattern for all of them. We also only collect the StdoutPipe results, but you could collect the StderrPipe in @@ -259,7 +259,7 @@ as if we had run them directly from the command-line.

    From 1be4329d35d946fa51ecea00c4b82a7874140fcd Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 13:17:52 +0200 Subject: [PATCH 048/283] Change HTML --- examples/spawning-processes/spawning-processes.hash | 4 ++-- public/spawning-processes | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index f36a1cc12..3c800a59f 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -64e8937dacf6d81f39a3b66584fb70f46dd2126b -jUpRr-RcUKf +6a62e3109c483c2b52a99905dc1ba5c8cb2a281b +m2CpSlHPEVq diff --git a/public/spawning-processes b/public/spawning-processes index 22aaecd43..1eea4b370 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -46,7 +46,7 @@ of spawning processes from Go.

    - +
    package main
     
    @@ -157,7 +157,7 @@ to exit.

    -

    We ommited error checks in the above example, but +

    We omitted error checks in the above example, but you could use the usual if err != nil pattern for all of them. We also only collect the StdoutPipe results, but you could collect the StderrPipe in From 6fed3e7e699ef8226b6316fb53f374679609dc5f Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 13:24:03 +0200 Subject: [PATCH 049/283] Add hash --- examples/testing/testing.hash | 4 ++-- examples/xml/xml.hash | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/testing/testing.hash b/examples/testing/testing.hash index e3a25164d..3a02134ef 100644 --- a/examples/testing/testing.hash +++ b/examples/testing/testing.hash @@ -1,2 +1,2 @@ -017c9d7ba927cdfbcef1643e86f9b8022f13fc31 -jCRgtgRwie3 +8e15d97f54c34ac1546c2ec6589cc1b60ff27f80 +GFuPdlBlyMU diff --git a/examples/xml/xml.hash b/examples/xml/xml.hash index aef8f3597..b9354ae78 100644 --- a/examples/xml/xml.hash +++ b/examples/xml/xml.hash @@ -1,2 +1,2 @@ -f42dec8593a45931145f0a55f104f2ca34b2d112 -wlkywJsuWqL +d5da1784f3aa0bbba452d21c70833621a62159f4 +RsNLhMBazeX From 22ddaa5fd030d015144f51d8c3b2af4f4fd34f67 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 13:29:54 +0200 Subject: [PATCH 050/283] html changes --- public/testing | 2 +- public/xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/public/testing b/public/testing index 385028c03..4061ff427 100644 --- a/public/testing +++ b/public/testing @@ -231,7 +231,7 @@ when executing go test -v.

    diff --git a/public/xml b/public/xml index 4c7e04815..f27d9f9fb 100644 --- a/public/xml +++ b/public/xml @@ -281,7 +281,7 @@ to nest all plants under <parent><child>... From 421044f18562d0661219c2a7e6becd91d2a38ba3 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 14:33:32 +0200 Subject: [PATCH 051/283] update html --- public/testing | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/testing b/public/testing index 4061ff427..26f4116c2 100644 --- a/public/testing +++ b/public/testing @@ -231,7 +231,7 @@ when executing go test -v.

    From ebd652c4f443dcb70d01355980a15e81b977a940 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 14:41:18 +0200 Subject: [PATCH 052/283] Revert "Add error check to time-parsing" This reverts commit 904c01a09867b3253517e1543fe58796de473634. --- .../time-formatting-parsing.go | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/examples/time-formatting-parsing/time-formatting-parsing.go b/examples/time-formatting-parsing/time-formatting-parsing.go index 34da49bf3..2968c3c68 100644 --- a/examples/time-formatting-parsing/time-formatting-parsing.go +++ b/examples/time-formatting-parsing/time-formatting-parsing.go @@ -18,12 +18,9 @@ func main() { p(t.Format(time.RFC3339)) // Time parsing uses the same layout values as `Format`. - t1, err := time.Parse( + t1, e := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") - if err != nil { - panic(err) - } p(t1) // `Format` and `Parse` use example-based layouts. Usually @@ -37,10 +34,7 @@ func main() { p(t.Format("Mon Jan _2 15:04:05 2006")) p(t.Format("2006-01-02T15:04:05.999999-07:00")) form := "3 04 PM" - t2, err := time.Parse(form, "8 41 PM") - if err != nil { - panic(err) - } + t2, e := time.Parse(form, "8 41 PM") p(t2) // For purely numeric representations you can also @@ -53,6 +47,6 @@ func main() { // `Parse` will return an error on malformed input // explaining the parsing problem. ansic := "Mon Jan _2 15:04:05 2006" - _, e := time.Parse(ansic, "8:41PM") + _, e = time.Parse(ansic, "8:41PM") p(e) } From bac19fd5d16f1f5634df1d65e71a9cdf6903c16a Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 9 Mar 2020 14:51:16 +0200 Subject: [PATCH 053/283] HTML changes --- .../temporary-files-and-directories.hash | 4 ++-- examples/writing-files/writing-files.hash | 4 ++-- public/temporary-files-and-directories | 5 +++-- public/writing-files | 6 ++++-- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/examples/temporary-files-and-directories/temporary-files-and-directories.hash b/examples/temporary-files-and-directories/temporary-files-and-directories.hash index ebe1eeb36..cf6faa7da 100644 --- a/examples/temporary-files-and-directories/temporary-files-and-directories.hash +++ b/examples/temporary-files-and-directories/temporary-files-and-directories.hash @@ -1,2 +1,2 @@ -371689e72c46daa43eefbd9b9f4eaa3c490e7fd2 -yKWE4QTsYQr +cc4755e23cb4ba3c0e0ef5554ec9e9477372422a +nMpjCsALS6P diff --git a/examples/writing-files/writing-files.hash b/examples/writing-files/writing-files.hash index 3d09d103c..1513200ba 100644 --- a/examples/writing-files/writing-files.hash +++ b/examples/writing-files/writing-files.hash @@ -1,2 +1,2 @@ -d4f19bc0168674b17551bbf55bab7af989452d0e -8kx-qYUXBpA +314a0074840e22b328b6412130c17b9bea53c9c9 +fQ7sd4gXv0F diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 3919f3635..c6f46d3a1 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -45,7 +45,7 @@ time.

    - +
    package main
     
    @@ -175,6 +175,7 @@ rather than an open file.

        dname, err := ioutil.TempDir("", "sampledir")
    +    check(err)
         fmt.Println("Temp dir name:", dname)
     
    @@ -241,7 +242,7 @@ prefixing them with our temporary directory.

    diff --git a/public/writing-files b/public/writing-files index 49214e1f1..3b20793d4 100644 --- a/public/writing-files +++ b/public/writing-files @@ -42,7 +42,7 @@ ones we saw earlier for reading.

    - +
    package main
     
    @@ -162,6 +162,7 @@ after opening a file.

        n3, err := f.WriteString("writes\n")
    +    check(err)
         fmt.Printf("wrote %d bytes\n", n3)
     
    @@ -191,6 +192,7 @@ to the buffered readers we saw earlier.

        w := bufio.NewWriter(f)
         n4, err := w.WriteString("buffered\n")
    +    check(err)
         fmt.Printf("wrote %d bytes\n", n4)
     
    @@ -287,7 +289,7 @@ we’ve just seen to the stdin and stdout streams. From a1fd3bf037c914888bb3d4ee7d15a532348448a0 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 17:49:18 -0700 Subject: [PATCH 054/283] Regenerate --- public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 2 +- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 2 +- public/collection-functions | 2 +- public/command-line-arguments | 2 +- public/command-line-flags | 2 +- public/command-line-subcommands | 2 +- public/constants | 2 +- public/context | 2 +- public/defer | 2 +- public/directories | 2 +- public/environment-variables | 2 +- public/epoch | 2 +- public/errors | 2 +- public/execing-processes | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/goroutines | 2 +- public/http-clients | 2 +- public/http-servers | 2 +- public/if-else | 2 +- public/interfaces | 2 +- public/json | 2 +- public/line-filters | 2 +- public/maps | 2 +- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 2 +- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 2 +- public/random-numbers | 2 +- public/range | 2 +- public/range-over-channels | 2 +- public/rate-limiting | 2 +- public/reading-files | 2 +- public/recursion | 2 +- public/regular-expressions | 2 +- public/select | 2 +- public/sha1-hashes | 2 +- public/signals | 2 +- public/slices | 2 +- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 2 +- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- 73 files changed, 73 insertions(+), 73 deletions(-) diff --git a/public/arrays b/public/arrays index 352a0108b..0a6010586 100644 --- a/public/arrays +++ b/public/arrays @@ -206,7 +206,7 @@ typical Go. We’ll look at slices next.

    diff --git a/public/atomic-counters b/public/atomic-counters index 2d5252981..a6fef3537 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -236,7 +236,7 @@ state.

    diff --git a/public/base64-encoding b/public/base64-encoding index 13baf617c..74ffc9ae7 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -191,7 +191,7 @@ but they both decode to the original string as desired.

    diff --git a/public/channel-buffering b/public/channel-buffering index 5f2d1f532..0bea69d36 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -153,7 +153,7 @@ concurrent receive.

    diff --git a/public/channel-directions b/public/channel-directions index f79750a4c..2814e819a 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -145,7 +145,7 @@ receive on this channel.

    diff --git a/public/channel-synchronization b/public/channel-synchronization index 71fec1264..804f06cfa 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -184,7 +184,7 @@ started.

    diff --git a/public/channels b/public/channels index 6ae7ade6f..c3f4a4a70 100644 --- a/public/channels +++ b/public/channels @@ -168,7 +168,7 @@ message without having to use any other synchronization.

    diff --git a/public/closing-channels b/public/closing-channels index 5271faab0..cba25386e 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -194,7 +194,7 @@ example: range over channels.

    diff --git a/public/closures b/public/closures index e31c87a21..3ef94eec0 100644 --- a/public/closures +++ b/public/closures @@ -190,7 +190,7 @@ recursion.

    diff --git a/public/collection-functions b/public/collection-functions index 33c38fdcc..6d7db8c6c 100644 --- a/public/collection-functions +++ b/public/collection-functions @@ -371,7 +371,7 @@ type.

    diff --git a/public/command-line-arguments b/public/command-line-arguments index 687aefd3f..a3f61e4ff 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -170,7 +170,7 @@ with flags.

    diff --git a/public/command-line-flags b/public/command-line-flags index 024349f26..b30884473 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -310,7 +310,7 @@ and show the help text again.

    diff --git a/public/command-line-subcommands b/public/command-line-subcommands index 6bee74c6d..60e99281e 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -263,7 +263,7 @@ way to parameterize programs.

    diff --git a/public/constants b/public/constants index b1cf8801f..737bfc05c 100644 --- a/public/constants +++ b/public/constants @@ -183,7 +183,7 @@ assignment or function call. For example, here diff --git a/public/context b/public/context index 3a3a40664..d808591c8 100644 --- a/public/context +++ b/public/context @@ -205,7 +205,7 @@ cancellation.

    diff --git a/public/defer b/public/defer index 54bb2d7e3..b15ef1e94 100644 --- a/public/defer +++ b/public/defer @@ -212,7 +212,7 @@ after being written.

    diff --git a/public/directories b/public/directories index c88a76c06..0d7d9f5c2 100644 --- a/public/directories +++ b/public/directories @@ -353,7 +353,7 @@ recursively by filepath.Walk.

    diff --git a/public/environment-variables b/public/environment-variables index e68934d4b..65b18c90e 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -186,7 +186,7 @@ program picks that value up.

    diff --git a/public/epoch b/public/epoch index 02bfc7ea8..192c24c58 100644 --- a/public/epoch +++ b/public/epoch @@ -177,7 +177,7 @@ parsing and formatting.

    diff --git a/public/errors b/public/errors index 3103a2efa..be57978b8 100644 --- a/public/errors +++ b/public/errors @@ -299,7 +299,7 @@ on the Go blog for more on error handling.

    diff --git a/public/execing-processes b/public/execing-processes index 585a266cb..687da4a79 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -203,7 +203,7 @@ processes covers most use cases for fork.

    diff --git a/public/file-paths b/public/file-paths index 3219a93c2..1e5e2046e 100644 --- a/public/file-paths +++ b/public/file-paths @@ -250,7 +250,7 @@ be made relative to base.

    diff --git a/public/for b/public/for index fea862c33..d4abec4eb 100644 --- a/public/for +++ b/public/for @@ -195,7 +195,7 @@ structures.

    diff --git a/public/functions b/public/functions index b4b80b384..2747daa7a 100644 --- a/public/functions +++ b/public/functions @@ -193,7 +193,7 @@ multiple return values, which we’ll look at next.

    diff --git a/public/goroutines b/public/goroutines index 105d9bdb3..0defc4cb5 100644 --- a/public/goroutines +++ b/public/goroutines @@ -207,7 +207,7 @@ concurrent Go programs: channels.

    diff --git a/public/http-clients b/public/http-clients index 09080b5eb..d3c773d35 100644 --- a/public/http-clients +++ b/public/http-clients @@ -169,7 +169,7 @@ settings.

    diff --git a/public/http-servers b/public/http-servers index c62ba61d5..72b4ef0f0 100644 --- a/public/http-servers +++ b/public/http-servers @@ -210,7 +210,7 @@ router we’ve just set up.

    diff --git a/public/if-else b/public/if-else index ed87d6a1d..b599e0926 100644 --- a/public/if-else +++ b/public/if-else @@ -184,7 +184,7 @@ for basic conditions.

    diff --git a/public/interfaces b/public/interfaces index 737c5180e..baf76af3f 100644 --- a/public/interfaces +++ b/public/interfaces @@ -236,7 +236,7 @@ these structs as arguments to measure.

    diff --git a/public/json b/public/json index 4a648d1b1..b39d5129f 100644 --- a/public/json +++ b/public/json @@ -416,7 +416,7 @@ for more.

    diff --git a/public/line-filters b/public/line-filters index ec8491568..d7e5fea49 100644 --- a/public/line-filters +++ b/public/line-filters @@ -204,7 +204,7 @@ lowercase lines.

    diff --git a/public/maps b/public/maps index f0c7c0f03..c3bb8822f 100644 --- a/public/maps +++ b/public/maps @@ -232,7 +232,7 @@ printed with fmt.Println.

    diff --git a/public/methods b/public/methods index a053c8599..b8e0a5888 100644 --- a/public/methods +++ b/public/methods @@ -197,7 +197,7 @@ naming related sets of methods: interfaces.

    diff --git a/public/multiple-return-values b/public/multiple-return-values index ec3ebcb5c..fa3ca351d 100644 --- a/public/multiple-return-values +++ b/public/multiple-return-values @@ -166,7 +166,7 @@ feature of Go functions; we’ll look at this next.

    diff --git a/public/mutexes b/public/mutexes index fb406ee34..94208eb5e 100644 --- a/public/mutexes +++ b/public/mutexes @@ -297,7 +297,7 @@ management task using only goroutines and channels.

    diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations index 6a529c8bf..ea30fd122 100644 --- a/public/non-blocking-channel-operations +++ b/public/non-blocking-channel-operations @@ -176,7 +176,7 @@ on both messages and signals.

    diff --git a/public/number-parsing b/public/number-parsing index 6b063ee98..e222bc792 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -213,7 +213,7 @@ bits.

    diff --git a/public/panic b/public/panic index f078c0304..9242fcc43 100644 --- a/public/panic +++ b/public/panic @@ -172,7 +172,7 @@ to use error-indicating return values wherever possible.

    diff --git a/public/pointers b/public/pointers index 53d075a4c..62d3a709c 100644 --- a/public/pointers +++ b/public/pointers @@ -193,7 +193,7 @@ the memory address for that variable.

    diff --git a/public/random-numbers b/public/random-numbers index 7d14d7961..39f924615 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -229,7 +229,7 @@ that Go can provide.

    diff --git a/public/range b/public/range index 947af8601..81877c9cb 100644 --- a/public/range +++ b/public/range @@ -200,7 +200,7 @@ of the rune and the second the rune itself.

    diff --git a/public/range-over-channels b/public/range-over-channels index cc279fbd4..6eedb6af4 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -154,7 +154,7 @@ values be received.

    diff --git a/public/rate-limiting b/public/rate-limiting index 49e16b918..25900dd6f 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -261,7 +261,7 @@ then serve the remaining 2 with ~200ms delays each.

    diff --git a/public/reading-files b/public/reading-files index 62e692cfe..abed995c1 100644 --- a/public/reading-files +++ b/public/reading-files @@ -287,7 +287,7 @@ be scheduled immediately after Opening with diff --git a/public/recursion b/public/recursion index 12b7ffacd..d1125aa3d 100644 --- a/public/recursion +++ b/public/recursion @@ -125,7 +125,7 @@ base case of fact(0).

    diff --git a/public/regular-expressions b/public/regular-expressions index 20d4fbd00..7a312eb74 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -342,7 +342,7 @@ the regexp package docs diff --git a/public/select b/public/select index fc1eda7c9..c92146fa8 100644 --- a/public/select +++ b/public/select @@ -183,7 +183,7 @@ concurrently.

    diff --git a/public/sha1-hashes b/public/sha1-hashes index 9bbcddf77..82dfb4fc4 100644 --- a/public/sha1-hashes +++ b/public/sha1-hashes @@ -203,7 +203,7 @@ you should carefully research diff --git a/public/signals b/public/signals index 786fb5a69..af1a0018e 100644 --- a/public/signals +++ b/public/signals @@ -188,7 +188,7 @@ causing the program to print interrupt and then exit.

    diff --git a/public/slices b/public/slices index c61dcb758..798a0ca4d 100644 --- a/public/slices +++ b/public/slices @@ -308,7 +308,7 @@ Go’s other key builtin data structure: maps.

    diff --git a/public/sorting b/public/sorting index 18f89fbdf..e341758ed 100644 --- a/public/sorting +++ b/public/sorting @@ -160,7 +160,7 @@ slices and true as the result of our AreSorted test. diff --git a/public/sorting-by-functions b/public/sorting-by-functions index 0d2b44217..4f0f50ea2 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -177,7 +177,7 @@ functions.

    diff --git a/public/spawning-processes b/public/spawning-processes index 22aaecd43..3ee9ff8c5 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -259,7 +259,7 @@ as if we had run them directly from the command-line.

    diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 25b8f59b4..88182c584 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -312,7 +312,7 @@ program.

    diff --git a/public/string-formatting b/public/string-formatting index 6ec05687a..5c1f5741c 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -457,7 +457,7 @@ and returns a string without printing it anywhere.

    diff --git a/public/string-functions b/public/string-functions index 3c0ddfabe..f4869763d 100644 --- a/public/string-functions +++ b/public/string-functions @@ -209,7 +209,7 @@ for more information.

    diff --git a/public/structs b/public/structs index e941fefd2..26dfab353 100644 --- a/public/structs +++ b/public/structs @@ -266,7 +266,7 @@ pointers are automatically dereferenced.

    diff --git a/public/switch b/public/switch index ead4de41d..3cf0fc607 100644 --- a/public/switch +++ b/public/switch @@ -203,7 +203,7 @@ type corresponding to its clause.

    diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 3919f3635..346ae7474 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -241,7 +241,7 @@ prefixing them with our temporary directory.

    diff --git a/public/testing b/public/testing index e8a3bc291..6b0a3aa16 100644 --- a/public/testing +++ b/public/testing @@ -232,7 +232,7 @@ when executing go test -v.

    diff --git a/public/tickers b/public/tickers index 6b219ab42..aa0fac7dd 100644 --- a/public/tickers +++ b/public/tickers @@ -171,7 +171,7 @@ before we stop it.

    diff --git a/public/time b/public/time index ae8046955..246ffa8b3 100644 --- a/public/time +++ b/public/time @@ -270,7 +270,7 @@ the Unix epoch.

    diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index e6b54d831..6e7fbcb70 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -204,7 +204,7 @@ explaining the parsing problem.

    diff --git a/public/timeouts b/public/timeouts index 36abd5467..0d1854d30 100644 --- a/public/timeouts +++ b/public/timeouts @@ -181,7 +181,7 @@ out and the second succeeding.

    diff --git a/public/timers b/public/timers index 6f79311e9..4e7536838 100644 --- a/public/timers +++ b/public/timers @@ -184,7 +184,7 @@ a chance to fire.

    diff --git a/public/url-parsing b/public/url-parsing index 4fd0fb873..cb70ac77b 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -235,7 +235,7 @@ pieces that we extracted.

    diff --git a/public/values b/public/values index 807830bd0..aee60a22a 100644 --- a/public/values +++ b/public/values @@ -152,7 +152,7 @@ basic examples.

    diff --git a/public/variables b/public/variables index b10cded1c..312b5e59e 100644 --- a/public/variables +++ b/public/variables @@ -183,7 +183,7 @@ initializing a variable, e.g. for diff --git a/public/variadic-functions b/public/variadic-functions index d36665815..0ce77f5d3 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -172,7 +172,7 @@ to form closures, which we’ll look at next.

    diff --git a/public/waitgroups b/public/waitgroups index e47765d57..85856cee7 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -229,7 +229,7 @@ is likely to be different for each invocation.

    diff --git a/public/worker-pools b/public/worker-pools index 0b7c7d1b0..e7fec3230 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -224,7 +224,7 @@ there are 3 workers operating concurrently.

    diff --git a/public/writing-files b/public/writing-files index 49214e1f1..6d0626cb9 100644 --- a/public/writing-files +++ b/public/writing-files @@ -287,7 +287,7 @@ we’ve just seen to the stdin and stdout streams. diff --git a/public/xml b/public/xml index 85a2d15db..66f7c5ab7 100644 --- a/public/xml +++ b/public/xml @@ -281,7 +281,7 @@ to nest all plants under <parent><child>... From 0b7926ac8dda1a0821ef1cece2792e280f05f37b Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 17:50:26 -0700 Subject: [PATCH 055/283] No need for a public function --- examples/structs/structs.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/structs/structs.go b/examples/structs/structs.go index 384b57c51..268f65f1e 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -12,8 +12,8 @@ type person struct { age int } -// NewPerson constructs a new person struct with the given name -func NewPerson(name string) *person { +// `newPerson` constructs a new person struct with the given name. +func newPerson(name string) *person { // You can safely return a pointer to local variable // as a local variable will survive the scope of the function. p := person{name: name} @@ -36,7 +36,7 @@ func main() { fmt.Println(&person{name: "Ann", age: 40}) // It's idiomatic to encapsulate new struct creation in constructor functions - fmt.Println(NewPerson("Jon")) + fmt.Println(newPerson("Jon")) // Access struct fields with a dot. s := person{name: "Sean", age: 50} From 2b08f4b1f401971157d029000fd1deb931eb99e0 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 17:50:55 -0700 Subject: [PATCH 056/283] Regenerate --- examples/structs/structs.hash | 4 ++-- public/structs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index ca7cc8523..fe4d3671d 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -e630f9890f89e157aa88f5d774dbed0c0c04224e -qHz9gNnAtyw +f1dcc357b5e20c3aa3a97df8245efe4aea7940d6 +n7jt1x3iw4Z diff --git a/public/structs b/public/structs index 26dfab353..552be5a30 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.

    - +
    package main
     
    @@ -80,12 +80,12 @@ records.

    -

    NewPerson constructs a new person struct with the given name

    +

    newPerson constructs a new person struct with the given name.

    -
    func NewPerson(name string) *person {
    +          
    func newPerson(name string) *person {
     
    -
        fmt.Println(NewPerson("Jon"))
    +          
        fmt.Println(newPerson("Jon"))
     
    - +
    package main
     
    @@ -242,10 +242,11 @@ function name.

    -

    When creating constants with regular expressions -you can use the MustCompile variation of -Compile. A plain Compile won’t work for -constants because it has 2 return values.

    +

    When creating global variables with regular +expressions you can use the MustCompile variation +of Compile. MustCompile panics instead of +returning an error, which makes it safer to use for +global variables.

    From ce206e9c31214726b262ad018eb0143cb652a3f6 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 18:01:39 -0700 Subject: [PATCH 059/283] Try updating Go in Travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 96a94a185..76baa9fc9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: go go: - - 1.12 + - 1.14 before_install: # We need Python to run pygmentize for generating HTML. From 448c597a5837c4b987e8f219687bd46a00b5577a Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Fri, 10 Apr 2020 18:06:38 -0700 Subject: [PATCH 060/283] Regenerate --- examples/for/for.hash | 4 ++-- public/for | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/for/for.hash b/examples/for/for.hash index 2b9b9907d..9473e965f 100644 --- a/examples/for/for.hash +++ b/examples/for/for.hash @@ -1,2 +1,2 @@ -50eb0c667de576107da5f814f5780754b724346a -jPI-IwqVC1c +7af221b7da2f2b22b0b1b0a1b365afc5a56ef815 +2-4H-ArwHHS diff --git a/public/for b/public/for index d4abec4eb..e7b756bec 100644 --- a/public/for +++ b/public/for @@ -28,7 +28,7 @@

    for is Go’s only looping construct. Here are -three basic types of for loops.

    +some basic types of for loops.

    @@ -42,7 +42,7 @@ three basic types of for loops.

    - +
    package main
     
    From 7823e44fc9634d6859460b59122e51082030efdf Mon Sep 17 00:00:00 2001 From: szTheory Date: Sat, 13 Jun 2020 12:42:00 +0000 Subject: [PATCH 061/283] Update timeouts.go: Fix typo --- examples/timeouts/timeouts.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/timeouts/timeouts.go b/examples/timeouts/timeouts.go index 3f25aec86..be5de76ef 100644 --- a/examples/timeouts/timeouts.go +++ b/examples/timeouts/timeouts.go @@ -25,7 +25,7 @@ func main() { }() // Here's the `select` implementing a timeout. - // `res := <-c1` awaits the result and `<-Time.After` + // `res := <-c1` awaits the result and `<-time.After` // awaits a value to be sent after the timeout of // 1s. Since `select` proceeds with the first // receive that's ready, we'll take the timeout case From 7d87b1b9f0a050650d3acb15293a9ea475f2b163 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 23 Aug 2020 07:50:27 -0700 Subject: [PATCH 062/283] Rebuild --- examples/timeouts/timeouts.hash | 4 ++-- public/timeouts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/timeouts/timeouts.hash b/examples/timeouts/timeouts.hash index 8fbb39d99..82f34b704 100644 --- a/examples/timeouts/timeouts.hash +++ b/examples/timeouts/timeouts.hash @@ -1,2 +1,2 @@ -fb913ae361c41095a39bb3fa0c5e9dcd54ec840e -4oOz0j29MJ6 +79963f30cb3ca93d559a409e3ded40c2bb64df66 +gyr0NbVKBVf diff --git a/public/timeouts b/public/timeouts index 0d1854d30..b4d14e78b 100644 --- a/public/timeouts +++ b/public/timeouts @@ -44,7 +44,7 @@ elegant thanks to channels and select.

    - +
    package main
     
    @@ -103,7 +103,7 @@ channel is never read.

    Here’s the select implementing a timeout. -res := <-c1 awaits the result and <-Time.After +res := <-c1 awaits the result and <-time.After awaits a value to be sent after the timeout of 1s. Since select proceeds with the first receive that’s ready, we’ll take the timeout case From 71719ea0f3204160ecc8c089a560279496a394e5 Mon Sep 17 00:00:00 2001 From: legonian Date: Sun, 18 Oct 2020 14:34:13 +0300 Subject: [PATCH 063/283] Change t.Fail to t.Fatal Fail* continues execution, right function probably Fatal*. --- examples/testing/main_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index c91540f10..e409d9d2e 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -31,7 +31,7 @@ func TestIntMinBasic(t *testing.T) { ans := IntMin(2, -2) if ans != -2 { // `t.Error*` will report test failures but continue - // executing the test. `t.Fail*` will report test + // executing the test. `t.Fatal*` will report test // failures and stop the test immediately. t.Errorf("IntMin(2, -2) = %d; want -2", ans) } From f72f11e64157dc151fa604c545b29fbaf1424ef0 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Mon, 19 Oct 2020 08:04:08 -0700 Subject: [PATCH 064/283] Rebuild --- examples/testing/testing.hash | 4 ++-- public/testing | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/testing/testing.hash b/examples/testing/testing.hash index 3a02134ef..6dc53a9ef 100644 --- a/examples/testing/testing.hash +++ b/examples/testing/testing.hash @@ -1,2 +1,2 @@ -8e15d97f54c34ac1546c2ec6589cc1b60ff27f80 -GFuPdlBlyMU +c9ca6b71d9f762b689f1f08a490d8c7f7764fcb3 +vY8PN0c6BSx diff --git a/public/testing b/public/testing index 385028c03..673e027a1 100644 --- a/public/testing +++ b/public/testing @@ -47,7 +47,7 @@ typically lives in the same package as the code it tests.

    - +
    package main
     
    @@ -110,7 +110,7 @@ beginning with Test.

    t.Error* will report test failures but continue -executing the test. t.Fail* will report test +executing the test. t.Fatal* will report test failures and stop the test immediately.

    `` which has one row and two - cells: one containing the line numbers and one containing the code. - Example: - - .. sourcecode:: html - -
    -
    - - -
    -
    1
    -            2
    -
    -
    def foo(bar):
    -              pass
    -            
    -
    - - (whitespace added to improve clarity). - - Wrapping can be disabled using the `nowrap` option. - - A list of lines can be specified using the `hl_lines` option to make these - lines highlighted (as of Pygments 0.11). - - With the `full` option, a complete HTML 4 document is output, including - the style definitions inside a `` - - -

    Error

    - - - -
    Path: #{path}
    -
    #{CGI.escapeHTML(error.to_s)}
    -
    - Reload this page. - Go to the referer or the home page. -
    -
    - - In file '#{error.hot_file}' #{error.hot_file =~ /\.xhtml$/ ? '(line numbering is aproximate due to template transformation)' : nil}: -

    - -
    #{line}
    - -
    #{line}
    - -
    -

    Stack Trace

    - - - -

    Request

    - - -

    Response

    - - -

    Session

    - - -

    - Powered by Nitro version #{Nitro::Version} - - - - - -

    Home > System > #{"%plural%".humanize} > Edit #{"%name%".humanize}

    - - Show editable - #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list", :all => true} - - Show all - #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list"} - -
    -#{form_for(@%name%)} - - -

    #{"%plural%".humanize}

    -

    New #{"%name%".humanize}

    -
    - Search #{"%plural%".humanize}:   -
    - - - - - - - - - - - -
    #{obj.to_s}#{obj.update_time.stamp(:db)}editdel
    -
    - - -

    Home > System > #{"%plural%".humanize}

    - New #{"%name%".humanize} -

    -

    - Search #{"%plural%".humanize}:   -
    -

    - - - - - - - - - - - -
    #(obj.to_s)#{obj.update_time.stamp(:db)}editdel
    -
    - #{@pager.navigation} -
    -
    - - -

    Home > System > #{"%plural%".humanize} > New #{"%name%".humanize}

    - - Show editable - #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list", :all => true, :enctype => "multipart/form-data"} - - Show all - #{form_for @obj, :action => "#{base}/save", :cancel => "#{base}/list", :enctype => "multipart/form-data"} - -
    - - -

    Home > System > #{"%plural%".humanize} > Search for '#@query'

    -

    -

    - Search #{"%plural%".humanize}:   -
    -

    - -

    Search method is not implemented for this object

    - - - - - - - - - - - - -
    #(obj.to_s)#{obj.update_time.stamp(:db)}editdel
    -
    - #{@pager.navigation} -
    - -
    - - -

    View %name%

    -

    List of %plural%

    - - #{@obj.to_yaml} - -
    -Access denied - - -

    Home > System

    - -

    Og managed classes

    - - - - - - - - - - - - - - - - - -
    ClassCountCleanupProperties
    #{c.name}#{c.count}deletedestroy#{c.properties.values.join(', ')}
    - -

    System configuration

    - - - - - - - - - - - - - - - - -
    NameValueTypeDescription
    #{s.owner}.#{s.name}#{s.value.inspect}#{s.type}#{s.options[:doc]}
    -
    - - - - - Test - - - - - - - -hello -Hello #{username} - -how do you feel? - -Here is your Token: #{token} - -
    - -

    Questions with Tags: #{@tags.join(" ")}

    - - 0 ?> - - Too many results for that Tag, please reduce the number by using one of the following Tags: - #{cloud_of(@qtags)} - -
    - -

    #{q.question}

    -

    - - #{excerpt} -

    -

    #{q.answers.size.to_i} answers

    - -
    -
    - #{@qpager.navigation} -
    - -
    -

    no question with this/these tag(s) found

    -

    Ask a question here.

    -
    - - - 0 ?> -

    Tips with Tags: #{@tags.join(" ")}

    - - Too many results for that Tag, please reduce the number by using one of the following Tags: - #{cloud_of(@ttags)} - -
    - -

    #{t.title}

    -

    - - #{excerpt} -

    - -
    -
    - #{@tpager.navigation} -
    - - - 0 ?> -

    Tutorials with Tags: #{@tags.join(" ")}

    - - Too many results for that Tag, please reduce the number by using one of the following Tags: - #{cloud_of(@tuttags)} - -
    - -

    #{t.title}

    -

    - - #{excerpt} -

    - -
    -
    - #{@tpager.navigation} -
    - - - - -
    - - - #{t.name} - -
    - -
    - - -
    - - diff --git a/third_party/pygments/tests/examplefiles/example.xtend b/third_party/pygments/tests/examplefiles/example.xtend deleted file mode 100644 index f6a51f7ae..000000000 --- a/third_party/pygments/tests/examplefiles/example.xtend +++ /dev/null @@ -1,34 +0,0 @@ -package beer - -import static extension beer.BottleSupport.* -import org.junit.Test - -class BottleSong { - - @Test - def void singIt() { - println(singTheSong(99)) - } - - def singTheSong(int all) ''' - �FOR i : all .. 1� - �i.Bottles� of beer on the wall, �i.bottles� of beer. - Take one down and pass it around, �(i - 1).bottles� of beer on the wall. - - �ENDFOR� - No more bottles of beer on the wall, no more bottles of beer. - Go to the store and buy some more, �all.bottles� of beer on the wall. - ''' - - def private java.lang.String bottles(int i) { - switch i { - case 0 : 'no more bottles' - case 1 : 'one bottle' - default : '''�i� bottles''' - }.toString - } - - def String Bottles(int i) { - bottles(i).toFirstUpper - } -} \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/example.yaml b/third_party/pygments/tests/examplefiles/example.yaml deleted file mode 100644 index 9c0ed9d08..000000000 --- a/third_party/pygments/tests/examplefiles/example.yaml +++ /dev/null @@ -1,302 +0,0 @@ - -# -# Examples from the Preview section of the YAML specification -# (http://yaml.org/spec/1.2/#Preview) -# - -# Sequence of scalars ---- -- Mark McGwire -- Sammy Sosa -- Ken Griffey - -# Mapping scalars to scalars ---- -hr: 65 # Home runs -avg: 0.278 # Batting average -rbi: 147 # Runs Batted In - -# Mapping scalars to sequences ---- -american: - - Boston Red Sox - - Detroit Tigers - - New York Yankees -national: - - New York Mets - - Chicago Cubs - - Atlanta Braves - -# Sequence of mappings ---- -- - name: Mark McGwire - hr: 65 - avg: 0.278 -- - name: Sammy Sosa - hr: 63 - avg: 0.288 - -# Sequence of sequences ---- -- [name , hr, avg ] -- [Mark McGwire, 65, 0.278] -- [Sammy Sosa , 63, 0.288] - -# Mapping of mappings ---- -Mark McGwire: {hr: 65, avg: 0.278} -Sammy Sosa: { - hr: 63, - avg: 0.288 - } - -# Two documents in a stream ---- # Ranking of 1998 home runs -- Mark McGwire -- Sammy Sosa -- Ken Griffey ---- # Team ranking -- Chicago Cubs -- St Louis Cardinals - -# Documents with the end indicator ---- -time: 20:03:20 -player: Sammy Sosa -action: strike (miss) -... ---- -time: 20:03:47 -player: Sammy Sosa -action: grand slam -... - -# Comments ---- -hr: # 1998 hr ranking - - Mark McGwire - - Sammy Sosa -rbi: - # 1998 rbi ranking - - Sammy Sosa - - Ken Griffey - -# Anchors and aliases ---- -hr: - - Mark McGwire - # Following node labeled SS - - &SS Sammy Sosa -rbi: - - *SS # Subsequent occurrence - - Ken Griffey - -# Mapping between sequences ---- -? - Detroit Tigers - - Chicago cubs -: - - 2001-07-23 -? [ New York Yankees, - Atlanta Braves ] -: [ 2001-07-02, 2001-08-12, - 2001-08-14 ] - -# Inline nested mapping ---- -# products purchased -- item : Super Hoop - quantity: 1 -- item : Basketball - quantity: 4 -- item : Big Shoes - quantity: 1 - -# Literal scalars ---- | # ASCII art - \//||\/|| - // || ||__ - -# Folded scalars ---- > - Mark McGwire's - year was crippled - by a knee injury. - -# Preserved indented block in a folded scalar ---- -> - Sammy Sosa completed another - fine season with great stats. - - 63 Home Runs - 0.288 Batting Average - - What a year! - -# Indentation determines scope ---- -name: Mark McGwire -accomplishment: > - Mark set a major league - home run record in 1998. -stats: | - 65 Home Runs - 0.278 Batting Average - -# Quoted scalars ---- -unicode: "Sosa did fine.\u263A" -control: "\b1998\t1999\t2000\n" -hex esc: "\x0d\x0a is \r\n" -single: '"Howdy!" he cried.' -quoted: ' # not a ''comment''.' -tie-fighter: '|\-*-/|' - -# Multi-line flow scalars ---- -plain: - This unquoted scalar - spans many lines. -quoted: "So does this - quoted scalar.\n" - -# Integers ---- -canonical: 12345 -decimal: +12_345 -sexagesimal: 3:25:45 -octal: 014 -hexadecimal: 0xC - -# Floating point ---- -canonical: 1.23015e+3 -exponential: 12.3015e+02 -sexagesimal: 20:30.15 -fixed: 1_230.15 -negative infinity: -.inf -not a number: .NaN - -# Miscellaneous ---- -null: ~ -true: boolean -false: boolean -string: '12345' - -# Timestamps ---- -canonical: 2001-12-15T02:59:43.1Z -iso8601: 2001-12-14t21:59:43.10-05:00 -spaced: 2001-12-14 21:59:43.10 -5 -date: 2002-12-14 - -# Various explicit tags ---- -not-date: !!str 2002-04-28 -picture: !!binary | - R0lGODlhDAAMAIQAAP//9/X - 17unp5WZmZgAAAOfn515eXv - Pz7Y6OjuDg4J+fn5OTk6enp - 56enmleECcgggoBADs= -application specific tag: !something | - The semantics of the tag - above may be different for - different documents. - -# Global tags -%TAG ! tag:clarkevans.com,2002: ---- !shape - # Use the ! handle for presenting - # tag:clarkevans.com,2002:circle -- !circle - center: &ORIGIN {x: 73, y: 129} - radius: 7 -- !line - start: *ORIGIN - finish: { x: 89, y: 102 } -- !label - start: *ORIGIN - color: 0xFFEEBB - text: Pretty vector drawing. - -# Unordered sets ---- !!set -# sets are represented as a -# mapping where each key is -# associated with the empty string -? Mark McGwire -? Sammy Sosa -? Ken Griff - -# Ordered mappings ---- !!omap -# ordered maps are represented as -# a sequence of mappings, with -# each mapping having one key -- Mark McGwire: 65 -- Sammy Sosa: 63 -- Ken Griffy: 58 - -# Full length example ---- ! -invoice: 34843 -date : 2001-01-23 -bill-to: &id001 - given : Chris - family : Dumars - address: - lines: | - 458 Walkman Dr. - Suite #292 - city : Royal Oak - state : MI - postal : 48046 -ship-to: *id001 -product: - - sku : BL394D - quantity : 4 - description : Basketball - price : 450.00 - - sku : BL4438H - quantity : 1 - description : Super Hoop - price : 2392.00 -tax : 251.42 -total: 4443.52 -comments: - Late afternoon is best. - Backup contact is Nancy - Billsmer @ 338-4338. - -# Another full-length example ---- -Time: 2001-11-23 15:01:42 -5 -User: ed -Warning: - This is an error message - for the log file ---- -Time: 2001-11-23 15:02:31 -5 -User: ed -Warning: - A slightly different error - message. ---- -Date: 2001-11-23 15:03:17 -5 -User: ed -Fatal: - Unknown variable "bar" -Stack: - - file: TopClass.py - line: 23 - code: | - x = MoreObject("345\n") - - file: MoreClass.py - line: 58 - code: |- - foo = bar - diff --git a/third_party/pygments/tests/examplefiles/example1.cadl b/third_party/pygments/tests/examplefiles/example1.cadl deleted file mode 100644 index 3350fa3bb..000000000 --- a/third_party/pygments/tests/examplefiles/example1.cadl +++ /dev/null @@ -1,149 +0,0 @@ - -- - -- Example fragment of an openEHR Archetype, written in cADL, a subsyntax of the Archetype Definition Language (ADL) - -- definition available here: http://www.openehr.org/releases/trunk/architecture/am/adl2.pdf - -- Author: Thomas Beale - -- - - EVALUATION[id1] matches { -- Adverse Reaction - data matches { - ITEM_TREE[id2] matches { - items cardinality matches {1..*; unordered} matches { - ELEMENT[id3] matches { -- Substance/Agent - value matches { - DV_TEXT[id51] - } - } - ELEMENT[id5] occurrences matches {0..1} matches { -- Absolute Contraindication? - value matches { - DV_BOOLEAN[id52] matches { - value matches {True} - } - } - } - ELEMENT[id50] occurrences matches {0..1} matches { -- Future Use - value matches { - DV_TEXT[id53] - } - } - ELEMENT[id7] occurrences matches {0..1} matches { -- Overall Comment - value matches { - DV_TEXT[id54] - } - } - CLUSTER[id10] matches { -- Reaction Event - items matches { - ELEMENT[id11] occurrences matches {0..1} matches { -- Specific Substance/Agent - value matches { - DV_TEXT[id55] - } - } - ELEMENT[id12] matches { -- Manifestation - value matches { - DV_TEXT[id56] - } - } - ELEMENT[id17] occurrences matches {0..1} matches { -- Reaction Type - value matches { - DV_TEXT[id57] - } - } - ELEMENT[id22] occurrences matches {0..1} matches { -- Certainty - value matches { - DV_CODED_TEXT[id58] matches { - defining_code matches {[ac1]} -- Certainty (synthesised) - } - } - } - ELEMENT[id13] occurrences matches {0..1} matches { -- Reaction Description - value matches { - DV_TEXT[id59] - } - } - ELEMENT[id28] occurrences matches {0..1} matches { -- Onset of Reaction - value matches { - DV_DATE_TIME[id60] - } - } - ELEMENT[id29] occurrences matches {0..1} matches { -- Duration of Reaction - value matches { - DV_DURATION[id61] - } - } - allow_archetype CLUSTER[id30] matches { -- Additional Reaction Detail - include - archetype_id/value matches {/openEHR-EHR-CLUSTER\.anatomical_location(-a-zA-Z0-9_]+)*\.v1/} - } - ELEMENT[id19] occurrences matches {0..1} matches { -- Exposure Description - value matches { - DV_TEXT[id62] - } - } - ELEMENT[id21] occurrences matches {0..1} matches { -- Earliest Exposure - value matches { - DV_DATE_TIME[id63] - } - } - ELEMENT[id26] occurrences matches {0..1} matches { -- Duration of Exposure - value matches { - DV_DURATION[id64] - } - } - allow_archetype CLUSTER[id20] matches { -- Additional Exposure Detail - include - archetype_id/value matches {/openEHR-EHR-CLUSTER\.amount(-a-zA-Z0-9_]+)*\.v1|openEHR-EHR-CLUSTER\.medication_admin(-a-zA-Z0-9_]+)*\.v1|openEHR-EHR-CLUSTER\.timing(-a-zA-Z0-9_]+)*\.v1/} - } - ELEMENT[id41] occurrences matches {0..1} matches { -- Clinical Management Description - value matches { - DV_TEXT[id65] - } - } - ELEMENT[id32] matches { -- Multimedia - value matches { - DV_MULTIMEDIA[id66] matches { - media_type - } - } - } - allow_archetype CLUSTER[id42] matches { -- Reporting Details - include - archetype_id/value matches {/.*/} - } - ELEMENT[id33] occurrences matches {0..1} matches { -- Reaction Comment - value matches { - DV_TEXT[id67] - } - } - } - } - } - } - } - protocol matches { - ITEM_TREE[id43] matches { - items matches { - ELEMENT[id45] occurrences matches {0..1} matches { -- Reaction Reported? - value matches { - DV_BOOLEAN[id68] matches { - value matches {True, False} - } - } - } - ELEMENT[id49] occurrences matches {0..1} matches { -- Report Comment - value matches { - DV_TEXT[id69] - } - } - ELEMENT[id46] matches { -- Adverse Reaction Report - value matches { - DV_URI[id70] - } - } - ELEMENT[id48] occurrences matches {0..1} matches { -- Supporting Clinical Record Information - value matches { - DV_EHR_URI[id71] - } - } - } - } - } - } diff --git a/third_party/pygments/tests/examplefiles/example2.aspx b/third_party/pygments/tests/examplefiles/example2.aspx deleted file mode 100644 index 52b7c0017..000000000 --- a/third_party/pygments/tests/examplefiles/example2.aspx +++ /dev/null @@ -1,29 +0,0 @@ -<%@ Register TagPrefix="Acme" TagName="Message" Src="userctrl2_vb.ascx" %> - - - - - - - -

    A Simple User Control w/ Properties

    - -
    - - - -

    - - - - - - - diff --git a/third_party/pygments/tests/examplefiles/example2.msc b/third_party/pygments/tests/examplefiles/example2.msc deleted file mode 100644 index 61e2ef837..000000000 --- a/third_party/pygments/tests/examplefiles/example2.msc +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/mscgen -Tpng -# -# testinput2.msc : Sample msc input file with URLs -# -# This file is PUBLIC DOMAIN and may be freely reproduced, distributed, -# transmitted, used, modified, built upon, or otherwise exploited by -# anyone for any purpose, commercial or non-commercial, and in any way, -# including by methods that have not yet been invented or conceived. -# -# This file is provided "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. -# - -# Note: This is from mscgen-0.20 - -msc { - -A,B; - ---- [label="Start", ID="1"]; - -A->B [label="signal"]; -A<-B [label="signal"]; - - -A=>B [label="method"]; -A<=B [label="method"]; - -A>>B [label="return"]; -A<>B [label="call-back"]; -A<<=B [label="call-back", URL="www.google.com"]; - -A x- B [label="loss"]; -A -x B [label="loss"]; - ---- [label="Left arcs", ID="2", IDURL="www.google.co.uk"]; - -A->A [label="signal"]; -A<-A [label="signal"]; - - -A=>A [label="method"]; -A<=A [label="method"]; - -A>>A [label="return"]; -A<>A [label="call-back"]; -A<<=A [label="call-back", URL="www.google.com", ID="3"]; - -A x- A [label="loss"]; -A -x A [label="loss"]; - ---- [label="Right arcs"]; - -B->B [label="signal"]; -B<-B [label="signal"]; - - -B=>B [label="method"]; -B<=B [label="method"]; - -B>>B [label="return"]; -B<>B [label="call-back", ID="4"]; -B<<=B [label="call-back", URL="www.google.com"]; - -B x- B [label="loss"]; -B -x B [label="loss"]; - ---- [label="End of arcs", URL="www.google.com"]; - - -... [label="Some time passes", URL="www.google.com"]; -} diff --git a/third_party/pygments/tests/examplefiles/exampleScript.cfc b/third_party/pygments/tests/examplefiles/exampleScript.cfc deleted file mode 100644 index 002acbcdc..000000000 --- a/third_party/pygments/tests/examplefiles/exampleScript.cfc +++ /dev/null @@ -1,241 +0,0 @@ - -/** -******************************************************************************** -ContentBox - A Modular Content Platform -Copyright 2012 by Luis Majano and Ortus Solutions, Corp -www.gocontentbox.org | www.luismajano.com | www.ortussolutions.com -******************************************************************************** -Apache License, Version 2.0 - -Copyright Since [2012] [Luis Majano and Ortus Solutions,Corp] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -******************************************************************************** -* A generic content service for content objects -*/ -component extends="coldbox.system.orm.hibernate.VirtualEntityService" singleton{ - - // DI - property name="settingService" inject="id:settingService@cb"; - property name="cacheBox" inject="cachebox"; - property name="log" inject="logbox:logger:{this}"; - property name="customFieldService" inject="customFieldService@cb"; - property name="categoryService" inject="categoryService@cb"; - property name="commentService" inject="commentService@cb"; - property name="contentVersionService" inject="contentVersionService@cb"; - property name="authorService" inject="authorService@cb"; - property name="populator" inject="wirebox:populator"; - property name="systemUtil" inject="SystemUtil@cb"; - - /* - * Constructor - * @entityName.hint The content entity name to bind this service to. - */ - ContentService function init(entityName="cbContent"){ - // init it - super.init(entityName=arguments.entityName, useQueryCaching=true); - - // Test scope coloring in pygments - this.colorTestVar = "Just for testing pygments!"; - cookie.colorTestVar = ""; - client.colorTestVar = "" - session.colorTestVar = ""; - application.colorTestVar = ""; - - return this; - } - - /** - * Clear all content caches - * @async.hint Run it asynchronously or not, defaults to false - */ - function clearAllCaches(boolean async=false){ - var settings = settingService.getAllSettings(asStruct=true); - // Get appropriate cache provider - var cache = cacheBox.getCache( settings.cb_content_cacheName ); - cache.clearByKeySnippet(keySnippet="cb-content",async=arguments.async); - return this; - } - - /** - * Clear all page wrapper caches - * @async.hint Run it asynchronously or not, defaults to false - */ - function clearAllPageWrapperCaches(boolean async=false){ - var settings = settingService.getAllSettings(asStruct=true); - // Get appropriate cache provider - var cache = cacheBox.getCache( settings.cb_content_cacheName ); - cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper",async=arguments.async); - return this; - } - - /** - * Clear all page wrapper caches - * @slug.hint The slug partial to clean on - * @async.hint Run it asynchronously or not, defaults to false - */ - function clearPageWrapperCaches(required any slug, boolean async=false){ - var settings = settingService.getAllSettings(asStruct=true); - // Get appropriate cache provider - var cache = cacheBox.getCache( settings.cb_content_cacheName ); - cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper-#arguments.slug#",async=arguments.async); - return this; - } - - /** - * Clear a page wrapper cache - * @slug.hint The slug to clean - * @async.hint Run it asynchronously or not, defaults to false - */ - function clearPageWrapper(required any slug, boolean async=false){ - var settings = settingService.getAllSettings(asStruct=true); - // Get appropriate cache provider - var cache = cacheBox.getCache( settings.cb_content_cacheName ); - cache.clear("cb-content-pagewrapper-#arguments.slug#/"); - return this; - } - - /** - * Searches published content with cool paramters, remember published content only - * @searchTerm.hint The search term to search - * @max.hint The maximum number of records to paginate - * @offset.hint The offset in the pagination - * @asQuery.hint Return as query or array of objects, defaults to array of objects - * @sortOrder.hint The sorting of the search results, defaults to publishedDate DESC - * @isPublished.hint Search for published, non-published or both content objects [true, false, 'all'] - * @searchActiveContent.hint Search only content titles or both title and active content. Defaults to both. - */ - function searchContent( - any searchTerm="", - numeric max=0, - numeric offset=0, - boolean asQuery=false, - any sortOrder="publishedDate DESC", - any isPublished=true, - boolean searchActiveContent=true){ - - var results = {}; - var c = newCriteria(); - - // only published content - if( isBoolean( arguments.isPublished ) ){ - // Published bit - c.isEq( "isPublished", javaCast( "Boolean", arguments.isPublished ) ); - // Published eq true evaluate other params - if( arguments.isPublished ){ - c.isLt("publishedDate", now() ) - .$or( c.restrictions.isNull("expireDate"), c.restrictions.isGT("expireDate", now() ) ) - .isEq("passwordProtection",""); - } - } - - // Search Criteria - if( len( arguments.searchTerm ) ){ - // like disjunctions - c.createAlias("activeContent","ac"); - // Do we search title and active content or just title? - if( arguments.searchActiveContent ){ - c.$or( c.restrictions.like("title","%#arguments.searchTerm#%"), - c.restrictions.like("ac.content", "%#arguments.searchTerm#%") ); - } - else{ - c.like( "title", "%#arguments.searchTerm#%" ); - } - } - - // run criteria query and projections count - results.count = c.count( "contentID" ); - results.content = c.resultTransformer( c.DISTINCT_ROOT_ENTITY ) - .list(offset=arguments.offset, max=arguments.max, sortOrder=arguments.sortOrder, asQuery=arguments.asQuery); - - return results; - } - -/********************************************* PRIVATE *********************************************/ - - - /** - * Update the content hits - * @contentID.hint The content id to update - */ - private function syncUpdateHits(required contentID){ - var q = new Query(sql="UPDATE cb_content SET hits = hits + 1 WHERE contentID = #arguments.contentID#").execute(); - return this; - } - - - private function closureTest(){ - methodCall( - param1, - function( arg1, required arg2 ){ - var settings = settingService.getAllSettings(asStruct=true); - // Get appropriate cache provider - var cache = cacheBox.getCache( settings.cb_content_cacheName ); - cache.clear("cb-content-pagewrapper-#arguments.slug#/"); - return this; - }, - param1 - ); - } - - private function StructliteralTest(){ - return { - foo = bar, - brad = 'Wood', - func = function( arg1, required arg2 ){ - var settings = settingService.getAllSettings(asStruct=true); - // Get appropriate cache provider - var cache = cacheBox.getCache( settings.cb_content_cacheName ); - cache.clear("cb-content-pagewrapper-#arguments.slug#/"); - return this; - }, - array = [ - 1, - 2, - 3, - 4, - 5, - 'test', - 'testing', - 'testerton', - { - foo = true, - brad = false, - wood = null - } - ], - last = "final" - }; - } - - private function arrayliteralTest(){ - return [ - 1, - 2, - 3, - 4, - 5, - 'test', - 'testing', - 'testerton', - { - foo = true, - brad = false, - wood = null - }, - 'testy-von-testavich' - ]; - } - -} - \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/exampleTag.cfc b/third_party/pygments/tests/examplefiles/exampleTag.cfc deleted file mode 100644 index 753bb8268..000000000 --- a/third_party/pygments/tests/examplefiles/exampleTag.cfc +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/example_coq.v b/third_party/pygments/tests/examplefiles/example_coq.v deleted file mode 100644 index fd1a7bc8c..000000000 --- a/third_party/pygments/tests/examplefiles/example_coq.v +++ /dev/null @@ -1,4 +0,0 @@ -Lemma FalseLemma : False <-> False. -tauto. -Qed. -Check FalseLemma. diff --git a/third_party/pygments/tests/examplefiles/example_elixir.ex b/third_party/pygments/tests/examplefiles/example_elixir.ex deleted file mode 100644 index ddca7f606..000000000 --- a/third_party/pygments/tests/examplefiles/example_elixir.ex +++ /dev/null @@ -1,233 +0,0 @@ -# Numbers -0b0101011 -1234 ; 0x1A ; 0xbeef ; 0763 ; 0o123 -3.14 ; 5.0e21 ; 0.5e-12 -100_000_000 - -# these are not valid numbers -0b012 ; 0xboar ; 0o888 -0B01 ; 0XAF ; 0O123 - -# Characters -?a ; ?1 ; ?\n ; ?\s ; ?\c ; ? ; ?, -?\x{12} ; ?\x{abcd} -?\x34 ; ?\xF - -# these show that only the first digit is part of the character -?\123 ; ?\12 ; ?\7 - -# Atoms -:this ; :that -:'complex atom' -:"with' \"\" 'quotes" -:" multi - line ' \s \123 \xff -atom" -:... ; :<<>> ; :%{} ; :% ; :{} -:++; :--; :*; :~~~; ::: -:% ; :. ; :<- - -# Strings -"Hello world" -"Interspersed \x{ff} codes \7 \8 \65 \016 and \t\s\\s\z\+ \\ escapes" -"Quotes ' inside \" \123 the \"\" \xF \\xF string \\\" end" -"Multiline - string" - -# Char lists -'this is a list' -'escapes \' \t \\\'' -'Multiline - char - list -' - -# Binaries -<<1, 2, 3>> -<<"hello"::binary, c :: utf8, x::[4, unit(2)]>> = "hello™1" - -# Sigils -~r/this + i\s "a" regex/ -~R'this + i\s "a" regex too' -~w(hello #{ ["has" <> "123", '\c\d', "\123 interpol" | []] } world)s -~W(hello #{no "123" \c\d \123 interpol} world)s - -~s{Escapes terminators \{ and \}, but no {balancing} # outside of sigil here } - -~S"No escapes \s\t\n and no #{interpolation}" - -:"atoms work #{"to" <> "o"}" - -# Operators -x = 1 + 2.0 * 3 -y = true and false; z = false or true -... = 144 -... == !x && y || z -"hello" |> String.upcase |> String.downcase() -{^z, a} = {true, x} - -# Free operators (added in 1.0.0) -p ~>> f = bind(p, f) -p1 ~> p2 = pair_right(p1, p2) -p1 <~ p2 = pair_left(p1, p2) -p1 <~> p2 = pair_both(p1, p2) -p |~> f = map(p, f) -p1 <|> p2 = either(p1, p2) - -# Lists, tuples, maps, keywords -[1, :a, 'hello'] ++ [2, 3] -[:head | [?t, ?a, ?i, ?l]] - -{:one, 2.0, "three"} - -[...: "this", <<>>: "is", %{}: "a keyword", %: "list", {}: "too"] -["this is an atom too": 1, "so is this": 2] -[option: "value", key: :word] -[++: "operator", ~~~: :&&&] - -map = %{shortcut: "syntax"} -%{map | "update" => "me"} -%{ 12 => 13, :weird => ['thing'] } - -# Comprehensions -for x <- 1..10, x < 5, do: {x, x} -pixels = "12345678" -for << <> <- pixels >> do - [r, {g, %{"b" => a}}] -end - -# String interpolation -"String #{inspect "interpolation"} is quite #{1+4+7} difficult" - -# Identifiers -abc_123 = 1 -_018OP = 2 -A__0 == 3 - -# Modules -defmodule Long.Module.Name do - @moduledoc "Simple module docstring" - - @doc """ - Multiline docstring - "with quotes" - and #{ inspect %{"interpolation" => "in" <> "action"} } - now with #{ {:a, 'tuple'} } - and #{ inspect { - :tuple, - %{ with: "nested #{ inspect %{ :interpolation => %{} } }" } - } } - """ - defstruct [:a, :name, :height] - - @doc ~S''' - No #{interpolation} of any kind. - \000 \x{ff} - - \n #{\x{ff}} - ''' - def func(a, b \\ []), do: :ok - - @doc false - def __before_compile__(_) do - :ok - end -end - -# Structs -defmodule Second.Module do - s = %Long.Module.Name{name: "Silly"} - %Long.Module.Name{s | height: {192, :cm}} - ".. #{%Long.Module.Name{s | height: {192, :cm}}} .." -end - -# Types, pseudo-vars, attributes -defmodule M do - @custom_attr :some_constant - - @before_compile Long.Module.Name - - @typedoc "This is a type" - @type typ :: integer - - @typedoc """ - Another type - """ - @opaque typtyp :: 1..10 - - @spec func(typ, typtyp) :: :ok | :fail - def func(a, b) do - a || b || :ok || :fail - Path.expand("..", __DIR__) - IO.inspect __ENV__ - __NOTAPSEUDOVAR__ = 11 - __MODULE__.func(b, a) - end - - defmacro m() do - __CALLER__ - end -end - -# Functions -anon = fn x, y, z -> - fn(a, b, c) -> - &(x + y - z * a / &1 + b + div(&2, c)) - end -end - -&Set.put(&1, &2) ; & Set.put(&1, &2) ; &( Set.put(&1, &1) ) - -# Function calls -anon.(1, 2, 3); self; hd([1,2,3]) -Kernel.spawn(fn -> :ok end) -IO.ANSI.black - -# Control flow -if :this do - :that -else - :otherwise -end - -pid = self -receive do - {:EXIT, _} -> :done - {^pid, :_} -> nil - after 100 -> :no_luck -end - -case __ENV__.line do - x when is_integer(x) -> x - x when x in 1..12 -> -x -end - -cond do - false -> "too bad" - 4 > 5 -> "oops" - true -> nil -end - -# Lexical scope modifiers -import Kernel, except: [spawn: 1, +: 2, /: 2, Unless: 2] -alias Long.Module.Name, as: N0men123_and4 -use Bitwise - -4 &&& 5 -2 <<< 3 - -# Protocols -defprotocol Useless do - def func1(this) - def func2(that) -end - -defimpl Useless, for: Atom do -end - -# Exceptions -defmodule NotAnError do - defexception [:message] -end - -raise NotAnError, message: "This is not an error" diff --git a/third_party/pygments/tests/examplefiles/example_file.fy b/third_party/pygments/tests/examplefiles/example_file.fy deleted file mode 100644 index 43e80c1d7..000000000 --- a/third_party/pygments/tests/examplefiles/example_file.fy +++ /dev/null @@ -1,128 +0,0 @@ -class Person { - def initialize: @name age: @age { - """ - This is a docstring for the Person constructor method. - Docstrings usually are multi-line, like this one. - """ - } - - def to_s { - # return is optional in this case, but we use it nontheless - return "Person with name: #{@name inspect} and age: #{@age}" - } -} - -class PersonWithCity : Person { - def initialize: @name age: @age city: @city { - } - - def to_s { - super to_s ++ " living in: #{@city inspect}" - } -} - -p1 = Person new: "Johnny Jackson" age: 42 -p1 println # prints: Person with name: "Johnny Jackson" and age: 42 - -p2 = PersonWithCity new: "John Appleseed" age: 55 city: "New York" -p2 println # prints: Person with name: "John Appleseed" age: 55 living in: "New York" - -array = [1,2,3, "foo", 'bar] -hash = <['foo => "bar", 'bar => 42]> -tuple = (1,2,"hello","world") -block = |x, y| { - x + y println -} -block call: [4,2] - -0b010101 & 0b00101 to_s: 2 . println -0xFF & 0xAB to_s: 16 . println -0o77 > 0o76 println -123.123 + 0.222 println - -x = 0 -try { - 10 / x println -} catch ZeroDivisionError => e { - x = 3 - retry -} finally { - "Finally, done!" println -} - -def a_method: arg1 with_default_arg: arg2 (42) { - arg1 * arg2 println -} - -a_method: 42 -a_method: 42 with_default_arg: 85 - -class ClassWithClassMethod { - def self class_method1 { - 'works - } - - def ClassWithClassMethod class_method2 { - 'this_as_well - } -} - -ClassWithClassMethod class_method1 println -ClassWithClassMethod class_method2 println - -def another_method: block { - 1 upto: 10 . map: block -} - -# local returns -another_method: |x| { return_local x * 2 } . inspect println - - -# pattern matching: -class PatternMatching { - def match_it: obj { - match obj { - case String -> "It's a String!" println - case Fixnum -> "It's a Number!" println - case _ -> "Aything else!" println - } - } - - def match_with_extract: str { - match str { - # m holds the MatchData object, m1 & m2 the first and second matches - case /^(.*) : (.*)$/ -> |m, m1, m2| - "First match: #{m1}" println - "Second match: #{m2}" println - } - } -} - -pm = PatternMatching new -pm match_it: "foo" -pm match_it: 42 -pm match_it: 'foo - -pm match_with_extract: "Hello : World!" - - -# calling ruby methods: -[3, 2, 1] reverse() each() |a| { puts(a) } -"Hello" sub("ll", "y") println -[3, 2, 1] map() |a| { a * 2 } inject(0) |s i| { s + i } println - -# test symbol highlighting -['foo] -['foo?!] -{'foo} -{'foo!?} -{'foo:bar?!=&/:} -('foo) - -# future sends -42 @ to_s class println -42 @ to_s: 16 . value println - -# async sends -42 @@ println -42 @@ upto: 100 diff --git a/third_party/pygments/tests/examplefiles/ezhil_primefactors.n b/third_party/pygments/tests/examplefiles/ezhil_primefactors.n deleted file mode 100644 index 133906118..000000000 --- a/third_party/pygments/tests/examplefiles/ezhil_primefactors.n +++ /dev/null @@ -1,152 +0,0 @@ -# (C) முத்தையா அண்ணாமலை 2013 -# (A) என். சொக்கன் -# எழில் தமிழ் நிரலாக்க மொழி உதாரணம் -# Muthu A granted permission for this to be included under the BSD license -# https://bitbucket.org/birkenfeld/pygments-main/pull-requests/443/ezhil-language-lexer-for-pygments/diff - -## Prime Factors Example -## பகா எண் கூறுகளைக் கண்டறியும் உதாரணம் - -## இது நிரல் தரப்பட்ட எண்ணின் பகாஎண் கூறுகளைக் கண்டறியும் - -நிரல்பாகம் பகாஎண்ணா(எண்1) - - ## இது நிரல்பாகம் தரப்பட்ட எண் பகு எண்ணா அல்லது பகா எண்ணா என்று கண்டறிந்து சொல்லும் - ## பகுஎண் என்றால் 0 திரும்பத் தரப்படும் - ## பகாஎண் என்றால் 1 திரும்பத் தரப்படும் - - @(எண்1 < 0) ஆனால் - - ## எதிர்மறை எண்களை நேராக்குதல் - - எண்1 = எண்1 * (-1) - - முடி - - @(எண்1 < 2) ஆனால் - - ## பூஜ்ஜியம், ஒன்று ஆகியவை பகா எண்கள் அல்ல - - பின்கொடு 0 - - முடி - - @(எண்1 == 2) ஆனால் - - ## இரண்டு என்ற எண் ஒரு பகா எண் - - பின்கொடு 1 - - முடி - - மீதம் = எண்1%2 - - @(மீதம் == 0) ஆனால் - - ## இரட்டைப்படை எண், ஆகவே, இது பகா எண் அல்ல - - பின்கொடு 0 - - முடி - - எண்1வர்க்கமூலம் = எண்1^0.5 - - @(எண்2 = 3, எண்2 <= எண்1வர்க்கமூலம், எண்2 = எண்2 + 2) ஆக - - மீதம்1 = எண்1%எண்2 - - @(மீதம்1 == 0) ஆனால் - - ## ஏதேனும் ஓர் எண்ணால் முழுமையாக வகுபட்டுவிட்டது, ஆகவே அது பகா எண் அல்ல - - பின்கொடு 0 - - முடி - - முடி - - பின்கொடு 1 - -முடி - -நிரல்பாகம் பகுத்தெடு(எண்1) - - ## இது எண் தரப்பட்ட எண்ணின் பகா எண் கூறுகளைக் கண்டறிந்து பட்டியல் இடும் - - கூறுகள் = பட்டியல்() - - @(எண்1 < 0) ஆனால் - - ## எதிர்மறை எண்களை நேராக்குதல் - - எண்1 = எண்1 * (-1) - - முடி - - @(எண்1 <= 1) ஆனால் - - ## ஒன்று அல்லது அதற்குக் குறைவான எண்களுக்குப் பகா எண் விகிதம் கண்டறியமுடியாது - - பின்கொடு கூறுகள் - - முடி - - @(பகாஎண்ணா(எண்1) == 1) ஆனால் - - ## தரப்பட்ட எண்ணே பகா எண்ணாக அமைந்துவிட்டால், அதற்கு அதுவே பகாஎண் கூறு ஆகும் - - பின்இணை(கூறுகள், எண்1) - பின்கொடு கூறுகள் - - முடி - - தாற்காலிகஎண் = எண்1 - - எண்2 = 2 - - @(எண்2 <= தாற்காலிகஎண்) வரை - - விடை1 = பகாஎண்ணா(எண்2) - மீண்டும்தொடங்கு = 0 - - @(விடை1 == 1) ஆனால் - - விடை2 = தாற்காலிகஎண்%எண்2 - - @(விடை2 == 0) ஆனால் - - ## பகா எண்ணால் முழுமையாக வகுபட்டுள்ளது, அதனைப் பட்டியலில் இணைக்கிறோம் - - பின்இணை(கூறுகள், எண்2) - தாற்காலிகஎண் = தாற்காலிகஎண்/எண்2 - - ## மீண்டும் இரண்டில் தொடங்கி இதே கணக்கிடுதலைத் தொடரவேண்டும் - - எண்2 = 2 - மீண்டும்தொடங்கு = 1 - - முடி - - முடி - - @(மீண்டும்தொடங்கு == 0) ஆனால் - - ## அடுத்த எண்ணைத் தேர்ந்தெடுத்துக் கணக்கிடுதலைத் தொடரவேண்டும் - - எண்2 = எண்2 + 1 - - முடி - - முடி - - பின்கொடு கூறுகள் - -முடி - -அ = int(உள்ளீடு("உங்களுக்குப் பிடித்த ஓர் எண்ணைத் தாருங்கள்: ")) - -பகாஎண்கூறுகள் = பட்டியல்() - -பகாஎண்கூறுகள் = பகுத்தெடு(அ) - -பதிப்பி "நீங்கள் தந்த எண்ணின் பகா எண் கூறுகள் இவை: ", பகாஎண்கூறுகள் diff --git a/third_party/pygments/tests/examplefiles/firefox.mak b/third_party/pygments/tests/examplefiles/firefox.mak deleted file mode 100644 index 4dc0f1674..000000000 --- a/third_party/pygments/tests/examplefiles/firefox.mak +++ /dev/null @@ -1,586 +0,0 @@ -# -# ***** BEGIN LICENSE BLOCK ***** -# Version: MPL 1.1/GPL 2.0/LGPL 2.1 -# -# The contents of this file are subject to the Mozilla Public License Version -# 1.1 (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# http://www.mozilla.org/MPL/ -# -# Software distributed under the License is distributed on an "AS IS" basis, -# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License -# for the specific language governing rights and limitations under the -# License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is -# Netscape Communications Corporation. -# Portions created by the Initial Developer are Copyright (C) 1998 -# the Initial Developer. All Rights Reserved. -# -# Contributor(s): -# -# Alternatively, the contents of this file may be used under the terms of -# either the GNU General Public License Version 2 or later (the "GPL"), or -# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), -# in which case the provisions of the GPL or the LGPL are applicable instead -# of those above. If you wish to allow use of your version of this file only -# under the terms of either the GPL or the LGPL, and not to allow others to -# use your version of this file under the terms of the MPL, indicate your -# decision by deleting the provisions above and replace them with the notice -# and other provisions required by the GPL or the LGPL. If you do not delete -# the provisions above, a recipient may use your version of this file under -# the terms of any one of the MPL, the GPL or the LGPL. -# -# ***** END LICENSE BLOCK ***** - -DEPTH = . -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -include $(topsrcdir)/build/unix/modules.mk - -ifeq ($(BUILD_MODULES),all) -# -# And now for something completely different... -# Divide the default build into tiers. -# Tiers must be defined on module boundaries -# -SUPPRESS_DEFAULT_RULES = 1 - -default alldep all:: $(SUBMAKEFILES) - $(RM) -rf $(DIST)/sdk - $(RM) -rf $(DIST)/include - $(MAKE) -C config export - $(MAKE) nspr - $(MAKE) ldap - $(MAKE) tier_0 - $(MAKE) tier_1 - $(MAKE) tier_2 - $(MAKE) tier_9 - $(MAKE) tier_50 - $(MAKE) tier_99 - -# Make sure that the existing rulesets work -DIRS = \ - $(tier_0_dirs) \ - $(tier_1_dirs) \ - $(tier_2_dirs) \ - $(tier_9_dirs) \ - $(tier_50_dirs) \ - $(NULL) - -ifdef GC_LEAK_DETECTOR -DIRS += gc/boehm -endif - -DIRS += $(tier_99_dirs) - -# -# tier 0 - base build config dirs -# -tier_0_dirs = \ - config \ - build \ - $(NULL) - -# -# tier 1 - 3rd party individual libraries -# -tier_1_dirs += dbm - -ifndef MOZ_NATIVE_JPEG -tier_1_dirs += jpeg -endif - -ifndef MOZ_NATIVE_ZLIB -tier_1_dirs += modules/zlib -endif - -# Installer needs standalone libjar, hence standalone zlib -ifdef MOZ_INSTALLER -tier_1_dirs += modules/zlib/standalone -endif - -ifdef MOZ_UPDATER -tier_1_dirs += modules/libbz2 -tier_1_dirs += modules/libmar -endif - -ifdef MOZ_SVG_RENDERER_LIBART -tier_1_dirs += other-licenses/libart_lgpl -endif - -# -# tier 2 - base libraries -# -tier_2_dirs = \ - js \ - xpcom \ - $(NULL) - -ifndef MOZ_NO_XPCOM_OBSOLETE -tier_2_dirs += modules/libreg xpcom/obsolete -endif - -ifdef NS_TRACE_MALLOC -tier_2_dirs += tools/trace-malloc/lib -endif - -# -# tier 9 - core components (necko,gecko) -# - -tier_9_dirs += \ - js/src/xpconnect \ - intl \ - db \ - $(NULL) - -ifdef MOZ_STORAGE -tier_9_dirs += storage -endif - -ifdef MOZ_ENABLE_XLIB -tier_9_dirs += gfx/src/xlibrgb widget/src/xlibxtbin -endif - -ifdef MOZ_ENABLE_GTK -tier_9_dirs += widget/src/gtksuperwin widget/src/gtkxtbin -endif - -ifdef MOZ_ENABLE_GTK2 -tier_9_dirs += widget/src/gtkxtbin -endif - -ifdef MOZ_IPCD -tier_9_dirs += ipc/ipcd -endif - -ifdef MOZ_JSDEBUGGER -tier_9_dirs += js/jsd -endif - -tier_9_dirs += \ - modules/libutil \ - netwerk \ - modules/libjar \ - uriloader \ - modules/libpref \ - modules/libimg \ - caps \ - rdf \ - parser/expat \ - parser/xml \ - parser/htmlparser \ - gfx \ - modules/libpr0n \ - sun-java \ - modules/plugin \ - dom \ - view \ - widget \ - content \ - layout \ - xpfe/components/shistory \ - docshell \ - webshell \ - embedding \ - editor \ - xpfe/appshell \ - $(NULL) - -ifdef MOZ_OJI -tier_9_dirs += \ - js/src/liveconnect \ - modules/oji \ - $(NULL) -endif - -ifdef ACCESSIBILITY -tier_9_dirs += accessible -endif - -# -# tier 50 - xpfe & toolkit -# - -ifdef MOZ_XUL -ifdef MOZ_XUL_APP -tier_50_dirs += chrome -else -tier_50_dirs += rdf/chrome -endif -else -tier_50_dirs += embedding/minimo/chromelite -endif - -tier_50_dirs += profile - -# This must preceed xpfe -ifdef MOZ_JPROF -tier_50_dirs += tools/jprof -endif - -ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT))) -tier_50_dirs += xpfe/bootstrap/appleevents -endif - -tier_50_dirs += \ - xpfe \ - toolkit/components \ - $(NULL) - -ifndef MOZ_XUL_APP -tier_50_dirs += themes -endif - -ifdef MOZ_ENABLE_XREMOTE -tier_50_dirs += widget/src/xremoteclient -endif - -ifdef MOZ_XUL_APP -tier_50_dirs += toolkit -endif - -ifdef MOZ_PHOENIX -#XXXBlake this shell path is a temp hack; toolkit shouldn't depend on browser -tier_50_dirs += browser/components/shell/public -endif - -ifdef MOZ_XPINSTALL -tier_50_dirs += xpinstall -endif - -# JavaXPCOM JNI code is compiled into libXUL -ifdef MOZ_JAVAXPCOM -tier_50_dirs += extensions/java/xpcom/src -endif - -ifdef MOZ_ENABLE_LIBXUL -tier_50_dirs += \ - toolkit/library \ - xpcom/stub \ - $(NULL) -endif - -ifdef NS_TRACE_MALLOC -tier_50_dirs += tools/trace-malloc -endif - -ifdef MOZ_PSM -tier_50_dirs += security/manager -else -tier_50_dirs += security/manager/boot/public security/manager/ssl/public -endif - -ifdef MOZ_LDAP_XPCOM -tier_50_dirs += directory/xpcom -endif - -ifndef MINIMO -ifdef MOZ_XUL_APP -ifdef MOZ_ENABLE_GTK2 -tier_50_dirs += toolkit/components/gnome -endif -endif -endif - -ifdef MOZ_LEAKY -tier_50_dirs += tools/leaky -endif - -ifdef MOZ_MAPINFO -tier_50_dirs += tools/codesighs -endif - -# -# tier 99 - application features -# - -ifdef MOZ_MAIL_NEWS -tier_99_dirs += mailnews -endif - -ifdef MOZ_CALENDAR -tier_99_dirs += calendar -endif - -ifdef MOZ_EXTENSIONS -tier_99_dirs += extensions -endif - -ifdef MOZ_JAVAXPCOM -tier_99_dirs += extensions/java -endif - -# axcontrol -ifeq ($(OS_ARCH),WINNT) -ifndef MOZ_NO_ACTIVEX_SUPPORT -tier_99_dirs += \ - embedding/browser/activex/src/control \ - embedding/browser/activex/src/control_kicker \ - $(NULL) -endif -endif - -# Java Embedding Plugin -ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT))) -tier_99_dirs += plugin/oji/JEP -endif - -ifneq (,$(filter browser suite,$(MOZ_BUILD_APP))) -tier_99_dirs += xpfe/components/search -endif - -ifdef MOZ_BRANDING_DIRECTORY -tier_99_dirs += $(MOZ_BRANDING_DIRECTORY) -endif - -ifdef MOZ_PHOENIX -tier_99_dirs += browser xpfe/bootstrap/init.d -endif - -ifdef MOZ_XULRUNNER -tier_99_dirs += xulrunner -endif - -ifdef MOZ_COMPOSER -tier_99_dirs += editor/ui -endif - -ifdef MOZ_THUNDERBIRD -tier_99_dirs += mail xpfe/bootstrap/init.d -endif - -ifdef MOZ_STANDALONE_COMPOSER -tier_99_dirs += composer -endif - -ifdef MOZ_SUNBIRD -tier_99_dirs += calendar/sunbird -endif - -ifdef MOZ_SUITE -tier_99_dirs += suite -endif - -ifdef MINIMO -tier_99_dirs += minimo -endif - -ifdef MOZ_XUL_APP -ifdef MOZ_INSTALLER -tier_99_dirs += toolkit/mozapps/installer -endif -else -ifneq (,$(MOZ_XPFE_COMPONENTS)$(MOZ_XUL)) -ifndef MINIMO -tier_99_dirs += xpfe/bootstrap -endif -endif -endif - -ifneq (,$(MOZ_ENABLE_GTK)$(MOZ_ENABLE_GTK2)) -tier_99_dirs += embedding/browser/gtk -endif - -# viewer -ifneq (,$(ENABLE_TESTS)) -ifndef MOZ_ENABLE_LIBXUL -tier_99_dirs += webshell/tests -endif -endif - -# winembed, mfcembed -ifeq ($(OS_ARCH),WINNT) -ifneq (,$(ENABLE_TESTS)$(MOZILLA_OFFICIAL)) -tier_99_dirs += embedding/tests -endif -endif - -# os2embed -ifeq ($(OS_ARCH),OS2) -ifneq (,$(ENABLE_TESTS)$(MOZILLA_OFFICIAL)) -tier_99_dirs += embedding/tests -endif -endif - -ifeq ($(MOZ_BUILD_APP),macbrowser) -tier_99_dirs += \ - embedding/config \ - camino \ - $(NULL) -endif - -# test harnesses -ifdef ENABLE_TESTS -tier_99_dirs += tools/test-harness -endif - -else - -# Standalone build - -DIRS = $(BUILD_MODULE_DIRS) - -# Hack to generate xpidl Makefile -ifneq ($(BUILD_MODULES),all) -ifneq (,$(findstring xpcom, $(BUILD_MODULE_DIRS))) -DIRS := xpcom/typelib $(DIRS) -SUBMAKEFILES := xpcom/typelib/Makefile -endif -endif - -default:: $(SUBMAKEFILES) - $(MAKE) export - $(MAKE) libs - -endif # BUILD_MODULES == all - -STATIC_MAKEFILES := nsprpub directory/c-sdk security/nss - -GARBAGE_DIRS += dist -DIST_GARBAGE = config.cache config.log config.status config-defs.h \ - dependencies.beos config/autoconf.mk config/myrules.mk config/myconfig.mk \ - unallmakefiles mozilla-config.h \ - $(topsrcdir)/.mozconfig.mk $(topsrcdir)/.mozconfig.out - -# Build pseudo-external modules first when export is explicitly called -export:: - $(RM) -rf $(DIST)/sdk - $(MAKE) -C config export - $(MAKE) nspr - $(MAKE) ldap -ifneq ($(BUILD_MODULES),all) -ifneq (,$(findstring xpcom, $(BUILD_MODULE_DIRS))) - $(MAKE) -C xpcom/typelib - $(MAKE) export-idl -endif -endif - -install:: -ifndef MOZ_NATIVE_NSPR - $(MAKE) -C nsprpub real_install DESTDIR=$(DESTDIR) libdir=$(mozappdir) includedir=$(includedir)/nspr - $(RM) -f $(addprefix $(DESTDIR)$(mozappdir)/$(LIB_PREFIX), $(addsuffix .$(LIB_SUFFIX), nspr4 plds4 plc4)) - $(RM) -f $(addprefix $(DESTDIR)$(bindir)/,nspr-config compile-et.pl prerr.properties) -endif -ifdef MOZ_LDAP_XPCOM - $(MAKE) -C directory/c-sdk real_install DESTDIR=$(DESTDIR) libdir=$(mozappdir) includedir=$(includedir)/ldap -endif - -include $(topsrcdir)/config/rules.mk - -# Clean up after pseudo-external modules -clean clobber realclean clobber_all distclean:: -ifndef MOZ_NATIVE_NSPR - $(MAKE) -C nsprpub $@ -endif -ifdef MOZ_LDAP_XPCOM - $(MAKE) -C directory/c-sdk $@ -endif - -# Map mozilla targets to standard automake target -ifdef MOZ_ENABLE_LIBXUL -tier_50: $(addsuffix /Makefile, $(filter-out $(STATIC_MAKEFILES), $($@_dirs))) - @echo "tier_50: $(tier_50_dirs)" - @$(EXIT_ON_ERROR) \ - for d in $(tier_50_dirs); do \ - $(UPDATE_TITLE) \ - if test ! -f $$d/Makefile; then \ - $(PERL) $(AUTOCONF_TOOLS)/make-makefile -t $(topsrcdir) -d $(DEPTH) $(CYGWIN_TOPSRCDIR) $$d/Makefile; \ - fi; \ - $(MAKE) -C $$d export; \ - done ; \ - for d in $(tier_50_dirs); do \ - $(UPDATE_TITLE) \ - $(MAKE) -C $$d libs; \ - done - @echo "Building tools from tier 2/9/50" - @$(EXIT_ON_ERROR) \ - for d in $(tier_2_dirs) $(tier_9_dirs) $(tier_50_dirs); do \ - $(UPDATE_TITLE) \ - $(MAKE) -C $$d tools; \ - done; -endif - -tier_%: - @echo "$@: $($@_dirs)" - @$(EXIT_ON_ERROR) \ - for d in $($@_dirs); do \ - $(UPDATE_TITLE) \ - if test ! -f $$d/Makefile; then \ - $(PERL) $(AUTOCONF_TOOLS)/make-makefile -t $(topsrcdir) -d $(DEPTH) $(CYGWIN_TOPSRCDIR) $$d/Makefile; \ - fi; \ - $(MAKE) -C $$d export; \ - done ; \ - for d in $($@_dirs); do $(UPDATE_TITLE) \ - $(MAKE) -C $$d libs; \ - done - -# -# Individual modules -# -boehm: -ifdef GC_LEAK_DETECTOR - $(MAKE) -C gc/boehm -endif - -nspr: boehm -ifndef MOZ_NATIVE_NSPR - $(MAKE) -C nsprpub -endif - -ldap: -ifdef MOZ_LDAP_XPCOM - $(MAKE) -C directory/c-sdk -endif - -distclean:: - cat unallmakefiles | $(XARGS) rm -f - rm -f unallmakefiles $(DIST_GARBAGE) - -ifeq ($(OS_ARCH),WINNT) -rebase: -ifdef MOZILLA_OFFICIAL - echo rebasing $(DIST) - /bin/find $(DIST) -name "*.dll" > rebase.lst - rebase -b 60000000 -R . -G rebase.lst - rm rebase.lst -endif - -splitsymbols: -ifdef MOZILLA_OFFICIAL -ifdef MOZ_DEBUG_SYMBOLS - echo finding pdb files - mkdir -p $(DIST)/$(BUILDID) - -cp `/bin/find . -path "./dist" -prune -o -name "*.dll" | sed "s/\.dll$$/\.pdb/" | xargs` $(DIST)/$(BUILDID) - -cp `/bin/find . -path "./dist" -prune -o -name "*.exe" | sed "s/\.exe$$/\.pdb/" | xargs` $(DIST)/$(BUILDID) - -cp `/bin/find . -path "./dist" -prune -o -name "*.EXE" | sed "s/\.EXE$$/\.pdb/" | xargs` $(DIST)/$(BUILDID) -endif # MOZ_DEBUG_SYMBOLS -ifdef MOZ_PROFILE - echo splitting symbols out of binaries - /bin/find $(DIST) -name "*.dll" -exec splitsym {} \; - /bin/find $(DIST) -name "*.exe" -exec splitsym {} \; - /bin/find $(DIST) -name "*.EXE" -exec splitsym {} \; - mkdir -p $(DIST)/$(BUILDID) - /bin/find $(DIST) -name "*.dbg" -exec mv {} $(DIST)/$(BUILDID) \; -endif # MOZ_PROFILE -endif # MOZILLA_OFFICIAL - -signnss: -ifdef MOZILLA_OFFICIAL - echo signing NSS libs - cd $(DIST)/bin; ./shlibsign.exe -v -i softokn3.dll - cd $(DIST)/bin; ./shlibsign.exe -v -i freebl3.dll -endif # MOZILLA_OFFICIAL - -BUILDID = $(shell cat $(DEPTH)/config/build_number) -deliver: splitsymbols rebase signnss - -endif # WINNT - diff --git a/third_party/pygments/tests/examplefiles/flipflop.sv b/third_party/pygments/tests/examplefiles/flipflop.sv deleted file mode 100644 index fe52ed440..000000000 --- a/third_party/pygments/tests/examplefiles/flipflop.sv +++ /dev/null @@ -1,19 +0,0 @@ -module toplevel(clock,reset); - input clock; - input reset; - - reg flop1; - reg flop2; - - always @ (posedge reset or posedge clock) - if (reset) - begin - flop1 <= 0; - flop2 <= 1; - end - else - begin - flop1 <= flop2; - flop2 <= flop1; - end -endmodule diff --git a/third_party/pygments/tests/examplefiles/foo.sce b/third_party/pygments/tests/examplefiles/foo.sce deleted file mode 100644 index 0e5d6afe5..000000000 --- a/third_party/pygments/tests/examplefiles/foo.sce +++ /dev/null @@ -1,6 +0,0 @@ -// Scilab -// -disp(%pi); - -assert_checkequal(2+2,4); - diff --git a/third_party/pygments/tests/examplefiles/format.ml b/third_party/pygments/tests/examplefiles/format.ml deleted file mode 100644 index 49b406783..000000000 --- a/third_party/pygments/tests/examplefiles/format.ml +++ /dev/null @@ -1,1213 +0,0 @@ -(***********************************************************************) -(* *) -(* Objective Caml *) -(* *) -(* Pierre Weis, projet Cristal, INRIA Rocquencourt *) -(* *) -(* Copyright 1996 Institut National de Recherche en Informatique et *) -(* en Automatique. All rights reserved. This file is distributed *) -(* under the terms of the GNU Library General Public License, with *) -(* the special exception on linking described in file ../LICENSE. *) -(* *) -(***********************************************************************) - -(* $Id: format.ml,v 1.65 2005/09/26 10:13:08 weis Exp $ *) - -(************************************************************** - - Data structures definitions. - - **************************************************************) - -type size;; - -external size_of_int : int -> size = "%identity";; -external int_of_size : size -> int = "%identity";; - -(* Tokens are one of the following : *) - -type pp_token = -| Pp_text of string (* normal text *) -| Pp_break of int * int (* complete break *) -| Pp_tbreak of int * int (* go to next tabulation *) -| Pp_stab (* set a tabulation *) -| Pp_begin of int * block_type (* beginning of a block *) -| Pp_end (* end of a block *) -| Pp_tbegin of tblock (* beginning of a tabulation block *) -| Pp_tend (* end of a tabulation block *) -| Pp_newline (* to force a newline inside a block *) -| Pp_if_newline (* to do something only if this very - line has been broken *) -| Pp_open_tag of string (* opening a tag name *) -| Pp_close_tag (* closing the most recently opened tag *) - -and tag = string - -and block_type = -| Pp_hbox (* Horizontal block no line breaking *) -| Pp_vbox (* Vertical block each break leads to a new line *) -| Pp_hvbox (* Horizontal-vertical block: same as vbox, except if this block - is small enough to fit on a single line *) -| Pp_hovbox (* Horizontal or Vertical block: breaks lead to new line - only when necessary to print the content of the block *) -| Pp_box (* Horizontal or Indent block: breaks lead to new line - only when necessary to print the content of the block, or - when it leads to a new indentation of the current line *) -| Pp_fits (* Internal usage: when a block fits on a single line *) - -and tblock = Pp_tbox of int list ref (* Tabulation box *) -;; - -(* The Queue: - contains all formatting elements. - elements are tuples (size, token, length), where - size is set when the size of the block is known - len is the declared length of the token. *) -type pp_queue_elem = { - mutable elem_size : size; token : pp_token; length : int -};; - -(* Scan stack: - each element is (left_total, queue element) where left_total - is the value of pp_left_total when the element has been enqueued. *) -type pp_scan_elem = Scan_elem of int * pp_queue_elem;; - -(* Formatting stack: - used to break the lines while printing tokens. - The formatting stack contains the description of - the currently active blocks. *) -type pp_format_elem = Format_elem of block_type * int;; - -(* General purpose queues, used in the formatter. *) -type 'a queue_elem = | Nil | Cons of 'a queue_cell -and 'a queue_cell = {mutable head : 'a; mutable tail : 'a queue_elem};; - -type 'a queue = { - mutable insert : 'a queue_elem; - mutable body : 'a queue_elem -};; - -(* The formatter specific tag handling functions. *) -type formatter_tag_functions = { - mark_open_tag : tag -> string; - mark_close_tag : tag -> string; - print_open_tag : tag -> unit; - print_close_tag : tag -> unit; - -};; - -(* A formatter with all its machinery. *) -type formatter = { - mutable pp_scan_stack : pp_scan_elem list; - mutable pp_format_stack : pp_format_elem list; - mutable pp_tbox_stack : tblock list; - mutable pp_tag_stack : tag list; - mutable pp_mark_stack : tag list; - (* Global variables: default initialization is - set_margin 78 - set_min_space_left 0. *) - (* Value of right margin. *) - mutable pp_margin : int; - (* Minimal space left before margin, when opening a block. *) - mutable pp_min_space_left : int; - (* Maximum value of indentation: - no blocks can be opened further. *) - mutable pp_max_indent : int; - (* Space remaining on the current line. *) - mutable pp_space_left : int; - (* Current value of indentation. *) - mutable pp_current_indent : int; - (* True when the line has been broken by the pretty-printer. *) - mutable pp_is_new_line : bool; - (* Total width of tokens already printed. *) - mutable pp_left_total : int; - (* Total width of tokens ever put in queue. *) - mutable pp_right_total : int; - (* Current number of opened blocks. *) - mutable pp_curr_depth : int; - (* Maximum number of blocks which can be simultaneously opened. *) - mutable pp_max_boxes : int; - (* Ellipsis string. *) - mutable pp_ellipsis : string; - (* Output function. *) - mutable pp_output_function : string -> int -> int -> unit; - (* Flushing function. *) - mutable pp_flush_function : unit -> unit; - (* Output of new lines. *) - mutable pp_output_newline : unit -> unit; - (* Output of indentation spaces. *) - mutable pp_output_spaces : int -> unit; - (* Are tags printed ? *) - mutable pp_print_tags : bool; - (* Are tags marked ? *) - mutable pp_mark_tags : bool; - (* Find opening and closing markers of tags. *) - mutable pp_mark_open_tag : tag -> string; - mutable pp_mark_close_tag : tag -> string; - mutable pp_print_open_tag : tag -> unit; - mutable pp_print_close_tag : tag -> unit; - (* The pretty-printer queue. *) - mutable pp_queue : pp_queue_elem queue -};; - -(************************************************************** - - Auxilliaries and basic functions. - - **************************************************************) - - -(* Queues auxilliaries. *) -let make_queue () = {insert = Nil; body = Nil};; - -let clear_queue q = q.insert <- Nil; q.body <- Nil;; - -let add_queue x q = - let c = Cons {head = x; tail = Nil} in - match q with - | {insert = Cons cell} -> q.insert <- c; cell.tail <- c - (* Invariant: when insert is Nil body should be Nil. *) - | _ -> q.insert <- c; q.body <- c;; - -exception Empty_queue;; - -let peek_queue = function - | {body = Cons {head = x}} -> x - | _ -> raise Empty_queue;; - -let take_queue = function - | {body = Cons {head = x; tail = tl}} as q -> - q.body <- tl; - if tl = Nil then q.insert <- Nil; (* Maintain the invariant. *) - x - | _ -> raise Empty_queue;; - -(* Enter a token in the pretty-printer queue. *) -let pp_enqueue state ({length = len} as token) = - state.pp_right_total <- state.pp_right_total + len; - add_queue token state.pp_queue;; - -let pp_clear_queue state = - state.pp_left_total <- 1; state.pp_right_total <- 1; - clear_queue state.pp_queue;; - -(* Pp_infinity: large value for default tokens size. - - Pp_infinity is documented as being greater than 1e10; to avoid - confusion about the word ``greater'', we choose pp_infinity greater - than 1e10 + 1; for correct handling of tests in the algorithm, - pp_infinity must be even one more than 1e10 + 1; let's stand on the - safe side by choosing 1.e10+10. - - Pp_infinity could probably be 1073741823 that is 2^30 - 1, that is - the minimal upper bound for integers; now that max_int is defined, - this limit could also be defined as max_int - 1. - - However, before setting pp_infinity to something around max_int, we - must carefully double-check all the integer arithmetic operations - that involve pp_infinity, since any overflow would wreck havoc the - pretty-printing algorithm's invariants. Given that this arithmetic - correctness check is difficult and error prone and given that 1e10 - + 1 is in practice large enough, there is no need to attempt to set - pp_infinity to the theoretically maximum limit. Is it not worth the - burden ! *) - -let pp_infinity = 1000000010;; - -(* Output functions for the formatter. *) -let pp_output_string state s = state.pp_output_function s 0 (String.length s) -and pp_output_newline state = state.pp_output_newline ();; - -let pp_display_blanks state n = state.pp_output_spaces n;; - -(* To format a break, indenting a new line. *) -let break_new_line state offset width = - pp_output_newline state; - state.pp_is_new_line <- true; - let indent = state.pp_margin - width + offset in - (* Don't indent more than pp_max_indent. *) - let real_indent = min state.pp_max_indent indent in - state.pp_current_indent <- real_indent; - state.pp_space_left <- state.pp_margin - state.pp_current_indent; - pp_display_blanks state state.pp_current_indent;; - -(* To force a line break inside a block: no offset is added. *) -let break_line state width = break_new_line state 0 width;; - -(* To format a break that fits on the current line. *) -let break_same_line state width = - state.pp_space_left <- state.pp_space_left - width; - pp_display_blanks state width;; - -(* To indent no more than pp_max_indent, if one tries to open a block - beyond pp_max_indent, then the block is rejected on the left - by simulating a break. *) -let pp_force_break_line state = - match state.pp_format_stack with - | Format_elem (bl_ty, width) :: _ -> - if width > state.pp_space_left then - (match bl_ty with - | Pp_fits -> () | Pp_hbox -> () | _ -> break_line state width) - | _ -> pp_output_newline state;; - -(* To skip a token, if the previous line has been broken. *) -let pp_skip_token state = - (* When calling pp_skip_token the queue cannot be empty. *) - match take_queue state.pp_queue with - {elem_size = size; length = len} -> - state.pp_left_total <- state.pp_left_total - len; - state.pp_space_left <- state.pp_space_left + int_of_size size;; - -(************************************************************** - - The main pretting printing functions. - - **************************************************************) - -(* To format a token. *) -let format_pp_token state size = function - - | Pp_text s -> - state.pp_space_left <- state.pp_space_left - size; - pp_output_string state s; - state.pp_is_new_line <- false - - | Pp_begin (off, ty) -> - let insertion_point = state.pp_margin - state.pp_space_left in - if insertion_point > state.pp_max_indent then - (* can't open a block right there. *) - begin pp_force_break_line state end; - let offset = state.pp_space_left - off in - let bl_type = - begin match ty with - | Pp_vbox -> Pp_vbox - | _ -> if size > state.pp_space_left then ty else Pp_fits - end in - state.pp_format_stack <- - Format_elem (bl_type, offset) :: state.pp_format_stack - - | Pp_end -> - begin match state.pp_format_stack with - | x :: (y :: l as ls) -> state.pp_format_stack <- ls - | _ -> () (* No more block to close. *) - end - - | Pp_tbegin (Pp_tbox _ as tbox) -> - state.pp_tbox_stack <- tbox :: state.pp_tbox_stack - - | Pp_tend -> - begin match state.pp_tbox_stack with - | x :: ls -> state.pp_tbox_stack <- ls - | _ -> () (* No more tabulation block to close. *) - end - - | Pp_stab -> - begin match state.pp_tbox_stack with - | Pp_tbox tabs :: _ -> - let rec add_tab n = function - | [] -> [n] - | x :: l as ls -> if n < x then n :: ls else x :: add_tab n l in - tabs := add_tab (state.pp_margin - state.pp_space_left) !tabs - | _ -> () (* No opened tabulation block. *) - end - - | Pp_tbreak (n, off) -> - let insertion_point = state.pp_margin - state.pp_space_left in - begin match state.pp_tbox_stack with - | Pp_tbox tabs :: _ -> - let rec find n = function - | x :: l -> if x >= n then x else find n l - | [] -> raise Not_found in - let tab = - match !tabs with - | x :: l -> - begin try find insertion_point !tabs with Not_found -> x end - | _ -> insertion_point in - let offset = tab - insertion_point in - if offset >= 0 then break_same_line state (offset + n) else - break_new_line state (tab + off) state.pp_margin - | _ -> () (* No opened tabulation block. *) - end - - | Pp_newline -> - begin match state.pp_format_stack with - | Format_elem (_, width) :: _ -> break_line state width - | _ -> pp_output_newline state - end - - | Pp_if_newline -> - if state.pp_current_indent != state.pp_margin - state.pp_space_left - then pp_skip_token state - - | Pp_break (n, off) -> - begin match state.pp_format_stack with - | Format_elem (ty, width) :: _ -> - begin match ty with - | Pp_hovbox -> - if size > state.pp_space_left - then break_new_line state off width - else break_same_line state n - | Pp_box -> - (* Have the line just been broken here ? *) - if state.pp_is_new_line then break_same_line state n else - if size > state.pp_space_left - then break_new_line state off width else - (* break the line here leads to new indentation ? *) - if state.pp_current_indent > state.pp_margin - width + off - then break_new_line state off width - else break_same_line state n - | Pp_hvbox -> break_new_line state off width - | Pp_fits -> break_same_line state n - | Pp_vbox -> break_new_line state off width - | Pp_hbox -> break_same_line state n - end - | _ -> () (* No opened block. *) - end - - | Pp_open_tag tag_name -> - let marker = state.pp_mark_open_tag tag_name in - pp_output_string state marker; - state.pp_mark_stack <- tag_name :: state.pp_mark_stack - - | Pp_close_tag -> - begin match state.pp_mark_stack with - | tag_name :: tags -> - let marker = state.pp_mark_close_tag tag_name in - pp_output_string state marker; - state.pp_mark_stack <- tags - | _ -> () (* No more tag to close. *) - end;; - -(* Print if token size is known or printing is delayed. - Size is known when not negative. - Printing is delayed when the text waiting in the queue requires - more room to format than exists on the current line. *) -let rec advance_left state = - try - match peek_queue state.pp_queue with - {elem_size = size; token = tok; length = len} -> - let size = int_of_size size in - if not - (size < 0 && - (state.pp_right_total - state.pp_left_total < state.pp_space_left)) - then begin - ignore(take_queue state.pp_queue); - format_pp_token state (if size < 0 then pp_infinity else size) tok; - state.pp_left_total <- len + state.pp_left_total; - advance_left state - end - with Empty_queue -> ();; - -let enqueue_advance state tok = pp_enqueue state tok; advance_left state;; - -(* To enqueue a string : try to advance. *) -let make_queue_elem size tok len = - {elem_size = size; token = tok; length = len};; - -let enqueue_string_as state size s = - let len = int_of_size size in - enqueue_advance state (make_queue_elem size (Pp_text s) len);; - -let enqueue_string state s = - let len = String.length s in - enqueue_string_as state (size_of_int len) s;; - -(* Routines for scan stack - determine sizes of blocks. *) - -(* The scan_stack is never empty. *) -let scan_stack_bottom = - let q_elem = make_queue_elem (size_of_int (-1)) (Pp_text "") 0 in - [Scan_elem (-1, q_elem)];; - -(* Set size of blocks on scan stack: - if ty = true then size of break is set else size of block is set; - in each case pp_scan_stack is popped. *) -let clear_scan_stack state = state.pp_scan_stack <- scan_stack_bottom;; - -(* Pattern matching on scan stack is exhaustive, - since scan_stack is never empty. - Pattern matching on token in scan stack is also exhaustive, - since scan_push is used on breaks and opening of boxes. *) -let set_size state ty = - match state.pp_scan_stack with - | Scan_elem - (left_tot, - ({elem_size = size; token = tok} as queue_elem)) :: t -> - let size = int_of_size size in - (* test if scan stack contains any data that is not obsolete. *) - if left_tot < state.pp_left_total then clear_scan_stack state else - begin match tok with - | Pp_break (_, _) | Pp_tbreak (_, _) -> - if ty then - begin - queue_elem.elem_size <- size_of_int (state.pp_right_total + size); - state.pp_scan_stack <- t - end - | Pp_begin (_, _) -> - if not ty then - begin - queue_elem.elem_size <- size_of_int (state.pp_right_total + size); - state.pp_scan_stack <- t - end - | _ -> () (* scan_push is only used for breaks and boxes. *) - end - | _ -> () (* scan_stack is never empty. *);; - -(* Push a token on scan stack. If b is true set_size is called. *) -let scan_push state b tok = - pp_enqueue state tok; - if b then set_size state true; - state.pp_scan_stack <- - Scan_elem (state.pp_right_total, tok) :: state.pp_scan_stack;; - -(* To open a new block : - the user may set the depth bound pp_max_boxes - any text nested deeper is printed as the ellipsis string. *) -let pp_open_box_gen state indent br_ty = - state.pp_curr_depth <- state.pp_curr_depth + 1; - if state.pp_curr_depth < state.pp_max_boxes then - let elem = - make_queue_elem - (size_of_int (- state.pp_right_total)) - (Pp_begin (indent, br_ty)) - 0 in - scan_push state false elem else - if state.pp_curr_depth = state.pp_max_boxes - then enqueue_string state state.pp_ellipsis;; - -(* The box which is always opened. *) -let pp_open_sys_box state = pp_open_box_gen state 0 Pp_hovbox;; - -(* Close a block, setting sizes of its subblocks. *) -let pp_close_box state () = - if state.pp_curr_depth > 1 then - begin - if state.pp_curr_depth < state.pp_max_boxes then - begin - pp_enqueue state - {elem_size = size_of_int 0; token = Pp_end; length = 0}; - set_size state true; set_size state false - end; - state.pp_curr_depth <- state.pp_curr_depth - 1; - end;; - -(* Open a tag, pushing it on the tag stack. *) -let pp_open_tag state tag_name = - if state.pp_print_tags then begin - state.pp_tag_stack <- tag_name :: state.pp_tag_stack; - state.pp_print_open_tag tag_name end; - if state.pp_mark_tags then - pp_enqueue state - {elem_size = size_of_int 0; token = Pp_open_tag tag_name; length = 0};; - -(* Close a tag, popping it from the tag stack. *) -let pp_close_tag state () = - if state.pp_mark_tags then - pp_enqueue state - {elem_size = size_of_int 0; token = Pp_close_tag; length = 0}; - if state.pp_print_tags then - begin match state.pp_tag_stack with - | tag_name :: tags -> - state.pp_print_close_tag tag_name; - state.pp_tag_stack <- tags - | _ -> () (* No more tag to close. *) - end;; - -let pp_set_print_tags state b = state.pp_print_tags <- b;; -let pp_set_mark_tags state b = state.pp_mark_tags <- b;; -let pp_get_print_tags state () = state.pp_print_tags;; -let pp_get_mark_tags state () = state.pp_mark_tags;; -let pp_set_tags state b = pp_set_print_tags state b; pp_set_mark_tags state b;; - -let pp_get_formatter_tag_functions state () = { - mark_open_tag = state.pp_mark_open_tag; - mark_close_tag = state.pp_mark_close_tag; - print_open_tag = state.pp_print_open_tag; - print_close_tag = state.pp_print_close_tag; -};; - -let pp_set_formatter_tag_functions state { - mark_open_tag = mot; - mark_close_tag = mct; - print_open_tag = pot; - print_close_tag = pct; - } = - state.pp_mark_open_tag <- mot; - state.pp_mark_close_tag <- mct; - state.pp_print_open_tag <- pot; - state.pp_print_close_tag <- pct;; - -(* Initialize pretty-printer. *) -let pp_rinit state = - pp_clear_queue state; - clear_scan_stack state; - state.pp_format_stack <- []; - state.pp_tbox_stack <- []; - state.pp_tag_stack <- []; - state.pp_mark_stack <- []; - state.pp_current_indent <- 0; - state.pp_curr_depth <- 0; - state.pp_space_left <- state.pp_margin; - pp_open_sys_box state;; - -(* Flushing pretty-printer queue. *) -let pp_flush_queue state b = - while state.pp_curr_depth > 1 do - pp_close_box state () - done; - state.pp_right_total <- pp_infinity; - advance_left state; - if b then pp_output_newline state; - pp_rinit state;; - -(************************************************************** - - Procedures to format objects, and use boxes - - **************************************************************) - -(* To format a string. *) -let pp_print_as_size state size s = - if state.pp_curr_depth < state.pp_max_boxes - then enqueue_string_as state size s;; - -let pp_print_as state isize s = - pp_print_as_size state (size_of_int isize) s;; - -let pp_print_string state s = - pp_print_as state (String.length s) s;; - -(* To format an integer. *) -let pp_print_int state i = pp_print_string state (string_of_int i);; - -(* To format a float. *) -let pp_print_float state f = pp_print_string state (string_of_float f);; - -(* To format a boolean. *) -let pp_print_bool state b = pp_print_string state (string_of_bool b);; - -(* To format a char. *) -let pp_print_char state c = - let s = String.create 1 in - s.[0] <- c; - pp_print_as state 1 s;; - -(* Opening boxes. *) -let pp_open_hbox state () = pp_open_box_gen state 0 Pp_hbox -and pp_open_vbox state indent = pp_open_box_gen state indent Pp_vbox - -and pp_open_hvbox state indent = pp_open_box_gen state indent Pp_hvbox -and pp_open_hovbox state indent = pp_open_box_gen state indent Pp_hovbox -and pp_open_box state indent = pp_open_box_gen state indent Pp_box;; - -(* Print a new line after printing all queued text - (same for print_flush but without a newline). *) -let pp_print_newline state () = - pp_flush_queue state true; state.pp_flush_function () -and pp_print_flush state () = - pp_flush_queue state false; state.pp_flush_function ();; - -(* To get a newline when one does not want to close the current block. *) -let pp_force_newline state () = - if state.pp_curr_depth < state.pp_max_boxes then - enqueue_advance state (make_queue_elem (size_of_int 0) Pp_newline 0);; - -(* To format something if the line has just been broken. *) -let pp_print_if_newline state () = - if state.pp_curr_depth < state.pp_max_boxes then - enqueue_advance state (make_queue_elem (size_of_int 0) Pp_if_newline 0);; - -(* Breaks: indicate where a block may be broken. - If line is broken then offset is added to the indentation of the current - block else (the value of) width blanks are printed. - To do (?) : add a maximum width and offset value. *) -let pp_print_break state width offset = - if state.pp_curr_depth < state.pp_max_boxes then - let elem = - make_queue_elem - (size_of_int (- state.pp_right_total)) - (Pp_break (width, offset)) - width in - scan_push state true elem;; - -let pp_print_space state () = pp_print_break state 1 0 -and pp_print_cut state () = pp_print_break state 0 0;; - -(* Tabulation boxes. *) -let pp_open_tbox state () = - state.pp_curr_depth <- state.pp_curr_depth + 1; - if state.pp_curr_depth < state.pp_max_boxes then - let elem = - make_queue_elem (size_of_int 0) (Pp_tbegin (Pp_tbox (ref []))) 0 in - enqueue_advance state elem;; - -(* Close a tabulation block. *) -let pp_close_tbox state () = - if state.pp_curr_depth > 1 then begin - if state.pp_curr_depth < state.pp_max_boxes then - let elem = make_queue_elem (size_of_int 0) Pp_tend 0 in - enqueue_advance state elem; - state.pp_curr_depth <- state.pp_curr_depth - 1 end;; - -(* Print a tabulation break. *) -let pp_print_tbreak state width offset = - if state.pp_curr_depth < state.pp_max_boxes then - let elem = - make_queue_elem - (size_of_int (- state.pp_right_total)) - (Pp_tbreak (width, offset)) - width in - scan_push state true elem;; - -let pp_print_tab state () = pp_print_tbreak state 0 0;; - -let pp_set_tab state () = - if state.pp_curr_depth < state.pp_max_boxes then - let elem = - make_queue_elem (size_of_int 0) Pp_stab 0 in - enqueue_advance state elem;; - -(************************************************************** - - Procedures to control the pretty-printers - - **************************************************************) - -(* Fit max_boxes. *) -let pp_set_max_boxes state n = if n > 1 then state.pp_max_boxes <- n;; - -(* To know the current maximum number of boxes allowed. *) -let pp_get_max_boxes state () = state.pp_max_boxes;; - -let pp_over_max_boxes state () = state.pp_curr_depth = state.pp_max_boxes;; - -(* Ellipsis. *) -let pp_set_ellipsis_text state s = state.pp_ellipsis <- s -and pp_get_ellipsis_text state () = state.pp_ellipsis;; - -(* To set the margin of pretty-printer. *) -let pp_limit n = - if n < pp_infinity then n else pred pp_infinity;; - -let pp_set_min_space_left state n = - if n >= 1 then - let n = pp_limit n in - state.pp_min_space_left <- n; - state.pp_max_indent <- state.pp_margin - state.pp_min_space_left; - pp_rinit state;; - -(* Initially, we have : - pp_max_indent = pp_margin - pp_min_space_left, and - pp_space_left = pp_margin. *) -let pp_set_max_indent state n = - pp_set_min_space_left state (state.pp_margin - n);; -let pp_get_max_indent state () = state.pp_max_indent;; - -let pp_set_margin state n = - if n >= 1 then - let n = pp_limit n in - state.pp_margin <- n; - let new_max_indent = - (* Try to maintain max_indent to its actual value. *) - if state.pp_max_indent <= state.pp_margin - then state.pp_max_indent else - (* If possible maintain pp_min_space_left to its actual value, - if this leads to a too small max_indent, take half of the - new margin, if it is greater than 1. *) - max (max (state.pp_margin - state.pp_min_space_left) - (state.pp_margin / 2)) 1 in - (* Rebuild invariants. *) - pp_set_max_indent state new_max_indent;; - -let pp_get_margin state () = state.pp_margin;; - -let pp_set_formatter_output_functions state f g = - state.pp_output_function <- f; state.pp_flush_function <- g;; -let pp_get_formatter_output_functions state () = - (state.pp_output_function, state.pp_flush_function);; - -let pp_set_all_formatter_output_functions state - ~out:f ~flush:g ~newline:h ~spaces:i = - pp_set_formatter_output_functions state f g; - state.pp_output_newline <- (function () -> h ()); - state.pp_output_spaces <- (function n -> i n);; -let pp_get_all_formatter_output_functions state () = - (state.pp_output_function, state.pp_flush_function, - state.pp_output_newline, state.pp_output_spaces);; - -let pp_set_formatter_out_channel state os = - state.pp_output_function <- output os; - state.pp_flush_function <- (fun () -> flush os);; - -(************************************************************** - - Creation of specific formatters - - **************************************************************) - -let default_pp_mark_open_tag s = "<" ^ s ^ ">";; -let default_pp_mark_close_tag s = "";; - -let default_pp_print_open_tag s = ();; -let default_pp_print_close_tag = default_pp_print_open_tag;; - -let pp_make_formatter f g h i = - (* The initial state of the formatter contains a dummy box. *) - let pp_q = make_queue () in - let sys_tok = - make_queue_elem (size_of_int (-1)) (Pp_begin (0, Pp_hovbox)) 0 in - add_queue sys_tok pp_q; - let sys_scan_stack = - (Scan_elem (1, sys_tok)) :: scan_stack_bottom in - {pp_scan_stack = sys_scan_stack; - pp_format_stack = []; - pp_tbox_stack = []; - pp_tag_stack = []; - pp_mark_stack = []; - pp_margin = 78; - pp_min_space_left = 10; - pp_max_indent = 78 - 10; - pp_space_left = 78; - pp_current_indent = 0; - pp_is_new_line = true; - pp_left_total = 1; - pp_right_total = 1; - pp_curr_depth = 1; - pp_max_boxes = max_int; - pp_ellipsis = "."; - pp_output_function = f; - pp_flush_function = g; - pp_output_newline = h; - pp_output_spaces = i; - pp_print_tags = false; - pp_mark_tags = false; - pp_mark_open_tag = default_pp_mark_open_tag; - pp_mark_close_tag = default_pp_mark_close_tag; - pp_print_open_tag = default_pp_print_open_tag; - pp_print_close_tag = default_pp_print_close_tag; - pp_queue = pp_q - };; - -(* Default function to output spaces. *) -let blank_line = String.make 80 ' ';; -let rec display_blanks state n = - if n > 0 then - if n <= 80 then state.pp_output_function blank_line 0 n else - begin - state.pp_output_function blank_line 0 80; - display_blanks state (n - 80) - end;; - -(* Default function to output new lines. *) -let display_newline state () = state.pp_output_function "\n" 0 1;; - -let make_formatter f g = - let ff = pp_make_formatter f g ignore ignore in - ff.pp_output_newline <- display_newline ff; - ff.pp_output_spaces <- display_blanks ff; - ff;; - -let formatter_of_out_channel oc = - make_formatter (output oc) (fun () -> flush oc);; - -let formatter_of_buffer b = - make_formatter (Buffer.add_substring b) ignore;; - -let stdbuf = Buffer.create 512;; - -let str_formatter = formatter_of_buffer stdbuf;; -let std_formatter = formatter_of_out_channel stdout;; -let err_formatter = formatter_of_out_channel stderr;; - -let flush_str_formatter () = - pp_flush_queue str_formatter false; - let s = Buffer.contents stdbuf in - Buffer.reset stdbuf; - s;; - -(************************************************************** - - Basic functions on the standard formatter - - **************************************************************) - -let open_hbox = pp_open_hbox std_formatter -and open_vbox = pp_open_vbox std_formatter -and open_hvbox = pp_open_hvbox std_formatter -and open_hovbox = pp_open_hovbox std_formatter -and open_box = pp_open_box std_formatter -and close_box = pp_close_box std_formatter -and open_tag = pp_open_tag std_formatter -and close_tag = pp_close_tag std_formatter -and print_as = pp_print_as std_formatter -and print_string = pp_print_string std_formatter -and print_int = pp_print_int std_formatter -and print_float = pp_print_float std_formatter -and print_char = pp_print_char std_formatter -and print_bool = pp_print_bool std_formatter -and print_break = pp_print_break std_formatter -and print_cut = pp_print_cut std_formatter -and print_space = pp_print_space std_formatter -and force_newline = pp_force_newline std_formatter -and print_flush = pp_print_flush std_formatter -and print_newline = pp_print_newline std_formatter -and print_if_newline = pp_print_if_newline std_formatter - -and open_tbox = pp_open_tbox std_formatter -and close_tbox = pp_close_tbox std_formatter -and print_tbreak = pp_print_tbreak std_formatter - -and set_tab = pp_set_tab std_formatter -and print_tab = pp_print_tab std_formatter - -and set_margin = pp_set_margin std_formatter -and get_margin = pp_get_margin std_formatter - -and set_max_indent = pp_set_max_indent std_formatter -and get_max_indent = pp_get_max_indent std_formatter - -and set_max_boxes = pp_set_max_boxes std_formatter -and get_max_boxes = pp_get_max_boxes std_formatter -and over_max_boxes = pp_over_max_boxes std_formatter - -and set_ellipsis_text = pp_set_ellipsis_text std_formatter -and get_ellipsis_text = pp_get_ellipsis_text std_formatter - -and set_formatter_out_channel = - pp_set_formatter_out_channel std_formatter - -and set_formatter_output_functions = - pp_set_formatter_output_functions std_formatter -and get_formatter_output_functions = - pp_get_formatter_output_functions std_formatter - -and set_all_formatter_output_functions = - pp_set_all_formatter_output_functions std_formatter -and get_all_formatter_output_functions = - pp_get_all_formatter_output_functions std_formatter - -and set_formatter_tag_functions = - pp_set_formatter_tag_functions std_formatter -and get_formatter_tag_functions = - pp_get_formatter_tag_functions std_formatter -and set_print_tags = - pp_set_print_tags std_formatter -and get_print_tags = - pp_get_print_tags std_formatter -and set_mark_tags = - pp_set_mark_tags std_formatter -and get_mark_tags = - pp_get_mark_tags std_formatter -and set_tags = - pp_set_tags std_formatter -;; - - -(************************************************************** - - Printf implementation. - - **************************************************************) - -(* Error messages when processing formats. *) - -(* Trailer: giving up at character number ... *) -let giving_up mess fmt i = - "fprintf: " ^ mess ^ " ``" ^ fmt ^ "'', \ - giving up at character number " ^ string_of_int i ^ - (if i < String.length fmt - then " (" ^ String.make 1 fmt.[i] ^ ")." - else String.make 1 '.');; - -(* When an invalid format deserves a special error explanation. *) -let format_invalid_arg mess fmt i = invalid_arg (giving_up mess fmt i);; - -(* Standard invalid format. *) -let invalid_format fmt i = format_invalid_arg "bad format" fmt i;; - -(* Cannot find a valid integer into that format. *) -let invalid_integer fmt i = - invalid_arg (giving_up "bad integer specification" fmt i);; - -(* Finding an integer out of a sub-string of the format. *) -let format_int_of_string fmt i s = - let sz = - try int_of_string s with - | Failure s -> invalid_integer fmt i in - size_of_int sz;; - -(* Getting strings out of buffers. *) -let get_buffer_out b = - let s = Buffer.contents b in - Buffer.reset b; - s;; - -(* [ppf] is supposed to be a pretty-printer that outputs in buffer [b]: - to extract contents of [ppf] as a string we flush [ppf] and get the string - out of [b]. *) -let string_out b ppf = - pp_flush_queue ppf false; - get_buffer_out b;; - -(* Applies [printer] to a formatter that outputs on a fresh buffer, - then returns the resulting material. *) -let exstring printer arg = - let b = Buffer.create 512 in - let ppf = formatter_of_buffer b in - printer ppf arg; - string_out b ppf;; - -(* To turn out a character accumulator into the proper string result. *) -let implode_rev s0 = function - | [] -> s0 - | l -> String.concat "" (List.rev (s0 :: l));; - -external format_to_string : ('a, 'b, 'c, 'd) format4 -> string = "%identity";; - -(* [fprintf_out] is the printf-like function generator: given the - - [str] flag that tells if we are printing into a string, - - the [out] function that has to be called at the end of formatting, - it generates a [fprintf] function that takes as arguments a [ppf] - formatter and a printing format to print the rest of arguments - according to the format. - Regular [fprintf]-like functions of this module are obtained via partial - applications of [fprintf_out]. *) -let mkprintf str get_out = - let rec kprintf k fmt = - let fmt = format_to_string fmt in - let len = String.length fmt in - - let kpr fmt v = - let ppf = get_out fmt in - let print_as = ref None in - let pp_print_as_char c = - match !print_as with - | None -> pp_print_char ppf c - | Some size -> - pp_print_as_size ppf size (String.make 1 c); - print_as := None - and pp_print_as_string s = - match !print_as with - | None -> pp_print_string ppf s - | Some size -> - pp_print_as_size ppf size s; - print_as := None in - - let rec doprn n i = - if i >= len then Obj.magic (k ppf) else - match fmt.[i] with - | '%' -> - Printf.scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m - | '@' -> - let i = succ i in - if i >= len then invalid_format fmt i else - begin match fmt.[i] with - | '[' -> - do_pp_open_box ppf n (succ i) - | ']' -> - pp_close_box ppf (); - doprn n (succ i) - | '{' -> - do_pp_open_tag ppf n (succ i) - | '}' -> - pp_close_tag ppf (); - doprn n (succ i) - | ' ' -> - pp_print_space ppf (); - doprn n (succ i) - | ',' -> - pp_print_cut ppf (); - doprn n (succ i) - | '?' -> - pp_print_flush ppf (); - doprn n (succ i) - | '.' -> - pp_print_newline ppf (); - doprn n (succ i) - | '\n' -> - pp_force_newline ppf (); - doprn n (succ i) - | ';' -> - do_pp_break ppf n (succ i) - | '<' -> - let got_size size n i = - print_as := Some size; - doprn n (skip_gt i) in - get_int n (succ i) got_size - | '@' as c -> - pp_print_as_char c; - doprn n (succ i) - | c -> invalid_format fmt i - end - | c -> - pp_print_as_char c; - doprn n (succ i) - - and cont_s n s i = - pp_print_as_string s; doprn n i - and cont_a n printer arg i = - if str then - pp_print_as_string ((Obj.magic printer : unit -> _ -> string) () arg) - else - printer ppf arg; - doprn n i - and cont_t n printer i = - if str then - pp_print_as_string ((Obj.magic printer : unit -> string) ()) - else - printer ppf; - doprn n i - and cont_f n i = - pp_print_flush ppf (); doprn n i - - and cont_m n sfmt i = - kprintf (Obj.magic (fun _ -> doprn n i)) sfmt - - and get_int n i c = - if i >= len then invalid_integer fmt i else - match fmt.[i] with - | ' ' -> get_int n (succ i) c - | '%' -> - let cont_s n s i = c (format_int_of_string fmt i s) n i - and cont_a n printer arg i = invalid_integer fmt i - and cont_t n printer i = invalid_integer fmt i - and cont_f n i = invalid_integer fmt i - and cont_m n sfmt i = invalid_integer fmt i in - Printf.scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m - | _ -> - let rec get j = - if j >= len then invalid_integer fmt j else - match fmt.[j] with - | '0' .. '9' | '-' -> get (succ j) - | _ -> - let size = - if j = i then size_of_int 0 else - format_int_of_string fmt j (String.sub fmt i (j - i)) in - c size n j in - get i - - and skip_gt i = - if i >= len then invalid_format fmt i else - match fmt.[i] with - | ' ' -> skip_gt (succ i) - | '>' -> succ i - | _ -> invalid_format fmt i - - and get_box_kind i = - if i >= len then Pp_box, i else - match fmt.[i] with - | 'h' -> - let i = succ i in - if i >= len then Pp_hbox, i else - begin match fmt.[i] with - | 'o' -> - let i = succ i in - if i >= len then format_invalid_arg "bad box format" fmt i else - begin match fmt.[i] with - | 'v' -> Pp_hovbox, succ i - | c -> - format_invalid_arg - ("bad box name ho" ^ String.make 1 c) fmt i end - | 'v' -> Pp_hvbox, succ i - | c -> Pp_hbox, i - end - | 'b' -> Pp_box, succ i - | 'v' -> Pp_vbox, succ i - | _ -> Pp_box, i - - and get_tag_name n i c = - let rec get accu n i j = - if j >= len - then c (implode_rev (String.sub fmt i (j - i)) accu) n j else - match fmt.[j] with - | '>' -> c (implode_rev (String.sub fmt i (j - i)) accu) n j - | '%' -> - let s0 = String.sub fmt i (j - i) in - let cont_s n s i = get (s :: s0 :: accu) n i i - and cont_a n printer arg i = - let s = - if str - then (Obj.magic printer : unit -> _ -> string) () arg - else exstring printer arg in - get (s :: s0 :: accu) n i i - and cont_t n printer i = - let s = - if str - then (Obj.magic printer : unit -> string) () - else exstring (fun ppf () -> printer ppf) () in - get (s :: s0 :: accu) n i i - and cont_f n i = - format_invalid_arg "bad tag name specification" fmt i - and cont_m n sfmt i = - format_invalid_arg "bad tag name specification" fmt i in - Printf.scan_format fmt v n j cont_s cont_a cont_t cont_f cont_m - | c -> get accu n i (succ j) in - get [] n i i - - and do_pp_break ppf n i = - if i >= len then begin pp_print_space ppf (); doprn n i end else - match fmt.[i] with - | '<' -> - let rec got_nspaces nspaces n i = - get_int n i (got_offset nspaces) - and got_offset nspaces offset n i = - pp_print_break ppf (int_of_size nspaces) (int_of_size offset); - doprn n (skip_gt i) in - get_int n (succ i) got_nspaces - | c -> pp_print_space ppf (); doprn n i - - and do_pp_open_box ppf n i = - if i >= len then begin pp_open_box_gen ppf 0 Pp_box; doprn n i end else - match fmt.[i] with - | '<' -> - let kind, i = get_box_kind (succ i) in - let got_size size n i = - pp_open_box_gen ppf (int_of_size size) kind; - doprn n (skip_gt i) in - get_int n i got_size - | c -> pp_open_box_gen ppf 0 Pp_box; doprn n i - - and do_pp_open_tag ppf n i = - if i >= len then begin pp_open_tag ppf ""; doprn n i end else - match fmt.[i] with - | '<' -> - let got_name tag_name n i = - pp_open_tag ppf tag_name; - doprn n (skip_gt i) in - get_tag_name n (succ i) got_name - | c -> pp_open_tag ppf ""; doprn n i in - - doprn (Printf.index_of_int 0) 0 in - - Printf.kapr kpr fmt in - - kprintf;; - -(************************************************************** - - Defining [fprintf] and various flavors of [fprintf]. - - **************************************************************) - -let kfprintf k ppf = mkprintf false (fun _ -> ppf) k;; - -let fprintf ppf = kfprintf ignore ppf;; -let printf fmt = fprintf std_formatter fmt;; -let eprintf fmt = fprintf err_formatter fmt;; - -let kbprintf k b = - mkprintf false (fun _ -> formatter_of_buffer b) k;; - -let bprintf b = kbprintf ignore b;; - -let ksprintf k = - let b = Buffer.create 512 in - let k ppf = k (string_out b ppf) in - mkprintf true (fun _ -> formatter_of_buffer b) k;; - -let kprintf = ksprintf;; - -let sprintf fmt = ksprintf (fun s -> s) fmt;; - -at_exit print_flush;; diff --git a/third_party/pygments/tests/examplefiles/fucked_up.rb b/third_party/pygments/tests/examplefiles/fucked_up.rb deleted file mode 100644 index b1d0ee3b8..000000000 --- a/third_party/pygments/tests/examplefiles/fucked_up.rb +++ /dev/null @@ -1,77 +0,0 @@ -# vim:ft=ruby - -events = Hash.new { |h, k| h[k] = [] } -DATA.read.split(/\n\n\n\s*/).each do |event| - name = event[/^.*/].sub(/http:.*/, '') - event[/\n.*/m].scan(/^([A-Z]{2}\S*)\s*(\S*)\s*(\S*)(\s*\S*)/) do |kind, day, daytime, comment| - events[ [day, daytime] ] << [kind, name + comment] - end -end - -conflicts = 0 -events.to_a.sort_by do |(day, daytime),| - [%w(Mo Di Mi Do Fr).index(day) || 0, daytime] -end.each do |(day, daytime), names| - if names.size > 1 - conflicts += 1 - print '!!! ' - end - print "#{day} #{daytime}: " - names.each { |kind, name| puts " #{kind} #{name}" } - puts -end - -puts '%d conflicts' % conflicts -puts '%d SWS' % (events.inject(0) { |sum, ((day, daytime),)| sum + (daytime[/\d+$/].to_i - daytime[/^\d+/].to_i) }) - -string = % foo # strange. huh? -print "Escape here: \n" -print 'Dont escape here: \n' - -__END__ -Informatik und Informationsgesellschaft I: Digitale Medien (32 214) -Computer lassen ihre eigentliche Bestimmung durch Multimedia und Vernetzung erkennen: Es sind digitale Medien, die alle bisherigen Massen- und Kommunikationsmedien simulieren, kopieren oder ersetzen können. Die kurze Geschichte elektronischer Medien vom Telegramm bis zum Fernsehen wird so zur Vorgeschichte des Computers als Medium. Der Prozess der Mediatisierung der Rechnernetze soll in Technik, Theorie und Praxis untersucht werden. Das PR soll die Techniken der ortsverteilten und zeitversetzten Lehre an Hand praktischer Übungen vorführen und untersuchen. -VL Di 15-17 wöch. RUD 25, 3.101 J. Koubek -VL Do 15-17 wöch. RUD 25, 3.101 -UE/PR Do 17-19 wöch. RUD 25, 3.101 J.-M. Loebel - - -Methoden und Modelle des Systementwurfs (32 223) -Gute Methoden zum Entwurf und zur Verifikation von Systemen sind ein Schlüssel für gute Software. Dieses Seminar betrachtet moderne Entwurfsmethoden. - VL Di 09-11 wöch. RUD 26, 0’313 W. Reisig - VL Do 09-11 wöch. RUD 26, 0’313 - UE Di 11-13 wöch. RUD 26, 0’313 - PR Di 13-15 wöch. RUD 26, 0’313 D. Weinberg - - -Komplexitätstheorie (32 229) -In dieser Vorlesung untersuchen wir eine Reihe von wichtigen algorithmischen Problemstellungen aus verschiedenen Bereichen der Informatik. Unser besonderes Interesse gilt dabei der Abschätzung der Rechenressourcen, die zu ihrer Lösung aufzubringen sind. Die Vorlesung bildet eine wichtige Grundlage für weiterführende Veranstaltungen in den Bereichen Algorithmen, Kryptologie, Algorithmisches Lernen und Algorithmisches Beweisen. - VL Di 09-11 wöch. RUD 26, 1’303 J. Köbler - VL Do 09-11 wöch. RUD 26, 1’305 - UE Do 11-13 wöch. RUD 26, 1’305 - - -Zuverlässige Systeme (32 234) -Mit zunehmender Verbreitung der Computertechnologie in immer mehr Bereichen des menschlichen Lebens wird die Zuverlässigkeit solcher Systeme zu einer immer zentraleren Frage. -Der Halbkurs "Zuverlässige Systeme" konzentriert sich auf folgende Schwerpunkte: Zuverlässigkeit, Fehlertoleranz, Responsivität, Messungen, Anwendungen, Systemmodelle und Techniken, Ausfallverhalten, Fehlermodelle, Schedulingtechniken, Software/Hardware - responsives Systemdesign, Analyse und Synthese, Bewertung, Fallstudien in Forschung und Industrie. -Der Halbkurs kann mit dem Halbkurs "Eigenschaften mobiler und eingebetteter Systeme" zu einem Projektkurs kombiniert werden. Ein gemeinsames Projekt begleitet beide Halbkurse. -VL Di 09-11 wöch. RUD 26, 1’308 M. Malek -VL Do 09-11 wöch. RUD 26, 1’308 -PR n.V. - - -Stochastik für InformatikerInnen (32 239) -Grundlagen der Wahrscheinlichkeitsrechnung, Diskrete und stetige Wahrscheinlichkeitsmodelle in der Informatik, Grenzwertsätze, Simulationsverfahren, Zufallszahlen, Statistische Schätz- und Testverfahren, Markoffsche Ketten, Simulated Annealing, Probabilistische Analyse von Algorithmen. -VL Mo 09-11 wöch. RUD 25, 3.101 W. Kössler -VL Mi 09-11 wöch. RUD 25, 3.101 -UE Mo 11-13 wöch. RUD 25, 3.101 - UE Mi 11-13 wöch. RUD 25. 3.101 - - -Geschichte der Informatik – Ausgewählte Kapitel (32 243) -VL Mi 13-15 wöch. RUD 25, 3.113 W. Coy - - -Aktuelle Themen der Theoretischen Informatik (32 260) -In diesem Seminar sollen wichtige aktuelle Veröffentlichungen aus der theoretischen Informatik gemeinsam erarbeitet werden. Genaueres wird erst kurz vor dem Seminar entschieden. Bei Interesse wenden Sie sich bitte möglichst frühzeitig an den Veranstalter. - SE Fr 09-11 wöch. RUD 26, 1’307 M. Grohe  diff --git a/third_party/pygments/tests/examplefiles/function.mu b/third_party/pygments/tests/examplefiles/function.mu deleted file mode 100644 index 46bb259d5..000000000 --- a/third_party/pygments/tests/examplefiles/function.mu +++ /dev/null @@ -1 +0,0 @@ -a::b () diff --git a/third_party/pygments/tests/examplefiles/functional.rst b/third_party/pygments/tests/examplefiles/functional.rst deleted file mode 100644 index bfe67d108..000000000 --- a/third_party/pygments/tests/examplefiles/functional.rst +++ /dev/null @@ -1,1472 +0,0 @@ -Functional Programming HOWTO -================================ - -**Version 0.30** - -(This is a first draft. Please send comments/error -reports/suggestions to amk@amk.ca. This URL is probably not going to -be the final location of the document, so be careful about linking to -it -- you may want to add a disclaimer.) - -In this document, we'll take a tour of Python's features suitable for -implementing programs in a functional style. After an introduction to -the concepts of functional programming, we'll look at language -features such as iterators and generators and relevant library modules -such as ``itertools`` and ``functools``. - - -.. contents:: - -Introduction ----------------------- - -This section explains the basic concept of functional programming; if -you're just interested in learning about Python language features, -skip to the next section. - -Programming languages support decomposing problems in several different -ways: - -* Most programming languages are **procedural**: - programs are lists of instructions that tell the computer what to - do with the program's input. - C, Pascal, and even Unix shells are procedural languages. - -* In **declarative** languages, you write a specification that describes - the problem to be solved, and the language implementation figures out - how to perform the computation efficiently. SQL is the declarative - language you're most likely to be familiar with; a SQL query describes - the data set you want to retrieve, and the SQL engine decides whether to - scan tables or use indexes, which subclauses should be performed first, - etc. - -* **Object-oriented** programs manipulate collections of objects. - Objects have internal state and support methods that query or modify - this internal state in some way. Smalltalk and Java are - object-oriented languages. C++ and Python are languages that - support object-oriented programming, but don't force the use - of object-oriented features. - -* **Functional** programming decomposes a problem into a set of functions. - Ideally, functions only take inputs and produce outputs, and don't have any - internal state that affects the output produced for a given input. - Well-known functional languages include the ML family (Standard ML, - OCaml, and other variants) and Haskell. - -The designers of some computer languages have chosen one approach to -programming that's emphasized. This often makes it difficult to -write programs that use a different approach. Other languages are -multi-paradigm languages that support several different approaches. Lisp, -C++, and Python are multi-paradigm; you can write programs or -libraries that are largely procedural, object-oriented, or functional -in all of these languages. In a large program, different sections -might be written using different approaches; the GUI might be object-oriented -while the processing logic is procedural or functional, for example. - -In a functional program, input flows through a set of functions. Each -function operates on its input and produces some output. Functional -style frowns upon functions with side effects that modify internal -state or make other changes that aren't visible in the function's -return value. Functions that have no side effects at all are -called **purely functional**. -Avoiding side effects means not using data structures -that get updated as a program runs; every function's output -must only depend on its input. - -Some languages are very strict about purity and don't even have -assignment statements such as ``a=3`` or ``c = a + b``, but it's -difficult to avoid all side effects. Printing to the screen or -writing to a disk file are side effects, for example. For example, in -Python a ``print`` statement or a ``time.sleep(1)`` both return no -useful value; they're only called for their side effects of sending -some text to the screen or pausing execution for a second. - -Python programs written in functional style usually won't go to the -extreme of avoiding all I/O or all assignments; instead, they'll -provide a functional-appearing interface but will use non-functional -features internally. For example, the implementation of a function -will still use assignments to local variables, but won't modify global -variables or have other side effects. - -Functional programming can be considered the opposite of -object-oriented programming. Objects are little capsules containing -some internal state along with a collection of method calls that let -you modify this state, and programs consist of making the right set of -state changes. Functional programming wants to avoid state changes as -much as possible and works with data flowing between functions. In -Python you might combine the two approaches by writing functions that -take and return instances representing objects in your application -(e-mail messages, transactions, etc.). - -Functional design may seem like an odd constraint to work under. Why -should you avoid objects and side effects? There are theoretical and -practical advantages to the functional style: - -* Formal provability. -* Modularity. -* Composability. -* Ease of debugging and testing. - -Formal provability -'''''''''''''''''''''' - -A theoretical benefit is that it's easier to construct a mathematical proof -that a functional program is correct. - -For a long time researchers have been interested in finding ways to -mathematically prove programs correct. This is different from testing -a program on numerous inputs and concluding that its output is usually -correct, or reading a program's source code and concluding that the -code looks right; the goal is instead a rigorous proof that a program -produces the right result for all possible inputs. - -The technique used to prove programs correct is to write down -**invariants**, properties of the input data and of the program's -variables that are always true. For each line of code, you then show -that if invariants X and Y are true **before** the line is executed, -the slightly different invariants X' and Y' are true **after** -the line is executed. This continues until you reach the end of the -program, at which point the invariants should match the desired -conditions on the program's output. - -Functional programming's avoidance of assignments arose because -assignments are difficult to handle with this technique; -assignments can break invariants that were true before the assignment -without producing any new invariants that can be propagated onward. - -Unfortunately, proving programs correct is largely impractical and not -relevant to Python software. Even trivial programs require proofs that -are several pages long; the proof of correctness for a moderately -complicated program would be enormous, and few or none of the programs -you use daily (the Python interpreter, your XML parser, your web -browser) could be proven correct. Even if you wrote down or generated -a proof, there would then be the question of verifying the proof; -maybe there's an error in it, and you wrongly believe you've proved -the program correct. - -Modularity -'''''''''''''''''''''' - -A more practical benefit of functional programming is that it forces -you to break apart your problem into small pieces. Programs are more -modular as a result. It's easier to specify and write a small -function that does one thing than a large function that performs a -complicated transformation. Small functions are also easier to read -and to check for errors. - - -Ease of debugging and testing -'''''''''''''''''''''''''''''''''' - -Testing and debugging a functional-style program is easier. - -Debugging is simplified because functions are generally small and -clearly specified. When a program doesn't work, each function is an -interface point where you can check that the data are correct. You -can look at the intermediate inputs and outputs to quickly isolate the -function that's responsible for a bug. - -Testing is easier because each function is a potential subject for a -unit test. Functions don't depend on system state that needs to be -replicated before running a test; instead you only have to synthesize -the right input and then check that the output matches expectations. - - - -Composability -'''''''''''''''''''''' - -As you work on a functional-style program, you'll write a number of -functions with varying inputs and outputs. Some of these functions -will be unavoidably specialized to a particular application, but -others will be useful in a wide variety of programs. For example, a -function that takes a directory path and returns all the XML files in -the directory, or a function that takes a filename and returns its -contents, can be applied to many different situations. - -Over time you'll form a personal library of utilities. Often you'll -assemble new programs by arranging existing functions in a new -configuration and writing a few functions specialized for the current -task. - - - -Iterators ------------------------ - -I'll start by looking at a Python language feature that's an important -foundation for writing functional-style programs: iterators. - -An iterator is an object representing a stream of data; this object -returns the data one element at a time. A Python iterator must -support a method called ``next()`` that takes no arguments and always -returns the next element of the stream. If there are no more elements -in the stream, ``next()`` must raise the ``StopIteration`` exception. -Iterators don't have to be finite, though; it's perfectly reasonable -to write an iterator that produces an infinite stream of data. - -The built-in ``iter()`` function takes an arbitrary object and tries -to return an iterator that will return the object's contents or -elements, raising ``TypeError`` if the object doesn't support -iteration. Several of Python's built-in data types support iteration, -the most common being lists and dictionaries. An object is called -an **iterable** object if you can get an iterator for it. - -You can experiment with the iteration interface manually:: - - >>> L = [1,2,3] - >>> it = iter(L) - >>> print it - - >>> it.next() - 1 - >>> it.next() - 2 - >>> it.next() - 3 - >>> it.next() - Traceback (most recent call last): - File "", line 1, in ? - StopIteration - >>> - -Python expects iterable objects in several different contexts, the -most important being the ``for`` statement. In the statement ``for X in Y``, -Y must be an iterator or some object for which ``iter()`` can create -an iterator. These two statements are equivalent:: - - for i in iter(obj): - print i - - for i in obj: - print i - -Iterators can be materialized as lists or tuples by using the -``list()`` or ``tuple()`` constructor functions:: - - >>> L = [1,2,3] - >>> iterator = iter(L) - >>> t = tuple(iterator) - >>> t - (1, 2, 3) - -Sequence unpacking also supports iterators: if you know an iterator -will return N elements, you can unpack them into an N-tuple:: - - >>> L = [1,2,3] - >>> iterator = iter(L) - >>> a,b,c = iterator - >>> a,b,c - (1, 2, 3) - -Built-in functions such as ``max()`` and ``min()`` can take a single -iterator argument and will return the largest or smallest element. -The ``"in"`` and ``"not in"`` operators also support iterators: ``X in -iterator`` is true if X is found in the stream returned by the -iterator. You'll run into obvious problems if the iterator is -infinite; ``max()``, ``min()``, and ``"not in"`` will never return, and -if the element X never appears in the stream, the ``"in"`` operator -won't return either. - -Note that you can only go forward in an iterator; there's no way to -get the previous element, reset the iterator, or make a copy of it. -Iterator objects can optionally provide these additional capabilities, -but the iterator protocol only specifies the ``next()`` method. -Functions may therefore consume all of the iterator's output, and if -you need to do something different with the same stream, you'll have -to create a new iterator. - - - -Data Types That Support Iterators -''''''''''''''''''''''''''''''''''' - -We've already seen how lists and tuples support iterators. In fact, -any Python sequence type, such as strings, will automatically support -creation of an iterator. - -Calling ``iter()`` on a dictionary returns an iterator that will loop -over the dictionary's keys:: - - >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, - ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} - >>> for key in m: - ... print key, m[key] - Mar 3 - Feb 2 - Aug 8 - Sep 9 - May 5 - Jun 6 - Jul 7 - Jan 1 - Apr 4 - Nov 11 - Dec 12 - Oct 10 - -Note that the order is essentially random, because it's based on the -hash ordering of the objects in the dictionary. - -Applying ``iter()`` to a dictionary always loops over the keys, but -dictionaries have methods that return other iterators. If you want to -iterate over keys, values, or key/value pairs, you can explicitly call -the ``iterkeys()``, ``itervalues()``, or ``iteritems()`` methods to -get an appropriate iterator. - -The ``dict()`` constructor can accept an iterator that returns a -finite stream of ``(key, value)`` tuples:: - - >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] - >>> dict(iter(L)) - {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'} - -Files also support iteration by calling the ``readline()`` -method until there are no more lines in the file. This means you can -read each line of a file like this:: - - for line in file: - # do something for each line - ... - -Sets can take their contents from an iterable and let you iterate over -the set's elements:: - - S = set((2, 3, 5, 7, 11, 13)) - for i in S: - print i - - - -Generator expressions and list comprehensions ----------------------------------------------------- - -Two common operations on an iterator's output are 1) performing some -operation for every element, 2) selecting a subset of elements that -meet some condition. For example, given a list of strings, you might -want to strip off trailing whitespace from each line or extract all -the strings containing a given substring. - -List comprehensions and generator expressions (short form: "listcomps" -and "genexps") are a concise notation for such operations, borrowed -from the functional programming language Haskell -(http://www.haskell.org). You can strip all the whitespace from a -stream of strings with the following code:: - - line_list = [' line 1\n', 'line 2 \n', ...] - - # Generator expression -- returns iterator - stripped_iter = (line.strip() for line in line_list) - - # List comprehension -- returns list - stripped_list = [line.strip() for line in line_list] - -You can select only certain elements by adding an ``"if"`` condition:: - - stripped_list = [line.strip() for line in line_list - if line != ""] - -With a list comprehension, you get back a Python list; -``stripped_list`` is a list containing the resulting lines, not an -iterator. Generator expressions return an iterator that computes the -values as necessary, not needing to materialize all the values at -once. This means that list comprehensions aren't useful if you're -working with iterators that return an infinite stream or a very large -amount of data. Generator expressions are preferable in these -situations. - -Generator expressions are surrounded by parentheses ("()") and list -comprehensions are surrounded by square brackets ("[]"). Generator -expressions have the form:: - - ( expression for expr in sequence1 - if condition1 - for expr2 in sequence2 - if condition2 - for expr3 in sequence3 ... - if condition3 - for exprN in sequenceN - if conditionN ) - -Again, for a list comprehension only the outside brackets are -different (square brackets instead of parentheses). - -The elements of the generated output will be the successive values of -``expression``. The ``if`` clauses are all optional; if present, -``expression`` is only evaluated and added to the result when -``condition`` is true. - -Generator expressions always have to be written inside parentheses, -but the parentheses signalling a function call also count. If you -want to create an iterator that will be immediately passed to a -function you can write:: - - obj_total = sum(obj.count for obj in list_all_objects()) - -The ``for...in`` clauses contain the sequences to be iterated over. -The sequences do not have to be the same length, because they are -iterated over from left to right, **not** in parallel. For each -element in ``sequence1``, ``sequence2`` is looped over from the -beginning. ``sequence3`` is then looped over for each -resulting pair of elements from ``sequence1`` and ``sequence2``. - -To put it another way, a list comprehension or generator expression is -equivalent to the following Python code:: - - for expr1 in sequence1: - if not (condition1): - continue # Skip this element - for expr2 in sequence2: - if not (condition2): - continue # Skip this element - ... - for exprN in sequenceN: - if not (conditionN): - continue # Skip this element - - # Output the value of - # the expression. - -This means that when there are multiple ``for...in`` clauses but no -``if`` clauses, the length of the resulting output will be equal to -the product of the lengths of all the sequences. If you have two -lists of length 3, the output list is 9 elements long:: - - seq1 = 'abc' - seq2 = (1,2,3) - >>> [ (x,y) for x in seq1 for y in seq2] - [('a', 1), ('a', 2), ('a', 3), - ('b', 1), ('b', 2), ('b', 3), - ('c', 1), ('c', 2), ('c', 3)] - -To avoid introducing an ambiguity into Python's grammar, if -``expression`` is creating a tuple, it must be surrounded with -parentheses. The first list comprehension below is a syntax error, -while the second one is correct:: - - # Syntax error - [ x,y for x in seq1 for y in seq2] - # Correct - [ (x,y) for x in seq1 for y in seq2] - - -Generators ------------------------ - -Generators are a special class of functions that simplify the task of -writing iterators. Regular functions compute a value and return it, -but generators return an iterator that returns a stream of values. - -You're doubtless familiar with how regular function calls work in -Python or C. When you call a function, it gets a private namespace -where its local variables are created. When the function reaches a -``return`` statement, the local variables are destroyed and the -value is returned to the caller. A later call to the same function -creates a new private namespace and a fresh set of local -variables. But, what if the local variables weren't thrown away on -exiting a function? What if you could later resume the function where -it left off? This is what generators provide; they can be thought of -as resumable functions. - -Here's the simplest example of a generator function:: - - def generate_ints(N): - for i in range(N): - yield i - -Any function containing a ``yield`` keyword is a generator function; -this is detected by Python's bytecode compiler which compiles the -function specially as a result. - -When you call a generator function, it doesn't return a single value; -instead it returns a generator object that supports the iterator -protocol. On executing the ``yield`` expression, the generator -outputs the value of ``i``, similar to a ``return`` -statement. The big difference between ``yield`` and a -``return`` statement is that on reaching a ``yield`` the -generator's state of execution is suspended and local variables are -preserved. On the next call to the generator's ``.next()`` method, -the function will resume executing. - -Here's a sample usage of the ``generate_ints()`` generator:: - - >>> gen = generate_ints(3) - >>> gen - - >>> gen.next() - 0 - >>> gen.next() - 1 - >>> gen.next() - 2 - >>> gen.next() - Traceback (most recent call last): - File "stdin", line 1, in ? - File "stdin", line 2, in generate_ints - StopIteration - -You could equally write ``for i in generate_ints(5)``, or -``a,b,c = generate_ints(3)``. - -Inside a generator function, the ``return`` statement can only be used -without a value, and signals the end of the procession of values; -after executing a ``return`` the generator cannot return any further -values. ``return`` with a value, such as ``return 5``, is a syntax -error inside a generator function. The end of the generator's results -can also be indicated by raising ``StopIteration`` manually, or by -just letting the flow of execution fall off the bottom of the -function. - -You could achieve the effect of generators manually by writing your -own class and storing all the local variables of the generator as -instance variables. For example, returning a list of integers could -be done by setting ``self.count`` to 0, and having the -``next()`` method increment ``self.count`` and return it. -However, for a moderately complicated generator, writing a -corresponding class can be much messier. - -The test suite included with Python's library, ``test_generators.py``, -contains a number of more interesting examples. Here's one generator -that implements an in-order traversal of a tree using generators -recursively. - -:: - - # A recursive generator that generates Tree leaves in in-order. - def inorder(t): - if t: - for x in inorder(t.left): - yield x - - yield t.label - - for x in inorder(t.right): - yield x - -Two other examples in ``test_generators.py`` produce -solutions for the N-Queens problem (placing N queens on an NxN -chess board so that no queen threatens another) and the Knight's Tour -(finding a route that takes a knight to every square of an NxN chessboard -without visiting any square twice). - - - -Passing values into a generator -'''''''''''''''''''''''''''''''''''''''''''''' - -In Python 2.4 and earlier, generators only produced output. Once a -generator's code was invoked to create an iterator, there was no way to -pass any new information into the function when its execution is -resumed. You could hack together this ability by making the -generator look at a global variable or by passing in some mutable object -that callers then modify, but these approaches are messy. - -In Python 2.5 there's a simple way to pass values into a generator. -``yield`` became an expression, returning a value that can be assigned -to a variable or otherwise operated on:: - - val = (yield i) - -I recommend that you **always** put parentheses around a ``yield`` -expression when you're doing something with the returned value, as in -the above example. The parentheses aren't always necessary, but it's -easier to always add them instead of having to remember when they're -needed. - -(PEP 342 explains the exact rules, which are that a -``yield``-expression must always be parenthesized except when it -occurs at the top-level expression on the right-hand side of an -assignment. This means you can write ``val = yield i`` but have to -use parentheses when there's an operation, as in ``val = (yield i) -+ 12``.) - -Values are sent into a generator by calling its -``send(value)`` method. This method resumes the -generator's code and the ``yield`` expression returns the specified -value. If the regular ``next()`` method is called, the -``yield`` returns ``None``. - -Here's a simple counter that increments by 1 and allows changing the -value of the internal counter. - -:: - - def counter (maximum): - i = 0 - while i < maximum: - val = (yield i) - # If value provided, change counter - if val is not None: - i = val - else: - i += 1 - -And here's an example of changing the counter: - - >>> it = counter(10) - >>> print it.next() - 0 - >>> print it.next() - 1 - >>> print it.send(8) - 8 - >>> print it.next() - 9 - >>> print it.next() - Traceback (most recent call last): - File ``t.py'', line 15, in ? - print it.next() - StopIteration - -Because ``yield`` will often be returning ``None``, you -should always check for this case. Don't just use its value in -expressions unless you're sure that the ``send()`` method -will be the only method used resume your generator function. - -In addition to ``send()``, there are two other new methods on -generators: - -* ``throw(type, value=None, traceback=None)`` is used to raise an exception inside the - generator; the exception is raised by the ``yield`` expression - where the generator's execution is paused. - -* ``close()`` raises a ``GeneratorExit`` - exception inside the generator to terminate the iteration. - On receiving this - exception, the generator's code must either raise - ``GeneratorExit`` or ``StopIteration``; catching the - exception and doing anything else is illegal and will trigger - a ``RuntimeError``. ``close()`` will also be called by - Python's garbage collector when the generator is garbage-collected. - - If you need to run cleanup code when a ``GeneratorExit`` occurs, - I suggest using a ``try: ... finally:`` suite instead of - catching ``GeneratorExit``. - -The cumulative effect of these changes is to turn generators from -one-way producers of information into both producers and consumers. - -Generators also become **coroutines**, a more generalized form of -subroutines. Subroutines are entered at one point and exited at -another point (the top of the function, and a ``return`` -statement), but coroutines can be entered, exited, and resumed at -many different points (the ``yield`` statements). - - -Built-in functions ----------------------------------------------- - -Let's look in more detail at built-in functions often used with iterators. - -Two Python's built-in functions, ``map()`` and ``filter()``, are -somewhat obsolete; they duplicate the features of list comprehensions -but return actual lists instead of iterators. - -``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0], -iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. - -:: - - def upper(s): - return s.upper() - map(upper, ['sentence', 'fragment']) => - ['SENTENCE', 'FRAGMENT'] - - [upper(s) for s in ['sentence', 'fragment']] => - ['SENTENCE', 'FRAGMENT'] - -As shown above, you can achieve the same effect with a list -comprehension. The ``itertools.imap()`` function does the same thing -but can handle infinite iterators; it'll be discussed later, in the section on -the ``itertools`` module. - -``filter(predicate, iter)`` returns a list -that contains all the sequence elements that meet a certain condition, -and is similarly duplicated by list comprehensions. -A **predicate** is a function that returns the truth value of -some condition; for use with ``filter()``, the predicate must take a -single value. - -:: - - def is_even(x): - return (x % 2) == 0 - - filter(is_even, range(10)) => - [0, 2, 4, 6, 8] - -This can also be written as a list comprehension:: - - >>> [x for x in range(10) if is_even(x)] - [0, 2, 4, 6, 8] - -``filter()`` also has a counterpart in the ``itertools`` module, -``itertools.ifilter()``, that returns an iterator and -can therefore handle infinite sequences just as ``itertools.imap()`` can. - -``reduce(func, iter, [initial_value])`` doesn't have a counterpart in -the ``itertools`` module because it cumulatively performs an operation -on all the iterable's elements and therefore can't be applied to -infinite iterables. ``func`` must be a function that takes two elements -and returns a single value. ``reduce()`` takes the first two elements -A and B returned by the iterator and calculates ``func(A, B)``. It -then requests the third element, C, calculates ``func(func(A, B), -C)``, combines this result with the fourth element returned, and -continues until the iterable is exhausted. If the iterable returns no -values at all, a ``TypeError`` exception is raised. If the initial -value is supplied, it's used as a starting point and -``func(initial_value, A)`` is the first calculation. - -:: - - import operator - reduce(operator.concat, ['A', 'BB', 'C']) => - 'ABBC' - reduce(operator.concat, []) => - TypeError: reduce() of empty sequence with no initial value - reduce(operator.mul, [1,2,3], 1) => - 6 - reduce(operator.mul, [], 1) => - 1 - -If you use ``operator.add`` with ``reduce()``, you'll add up all the -elements of the iterable. This case is so common that there's a special -built-in called ``sum()`` to compute it:: - - reduce(operator.add, [1,2,3,4], 0) => - 10 - sum([1,2,3,4]) => - 10 - sum([]) => - 0 - -For many uses of ``reduce()``, though, it can be clearer to just write -the obvious ``for`` loop:: - - # Instead of: - product = reduce(operator.mul, [1,2,3], 1) - - # You can write: - product = 1 - for i in [1,2,3]: - product *= i - - -``enumerate(iter)`` counts off the elements in the iterable, returning -2-tuples containing the count and each element. - -:: - - enumerate(['subject', 'verb', 'object']) => - (0, 'subject'), (1, 'verb'), (2, 'object') - -``enumerate()`` is often used when looping through a list -and recording the indexes at which certain conditions are met:: - - f = open('data.txt', 'r') - for i, line in enumerate(f): - if line.strip() == '': - print 'Blank line at line #%i' % i - -``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` -collects all the elements of the iterable into a list, sorts -the list, and returns the sorted result. The ``cmp``, ``key``, -and ``reverse`` arguments are passed through to the -constructed list's ``.sort()`` method. - -:: - - import random - # Generate 8 random numbers between [0, 10000) - rand_list = random.sample(range(10000), 8) - rand_list => - [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] - sorted(rand_list) => - [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] - sorted(rand_list, reverse=True) => - [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] - -(For a more detailed discussion of sorting, see the Sorting mini-HOWTO -in the Python wiki at http://wiki.python.org/moin/HowTo/Sorting.) - -The ``any(iter)`` and ``all(iter)`` built-ins look at -the truth values of an iterable's contents. ``any()`` returns -True if any element in the iterable is a true value, and ``all()`` -returns True if all of the elements are true values:: - - any([0,1,0]) => - True - any([0,0,0]) => - False - any([1,1,1]) => - True - all([0,1,0]) => - False - all([0,0,0]) => - False - all([1,1,1]) => - True - - -Small functions and the lambda statement ----------------------------------------------- - -When writing functional-style programs, you'll often need little -functions that act as predicates or that combine elements in some way. - -If there's a Python built-in or a module function that's suitable, you -don't need to define a new function at all:: - - stripped_lines = [line.strip() for line in lines] - existing_files = filter(os.path.exists, file_list) - -If the function you need doesn't exist, you need to write it. One way -to write small functions is to use the ``lambda`` statement. ``lambda`` -takes a number of parameters and an expression combining these parameters, -and creates a small function that returns the value of the expression:: - - lowercase = lambda x: x.lower() - - print_assign = lambda name, value: name + '=' + str(value) - - adder = lambda x, y: x+y - -An alternative is to just use the ``def`` statement and define a -function in the usual way:: - - def lowercase(x): - return x.lower() - - def print_assign(name, value): - return name + '=' + str(value) - - def adder(x,y): - return x + y - -Which alternative is preferable? That's a style question; my usual -course is to avoid using ``lambda``. - -One reason for my preference is that ``lambda`` is quite limited in -the functions it can define. The result has to be computable as a -single expression, which means you can't have multiway -``if... elif... else`` comparisons or ``try... except`` statements. -If you try to do too much in a ``lambda`` statement, you'll end up -with an overly complicated expression that's hard to read. Quick, -what's the following code doing? - -:: - - total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1] - -You can figure it out, but it takes time to disentangle the expression -to figure out what's going on. Using a short nested -``def`` statements makes things a little bit better:: - - def combine (a, b): - return 0, a[1] + b[1] - - total = reduce(combine, items)[1] - -But it would be best of all if I had simply used a ``for`` loop:: - - total = 0 - for a, b in items: - total += b - -Or the ``sum()`` built-in and a generator expression:: - - total = sum(b for a,b in items) - -Many uses of ``reduce()`` are clearer when written as ``for`` loops. - -Fredrik Lundh once suggested the following set of rules for refactoring -uses of ``lambda``: - -1) Write a lambda function. -2) Write a comment explaining what the heck that lambda does. -3) Study the comment for a while, and think of a name that captures - the essence of the comment. -4) Convert the lambda to a def statement, using that name. -5) Remove the comment. - -I really like these rules, but you're free to disagree that this -lambda-free style is better. - - -The itertools module ------------------------ - -The ``itertools`` module contains a number of commonly-used iterators -as well as functions for combining several iterators. This section -will introduce the module's contents by showing small examples. - -The module's functions fall into a few broad classes: - -* Functions that create a new iterator based on an existing iterator. -* Functions for treating an iterator's elements as function arguments. -* Functions for selecting portions of an iterator's output. -* A function for grouping an iterator's output. - -Creating new iterators -'''''''''''''''''''''' - -``itertools.count(n)`` returns an infinite stream of -integers, increasing by 1 each time. You can optionally supply the -starting number, which defaults to 0:: - - itertools.count() => - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... - itertools.count(10) => - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... - -``itertools.cycle(iter)`` saves a copy of the contents of a provided -iterable and returns a new iterator that returns its elements from -first to last. The new iterator will repeat these elements infinitely. - -:: - - itertools.cycle([1,2,3,4,5]) => - 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... - -``itertools.repeat(elem, [n])`` returns the provided element ``n`` -times, or returns the element endlessly if ``n`` is not provided. - -:: - - itertools.repeat('abc') => - abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... - itertools.repeat('abc', 5) => - abc, abc, abc, abc, abc - -``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of -iterables as input, and returns all the elements of the first -iterator, then all the elements of the second, and so on, until all of -the iterables have been exhausted. - -:: - - itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => - a, b, c, 1, 2, 3 - -``itertools.izip(iterA, iterB, ...)`` takes one element from each iterable -and returns them in a tuple:: - - itertools.izip(['a', 'b', 'c'], (1, 2, 3)) => - ('a', 1), ('b', 2), ('c', 3) - -It's similiar to the built-in ``zip()`` function, but doesn't -construct an in-memory list and exhaust all the input iterators before -returning; instead tuples are constructed and returned only if they're -requested. (The technical term for this behaviour is -`lazy evaluation `__.) - -This iterator is intended to be used with iterables that are all of -the same length. If the iterables are of different lengths, the -resulting stream will be the same length as the shortest iterable. - -:: - - itertools.izip(['a', 'b'], (1, 2, 3)) => - ('a', 1), ('b', 2) - -You should avoid doing this, though, because an element may be taken -from the longer iterators and discarded. This means you can't go on -to use the iterators further because you risk skipping a discarded -element. - -``itertools.islice(iter, [start], stop, [step])`` returns a stream -that's a slice of the iterator. With a single ``stop`` argument, -it will return the first ``stop`` -elements. If you supply a starting index, you'll get ``stop-start`` -elements, and if you supply a value for ``step``, elements will be -skipped accordingly. Unlike Python's string and list slicing, you -can't use negative values for ``start``, ``stop``, or ``step``. - -:: - - itertools.islice(range(10), 8) => - 0, 1, 2, 3, 4, 5, 6, 7 - itertools.islice(range(10), 2, 8) => - 2, 3, 4, 5, 6, 7 - itertools.islice(range(10), 2, 8, 2) => - 2, 4, 6 - -``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n`` -independent iterators that will all return the contents of the source -iterator. If you don't supply a value for ``n``, the default is 2. -Replicating iterators requires saving some of the contents of the source -iterator, so this can consume significant memory if the iterator is large -and one of the new iterators is consumed more than the others. - -:: - - itertools.tee( itertools.count() ) => - iterA, iterB - - where iterA -> - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... - - and iterB -> - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... - - -Calling functions on elements -''''''''''''''''''''''''''''' - -Two functions are used for calling other functions on the contents of an -iterable. - -``itertools.imap(f, iterA, iterB, ...)`` returns -a stream containing ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), -f(iterA[2], iterB[2]), ...``:: - - itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) => - 6, 8, 8 - -The ``operator`` module contains a set of functions -corresponding to Python's operators. Some examples are -``operator.add(a, b)`` (adds two values), -``operator.ne(a, b)`` (same as ``a!=b``), -and -``operator.attrgetter('id')`` (returns a callable that -fetches the ``"id"`` attribute). - -``itertools.starmap(func, iter)`` assumes that the iterable will -return a stream of tuples, and calls ``f()`` using these tuples as the -arguments:: - - itertools.starmap(os.path.join, - [('/usr', 'bin', 'java'), ('/bin', 'python'), - ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')]) - => - /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby - - -Selecting elements -'''''''''''''''''' - -Another group of functions chooses a subset of an iterator's elements -based on a predicate. - -``itertools.ifilter(predicate, iter)`` returns all the elements for -which the predicate returns true:: - - def is_even(x): - return (x % 2) == 0 - - itertools.ifilter(is_even, itertools.count()) => - 0, 2, 4, 6, 8, 10, 12, 14, ... - -``itertools.ifilterfalse(predicate, iter)`` is the opposite, -returning all elements for which the predicate returns false:: - - itertools.ifilterfalse(is_even, itertools.count()) => - 1, 3, 5, 7, 9, 11, 13, 15, ... - -``itertools.takewhile(predicate, iter)`` returns elements for as long -as the predicate returns true. Once the predicate returns false, -the iterator will signal the end of its results. - -:: - - def less_than_10(x): - return (x < 10) - - itertools.takewhile(less_than_10, itertools.count()) => - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - - itertools.takewhile(is_even, itertools.count()) => - 0 - -``itertools.dropwhile(predicate, iter)`` discards elements while the -predicate returns true, and then returns the rest of the iterable's -results. - -:: - - itertools.dropwhile(less_than_10, itertools.count()) => - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... - - itertools.dropwhile(is_even, itertools.count()) => - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... - - -Grouping elements -''''''''''''''''' - -The last function I'll discuss, ``itertools.groupby(iter, -key_func=None)``, is the most complicated. ``key_func(elem)`` is a -function that can compute a key value for each element returned by the -iterable. If you don't supply a key function, the key is simply each -element itself. - -``groupby()`` collects all the consecutive elements from the -underlying iterable that have the same key value, and returns a stream -of 2-tuples containing a key value and an iterator for the elements -with that key. - -:: - - city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), - ('Anchorage', 'AK'), ('Nome', 'AK'), - ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), - ... - ] - - def get_state ((city, state)): - return state - - itertools.groupby(city_list, get_state) => - ('AL', iterator-1), - ('AK', iterator-2), - ('AZ', iterator-3), ... - - where - iterator-1 => - ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') - iterator-2 => - ('Anchorage', 'AK'), ('Nome', 'AK') - iterator-3 => - ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ') - -``groupby()`` assumes that the underlying iterable's contents will -already be sorted based on the key. Note that the returned iterators -also use the underlying iterable, so you have to consume the results -of iterator-1 before requesting iterator-2 and its corresponding key. - - -The functools module ----------------------------------------------- - -The ``functools`` module in Python 2.5 contains some higher-order -functions. A **higher-order function** takes one or more functions as -input and returns a new function. The most useful tool in this module -is the ``partial()`` function. - -For programs written in a functional style, you'll sometimes want to -construct variants of existing functions that have some of the -parameters filled in. Consider a Python function ``f(a, b, c)``; you -may wish to create a new function ``g(b, c)`` that's equivalent to -``f(1, b, c)``; you're filling in a value for one of ``f()``'s parameters. -This is called "partial function application". - -The constructor for ``partial`` takes the arguments ``(function, arg1, -arg2, ... kwarg1=value1, kwarg2=value2)``. The resulting object is -callable, so you can just call it to invoke ``function`` with the -filled-in arguments. - -Here's a small but realistic example:: - - import functools - - def log (message, subsystem): - "Write the contents of 'message' to the specified subsystem." - print '%s: %s' % (subsystem, message) - ... - - server_log = functools.partial(log, subsystem='server') - server_log('Unable to open socket') - - -The operator module -------------------- - -The ``operator`` module was mentioned earlier. It contains a set of -functions corresponding to Python's operators. These functions -are often useful in functional-style code because they save you -from writing trivial functions that perform a single operation. - -Some of the functions in this module are: - -* Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``, - ``abs()``, ... -* Logical operations: ``not_()``, ``truth()``. -* Bitwise operations: ``and_()``, ``or_()``, ``invert()``. -* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``. -* Object identity: ``is_()``, ``is_not()``. - -Consult `the operator module's documentation `__ for a complete -list. - - - -The functional module ---------------------- - -Collin Winter's `functional module `__ -provides a number of more -advanced tools for functional programming. It also reimplements -several Python built-ins, trying to make them more intuitive to those -used to functional programming in other languages. - -This section contains an introduction to some of the most important -functions in ``functional``; full documentation can be found at `the -project's website `__. - -``compose(outer, inner, unpack=False)`` - -The ``compose()`` function implements function composition. -In other words, it returns a wrapper around the ``outer`` and ``inner`` callables, such -that the return value from ``inner`` is fed directly to ``outer``. That is, - -:: - - >>> def add(a, b): - ... return a + b - ... - >>> def double(a): - ... return 2 * a - ... - >>> compose(double, add)(5, 6) - 22 - -is equivalent to - -:: - - >>> double(add(5, 6)) - 22 - -The ``unpack`` keyword is provided to work around the fact that Python functions are not always -`fully curried `__. -By default, it is expected that the ``inner`` function will return a single object and that the ``outer`` -function will take a single argument. Setting the ``unpack`` argument causes ``compose`` to expect a -tuple from ``inner`` which will be expanded before being passed to ``outer``. Put simply, - -:: - - compose(f, g)(5, 6) - -is equivalent to:: - - f(g(5, 6)) - -while - -:: - - compose(f, g, unpack=True)(5, 6) - -is equivalent to:: - - f(*g(5, 6)) - -Even though ``compose()`` only accepts two functions, it's trivial to -build up a version that will compose any number of functions. We'll -use ``reduce()``, ``compose()`` and ``partial()`` (the last of which -is provided by both ``functional`` and ``functools``). - -:: - - from functional import compose, partial - - multi_compose = partial(reduce, compose) - - -We can also use ``map()``, ``compose()`` and ``partial()`` to craft a -version of ``"".join(...)`` that converts its arguments to string:: - - from functional import compose, partial - - join = compose("".join, partial(map, str)) - - -``flip(func)`` - -``flip()`` wraps the callable in ``func`` and -causes it to receive its non-keyword arguments in reverse order. - -:: - - >>> def triple(a, b, c): - ... return (a, b, c) - ... - >>> triple(5, 6, 7) - (5, 6, 7) - >>> - >>> flipped_triple = flip(triple) - >>> flipped_triple(5, 6, 7) - (7, 6, 5) - -``foldl(func, start, iterable)`` - -``foldl()`` takes a binary function, a starting value (usually some kind of 'zero'), and an iterable. -The function is applied to the starting value and the first element of the list, then the result of -that and the second element of the list, then the result of that and the third element of the list, -and so on. - -This means that a call such as:: - - foldl(f, 0, [1, 2, 3]) - -is equivalent to:: - - f(f(f(0, 1), 2), 3) - - -``foldl()`` is roughly equivalent to the following recursive function:: - - def foldl(func, start, seq): - if len(seq) == 0: - return start - - return foldl(func, func(start, seq[0]), seq[1:]) - -Speaking of equivalence, the above ``foldl`` call can be expressed in terms of the built-in ``reduce`` like -so:: - - reduce(f, [1, 2, 3], 0) - - -We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to -write a cleaner, more aesthetically-pleasing version of Python's -``"".join(...)`` idiom:: - - from functional import foldl, partial - from operator import concat - - join = partial(foldl, concat, "") - - -Revision History and Acknowledgements ------------------------------------------------- - -The author would like to thank the following people for offering -suggestions, corrections and assistance with various drafts of this -article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, -Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, -Collin Winter, Blake Winton. - -Version 0.1: posted June 30 2006. - -Version 0.11: posted July 1 2006. Typo fixes. - -Version 0.2: posted July 10 2006. Merged genexp and listcomp -sections into one. Typo fixes. - -Version 0.21: Added more references suggested on the tutor mailing list. - -Version 0.30: Adds a section on the ``functional`` module written by -Collin Winter; adds short section on the operator module; a few other -edits. - - -References --------------------- - -General -''''''''''''''' - -**Structure and Interpretation of Computer Programs**, by -Harold Abelson and Gerald Jay Sussman with Julie Sussman. -Full text at http://mitpress.mit.edu/sicp/. -In this classic textbook of computer science, chapters 2 and 3 discuss the -use of sequences and streams to organize the data flow inside a -program. The book uses Scheme for its examples, but many of the -design approaches described in these chapters are applicable to -functional-style Python code. - -http://www.defmacro.org/ramblings/fp.html: A general -introduction to functional programming that uses Java examples -and has a lengthy historical introduction. - -http://en.wikipedia.org/wiki/Functional_programming: -General Wikipedia entry describing functional programming. - -http://en.wikipedia.org/wiki/Coroutine: -Entry for coroutines. - -http://en.wikipedia.org/wiki/Currying: -Entry for the concept of currying. - -Python-specific -''''''''''''''''''''''''''' - -http://gnosis.cx/TPiP/: -The first chapter of David Mertz's book :title-reference:`Text Processing in Python` -discusses functional programming for text processing, in the section titled -"Utilizing Higher-Order Functions in Text Processing". - -Mertz also wrote a 3-part series of articles on functional programming -for IBM's DeveloperWorks site; see -`part 1 `__, -`part 2 `__, and -`part 3 `__, - - -Python documentation -''''''''''''''''''''''''''' - -http://docs.python.org/lib/module-itertools.html: -Documentation for the ``itertools`` module. - -http://docs.python.org/lib/module-operator.html: -Documentation for the ``operator`` module. - -http://www.python.org/dev/peps/pep-0289/: -PEP 289: "Generator Expressions" - -http://www.python.org/dev/peps/pep-0342/ -PEP 342: "Coroutines via Enhanced Generators" describes the new generator -features in Python 2.5. - -.. comment - - Topics to place - ----------------------------- - - XXX os.walk() - - XXX Need a large example. - - But will an example add much? I'll post a first draft and see - what the comments say. - -.. comment - - Original outline: - Introduction - Idea of FP - Programs built out of functions - Functions are strictly input-output, no internal state - Opposed to OO programming, where objects have state - - Why FP? - Formal provability - Assignment is difficult to reason about - Not very relevant to Python - Modularity - Small functions that do one thing - Debuggability: - Easy to test due to lack of state - Easy to verify output from intermediate steps - Composability - You assemble a toolbox of functions that can be mixed - - Tackling a problem - Need a significant example - - Iterators - Generators - The itertools module - List comprehensions - Small functions and the lambda statement - Built-in functions - map - filter - reduce - -.. comment - - Handy little function for printing part of an iterator -- used - while writing this document. - - import itertools - def print_iter(it): - slice = itertools.islice(it, 10) - for elem in slice[:-1]: - sys.stdout.write(str(elem)) - sys.stdout.write(', ') - print elem[-1] - - diff --git a/third_party/pygments/tests/examplefiles/garcia-wachs.kk b/third_party/pygments/tests/examplefiles/garcia-wachs.kk deleted file mode 100644 index 91a01fbeb..000000000 --- a/third_party/pygments/tests/examplefiles/garcia-wachs.kk +++ /dev/null @@ -1,133 +0,0 @@ -// Koka language test module - -// This module implements the GarsiaWachs algorithm. -// It is an adaptation of the algorithm in ML as described by JeanChristophe Filli�tre: -// in ''A functional implementation of the GarsiaWachs algorithm. (functional pearl). ML workshop 2008, pages 91--96''. -// See: http://www.lri.fr/~filliatr/publis/gwWml08.pdf -// -// The algorithm is interesting since it uses mutable references shared between a list and tree but the -// side effects are not observable from outside. Koka automatically infers that the final algorithm is pure. -// Note: due to a current limitation in the divergence analysis, koka cannot yet infer that mutually recursive -// definitions in "insert" and "extract" are terminating and the final algorithm still has a divergence effect. -// However, koka does infer that no other effect (i.e. an exception due to a partial match) can occur. -module garcsiaWachs - -import test = qualified std/flags - -# pre processor test - -public function main() { - wlist = Cons1(('a',3), [('b',2),('c',1),('d',4),('e',5)]) - tree = wlist.garsiaWachs() - tree.show.println() -} - -//---------------------------------------------------- -// Trees -//---------------------------------------------------- -public type tree { - con Leaf(value :a) - con Node(left :tree, right :tree) -} - -function show( t : tree ) : string { - match(t) { - Leaf(c) -> core/show(c) - Node(l,r) -> "Node(" + show(l) + "," + show(r) + ")" - } -} - - -//---------------------------------------------------- -// Non empty lists -//---------------------------------------------------- -public type list1 { - Cons1( head : a, tail : list ) -} - -function map( xs, f ) { - val Cons1(y,ys) = xs - return Cons1(f(y), core/map(ys,f)) -} - -function zip( xs :list1, ys :list1 ) : list1<(a,b)> { - Cons1( (xs.head, ys.head), zip(xs.tail, ys.tail)) -} - - -//---------------------------------------------------- -// Phase 1 -//---------------------------------------------------- - -function insert( after : list<(tree,int)>, t : (tree,int), before : list<(tree,int)> ) : div tree -{ - match(before) { - Nil -> extract( [], Cons1(t,after) ) - Cons(x,xs) -> { - if (x.snd < t.snd) then return insert( Cons(x,after), t, xs ) - match(xs) { - Nil -> extract( [], Cons1(x,Cons(t,after)) ) - Cons(y,ys) -> extract( ys, Cons1(y,Cons(x,Cons(t,after))) ) - } - } - } -} - -function extract( before : list<(tree,int)>, after : list1<(tree,int)> ) : div tree -{ - val Cons1((t1,w1) as x, xs ) = after - match(xs) { - Nil -> t1 - Cons((t2,w2) as y, ys) -> match(ys) { - Nil -> insert( [], (Node(t1,t2), w1+w2), before ) - Cons((_,w3),_zs) -> - if (w1 <= w3) - then insert(ys, (Node(t1,t2), w1+w2), before) - else extract(Cons(x,before), Cons1(y,ys)) - } - } -} - -function balance( xs : list1<(tree,int)> ) : div tree { - extract( [], xs ) -} - -//---------------------------------------------------- -// Phase 2 -//---------------------------------------------------- - -function mark( depth :int, t :tree<(a,ref)> ) : > () { - match(t) { - Leaf((_,d)) -> d := depth - Node(l,r) -> { mark(depth+1,l); mark(depth+1,r) } - } -} - -function build( depth :int, xs :list1<(a,ref)> ) : ,div> (tree,list<(a,ref)>) -{ - if (!(xs.head.snd) == depth) return (Leaf(xs.head.fst), xs.tail) - - l = build(depth+1, xs) - match(l.snd) { - Nil -> (l.fst, Nil) - Cons(y,ys) -> { - r = build(depth+1, Cons1(y,ys)) - (Node(l.fst,r.fst), r.snd) - } - } -} - -//---------------------------------------------------- -// Main -//---------------------------------------------------- - -public function garsiaWachs( xs : list1<(a,int)> ) : div tree -{ - refs = xs.map(fst).map( fun(x) { (x, ref(0)) } ) - wleafs = zip( refs.map(Leaf), xs.map(snd) ) - - tree = balance(wleafs) - mark(0,tree) - build(0,refs).fst -} - diff --git a/third_party/pygments/tests/examplefiles/genclass.clj b/third_party/pygments/tests/examplefiles/genclass.clj deleted file mode 100644 index c63da8fd1..000000000 --- a/third_party/pygments/tests/examplefiles/genclass.clj +++ /dev/null @@ -1,510 +0,0 @@ -; Copyright (c) Rich Hickey. All rights reserved. -; The use and distribution terms for this software are covered by the -; Common Public License 1.0 (http://opensource.org/licenses/cpl.php) -; which can be found in the file CPL.TXT at the root of this distribution. -; By using this software in any fashion, you are agreeing to be bound by -; the terms of this license. -; You must not remove this notice, or any other, from this software. - -(in-ns 'clojure) - -(import '(java.lang.reflect Modifier Constructor) - '(clojure.asm ClassWriter ClassVisitor Opcodes Type) - '(clojure.asm.commons Method GeneratorAdapter) - '(clojure.lang IPersistentMap)) - -;(defn method-sig [#^java.lang.reflect.Method meth] -; [(. meth (getName)) (seq (. meth (getParameterTypes)))]) - -(defn- non-private-methods [#^Class c] - (loop [mm {} - considered #{} - c c] - (if c - (let [[mm considered] - (loop [mm mm - considered considered - meths (concat - (seq (. c (getDeclaredMethods))) - (seq (. c (getMethods))))] - (if meths - (let [#^Method meth (first meths) - mods (. meth (getModifiers)) - mk (method-sig meth)] - (if (or (considered mk) - (. Modifier (isPrivate mods)) - (. Modifier (isStatic mods)) - (. Modifier (isFinal mods))) - (recur mm (conj considered mk) (rest meths)) - (recur (assoc mm mk meth) (conj considered mk) (rest meths)))) - [mm considered]))] - (recur mm considered (. c (getSuperclass)))) - mm))) - -(defn- ctor-sigs [super] - (for [#^Constructor ctor (. super (getDeclaredConstructors)) - :when (not (. Modifier (isPrivate (. ctor (getModifiers)))))] - (apply vector (. ctor (getParameterTypes))))) - -(defn- escape-class-name [c] - (.. (.getSimpleName c) - (replace "[]" "<>"))) - -(defn- overload-name [mname pclasses] - (if (seq pclasses) - (apply str mname (interleave (repeat \-) - (map escape-class-name pclasses))) - (str mname "-void"))) - -;(distinct (map first(keys (mapcat non-private-methods [Object IPersistentMap])))) - -(defn gen-class - "Generates compiled bytecode for a class with the given - package-qualified cname (which, as all names in these parameters, can - be a string or symbol). The gen-class construct contains no - implementation, as the implementation will be dynamically sought by - the generated class in functions in a corresponding Clojure - namespace. Given a generated class org.mydomain.MyClass, methods - will be implemented that look for same-named functions in a Clojure - namespace called org.domain.MyClass. The init and main - functions (see below) will be found similarly. The static - initializer for the generated class will attempt to load the Clojure - support code for the class as a resource from the claspath, e.g. in - the example case, org/mydomain/MyClass.clj - - Returns a map containing :name and :bytecode. Most uses will be - satisfied by the higher-level gen-and-load-class and - gen-and-store-class functions, which generate and immediately load, - or generate and store to disk, respectively. - - Options should be a set of key/value pairs, all of which are optional: - - :extends aclass - - Specifies the superclass, the non-private methods of which will be - overridden by the class. If not provided, defaults to Object. - - :implements [interface ...] - - One or more interfaces, the methods of which will be implemented by the class. - - :init name - - If supplied, names a function that will be called with the arguments - to the constructor. Must return [[superclass-constructor-args] state] - If not supplied, the constructor args are passed directly to - the superclass constructor and the state will be nil - - :constructors {[param-types] [super-param-types], ...} - - By default, constructors are created for the generated class which - match the signature(s) of the constructors for the superclass. This - parameter may be used to explicitly specify constructors, each entry - providing a mapping from a constructor signature to a superclass - constructor signature. When you supply this, you must supply an :init - specifier. - - :methods [[name [param-types] return-type], ...] - - The generated class automatically defines all of the non-private - methods of its superclasses/interfaces. This parameter can be used - to specify the signatures of additional methods of the generated - class. Do not repeat superclass/interface signatures here. - - :main boolean - - If supplied and true, a static public main function will be - generated. It will pass each string of the String[] argument as a - separate argument to a function called 'main. - - :factory name - - If supplied, a (set of) public static factory function(s) will be - created with the given name, and the same signature(s) as the - constructor(s). - - :state name - - If supplied, a public final instance field with the given name will be - created. You must supply an :init function in order to provide a - value for the state. Note that, though final, the state can be a ref - or agent, supporting the creation of Java objects with transactional - or asynchronous mutation semantics. - - :exposes {protected-field-name {:get name :set name}, ...} - - Since the implementations of the methods of the generated class - occur in Clojure functions, they have no access to the inherited - protected fields of the superclass. This parameter can be used to - generate public getter/setter methods exposing the protected field(s) - for use in the implementation." - - [cname & options] - (let [name (str cname) - {:keys [extends implements constructors methods main factory state init exposes]} (apply hash-map options) - super (or extends Object) - interfaces implements - supers (cons super (seq interfaces)) - ctor-sig-map (or constructors (zipmap (ctor-sigs super) (ctor-sigs super))) - cv (new ClassWriter (. ClassWriter COMPUTE_MAXS)) - cname (. name (replace "." "/")) - ctype (. Type (getObjectType cname)) - iname (fn [c] (.. Type (getType c) (getInternalName))) - totype (fn [c] (. Type (getType c))) - to-types (fn [cs] (if (pos? (count cs)) - (into-array (map totype cs)) - (make-array Type 0))) - obj-type (totype Object) - arg-types (fn [n] (if (pos? n) - (into-array (replicate n obj-type)) - (make-array Type 0))) - super-type (totype super) - init-name (str init) - factory-name (str factory) - state-name (str state) - main-name "main" - var-name (fn [s] (str s "__var")) - rt-type (totype clojure.lang.RT) - var-type (totype clojure.lang.Var) - ifn-type (totype clojure.lang.IFn) - iseq-type (totype clojure.lang.ISeq) - ex-type (totype java.lang.UnsupportedOperationException) - all-sigs (distinct (concat (map #(let[[m p] (key %)] {m [p]}) (mapcat non-private-methods supers)) - (map (fn [[m p]] {(str m) [p]}) methods))) - sigs-by-name (apply merge-with concat {} all-sigs) - overloads (into {} (filter (fn [[m s]] (rest s)) sigs-by-name)) - var-fields (concat (and init [init-name]) - (and main [main-name]) - (distinct (concat (keys sigs-by-name) - (mapcat (fn [[m s]] (map #(overload-name m %) s)) overloads) - (mapcat (comp (partial map str) vals val) exposes)))) - emit-get-var (fn [gen v] - (let [false-label (. gen newLabel) - end-label (. gen newLabel)] - (. gen getStatic ctype (var-name v) var-type) - (. gen dup) - (. gen invokeVirtual var-type (. Method (getMethod "boolean isBound()"))) - (. gen ifZCmp (. GeneratorAdapter EQ) false-label) - (. gen invokeVirtual var-type (. Method (getMethod "Object get()"))) - (. gen goTo end-label) - (. gen mark false-label) - (. gen pop) - (. gen visitInsn (. Opcodes ACONST_NULL)) - (. gen mark end-label))) - emit-forwarding-method - (fn [mname pclasses rclass else-gen] - (let [ptypes (to-types pclasses) - rtype (totype rclass) - m (new Method mname rtype ptypes) - is-overload (overloads mname) - gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv) - found-label (. gen (newLabel)) - else-label (. gen (newLabel)) - end-label (. gen (newLabel))] - (. gen (visitCode)) - (when is-overload - (emit-get-var gen (overload-name mname pclasses)) - (. gen (dup)) - (. gen (ifNonNull found-label)) - (. gen (pop))) - (emit-get-var gen mname) - (. gen (dup)) - (. gen (ifNull else-label)) - (when is-overload - (. gen (mark found-label))) - ;if found - (. gen (loadThis)) - ;box args - (dotimes i (count ptypes) - (. gen (loadArg i)) - (. clojure.lang.Compiler$HostExpr (emitBoxReturn nil gen (nth pclasses i)))) - ;call fn - (. gen (invokeInterface ifn-type (new Method "invoke" obj-type - (into-array (cons obj-type - (replicate (count ptypes) obj-type)))))) - ;unbox return - (. gen (unbox rtype)) - (when (= (. rtype (getSort)) (. Type VOID)) - (. gen (pop))) - (. gen (goTo end-label)) - - ;else call supplied alternative generator - (. gen (mark else-label)) - (. gen (pop)) - - (else-gen gen m) - - (. gen (mark end-label)) - (. gen (returnValue)) - (. gen (endMethod)))) - ] - ;start class definition - (. cv (visit (. Opcodes V1_5) (. Opcodes ACC_PUBLIC) - cname nil (iname super) - (when interfaces - (into-array (map iname interfaces))))) - - ;static fields for vars - (doseq v var-fields - (. cv (visitField (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_FINAL) (. Opcodes ACC_STATIC)) - (var-name v) - (. var-type getDescriptor) - nil nil))) - - ;instance field for state - (when state - (. cv (visitField (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_FINAL)) - state-name - (. obj-type getDescriptor) - nil nil))) - - ;static init to set up var fields and load clj - (let [gen (new GeneratorAdapter (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_STATIC)) - (. Method getMethod "void ()") - nil nil cv)] - (. gen (visitCode)) - (doseq v var-fields - (. gen push name) - (. gen push v) - (. gen (invokeStatic rt-type (. Method (getMethod "clojure.lang.Var var(String,String)")))) - (. gen putStatic ctype (var-name v) var-type)) - - (. gen push ctype) - (. gen push (str (. name replace \. (. java.io.File separatorChar)) ".clj")) - (. gen (invokeStatic rt-type (. Method (getMethod "void loadResourceScript(Class,String)")))) - - (. gen (returnValue)) - (. gen (endMethod))) - - ;ctors - (doseq [pclasses super-pclasses] ctor-sig-map - (let [ptypes (to-types pclasses) - super-ptypes (to-types super-pclasses) - m (new Method "" (. Type VOID_TYPE) ptypes) - super-m (new Method "" (. Type VOID_TYPE) super-ptypes) - gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv) - no-init-label (. gen newLabel) - end-label (. gen newLabel) - nth-method (. Method (getMethod "Object nth(Object,int)")) - local (. gen newLocal obj-type)] - (. gen (visitCode)) - - (if init - (do - (emit-get-var gen init-name) - (. gen dup) - (. gen ifNull no-init-label) - ;box init args - (dotimes i (count pclasses) - (. gen (loadArg i)) - (. clojure.lang.Compiler$HostExpr (emitBoxReturn nil gen (nth pclasses i)))) - ;call init fn - (. gen (invokeInterface ifn-type (new Method "invoke" obj-type - (arg-types (count ptypes))))) - ;expecting [[super-ctor-args] state] returned - (. gen dup) - (. gen push 0) - (. gen (invokeStatic rt-type nth-method)) - (. gen storeLocal local) - - (. gen (loadThis)) - (. gen dupX1) - (dotimes i (count super-pclasses) - (. gen loadLocal local) - (. gen push i) - (. gen (invokeStatic rt-type nth-method)) - (. clojure.lang.Compiler$HostExpr (emitUnboxArg nil gen (nth super-pclasses i)))) - (. gen (invokeConstructor super-type super-m)) - - (if state - (do - (. gen push 1) - (. gen (invokeStatic rt-type nth-method)) - (. gen (putField ctype state-name obj-type))) - (. gen pop)) - - (. gen goTo end-label) - ;no init found - (. gen mark no-init-label) - (. gen (throwException ex-type (str init-name " not defined"))) - (. gen mark end-label)) - (if (= pclasses super-pclasses) - (do - (. gen (loadThis)) - (. gen (loadArgs)) - (. gen (invokeConstructor super-type super-m))) - (throw (new Exception ":init not specified, but ctor and super ctor args differ")))) - - (. gen (returnValue)) - (. gen (endMethod)) - ;factory - (when factory - (let [fm (new Method factory-name ctype ptypes) - gen (new GeneratorAdapter (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_STATIC)) - fm nil nil cv)] - (. gen (visitCode)) - (. gen newInstance ctype) - (. gen dup) - (. gen (loadArgs)) - (. gen (invokeConstructor ctype m)) - (. gen (returnValue)) - (. gen (endMethod)))))) - - ;add methods matching supers', if no fn -> call super - (let [mm (non-private-methods super)] - (doseq #^java.lang.reflect.Method meth (vals mm) - (emit-forwarding-method (.getName meth) (.getParameterTypes meth) (.getReturnType meth) - (fn [gen m] - (. gen (loadThis)) - ;push args - (. gen (loadArgs)) - ;call super - (. gen (visitMethodInsn (. Opcodes INVOKESPECIAL) - (. super-type (getInternalName)) - (. m (getName)) - (. m (getDescriptor))))))) - ;add methods matching interfaces', if no fn -> throw - (doseq #^Class iface interfaces - (doseq #^java.lang.reflect.Method meth (. iface (getMethods)) - (when-not (contains? mm (method-sig meth)) - (emit-forwarding-method (.getName meth) (.getParameterTypes meth) (.getReturnType meth) - (fn [gen m] - (. gen (throwException ex-type (. m (getName))))))))) - ;extra methods - (doseq [mname pclasses rclass :as msig] methods - (emit-forwarding-method (str mname) pclasses rclass - (fn [gen m] - (. gen (throwException ex-type (. m (getName)))))))) - - ;main - (when main - (let [m (. Method getMethod "void main (String[])") - gen (new GeneratorAdapter (+ (. Opcodes ACC_PUBLIC) (. Opcodes ACC_STATIC)) - m nil nil cv) - no-main-label (. gen newLabel) - end-label (. gen newLabel)] - (. gen (visitCode)) - - (emit-get-var gen main-name) - (. gen dup) - (. gen ifNull no-main-label) - (. gen loadArgs) - (. gen (invokeStatic rt-type (. Method (getMethod "clojure.lang.ISeq seq(Object)")))) - (. gen (invokeInterface ifn-type (new Method "applyTo" obj-type - (into-array [iseq-type])))) - (. gen pop) - (. gen goTo end-label) - ;no main found - (. gen mark no-main-label) - (. gen (throwException ex-type (str main-name " not defined"))) - (. gen mark end-label) - (. gen (returnValue)) - (. gen (endMethod)))) - ;field exposers - (doseq [f {getter :get setter :set}] exposes - (let [fld (.getField super (str f)) - ftype (totype (.getType fld))] - (when getter - (let [m (new Method (str getter) ftype (to-types [])) - gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv)] - (. gen (visitCode)) - (. gen loadThis) - (. gen getField ctype (str f) ftype) - (. gen (returnValue)) - (. gen (endMethod)))) - (when setter - (let [m (new Method (str setter) (. Type VOID_TYPE) (into-array [ftype])) - gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv)] - (. gen (visitCode)) - (. gen loadThis) - (. gen loadArgs) - (. gen putField ctype (str f) ftype) - (. gen (returnValue)) - (. gen (endMethod)))))) - ;finish class def - (. cv (visitEnd)) - {:name name :bytecode (. cv (toByteArray))})) - -(defn gen-and-load-class - "Generates and immediately loads the bytecode for the specified - class. Note that a class generated this way can be loaded only once - - the JVM supports only one class with a given name per - classloader. Subsequent to generation you can import it into any - desired namespaces just like any other class. See gen-class for a - description of the options." - - [name & options] - (let [{:keys [name bytecode]} - (apply gen-class (str name) options)] - (.. clojure.lang.RT ROOT_CLASSLOADER (defineClass (str name) bytecode)))) - -(defn gen-and-save-class - "Generates the bytecode for the named class and stores in a .class - file in a subpath of the supplied path, the directories for which - must already exist. See gen-class for a description of the options" - - [path name & options] - (let [{:keys [name bytecode]} (apply gen-class (str name) options) - file (java.io.File. path (str (. name replace \. (. java.io.File separatorChar)) ".class"))] - (.createNewFile file) - (with-open f (java.io.FileOutputStream. file) - (.write f bytecode)))) - -(comment -;usage -(gen-class - package-qualified-name - ;all below are optional - :extends aclass - :implements [interface ...] - :constructors {[param-types] [super-param-types], } - :methods [[name [param-types] return-type], ] - :main boolean - :factory name - :state name - :init name - :exposes {protected-field {:get name :set name}, }) - -;(gen-and-load-class -(clojure/gen-and-save-class - "/Users/rich/Downloads" - 'fred.lucy.Ethel - :extends clojure.lang.Box ;APersistentMap - :implements [clojure.lang.IPersistentMap] - :state 'state - ;:constructors {[Object] [Object]} - ;:init 'init - :main true - :factory 'create - :methods [['foo [Object] Object] - ['foo [] Object]] - :exposes {'val {:get 'getVal :set 'setVal}}) - -(in-ns 'fred.lucy.Ethel__2276) -(clojure/refer 'clojure :exclude '(assoc seq count cons)) -(defn init [n] [[] n]) -(defn foo - ([this] :foo) - ([this x] x)) -(defn main [x y] (println x y)) -(in-ns 'user) -(def ethel (new fred.lucy.Ethel__2276 42)) -(def ethel (fred.lucy.Ethel__2276.create 21)) -(fred.lucy.Ethel__2276.main (into-array ["lucy" "ricky"])) -(.state ethel) -(.foo ethel 7) -(.foo ethel) -(.getVal ethel) -(.setVal ethel 12) - -(gen-class org.clojure.MyComparator :implements [Comparator]) -(in-ns 'org.clojure.MyComparator) -(defn compare [this x y] ...) - -(load-file "/Users/rich/dev/clojure/src/genclass.clj") - -(clojure/gen-and-save-class "/Users/rich/dev/clojure/gen/" - 'org.clojure.ClojureServlet - :extends javax.servlet.http.HttpServlet) - -) diff --git a/third_party/pygments/tests/examplefiles/genshi_example.xml+genshi b/third_party/pygments/tests/examplefiles/genshi_example.xml+genshi deleted file mode 100644 index 8576b0423..000000000 --- a/third_party/pygments/tests/examplefiles/genshi_example.xml+genshi +++ /dev/null @@ -1,193 +0,0 @@ - - - - - $title - - - - -

    - - - (${v or 'No'} match${v != 1 and 'es' or ''}) - - -
    -

    $title ${num_matches(len(tickets))}

    - -
    -
    - Filters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -   - - -
    -
    - -

    - - - - -

    - -

    - - -

    - -
    - - - -
    -
    -
    - - - - - -
    - Note: See TracQuery - for help on using queries. -
    - -
    - - diff --git a/third_party/pygments/tests/examplefiles/genshitext_example.genshitext b/third_party/pygments/tests/examplefiles/genshitext_example.genshitext deleted file mode 100644 index b82708d28..000000000 --- a/third_party/pygments/tests/examplefiles/genshitext_example.genshitext +++ /dev/null @@ -1,33 +0,0 @@ - ## a comment - -\## not a comment - -#if foo - ${bar} -#endif - -The answer is: -#choose - #when 0 == 1 - 0 - #end - #when 1 == 1 - 1 - #end - #otherwise - 2 - #end -#end -- comment about choose - -#for item in items - * ${item} -#end - -#def greeting(name) - Hello, ${name}! -#end -${greeting('world')} - -#with y=7; z=x+10 - $x $y $z -#end diff --git a/third_party/pygments/tests/examplefiles/glsl.frag b/third_party/pygments/tests/examplefiles/glsl.frag deleted file mode 100644 index 132b0353d..000000000 --- a/third_party/pygments/tests/examplefiles/glsl.frag +++ /dev/null @@ -1,7 +0,0 @@ -/* Fragment shader */ -void main() -{ - gl_FragColor[0] = gl_FragCoord[0] / 400.0; - gl_FragColor[1] = gl_FragCoord[1] / 400.0; - gl_FragColor[2] = 1.0; -} diff --git a/third_party/pygments/tests/examplefiles/glsl.vert b/third_party/pygments/tests/examplefiles/glsl.vert deleted file mode 100644 index 23dc6a6bf..000000000 --- a/third_party/pygments/tests/examplefiles/glsl.vert +++ /dev/null @@ -1,13 +0,0 @@ -/* Vertex shader */ -uniform float waveTime; -uniform float waveWidth; -uniform float waveHeight; - -void main(void) -{ - vec4 v = vec4(gl_Vertex); - - v.z = sin(waveWidth * v.x + waveTime) * cos(waveWidth * v.y + waveTime) * waveHeight; - - gl_Position = gl_ModelViewProjectionMatrix * v; -} diff --git a/third_party/pygments/tests/examplefiles/grammar-test.p6 b/third_party/pygments/tests/examplefiles/grammar-test.p6 deleted file mode 100644 index 28107f3e4..000000000 --- a/third_party/pygments/tests/examplefiles/grammar-test.p6 +++ /dev/null @@ -1,22 +0,0 @@ -token pod_formatting_code { - $=<[A..Z]> - '<' { $*POD_IN_FORMATTINGCODE := 1 } - $=[ '> ]+ - '>' { $*POD_IN_FORMATTINGCODE := 0 } -} - -token pod_string { - + -} - -token something:sym«<» { - -} - -token name { - -} - -token comment:sym<#> { - '#' {} \N* -} diff --git a/third_party/pygments/tests/examplefiles/hash_syntax.rb b/third_party/pygments/tests/examplefiles/hash_syntax.rb deleted file mode 100644 index 35b27723d..000000000 --- a/third_party/pygments/tests/examplefiles/hash_syntax.rb +++ /dev/null @@ -1,5 +0,0 @@ -{ :old_syntax => 'ok' } -{ 'stings as key' => 'should be ok' } -{ new_syntax: 'broken until now' } -{ withoutunderscore: 'should be ok' } -{ _underscoreinfront: 'might be ok, if I understand the pygments code correct' } diff --git a/third_party/pygments/tests/examplefiles/hello.at b/third_party/pygments/tests/examplefiles/hello.at deleted file mode 100644 index 23af2f2d5..000000000 --- a/third_party/pygments/tests/examplefiles/hello.at +++ /dev/null @@ -1,6 +0,0 @@ -def me := object: { - def name := "Kevin"; - def sayHello(peerName) { - system.println(peerName + " says hello!"); - }; -}; diff --git a/third_party/pygments/tests/examplefiles/hello.golo b/third_party/pygments/tests/examplefiles/hello.golo deleted file mode 100644 index 7e8ca214f..000000000 --- a/third_party/pygments/tests/examplefiles/hello.golo +++ /dev/null @@ -1,5 +0,0 @@ -module hello.World - -function main = |args| { - println("Hello world!") -} diff --git a/third_party/pygments/tests/examplefiles/hello.lsl b/third_party/pygments/tests/examplefiles/hello.lsl deleted file mode 100644 index 61697e7f1..000000000 --- a/third_party/pygments/tests/examplefiles/hello.lsl +++ /dev/null @@ -1,12 +0,0 @@ -default -{ - state_entry() - { - llSay(0, "Hello, Avatar!"); - } - - touch_start(integer total_number) - { - llSay(0, "Touched."); - } -} diff --git a/third_party/pygments/tests/examplefiles/hello.smali b/third_party/pygments/tests/examplefiles/hello.smali deleted file mode 100644 index e539f00e0..000000000 --- a/third_party/pygments/tests/examplefiles/hello.smali +++ /dev/null @@ -1,40 +0,0 @@ -# To Recreate: -# -# echo -e 'class hello {\n public static void main(String[] args) {\n -# System.out.println("hi");\n }\n}\n' > hello.java -# javac -target 1.4 -source 1.4 hello.java -# dx --dex --output=hello.dex hello.class -# baksmali hello.dex -# cat out/hello.smali - -.class Lhello; -.super Ljava/lang/Object; -.source "hello.java" - - -# direct methods -.method constructor ()V - .registers 1 - - .prologue - .line 1 - invoke-direct {p0}, Ljava/lang/Object;->()V - - return-void -.end method - -.method public static main([Ljava/lang/String;)V - .registers 3 - .parameter - - .prologue - .line 3 - sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; - - const-string v1, "hi" - - invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V - - .line 4 - return-void -.end method diff --git a/third_party/pygments/tests/examplefiles/hello.sp b/third_party/pygments/tests/examplefiles/hello.sp deleted file mode 100644 index 7102d2734..000000000 --- a/third_party/pygments/tests/examplefiles/hello.sp +++ /dev/null @@ -1,9 +0,0 @@ -#include - -// Single line comment -/* Multi line - comment */ - -public OnPluginStart() { - PrintToServer("Hello."); -} diff --git a/third_party/pygments/tests/examplefiles/hexdump_debugexe b/third_party/pygments/tests/examplefiles/hexdump_debugexe deleted file mode 100644 index 31fefdb77..000000000 --- a/third_party/pygments/tests/examplefiles/hexdump_debugexe +++ /dev/null @@ -1,309 +0,0 @@ -0000:0000 2F 2F 20 43 72 65 61 74-65 64 20 62 79 20 4C 69 // Created by Li -0000:0010 6F 6E 65 6C 6C 6F 20 4C-75 6E 65 73 75 20 61 6E onello Lunesu an -0000:0020 64 20 70 6C 61 63 65 64-20 69 6E 20 74 68 65 20 d placed in the -0000:0030 70 75 62 6C 69 63 20 64-6F 6D 61 69 6E 2E 0A 2F public domain.◙/ -0000:0040 2F 20 54 68 69 73 20 66-69 6C 65 20 68 61 73 20 / This file has -0000:0050 62 65 65 6E 20 6D 6F 64-69 66 69 65 64 20 66 72 been modified fr -0000:0060 6F 6D 20 69 74 73 20 6F-72 69 67 69 6E 61 6C 20 om its original -0000:0070 76 65 72 73 69 6F 6E 2E-0A 2F 2F 20 49 74 20 68 version.◙// It h -0000:0080 61 73 20 62 65 65 6E 20-66 6F 72 6D 61 74 74 65 as been formatte -0000:0090 64 20 74 6F 20 66 69 74-20 79 6F 75 72 20 73 63 d to fit your sc -0000:00A0 72 65 65 6E 2E 0A 6D 6F-64 75 6C 65 20 70 68 6F reen.◙module pho -0000:00B0 6E 65 6E 6F 3B 20 20 20-20 20 2F 2F 20 6F 70 74 neno; // opt -0000:00C0 69 6F 6E 61 6C 0A 69 6D-70 6F 72 74 20 73 74 64 ional◙import std -0000:00D0 2E 73 74 64 69 6F 3B 20-20 20 2F 2F 20 77 72 69 .stdio; // wri -0000:00E0 74 65 66 6C 6E 20 20 20-20 20 0A 69 6D 70 6F 72 tefln ◙impor -0000:00F0 74 20 73 74 64 2E 63 74-79 70 65 3B 20 20 20 2F t std.ctype; / -0000:0100 2F 20 69 73 64 69 67 69-74 20 20 20 20 20 0A 69 / isdigit ◙i -0000:0110 6D 70 6F 72 74 20 73 74-64 2E 73 74 72 65 61 6D mport std.stream -0000:0120 3B 20 20 2F 2F 20 42 75-66 66 65 72 65 64 46 69 ; // BufferedFi -0000:0130 6C 65 0A 0A 2F 2F 20 4A-75 73 74 20 66 6F 72 20 le◙◙// Just for -0000:0140 72 65 61 64 61 62 69 6C-69 74 79 20 28 69 6D 61 readability (ima -0000:0150 67 69 6E 65 20 63 68 61-72 5B 5D 5B 5D 5B 63 68 gine char[][][ch -0000:0160 61 72 5B 5D 5D 29 20 20-20 20 0A 61 6C 69 61 73 ar[]]) ◙alias -0000:0170 20 63 68 61 72 5B 5D 20-73 74 72 69 6E 67 3B 0A char[] string;◙ -0000:0180 61 6C 69 61 73 20 73 74-72 69 6E 67 5B 5D 20 73 alias string[] s -0000:0190 74 72 69 6E 67 61 72 72-61 79 3B 0A 0A 2F 2F 2F tringarray;◙◙/// -0000:01A0 20 53 74 72 69 70 73 20-6E 6F 6E 2D 64 69 67 69 Strips non-digi -0000:01B0 74 20 63 68 61 72 61 63-74 65 72 73 20 66 72 6F t characters fro -0000:01C0 6D 20 74 68 65 20 73 74-72 69 6E 67 20 28 43 4F m the string (CO -0000:01D0 57 29 0A 73 74 72 69 6E-67 20 73 74 72 69 70 4E W)◙string stripN -0000:01E0 6F 6E 44 69 67 69 74 28-20 69 6E 20 73 74 72 69 onDigit( in stri -0000:01F0 6E 67 20 6C 69 6E 65 20-29 20 0A 7B 0A 20 20 20 ng line ) ◙{◙ -0000:0200 20 73 74 72 69 6E 67 20-72 65 74 3B 0A 20 20 20 string ret;◙ -0000:0210 20 66 6F 72 65 61 63 68-28 75 69 6E 74 20 69 2C foreach(uint i, -0000:0220 20 63 3B 20 6C 69 6E 65-29 20 7B 0A 20 20 20 20 c; line) {◙ -0000:0230 20 20 20 20 2F 2F 20 45-72 72 6F 72 3A 20 73 74 // Error: st -0000:0240 64 2E 63 74 79 70 65 2E-69 73 64 69 67 69 74 20 d.ctype.isdigit -0000:0250 61 74 20 43 3A 5C 64 6D-64 5C 73 72 63 5C 70 68 at C:\dmd\src\ph -0000:0260 6F 62 6F 73 5C 73 74 64-5C 63 74 79 70 65 2E 64 obos\std\ctype.d -0000:0270 28 33 37 29 20 0A 20 20-20 20 20 20 20 20 2F 2F (37) ◙ // -0000:0280 20 63 6F 6E 66 6C 69 63-74 73 20 77 69 74 68 20 conflicts with -0000:0290 73 74 64 2E 73 74 72 65-61 6D 2E 69 73 64 69 67 std.stream.isdig -0000:02A0 69 74 20 61 74 20 43 3A-5C 64 6D 64 5C 73 72 63 it at C:\dmd\src -0000:02B0 5C 70 68 6F 62 6F 73 5C-73 74 64 5C 73 74 72 65 \phobos\std\stre -0000:02C0 61 6D 2E 64 28 32 39 32-34 29 0A 20 20 20 20 20 am.d(2924)◙ -0000:02D0 20 20 20 69 66 20 28 21-73 74 64 2E 63 74 79 70 if (!std.ctyp -0000:02E0 65 2E 69 73 64 69 67 69-74 28 63 29 29 20 7B 0A e.isdigit(c)) {◙ -0000:02F0 20 20 20 20 20 20 20 20-20 20 20 20 69 66 20 28 if ( -0000:0300 21 72 65 74 29 0A 20 20-20 20 20 20 20 20 20 20 !ret)◙ -0000:0310 20 20 20 20 20 20 72 65-74 20 3D 20 6C 69 6E 65 ret = line -0000:0320 5B 30 2E 2E 69 5D 3B 20-20 20 20 0A 20 20 20 20 [0..i]; ◙ -0000:0330 20 20 20 20 7D 20 20 20-20 0A 20 20 20 20 20 20 } ◙ -0000:0340 20 20 65 6C 73 65 20 69-66 20 28 72 65 74 29 0A else if (ret)◙ -0000:0350 20 20 20 20 20 20 20 20-20 20 20 20 72 65 74 20 ret -0000:0360 7E 3D 20 63 3B 20 20 20-20 0A 20 20 20 20 7D 20 ~= c; ◙ } -0000:0370 20 20 20 0A 20 20 20 20-72 65 74 75 72 6E 20 72 ◙ return r -0000:0380 65 74 3F 72 65 74 3A 6C-69 6E 65 3B 0A 7D 0A 0A et?ret:line;◙}◙◙ -0000:0390 75 6E 69 74 74 65 73 74-20 7B 0A 20 20 20 20 61 unittest {◙ a -0000:03A0 73 73 65 72 74 28 20 73-74 72 69 70 4E 6F 6E 44 ssert( stripNonD -0000:03B0 69 67 69 74 28 22 61 73-64 66 22 29 20 3D 3D 20 igit("asdf") == -0000:03C0 22 22 20 20 29 3B 0A 20-20 20 20 61 73 73 65 72 "" );◙ asser -0000:03D0 74 28 20 73 74 72 69 70-4E 6F 6E 44 69 67 69 74 t( stripNonDigit -0000:03E0 28 22 5C 27 31 33 2D 3D-32 20 34 6B 6F 70 22 29 ("\'13-=2 4kop") -0000:03F0 20 3D 3D 20 20 22 31 33-32 34 22 20 20 29 3B 0A == "1324" );◙ -0000:0400 7D 0A 0A 2F 2F 2F 20 43-6F 6E 76 65 72 74 73 20 }◙◙/// Converts -0000:0410 61 20 77 6F 72 64 20 69-6E 74 6F 20 61 20 6E 75 a word into a nu -0000:0420 6D 62 65 72 2C 20 69 67-6E 6F 72 69 6E 67 20 61 mber, ignoring a -0000:0430 6C 6C 20 6E 6F 6E 20 61-6C 70 68 61 20 63 68 61 ll non alpha cha -0000:0440 72 61 63 74 65 72 73 20-20 0A 73 74 72 69 6E 67 racters ◙string -0000:0450 20 77 6F 72 64 54 6F 4E-75 6D 28 20 69 6E 20 73 wordToNum( in s -0000:0460 74 72 69 6E 67 20 77 6F-72 64 20 29 0A 7B 0A 2F tring word )◙{◙/ -0000:0470 2F 20 74 72 61 6E 73 6C-61 74 69 6F 6E 20 74 61 / translation ta -0000:0480 62 6C 65 20 66 6F 72 20-74 68 65 20 74 61 73 6B ble for the task -0000:0490 20 61 74 20 68 61 6E 64-0A 63 6F 6E 73 74 20 63 at hand◙const c -0000:04A0 68 61 72 5B 32 35 36 5D-20 54 52 41 4E 53 4C 41 har[256] TRANSLA -0000:04B0 54 45 20 3D 20 20 20 20-0A 20 20 20 20 22 20 20 TE = ◙ " -0000:04C0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:04D0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 22 20 " -0000:04E0 20 2F 2F 20 30 20 20 20-0A 20 20 20 20 22 20 20 // 0 ◙ " -0000:04F0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 30 31 01 -0000:0500 32 33 34 35 36 37 38 39-20 20 20 20 20 20 22 20 23456789 " -0000:0510 20 2F 2F 20 33 32 20 20-20 20 20 0A 20 20 20 20 // 32 ◙ -0000:0520 22 20 35 37 36 33 30 34-39 39 36 31 37 38 35 31 " 57630499617851 -0000:0530 38 38 31 32 33 34 37 36-32 32 33 39 20 20 20 20 881234762239 -0000:0540 20 22 20 20 2F 2F 20 36-34 20 20 20 0A 20 20 20 " // 64 ◙ -0000:0550 20 22 20 35 37 36 33 30-34 39 39 36 31 37 38 35 " 5763049961785 -0000:0560 31 38 38 31 32 33 34 37-36 32 32 33 39 20 20 20 1881234762239 -0000:0570 20 20 22 0A 20 20 20 20-22 20 20 20 20 20 20 20 "◙ " -0000:0580 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:0590 20 20 20 20 20 20 20 20-20 22 0A 20 20 20 20 22 "◙ " -0000:05A0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:05B0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:05C0 22 0A 20 20 20 20 22 20-20 20 20 20 20 20 20 20 "◙ " -0000:05D0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:05E0 20 20 20 20 20 20 20 22-20 20 20 20 0A 20 20 20 " ◙ -0000:05F0 20 22 20 20 20 20 20 20-20 20 20 20 20 20 20 20 " -0000:0600 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:0610 20 20 22 3B 0A 20 20 20-20 73 74 72 69 6E 67 20 ";◙ string -0000:0620 72 65 74 3B 0A 20 20 20-20 66 6F 72 65 61 63 68 ret;◙ foreach -0000:0630 28 63 3B 20 63 61 73 74-28 75 62 79 74 65 5B 5D (c; cast(ubyte[] -0000:0640 29 77 6F 72 64 29 0A 20-20 20 20 20 20 20 20 69 )word)◙ i -0000:0650 66 20 28 54 52 41 4E 53-4C 41 54 45 5B 63 5D 20 f (TRANSLATE[c] -0000:0660 21 3D 20 27 20 27 29 0A-20 20 20 20 20 20 20 20 != ' ')◙ -0000:0670 20 20 20 20 72 65 74 20-7E 3D 20 54 52 41 4E 53 ret ~= TRANS -0000:0680 4C 41 54 45 5B 63 5D 3B-0A 20 20 20 20 72 65 74 LATE[c];◙ ret -0000:0690 75 72 6E 20 72 65 74 3B-0A 7D 0A 0A 75 6E 69 74 urn ret;◙}◙◙unit -0000:06A0 74 65 73 74 20 7B 0A 20-2F 2F 20 54 65 73 74 20 test {◙ // Test -0000:06B0 77 6F 72 64 54 6F 4E 75-6D 20 75 73 69 6E 67 20 wordToNum using -0000:06C0 74 68 65 20 74 61 62 6C-65 20 66 72 6F 6D 20 74 the table from t -0000:06D0 68 65 20 74 61 73 6B 20-64 65 73 63 72 69 70 74 he task descript -0000:06E0 69 6F 6E 2E 0A 20 61 73-73 65 72 74 28 20 22 30 ion.◙ assert( "0 -0000:06F0 31 31 31 32 32 32 33 33-33 34 34 35 35 36 36 36 1112223334455666 -0000:0700 37 37 37 38 38 38 39 39-39 22 20 3D 3D 0A 20 20 777888999" ==◙ -0000:0710 20 77 6F 72 64 54 6F 4E-75 6D 28 22 45 20 7C 20 wordToNum("E | -0000:0720 4A 20 4E 20 51 20 7C 20-52 20 57 20 58 20 7C 20 J N Q | R W X | -0000:0730 44 20 53 20 59 20 7C 20-46 20 54 20 7C 20 41 20 D S Y | F T | A -0000:0740 4D 20 7C 20 43 20 49 20-56 20 7C 20 42 20 4B 20 M | C I V | B K -0000:0750 55 20 7C 20 4C 20 4F 20-50 20 7C 20 47 20 48 20 U | L O P | G H -0000:0760 5A 22 29 29 3B 0A 20 61-73 73 65 72 74 28 20 22 Z"));◙ assert( " -0000:0770 30 31 31 31 32 32 32 33-33 33 34 34 35 35 36 36 0111222333445566 -0000:0780 36 37 37 37 38 38 38 39-39 39 22 20 3D 3D 20 0A 6777888999" == ◙ -0000:0790 20 20 20 77 6F 72 64 54-6F 4E 75 6D 28 22 65 20 wordToNum("e -0000:07A0 7C 20 6A 20 6E 20 71 20-7C 20 72 20 77 20 78 20 | j n q | r w x -0000:07B0 7C 20 64 20 73 20 79 20-7C 20 66 20 74 20 7C 20 | d s y | f t | -0000:07C0 61 20 6D 20 7C 20 63 20-69 20 76 20 7C 20 62 20 a m | c i v | b -0000:07D0 6B 20 75 20 7C 20 6C 20-6F 20 70 20 7C 20 67 20 k u | l o p | g -0000:07E0 68 20 7A 22 29 29 3B 0A-20 61 73 73 65 72 74 28 h z"));◙ assert( -0000:07F0 20 22 30 31 32 33 34 35-36 37 38 39 22 20 3D 3D "0123456789" == -0000:0800 20 0A 20 20 20 77 6F 72-64 54 6F 4E 75 6D 28 22 ◙ wordToNum(" -0000:0810 30 20 7C 20 20 20 31 20-20 20 7C 20 20 20 32 20 0 | 1 | 2 -0000:0820 20 20 7C 20 20 20 33 20-20 20 7C 20 20 34 20 20 | 3 | 4 -0000:0830 7C 20 20 35 20 20 7C 20-20 20 36 20 20 20 7C 20 | 5 | 6 | -0000:0840 20 20 37 20 20 20 7C 20-20 20 38 20 20 20 7C 20 7 | 8 | -0000:0850 20 20 39 22 29 29 3B 0A-7D 0A 0A 76 6F 69 64 20 9"));◙}◙◙void -0000:0860 6D 61 69 6E 28 20 73 74-72 69 6E 67 5B 5D 20 61 main( string[] a -0000:0870 72 67 73 20 29 0A 7B 0A-20 20 20 20 2F 2F 20 54 rgs )◙{◙ // T -0000:0880 68 69 73 20 61 73 73 6F-63 69 61 74 69 76 65 20 his associative -0000:0890 61 72 72 61 79 20 6D 61-70 73 20 61 20 6E 75 6D array maps a num -0000:08A0 62 65 72 20 74 6F 20 61-6E 20 61 72 72 61 79 20 ber to an array -0000:08B0 6F 66 20 77 6F 72 64 73-2E 20 20 20 20 0A 20 20 of words. ◙ -0000:08C0 20 20 73 74 72 69 6E 67-61 72 72 61 79 5B 73 74 stringarray[st -0000:08D0 72 69 6E 67 5D 20 20 20-20 6E 75 6D 32 77 6F 72 ring] num2wor -0000:08E0 64 73 3B 0A 0A 20 20 20-20 66 6F 72 65 61 63 68 ds;◙◙ foreach -0000:08F0 28 73 74 72 69 6E 67 20-77 6F 72 64 3B 20 6E 65 (string word; ne -0000:0900 77 20 42 75 66 66 65 72-65 64 46 69 6C 65 28 22 w BufferedFile(" -0000:0910 64 69 63 74 69 6F 6E 61-72 79 2E 74 78 74 22 20 dictionary.txt" -0000:0920 29 20 29 0A 20 20 20 20-20 20 20 20 6E 75 6D 32 ) )◙ num2 -0000:0930 77 6F 72 64 73 5B 20 77-6F 72 64 54 6F 4E 75 6D words[ wordToNum -0000:0940 28 77 6F 72 64 29 20 5D-20 7E 3D 20 77 6F 72 64 (word) ] ~= word -0000:0950 2E 64 75 70 3B 20 20 20-20 20 20 20 20 2F 2F 20 .dup; // -0000:0960 6D 75 73 74 20 64 75 70-0A 0A 20 20 20 20 2F 2F must dup◙◙ // -0000:0970 2F 20 46 69 6E 64 73 20-61 6C 6C 20 61 6C 74 65 / Finds all alte -0000:0980 72 6E 61 74 69 76 65 73-20 66 6F 72 20 74 68 65 rnatives for the -0000:0990 20 67 69 76 65 6E 20 6E-75 6D 62 65 72 0A 20 20 given number◙ -0000:09A0 20 20 2F 2F 2F 20 28 73-68 6F 75 6C 64 20 68 61 /// (should ha -0000:09B0 76 65 20 62 65 65 6E 20-73 74 72 69 70 70 65 64 ve been stripped -0000:09C0 20 66 72 6F 6D 20 6E 6F-6E 2D 64 69 67 69 74 20 from non-digit -0000:09D0 63 68 61 72 61 63 74 65-72 73 29 0A 20 20 20 20 characters)◙ -0000:09E0 73 74 72 69 6E 67 61 72-72 61 79 20 5F 46 69 6E stringarray _Fin -0000:09F0 64 57 6F 72 64 73 28 20-73 74 72 69 6E 67 20 6E dWords( string n -0000:0A00 75 6D 62 65 72 73 2C 20-62 6F 6F 6C 20 64 69 67 umbers, bool dig -0000:0A10 69 74 6F 6B 20 29 0A 20-20 20 20 69 6E 20 7B 0A itok )◙ in {◙ -0000:0A20 20 20 20 20 20 20 20 20-61 73 73 65 72 74 28 6E assert(n -0000:0A30 75 6D 62 65 72 73 2E 6C-65 6E 67 74 68 20 3E 20 umbers.length > -0000:0A40 20 30 29 3B 20 20 20 20-0A 20 20 20 20 7D 20 20 0); ◙ } -0000:0A50 20 20 0A 20 20 20 20 6F-75 74 28 72 65 73 75 6C ◙ out(resul -0000:0A60 74 29 20 7B 0A 20 20 20-20 20 20 20 20 66 6F 72 t) {◙ for -0000:0A70 65 61 63 68 20 28 61 3B-20 72 65 73 75 6C 74 29 each (a; result) -0000:0A80 0A 20 20 20 20 20 20 20-20 20 20 20 20 61 73 73 ◙ ass -0000:0A90 65 72 74 28 20 77 6F 72-64 54 6F 4E 75 6D 28 61 ert( wordToNum(a -0000:0AA0 29 20 3D 3D 20 6E 75 6D-62 65 72 73 20 29 3B 0A ) == numbers );◙ -0000:0AB0 20 20 20 20 7D 20 20 20-20 0A 20 20 20 20 62 6F } ◙ bo -0000:0AC0 64 79 20 7B 0A 20 20 20-20 20 20 20 20 73 74 72 dy {◙ str -0000:0AD0 69 6E 67 61 72 72 61 79-20 72 65 74 3B 0A 20 20 ingarray ret;◙ -0000:0AE0 20 20 20 20 20 20 62 6F-6F 6C 20 66 6F 75 6E 64 bool found -0000:0AF0 77 6F 72 64 20 3D 20 66-61 6C 73 65 3B 0A 20 20 word = false;◙ -0000:0B00 20 20 20 20 20 20 66 6F-72 20 28 75 69 6E 74 20 for (uint -0000:0B10 74 3D 31 3B 20 74 3C 3D-6E 75 6D 62 65 72 73 2E t=1; t<=numbers. -0000:0B20 6C 65 6E 67 74 68 3B 20-2B 2B 74 29 20 7B 0A 20 length; ++t) {◙ -0000:0B30 20 20 20 20 20 20 20 20-20 20 20 61 75 74 6F 20 auto -0000:0B40 61 6C 74 65 72 6E 61 74-69 76 65 73 20 3D 20 6E alternatives = n -0000:0B50 75 6D 62 65 72 73 5B 30-2E 2E 74 5D 20 69 6E 20 umbers[0..t] in -0000:0B60 6E 75 6D 32 77 6F 72 64-73 3B 0A 20 20 20 20 20 num2words;◙ -0000:0B70 20 20 20 20 20 20 20 69-66 20 28 21 61 6C 74 65 if (!alte -0000:0B80 72 6E 61 74 69 76 65 73-29 0A 20 20 20 20 20 20 rnatives)◙ -0000:0B90 20 20 20 20 20 20 20 20-20 20 63 6F 6E 74 69 6E contin -0000:0BA0 75 65 3B 0A 20 20 20 20-20 20 20 20 20 20 20 20 ue;◙ -0000:0BB0 66 6F 75 6E 64 77 6F 72-64 20 3D 20 74 72 75 65 foundword = true -0000:0BC0 3B 0A 20 20 20 20 20 20-20 20 20 20 20 20 69 66 ;◙ if -0000:0BD0 20 28 6E 75 6D 62 65 72-73 2E 6C 65 6E 67 74 68 (numbers.length -0000:0BE0 20 3E 20 20 74 29 20 7B-0A 20 20 20 20 20 20 20 > t) {◙ -0000:0BF0 20 20 20 20 20 20 20 20-20 2F 2F 20 43 6F 6D 62 // Comb -0000:0C00 69 6E 65 20 61 6C 6C 20-63 75 72 72 65 6E 74 20 ine all current -0000:0C10 61 6C 74 65 72 6E 61 74-69 76 65 73 20 77 69 74 alternatives wit -0000:0C20 68 20 61 6C 6C 20 61 6C-74 65 72 6E 61 74 69 76 h all alternativ -0000:0C30 65 73 20 20 20 20 20 0A-20 20 20 20 20 20 20 20 es ◙ -0000:0C40 20 20 20 20 20 20 20 20-2F 2F 20 6F 66 20 74 68 // of th -0000:0C50 65 20 72 65 73 74 20 28-6E 65 78 74 20 70 69 65 e rest (next pie -0000:0C60 63 65 20 63 61 6E 20 73-74 61 72 74 20 77 69 74 ce can start wit -0000:0C70 68 20 61 20 64 69 67 69-74 29 20 20 20 20 20 20 h a digit) -0000:0C80 20 20 20 20 20 20 20 20-0A 20 20 20 20 20 20 20 ◙ -0000:0C90 20 20 20 20 20 20 20 20-20 66 6F 72 65 61 63 68 foreach -0000:0CA0 20 28 61 32 3B 20 5F 46-69 6E 64 57 6F 72 64 73 (a2; _FindWords -0000:0CB0 28 20 6E 75 6D 62 65 72-73 5B 74 2E 2E 24 5D 2C ( numbers[t..$], -0000:0CC0 20 74 72 75 65 20 20 20-20 20 29 20 29 0A 20 20 true ) )◙ -0000:0CD0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:0CE0 20 20 66 6F 72 65 61 63-68 28 61 31 3B 20 2A 61 foreach(a1; *a -0000:0CF0 6C 74 65 72 6E 61 74 69-76 65 73 29 0A 20 20 20 lternatives)◙ -0000:0D00 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:0D10 20 20 20 20 72 65 74 20-7E 3D 20 61 31 20 7E 20 ret ~= a1 ~ -0000:0D20 22 20 22 20 7E 20 61 32-3B 0A 20 20 20 20 20 20 " " ~ a2;◙ -0000:0D30 20 20 20 20 20 20 7D 0A-20 20 20 20 20 20 20 20 }◙ -0000:0D40 20 20 20 20 65 6C 73 65-20 20 20 20 0A 20 20 20 else ◙ -0000:0D50 20 20 20 20 20 20 20 20-20 20 20 20 20 72 65 74 ret -0000:0D60 20 7E 3D 20 2A 61 6C 74-65 72 6E 61 74 69 76 65 ~= *alternative -0000:0D70 73 3B 20 20 20 20 2F 2F-20 61 70 70 65 6E 64 20 s; // append -0000:0D80 74 68 65 73 65 20 61 6C-74 65 72 6E 61 74 69 76 these alternativ -0000:0D90 65 73 0A 20 20 20 20 20-20 20 20 7D 0A 20 20 20 es◙ }◙ -0000:0DA0 20 20 20 20 20 2F 2F 20-54 72 79 20 74 6F 20 6B // Try to k -0000:0DB0 65 65 70 20 31 20 64 69-67 69 74 2C 20 6F 6E 6C eep 1 digit, onl -0000:0DC0 79 20 69 66 20 77 65 27-72 65 20 61 6C 6C 6F 77 y if we're allow -0000:0DD0 65 64 20 61 6E 64 20 6E-6F 20 6F 74 68 65 72 0A ed and no other◙ -0000:0DE0 20 20 20 20 20 20 20 20-2F 2F 20 61 6C 74 65 72 // alter -0000:0DF0 6E 61 74 69 76 65 73 20-77 65 72 65 20 66 6F 75 natives were fou -0000:0E00 6E 64 0A 20 20 20 20 20-20 20 20 2F 2F 20 54 65 nd◙ // Te -0000:0E10 73 74 69 6E 67 20 22 72-65 74 2E 6C 65 6E 67 74 sting "ret.lengt -0000:0E20 68 22 20 6D 61 6B 65 73-20 6D 6F 72 65 20 73 65 h" makes more se -0000:0E30 6E 73 65 20 74 68 61 6E-20 74 65 73 74 69 6E 67 nse than testing -0000:0E40 20 22 66 6F 75 6E 64 77-6F 72 64 22 2C 0A 20 20 "foundword",◙ -0000:0E50 20 20 20 20 20 20 2F 2F-20 62 75 74 20 74 68 65 // but the -0000:0E60 20 6F 74 68 65 72 20 69-6D 70 6C 65 6D 65 6E 74 other implement -0000:0E70 61 74 69 6F 6E 73 20 73-65 65 6D 20 74 6F 20 64 ations seem to d -0000:0E80 6F 20 6A 75 73 74 20 74-68 69 73 2E 0A 20 20 20 o just this.◙ -0000:0E90 20 20 20 20 20 69 66 20-28 64 69 67 69 74 6F 6B if (digitok -0000:0EA0 20 26 26 20 21 66 6F 75-6E 64 77 6F 72 64 29 20 && !foundword) -0000:0EB0 7B 20 2F 2F 72 65 74 2E-6C 65 6E 67 74 68 20 3D { //ret.length = -0000:0EC0 3D 20 30 20 20 0A 20 20-20 20 20 20 20 20 20 20 = 0 ◙ -0000:0ED0 20 20 69 66 28 6E 75 6D-62 65 72 73 2E 6C 65 6E if(numbers.len -0000:0EE0 67 74 68 20 3E 20 20 31-29 20 7B 0A 20 20 20 20 gth > 1) {◙ -0000:0EF0 20 20 20 20 20 20 20 20-20 20 20 20 2F 2F 20 43 // C -0000:0F00 6F 6D 62 69 6E 65 20 31-20 64 69 67 69 74 20 77 ombine 1 digit w -0000:0F10 69 74 68 20 61 6C 6C 20-61 6C 74 65 6E 61 74 69 ith all altenati -0000:0F20 76 65 73 20 66 72 6F 6D-20 74 68 65 20 72 65 73 ves from the res -0000:0F30 74 20 20 20 20 0A 20 20-20 20 20 20 20 20 20 20 t ◙ -0000:0F40 20 20 20 20 20 20 2F 2F-20 28 6E 65 78 74 20 70 // (next p -0000:0F50 69 65 63 65 20 63 61 6E-20 6E 6F 74 20 73 74 61 iece can not sta -0000:0F60 72 74 20 77 69 74 68 20-61 20 64 69 67 69 74 29 rt with a digit) -0000:0F70 20 20 20 20 20 20 20 20-20 20 0A 20 20 20 20 20 ◙ -0000:0F80 20 20 20 20 20 20 20 20-20 20 20 66 6F 72 65 61 forea -0000:0F90 63 68 20 28 61 3B 20 5F-46 69 6E 64 57 6F 72 64 ch (a; _FindWord -0000:0FA0 73 28 20 6E 75 6D 62 65-72 73 5B 31 2E 2E 24 5D s( numbers[1..$] -0000:0FB0 2C 20 66 61 6C 73 65 20-29 20 29 0A 20 20 20 20 , false ) )◙ -0000:0FC0 20 20 20 20 20 20 20 20-20 20 20 20 20 20 20 20 -0000:0FD0 72 65 74 20 7E 3D 20 6E-75 6D 62 65 72 73 5B 30 ret ~= numbers[0 -0000:0FE0 2E 2E 31 5D 20 7E 20 22-20 22 20 7E 20 61 3B 0A ..1] ~ " " ~ a;◙ -0000:0FF0 20 20 20 20 20 20 20 20-20 20 20 20 7D 20 20 20 } -0000:1000 20 0A 20 20 20 20 20 20-20 20 20 20 20 20 65 6C ◙ el -0000:1010 73 65 20 20 20 20 0A 20-20 20 20 20 20 20 20 20 se ◙ -0000:1020 20 20 20 20 20 20 20 72-65 74 20 7E 3D 20 6E 75 ret ~= nu -0000:1030 6D 62 65 72 73 5B 30 2E-2E 31 5D 3B 20 20 20 20 mbers[0..1]; -0000:1040 2F 2F 20 6A 75 73 74 20-61 70 70 65 6E 64 20 74 // just append t -0000:1050 68 69 73 20 64 69 67 69-74 20 20 20 20 20 20 20 his digit -0000:1060 20 20 20 20 20 20 0A 20-20 20 20 20 20 20 20 7D ◙ } -0000:1070 20 20 20 20 0A 20 20 20-20 20 20 20 20 72 65 74 ◙ ret -0000:1080 75 72 6E 20 72 65 74 3B-0A 20 20 20 20 7D 0A 0A urn ret;◙ }◙◙ -0000:1090 20 20 20 20 2F 2F 2F 20-28 54 68 69 73 20 66 75 /// (This fu -0000:10A0 6E 63 74 69 6F 6E 20 77-61 73 20 69 6E 6C 69 6E nction was inlin -0000:10B0 65 64 20 69 6E 20 74 68-65 20 6F 72 69 67 69 6E ed in the origin -0000:10C0 61 6C 20 70 72 6F 67 72-61 6D 29 20 0A 20 20 20 al program) ◙ -0000:10D0 20 2F 2F 2F 20 46 69 6E-64 73 20 61 6C 6C 20 61 /// Finds all a -0000:10E0 6C 74 65 72 6E 61 74 69-76 65 73 20 66 6F 72 20 lternatives for -0000:10F0 74 68 65 20 67 69 76 65-6E 20 70 68 6F 6E 65 20 the given phone -0000:1100 6E 75 6D 62 65 72 20 0A-20 20 20 20 2F 2F 2F 20 number ◙ /// -0000:1110 52 65 74 75 72 6E 73 3A-20 61 72 72 61 79 20 6F Returns: array o -0000:1120 66 20 73 74 72 69 6E 67-73 20 0A 20 20 20 20 73 f strings ◙ s -0000:1130 74 72 69 6E 67 61 72 72-61 79 20 46 69 6E 64 57 tringarray FindW -0000:1140 6F 72 64 73 28 20 73 74-72 69 6E 67 20 70 68 6F ords( string pho -0000:1150 6E 65 5F 6E 75 6D 62 65-72 20 29 0A 20 20 20 20 ne_number )◙ -0000:1160 7B 0A 20 20 20 20 20 20-20 20 69 66 20 28 21 70 {◙ if (!p -0000:1170 68 6F 6E 65 5F 6E 75 6D-62 65 72 2E 6C 65 6E 67 hone_number.leng -0000:1180 74 68 29 0A 20 20 20 20-20 20 20 20 20 20 20 20 th)◙ -0000:1190 72 65 74 75 72 6E 20 6E-75 6C 6C 3B 0A 20 20 20 return null;◙ -0000:11A0 20 20 20 20 20 2F 2F 20-53 74 72 69 70 20 74 68 // Strip th -0000:11B0 65 20 6E 6F 6E 2D 64 69-67 69 74 20 63 68 61 72 e non-digit char -0000:11C0 61 63 74 65 72 73 20 66-72 6F 6D 20 74 68 65 20 acters from the -0000:11D0 70 68 6F 6E 65 20 6E 75-6D 62 65 72 2C 20 61 6E phone number, an -0000:11E0 64 0A 20 20 20 20 20 20-20 20 2F 2F 20 70 61 73 d◙ // pas -0000:11F0 73 20 69 74 20 74 6F 20-74 68 65 20 72 65 63 75 s it to the recu -0000:1200 72 73 69 76 65 20 66 75-6E 63 74 69 6F 6E 20 28 rsive function ( -0000:1210 6C 65 61 64 69 6E 67 20-64 69 67 69 74 20 69 73 leading digit is -0000:1220 20 61 6C 6C 6F 77 65 64-29 0A 20 20 20 20 20 20 allowed)◙ -0000:1230 20 20 72 65 74 75 72 6E-20 5F 46 69 6E 64 57 6F return _FindWo -0000:1240 72 64 73 28 20 73 74 72-69 70 4E 6F 6E 44 69 67 rds( stripNonDig -0000:1250 69 74 28 70 68 6F 6E 65-5F 6E 75 6D 62 65 72 29 it(phone_number) -0000:1260 2C 20 74 72 75 65 20 29-3B 20 20 20 20 0A 20 20 , true ); ◙ -0000:1270 20 20 7D 20 20 20 20 0A-20 20 20 20 0A 20 20 20 } ◙ ◙ -0000:1280 20 2F 2F 20 52 65 61 64-20 74 68 65 20 70 68 6F // Read the pho -0000:1290 6E 65 20 6E 75 6D 62 65-72 73 20 20 20 20 20 0A ne numbers ◙ -0000:12A0 20 20 20 20 66 6F 72 65-61 63 68 28 73 74 72 69 foreach(stri -0000:12B0 6E 67 20 70 68 6F 6E 65-3B 20 6E 65 77 20 42 75 ng phone; new Bu -0000:12C0 66 66 65 72 65 64 46 69-6C 65 28 22 69 6E 70 75 fferedFile("inpu -0000:12D0 74 2E 74 78 74 22 20 20-20 29 20 29 0A 20 20 20 t.txt" ) )◙ -0000:12E0 20 20 20 20 20 66 6F 72-65 61 63 68 28 61 6C 74 foreach(alt -0000:12F0 65 72 6E 61 74 69 76 65-3B 20 46 69 6E 64 57 6F ernative; FindWo -0000:1300 72 64 73 28 20 70 68 6F-6E 65 20 29 20 29 0A 20 rds( phone ) )◙ -0000:1310 20 20 20 20 20 20 20 20-20 20 20 77 72 69 74 65 write -0000:1320 66 6C 6E 28 70 68 6F 6E-65 2C 20 22 3A 20 22 2C fln(phone, ": ", -0000:1330 20 61 6C 74 65 72 6E 61-74 69 76 65 20 29 3B 0A alternative );◙ -0000:1340 7D 0A 0A }◙◙ diff --git a/third_party/pygments/tests/examplefiles/hexdump_hd b/third_party/pygments/tests/examplefiles/hexdump_hd deleted file mode 100644 index 4af46fcb6..000000000 --- a/third_party/pygments/tests/examplefiles/hexdump_hd +++ /dev/null @@ -1,310 +0,0 @@ -00000000 2f 2f 20 43 72 65 61 74 65 64 20 62 79 20 4c 69 |// Created by Li| -00000010 6f 6e 65 6c 6c 6f 20 4c 75 6e 65 73 75 20 61 6e |onello Lunesu an| -00000020 64 20 70 6c 61 63 65 64 20 69 6e 20 74 68 65 20 |d placed in the | -00000030 70 75 62 6c 69 63 20 64 6f 6d 61 69 6e 2e 0a 2f |public domain../| -00000040 2f 20 54 68 69 73 20 66 69 6c 65 20 68 61 73 20 |/ This file has | -00000050 62 65 65 6e 20 6d 6f 64 69 66 69 65 64 20 66 72 |been modified fr| -00000060 6f 6d 20 69 74 73 20 6f 72 69 67 69 6e 61 6c 20 |om its original | -00000070 76 65 72 73 69 6f 6e 2e 0a 2f 2f 20 49 74 20 68 |version..// It h| -00000080 61 73 20 62 65 65 6e 20 66 6f 72 6d 61 74 74 65 |as been formatte| -00000090 64 20 74 6f 20 66 69 74 20 79 6f 75 72 20 73 63 |d to fit your sc| -000000a0 72 65 65 6e 2e 0a 6d 6f 64 75 6c 65 20 70 68 6f |reen..module pho| -000000b0 6e 65 6e 6f 3b 20 20 20 20 20 2f 2f 20 6f 70 74 |neno; // opt| -000000c0 69 6f 6e 61 6c 0a 69 6d 70 6f 72 74 20 73 74 64 |ional.import std| -000000d0 2e 73 74 64 69 6f 3b 20 20 20 2f 2f 20 77 72 69 |.stdio; // wri| -000000e0 74 65 66 6c 6e 20 20 20 20 20 0a 69 6d 70 6f 72 |tefln .impor| -000000f0 74 20 73 74 64 2e 63 74 79 70 65 3b 20 20 20 2f |t std.ctype; /| -00000100 2f 20 69 73 64 69 67 69 74 20 20 20 20 20 0a 69 |/ isdigit .i| -00000110 6d 70 6f 72 74 20 73 74 64 2e 73 74 72 65 61 6d |mport std.stream| -00000120 3b 20 20 2f 2f 20 42 75 66 66 65 72 65 64 46 69 |; // BufferedFi| -00000130 6c 65 0a 0a 2f 2f 20 4a 75 73 74 20 66 6f 72 20 |le..// Just for | -00000140 72 65 61 64 61 62 69 6c 69 74 79 20 28 69 6d 61 |readability (ima| -00000150 67 69 6e 65 20 63 68 61 72 5b 5d 5b 5d 5b 63 68 |gine char[][][ch| -00000160 61 72 5b 5d 5d 29 20 20 20 20 0a 61 6c 69 61 73 |ar[]]) .alias| -00000170 20 63 68 61 72 5b 5d 20 73 74 72 69 6e 67 3b 0a | char[] string;.| -00000180 61 6c 69 61 73 20 73 74 72 69 6e 67 5b 5d 20 73 |alias string[] s| -00000190 74 72 69 6e 67 61 72 72 61 79 3b 0a 0a 2f 2f 2f |tringarray;..///| -000001a0 20 53 74 72 69 70 73 20 6e 6f 6e 2d 64 69 67 69 | Strips non-digi| -000001b0 74 20 63 68 61 72 61 63 74 65 72 73 20 66 72 6f |t characters fro| -000001c0 6d 20 74 68 65 20 73 74 72 69 6e 67 20 28 43 4f |m the string (CO| -000001d0 57 29 0a 73 74 72 69 6e 67 20 73 74 72 69 70 4e |W).string stripN| -000001e0 6f 6e 44 69 67 69 74 28 20 69 6e 20 73 74 72 69 |onDigit( in stri| -000001f0 6e 67 20 6c 69 6e 65 20 29 20 0a 7b 0a 20 20 20 |ng line ) .{. | -00000200 20 73 74 72 69 6e 67 20 72 65 74 3b 0a 20 20 20 | string ret;. | -00000210 20 66 6f 72 65 61 63 68 28 75 69 6e 74 20 69 2c | foreach(uint i,| -00000220 20 63 3b 20 6c 69 6e 65 29 20 7b 0a 20 20 20 20 | c; line) {. | -00000230 20 20 20 20 2f 2f 20 45 72 72 6f 72 3a 20 73 74 | // Error: st| -00000240 64 2e 63 74 79 70 65 2e 69 73 64 69 67 69 74 20 |d.ctype.isdigit | -00000250 61 74 20 43 3a 5c 64 6d 64 5c 73 72 63 5c 70 68 |at C:\dmd\src\ph| -00000260 6f 62 6f 73 5c 73 74 64 5c 63 74 79 70 65 2e 64 |obos\std\ctype.d| -00000270 28 33 37 29 20 0a 20 20 20 20 20 20 20 20 2f 2f |(37) . //| -00000280 20 63 6f 6e 66 6c 69 63 74 73 20 77 69 74 68 20 | conflicts with | -00000290 73 74 64 2e 73 74 72 65 61 6d 2e 69 73 64 69 67 |std.stream.isdig| -000002a0 69 74 20 61 74 20 43 3a 5c 64 6d 64 5c 73 72 63 |it at C:\dmd\src| -000002b0 5c 70 68 6f 62 6f 73 5c 73 74 64 5c 73 74 72 65 |\phobos\std\stre| -000002c0 61 6d 2e 64 28 32 39 32 34 29 0a 20 20 20 20 20 |am.d(2924). | -000002d0 20 20 20 69 66 20 28 21 73 74 64 2e 63 74 79 70 | if (!std.ctyp| -000002e0 65 2e 69 73 64 69 67 69 74 28 63 29 29 20 7b 0a |e.isdigit(c)) {.| -000002f0 20 20 20 20 20 20 20 20 20 20 20 20 69 66 20 28 | if (| -00000300 21 72 65 74 29 0a 20 20 20 20 20 20 20 20 20 20 |!ret). | -00000310 20 20 20 20 20 20 72 65 74 20 3d 20 6c 69 6e 65 | ret = line| -00000320 5b 30 2e 2e 69 5d 3b 20 20 20 20 0a 20 20 20 20 |[0..i]; . | -00000330 20 20 20 20 7d 20 20 20 20 0a 20 20 20 20 20 20 | } . | -00000340 20 20 65 6c 73 65 20 69 66 20 28 72 65 74 29 0a | else if (ret).| -00000350 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 20 | ret | -00000360 7e 3d 20 63 3b 20 20 20 20 0a 20 20 20 20 7d 20 |~= c; . } | -00000370 20 20 20 0a 20 20 20 20 72 65 74 75 72 6e 20 72 | . return r| -00000380 65 74 3f 72 65 74 3a 6c 69 6e 65 3b 0a 7d 0a 0a |et?ret:line;.}..| -00000390 75 6e 69 74 74 65 73 74 20 7b 0a 20 20 20 20 61 |unittest {. a| -000003a0 73 73 65 72 74 28 20 73 74 72 69 70 4e 6f 6e 44 |ssert( stripNonD| -000003b0 69 67 69 74 28 22 61 73 64 66 22 29 20 3d 3d 20 |igit("asdf") == | -000003c0 22 22 20 20 29 3b 0a 20 20 20 20 61 73 73 65 72 |"" );. asser| -000003d0 74 28 20 73 74 72 69 70 4e 6f 6e 44 69 67 69 74 |t( stripNonDigit| -000003e0 28 22 5c 27 31 33 2d 3d 32 20 34 6b 6f 70 22 29 |("\'13-=2 4kop")| -000003f0 20 3d 3d 20 20 22 31 33 32 34 22 20 20 29 3b 0a | == "1324" );.| -00000400 7d 0a 0a 2f 2f 2f 20 43 6f 6e 76 65 72 74 73 20 |}../// Converts | -00000410 61 20 77 6f 72 64 20 69 6e 74 6f 20 61 20 6e 75 |a word into a nu| -00000420 6d 62 65 72 2c 20 69 67 6e 6f 72 69 6e 67 20 61 |mber, ignoring a| -00000430 6c 6c 20 6e 6f 6e 20 61 6c 70 68 61 20 63 68 61 |ll non alpha cha| -00000440 72 61 63 74 65 72 73 20 20 0a 73 74 72 69 6e 67 |racters .string| -00000450 20 77 6f 72 64 54 6f 4e 75 6d 28 20 69 6e 20 73 | wordToNum( in s| -00000460 74 72 69 6e 67 20 77 6f 72 64 20 29 0a 7b 0a 2f |tring word ).{./| -00000470 2f 20 74 72 61 6e 73 6c 61 74 69 6f 6e 20 74 61 |/ translation ta| -00000480 62 6c 65 20 66 6f 72 20 74 68 65 20 74 61 73 6b |ble for the task| -00000490 20 61 74 20 68 61 6e 64 0a 63 6f 6e 73 74 20 63 | at hand.const c| -000004a0 68 61 72 5b 32 35 36 5d 20 54 52 41 4e 53 4c 41 |har[256] TRANSLA| -000004b0 54 45 20 3d 20 20 20 20 0a 20 20 20 20 22 20 20 |TE = . " | -000004c0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -000004d0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 22 20 | " | -000004e0 20 2f 2f 20 30 20 20 20 0a 20 20 20 20 22 20 20 | // 0 . " | -000004f0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 31 | 01| -00000500 32 33 34 35 36 37 38 39 20 20 20 20 20 20 22 20 |23456789 " | -00000510 20 2f 2f 20 33 32 20 20 20 20 20 0a 20 20 20 20 | // 32 . | -00000520 22 20 35 37 36 33 30 34 39 39 36 31 37 38 35 31 |" 57630499617851| -00000530 38 38 31 32 33 34 37 36 32 32 33 39 20 20 20 20 |881234762239 | -00000540 20 22 20 20 2f 2f 20 36 34 20 20 20 0a 20 20 20 | " // 64 . | -00000550 20 22 20 35 37 36 33 30 34 39 39 36 31 37 38 35 | " 5763049961785| -00000560 31 38 38 31 32 33 34 37 36 32 32 33 39 20 20 20 |1881234762239 | -00000570 20 20 22 0a 20 20 20 20 22 20 20 20 20 20 20 20 | ". " | -00000580 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -00000590 20 20 20 20 20 20 20 20 20 22 0a 20 20 20 20 22 | ". "| -000005a0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -* -000005c0 22 0a 20 20 20 20 22 20 20 20 20 20 20 20 20 20 |". " | -000005d0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -000005e0 20 20 20 20 20 20 20 22 20 20 20 20 0a 20 20 20 | " . | -000005f0 20 22 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | " | -00000600 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -00000610 20 20 22 3b 0a 20 20 20 20 73 74 72 69 6e 67 20 | ";. string | -00000620 72 65 74 3b 0a 20 20 20 20 66 6f 72 65 61 63 68 |ret;. foreach| -00000630 28 63 3b 20 63 61 73 74 28 75 62 79 74 65 5b 5d |(c; cast(ubyte[]| -00000640 29 77 6f 72 64 29 0a 20 20 20 20 20 20 20 20 69 |)word). i| -00000650 66 20 28 54 52 41 4e 53 4c 41 54 45 5b 63 5d 20 |f (TRANSLATE[c] | -00000660 21 3d 20 27 20 27 29 0a 20 20 20 20 20 20 20 20 |!= ' '). | -00000670 20 20 20 20 72 65 74 20 7e 3d 20 54 52 41 4e 53 | ret ~= TRANS| -00000680 4c 41 54 45 5b 63 5d 3b 0a 20 20 20 20 72 65 74 |LATE[c];. ret| -00000690 75 72 6e 20 72 65 74 3b 0a 7d 0a 0a 75 6e 69 74 |urn ret;.}..unit| -000006a0 74 65 73 74 20 7b 0a 20 2f 2f 20 54 65 73 74 20 |test {. // Test | -000006b0 77 6f 72 64 54 6f 4e 75 6d 20 75 73 69 6e 67 20 |wordToNum using | -000006c0 74 68 65 20 74 61 62 6c 65 20 66 72 6f 6d 20 74 |the table from t| -000006d0 68 65 20 74 61 73 6b 20 64 65 73 63 72 69 70 74 |he task descript| -000006e0 69 6f 6e 2e 0a 20 61 73 73 65 72 74 28 20 22 30 |ion.. assert( "0| -000006f0 31 31 31 32 32 32 33 33 33 34 34 35 35 36 36 36 |1112223334455666| -00000700 37 37 37 38 38 38 39 39 39 22 20 3d 3d 0a 20 20 |777888999" ==. | -00000710 20 77 6f 72 64 54 6f 4e 75 6d 28 22 45 20 7c 20 | wordToNum("E | | -00000720 4a 20 4e 20 51 20 7c 20 52 20 57 20 58 20 7c 20 |J N Q | R W X | | -00000730 44 20 53 20 59 20 7c 20 46 20 54 20 7c 20 41 20 |D S Y | F T | A | -00000740 4d 20 7c 20 43 20 49 20 56 20 7c 20 42 20 4b 20 |M | C I V | B K | -00000750 55 20 7c 20 4c 20 4f 20 50 20 7c 20 47 20 48 20 |U | L O P | G H | -00000760 5a 22 29 29 3b 0a 20 61 73 73 65 72 74 28 20 22 |Z"));. assert( "| -00000770 30 31 31 31 32 32 32 33 33 33 34 34 35 35 36 36 |0111222333445566| -00000780 36 37 37 37 38 38 38 39 39 39 22 20 3d 3d 20 0a |6777888999" == .| -00000790 20 20 20 77 6f 72 64 54 6f 4e 75 6d 28 22 65 20 | wordToNum("e | -000007a0 7c 20 6a 20 6e 20 71 20 7c 20 72 20 77 20 78 20 || j n q | r w x | -000007b0 7c 20 64 20 73 20 79 20 7c 20 66 20 74 20 7c 20 || d s y | f t | | -000007c0 61 20 6d 20 7c 20 63 20 69 20 76 20 7c 20 62 20 |a m | c i v | b | -000007d0 6b 20 75 20 7c 20 6c 20 6f 20 70 20 7c 20 67 20 |k u | l o p | g | -000007e0 68 20 7a 22 29 29 3b 0a 20 61 73 73 65 72 74 28 |h z"));. assert(| -000007f0 20 22 30 31 32 33 34 35 36 37 38 39 22 20 3d 3d | "0123456789" ==| -00000800 20 0a 20 20 20 77 6f 72 64 54 6f 4e 75 6d 28 22 | . wordToNum("| -00000810 30 20 7c 20 20 20 31 20 20 20 7c 20 20 20 32 20 |0 | 1 | 2 | -00000820 20 20 7c 20 20 20 33 20 20 20 7c 20 20 34 20 20 | | 3 | 4 | -00000830 7c 20 20 35 20 20 7c 20 20 20 36 20 20 20 7c 20 || 5 | 6 | | -00000840 20 20 37 20 20 20 7c 20 20 20 38 20 20 20 7c 20 | 7 | 8 | | -00000850 20 20 39 22 29 29 3b 0a 7d 0a 0a 76 6f 69 64 20 | 9"));.}..void | -00000860 6d 61 69 6e 28 20 73 74 72 69 6e 67 5b 5d 20 61 |main( string[] a| -00000870 72 67 73 20 29 0a 7b 0a 20 20 20 20 2f 2f 20 54 |rgs ).{. // T| -00000880 68 69 73 20 61 73 73 6f 63 69 61 74 69 76 65 20 |his associative | -00000890 61 72 72 61 79 20 6d 61 70 73 20 61 20 6e 75 6d |array maps a num| -000008a0 62 65 72 20 74 6f 20 61 6e 20 61 72 72 61 79 20 |ber to an array | -000008b0 6f 66 20 77 6f 72 64 73 2e 20 20 20 20 0a 20 20 |of words. . | -000008c0 20 20 73 74 72 69 6e 67 61 72 72 61 79 5b 73 74 | stringarray[st| -000008d0 72 69 6e 67 5d 20 20 20 20 6e 75 6d 32 77 6f 72 |ring] num2wor| -000008e0 64 73 3b 0a 0a 20 20 20 20 66 6f 72 65 61 63 68 |ds;.. foreach| -000008f0 28 73 74 72 69 6e 67 20 77 6f 72 64 3b 20 6e 65 |(string word; ne| -00000900 77 20 42 75 66 66 65 72 65 64 46 69 6c 65 28 22 |w BufferedFile("| -00000910 64 69 63 74 69 6f 6e 61 72 79 2e 74 78 74 22 20 |dictionary.txt" | -00000920 29 20 29 0a 20 20 20 20 20 20 20 20 6e 75 6d 32 |) ). num2| -00000930 77 6f 72 64 73 5b 20 77 6f 72 64 54 6f 4e 75 6d |words[ wordToNum| -00000940 28 77 6f 72 64 29 20 5d 20 7e 3d 20 77 6f 72 64 |(word) ] ~= word| -00000950 2e 64 75 70 3b 20 20 20 20 20 20 20 20 2f 2f 20 |.dup; // | -00000960 6d 75 73 74 20 64 75 70 0a 0a 20 20 20 20 2f 2f |must dup.. //| -00000970 2f 20 46 69 6e 64 73 20 61 6c 6c 20 61 6c 74 65 |/ Finds all alte| -00000980 72 6e 61 74 69 76 65 73 20 66 6f 72 20 74 68 65 |rnatives for the| -00000990 20 67 69 76 65 6e 20 6e 75 6d 62 65 72 0a 20 20 | given number. | -000009a0 20 20 2f 2f 2f 20 28 73 68 6f 75 6c 64 20 68 61 | /// (should ha| -000009b0 76 65 20 62 65 65 6e 20 73 74 72 69 70 70 65 64 |ve been stripped| -000009c0 20 66 72 6f 6d 20 6e 6f 6e 2d 64 69 67 69 74 20 | from non-digit | -000009d0 63 68 61 72 61 63 74 65 72 73 29 0a 20 20 20 20 |characters). | -000009e0 73 74 72 69 6e 67 61 72 72 61 79 20 5f 46 69 6e |stringarray _Fin| -000009f0 64 57 6f 72 64 73 28 20 73 74 72 69 6e 67 20 6e |dWords( string n| -00000a00 75 6d 62 65 72 73 2c 20 62 6f 6f 6c 20 64 69 67 |umbers, bool dig| -00000a10 69 74 6f 6b 20 29 0a 20 20 20 20 69 6e 20 7b 0a |itok ). in {.| -00000a20 20 20 20 20 20 20 20 20 61 73 73 65 72 74 28 6e | assert(n| -00000a30 75 6d 62 65 72 73 2e 6c 65 6e 67 74 68 20 3e 20 |umbers.length > | -00000a40 20 30 29 3b 20 20 20 20 0a 20 20 20 20 7d 20 20 | 0); . } | -00000a50 20 20 0a 20 20 20 20 6f 75 74 28 72 65 73 75 6c | . out(resul| -00000a60 74 29 20 7b 0a 20 20 20 20 20 20 20 20 66 6f 72 |t) {. for| -00000a70 65 61 63 68 20 28 61 3b 20 72 65 73 75 6c 74 29 |each (a; result)| -00000a80 0a 20 20 20 20 20 20 20 20 20 20 20 20 61 73 73 |. ass| -00000a90 65 72 74 28 20 77 6f 72 64 54 6f 4e 75 6d 28 61 |ert( wordToNum(a| -00000aa0 29 20 3d 3d 20 6e 75 6d 62 65 72 73 20 29 3b 0a |) == numbers );.| -00000ab0 20 20 20 20 7d 20 20 20 20 0a 20 20 20 20 62 6f | } . bo| -00000ac0 64 79 20 7b 0a 20 20 20 20 20 20 20 20 73 74 72 |dy {. str| -00000ad0 69 6e 67 61 72 72 61 79 20 72 65 74 3b 0a 20 20 |ingarray ret;. | -00000ae0 20 20 20 20 20 20 62 6f 6f 6c 20 66 6f 75 6e 64 | bool found| -00000af0 77 6f 72 64 20 3d 20 66 61 6c 73 65 3b 0a 20 20 |word = false;. | -00000b00 20 20 20 20 20 20 66 6f 72 20 28 75 69 6e 74 20 | for (uint | -00000b10 74 3d 31 3b 20 74 3c 3d 6e 75 6d 62 65 72 73 2e |t=1; t<=numbers.| -00000b20 6c 65 6e 67 74 68 3b 20 2b 2b 74 29 20 7b 0a 20 |length; ++t) {. | -00000b30 20 20 20 20 20 20 20 20 20 20 20 61 75 74 6f 20 | auto | -00000b40 61 6c 74 65 72 6e 61 74 69 76 65 73 20 3d 20 6e |alternatives = n| -00000b50 75 6d 62 65 72 73 5b 30 2e 2e 74 5d 20 69 6e 20 |umbers[0..t] in | -00000b60 6e 75 6d 32 77 6f 72 64 73 3b 0a 20 20 20 20 20 |num2words;. | -00000b70 20 20 20 20 20 20 20 69 66 20 28 21 61 6c 74 65 | if (!alte| -00000b80 72 6e 61 74 69 76 65 73 29 0a 20 20 20 20 20 20 |rnatives). | -00000b90 20 20 20 20 20 20 20 20 20 20 63 6f 6e 74 69 6e | contin| -00000ba0 75 65 3b 0a 20 20 20 20 20 20 20 20 20 20 20 20 |ue;. | -00000bb0 66 6f 75 6e 64 77 6f 72 64 20 3d 20 74 72 75 65 |foundword = true| -00000bc0 3b 0a 20 20 20 20 20 20 20 20 20 20 20 20 69 66 |;. if| -00000bd0 20 28 6e 75 6d 62 65 72 73 2e 6c 65 6e 67 74 68 | (numbers.length| -00000be0 20 3e 20 20 74 29 20 7b 0a 20 20 20 20 20 20 20 | > t) {. | -00000bf0 20 20 20 20 20 20 20 20 20 2f 2f 20 43 6f 6d 62 | // Comb| -00000c00 69 6e 65 20 61 6c 6c 20 63 75 72 72 65 6e 74 20 |ine all current | -00000c10 61 6c 74 65 72 6e 61 74 69 76 65 73 20 77 69 74 |alternatives wit| -00000c20 68 20 61 6c 6c 20 61 6c 74 65 72 6e 61 74 69 76 |h all alternativ| -00000c30 65 73 20 20 20 20 20 0a 20 20 20 20 20 20 20 20 |es . | -00000c40 20 20 20 20 20 20 20 20 2f 2f 20 6f 66 20 74 68 | // of th| -00000c50 65 20 72 65 73 74 20 28 6e 65 78 74 20 70 69 65 |e rest (next pie| -00000c60 63 65 20 63 61 6e 20 73 74 61 72 74 20 77 69 74 |ce can start wit| -00000c70 68 20 61 20 64 69 67 69 74 29 20 20 20 20 20 20 |h a digit) | -00000c80 20 20 20 20 20 20 20 20 0a 20 20 20 20 20 20 20 | . | -00000c90 20 20 20 20 20 20 20 20 20 66 6f 72 65 61 63 68 | foreach| -00000ca0 20 28 61 32 3b 20 5f 46 69 6e 64 57 6f 72 64 73 | (a2; _FindWords| -00000cb0 28 20 6e 75 6d 62 65 72 73 5b 74 2e 2e 24 5d 2c |( numbers[t..$],| -00000cc0 20 74 72 75 65 20 20 20 20 20 29 20 29 0a 20 20 | true ) ). | -00000cd0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -00000ce0 20 20 66 6f 72 65 61 63 68 28 61 31 3b 20 2a 61 | foreach(a1; *a| -00000cf0 6c 74 65 72 6e 61 74 69 76 65 73 29 0a 20 20 20 |lternatives). | -00000d00 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -00000d10 20 20 20 20 72 65 74 20 7e 3d 20 61 31 20 7e 20 | ret ~= a1 ~ | -00000d20 22 20 22 20 7e 20 61 32 3b 0a 20 20 20 20 20 20 |" " ~ a2;. | -00000d30 20 20 20 20 20 20 7d 0a 20 20 20 20 20 20 20 20 | }. | -00000d40 20 20 20 20 65 6c 73 65 20 20 20 20 0a 20 20 20 | else . | -00000d50 20 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 | ret| -00000d60 20 7e 3d 20 2a 61 6c 74 65 72 6e 61 74 69 76 65 | ~= *alternative| -00000d70 73 3b 20 20 20 20 2f 2f 20 61 70 70 65 6e 64 20 |s; // append | -00000d80 74 68 65 73 65 20 61 6c 74 65 72 6e 61 74 69 76 |these alternativ| -00000d90 65 73 0a 20 20 20 20 20 20 20 20 7d 0a 20 20 20 |es. }. | -00000da0 20 20 20 20 20 2f 2f 20 54 72 79 20 74 6f 20 6b | // Try to k| -00000db0 65 65 70 20 31 20 64 69 67 69 74 2c 20 6f 6e 6c |eep 1 digit, onl| -00000dc0 79 20 69 66 20 77 65 27 72 65 20 61 6c 6c 6f 77 |y if we're allow| -00000dd0 65 64 20 61 6e 64 20 6e 6f 20 6f 74 68 65 72 0a |ed and no other.| -00000de0 20 20 20 20 20 20 20 20 2f 2f 20 61 6c 74 65 72 | // alter| -00000df0 6e 61 74 69 76 65 73 20 77 65 72 65 20 66 6f 75 |natives were fou| -00000e00 6e 64 0a 20 20 20 20 20 20 20 20 2f 2f 20 54 65 |nd. // Te| -00000e10 73 74 69 6e 67 20 22 72 65 74 2e 6c 65 6e 67 74 |sting "ret.lengt| -00000e20 68 22 20 6d 61 6b 65 73 20 6d 6f 72 65 20 73 65 |h" makes more se| -00000e30 6e 73 65 20 74 68 61 6e 20 74 65 73 74 69 6e 67 |nse than testing| -00000e40 20 22 66 6f 75 6e 64 77 6f 72 64 22 2c 0a 20 20 | "foundword",. | -00000e50 20 20 20 20 20 20 2f 2f 20 62 75 74 20 74 68 65 | // but the| -00000e60 20 6f 74 68 65 72 20 69 6d 70 6c 65 6d 65 6e 74 | other implement| -00000e70 61 74 69 6f 6e 73 20 73 65 65 6d 20 74 6f 20 64 |ations seem to d| -00000e80 6f 20 6a 75 73 74 20 74 68 69 73 2e 0a 20 20 20 |o just this.. | -00000e90 20 20 20 20 20 69 66 20 28 64 69 67 69 74 6f 6b | if (digitok| -00000ea0 20 26 26 20 21 66 6f 75 6e 64 77 6f 72 64 29 20 | && !foundword) | -00000eb0 7b 20 2f 2f 72 65 74 2e 6c 65 6e 67 74 68 20 3d |{ //ret.length =| -00000ec0 3d 20 30 20 20 0a 20 20 20 20 20 20 20 20 20 20 |= 0 . | -00000ed0 20 20 69 66 28 6e 75 6d 62 65 72 73 2e 6c 65 6e | if(numbers.len| -00000ee0 67 74 68 20 3e 20 20 31 29 20 7b 0a 20 20 20 20 |gth > 1) {. | -00000ef0 20 20 20 20 20 20 20 20 20 20 20 20 2f 2f 20 43 | // C| -00000f00 6f 6d 62 69 6e 65 20 31 20 64 69 67 69 74 20 77 |ombine 1 digit w| -00000f10 69 74 68 20 61 6c 6c 20 61 6c 74 65 6e 61 74 69 |ith all altenati| -00000f20 76 65 73 20 66 72 6f 6d 20 74 68 65 20 72 65 73 |ves from the res| -00000f30 74 20 20 20 20 0a 20 20 20 20 20 20 20 20 20 20 |t . | -00000f40 20 20 20 20 20 20 2f 2f 20 28 6e 65 78 74 20 70 | // (next p| -00000f50 69 65 63 65 20 63 61 6e 20 6e 6f 74 20 73 74 61 |iece can not sta| -00000f60 72 74 20 77 69 74 68 20 61 20 64 69 67 69 74 29 |rt with a digit)| -00000f70 20 20 20 20 20 20 20 20 20 20 0a 20 20 20 20 20 | . | -00000f80 20 20 20 20 20 20 20 20 20 20 20 66 6f 72 65 61 | forea| -00000f90 63 68 20 28 61 3b 20 5f 46 69 6e 64 57 6f 72 64 |ch (a; _FindWord| -00000fa0 73 28 20 6e 75 6d 62 65 72 73 5b 31 2e 2e 24 5d |s( numbers[1..$]| -00000fb0 2c 20 66 61 6c 73 65 20 29 20 29 0a 20 20 20 20 |, false ) ). | -00000fc0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 | | -00000fd0 72 65 74 20 7e 3d 20 6e 75 6d 62 65 72 73 5b 30 |ret ~= numbers[0| -00000fe0 2e 2e 31 5d 20 7e 20 22 20 22 20 7e 20 61 3b 0a |..1] ~ " " ~ a;.| -00000ff0 20 20 20 20 20 20 20 20 20 20 20 20 7d 20 20 20 | } | -00001000 20 0a 20 20 20 20 20 20 20 20 20 20 20 20 65 6c | . el| -00001010 73 65 20 20 20 20 0a 20 20 20 20 20 20 20 20 20 |se . | -00001020 20 20 20 20 20 20 20 72 65 74 20 7e 3d 20 6e 75 | ret ~= nu| -00001030 6d 62 65 72 73 5b 30 2e 2e 31 5d 3b 20 20 20 20 |mbers[0..1]; | -00001040 2f 2f 20 6a 75 73 74 20 61 70 70 65 6e 64 20 74 |// just append t| -00001050 68 69 73 20 64 69 67 69 74 20 20 20 20 20 20 20 |his digit | -00001060 20 20 20 20 20 20 0a 20 20 20 20 20 20 20 20 7d | . }| -00001070 20 20 20 20 0a 20 20 20 20 20 20 20 20 72 65 74 | . ret| -00001080 75 72 6e 20 72 65 74 3b 0a 20 20 20 20 7d 0a 0a |urn ret;. }..| -00001090 20 20 20 20 2f 2f 2f 20 28 54 68 69 73 20 66 75 | /// (This fu| -000010a0 6e 63 74 69 6f 6e 20 77 61 73 20 69 6e 6c 69 6e |nction was inlin| -000010b0 65 64 20 69 6e 20 74 68 65 20 6f 72 69 67 69 6e |ed in the origin| -000010c0 61 6c 20 70 72 6f 67 72 61 6d 29 20 0a 20 20 20 |al program) . | -000010d0 20 2f 2f 2f 20 46 69 6e 64 73 20 61 6c 6c 20 61 | /// Finds all a| -000010e0 6c 74 65 72 6e 61 74 69 76 65 73 20 66 6f 72 20 |lternatives for | -000010f0 74 68 65 20 67 69 76 65 6e 20 70 68 6f 6e 65 20 |the given phone | -00001100 6e 75 6d 62 65 72 20 0a 20 20 20 20 2f 2f 2f 20 |number . /// | -00001110 52 65 74 75 72 6e 73 3a 20 61 72 72 61 79 20 6f |Returns: array o| -00001120 66 20 73 74 72 69 6e 67 73 20 0a 20 20 20 20 73 |f strings . s| -00001130 74 72 69 6e 67 61 72 72 61 79 20 46 69 6e 64 57 |tringarray FindW| -00001140 6f 72 64 73 28 20 73 74 72 69 6e 67 20 70 68 6f |ords( string pho| -00001150 6e 65 5f 6e 75 6d 62 65 72 20 29 0a 20 20 20 20 |ne_number ). | -00001160 7b 0a 20 20 20 20 20 20 20 20 69 66 20 28 21 70 |{. if (!p| -00001170 68 6f 6e 65 5f 6e 75 6d 62 65 72 2e 6c 65 6e 67 |hone_number.leng| -00001180 74 68 29 0a 20 20 20 20 20 20 20 20 20 20 20 20 |th). | -00001190 72 65 74 75 72 6e 20 6e 75 6c 6c 3b 0a 20 20 20 |return null;. | -000011a0 20 20 20 20 20 2f 2f 20 53 74 72 69 70 20 74 68 | // Strip th| -000011b0 65 20 6e 6f 6e 2d 64 69 67 69 74 20 63 68 61 72 |e non-digit char| -000011c0 61 63 74 65 72 73 20 66 72 6f 6d 20 74 68 65 20 |acters from the | -000011d0 70 68 6f 6e 65 20 6e 75 6d 62 65 72 2c 20 61 6e |phone number, an| -000011e0 64 0a 20 20 20 20 20 20 20 20 2f 2f 20 70 61 73 |d. // pas| -000011f0 73 20 69 74 20 74 6f 20 74 68 65 20 72 65 63 75 |s it to the recu| -00001200 72 73 69 76 65 20 66 75 6e 63 74 69 6f 6e 20 28 |rsive function (| -00001210 6c 65 61 64 69 6e 67 20 64 69 67 69 74 20 69 73 |leading digit is| -00001220 20 61 6c 6c 6f 77 65 64 29 0a 20 20 20 20 20 20 | allowed). | -00001230 20 20 72 65 74 75 72 6e 20 5f 46 69 6e 64 57 6f | return _FindWo| -00001240 72 64 73 28 20 73 74 72 69 70 4e 6f 6e 44 69 67 |rds( stripNonDig| -00001250 69 74 28 70 68 6f 6e 65 5f 6e 75 6d 62 65 72 29 |it(phone_number)| -00001260 2c 20 74 72 75 65 20 29 3b 20 20 20 20 0a 20 20 |, true ); . | -00001270 20 20 7d 20 20 20 20 0a 20 20 20 20 0a 20 20 20 | } . . | -00001280 20 2f 2f 20 52 65 61 64 20 74 68 65 20 70 68 6f | // Read the pho| -00001290 6e 65 20 6e 75 6d 62 65 72 73 20 20 20 20 20 0a |ne numbers .| -000012a0 20 20 20 20 66 6f 72 65 61 63 68 28 73 74 72 69 | foreach(stri| -000012b0 6e 67 20 70 68 6f 6e 65 3b 20 6e 65 77 20 42 75 |ng phone; new Bu| -000012c0 66 66 65 72 65 64 46 69 6c 65 28 22 69 6e 70 75 |fferedFile("inpu| -000012d0 74 2e 74 78 74 22 20 20 20 29 20 29 0a 20 20 20 |t.txt" ) ). | -000012e0 20 20 20 20 20 66 6f 72 65 61 63 68 28 61 6c 74 | foreach(alt| -000012f0 65 72 6e 61 74 69 76 65 3b 20 46 69 6e 64 57 6f |ernative; FindWo| -00001300 72 64 73 28 20 70 68 6f 6e 65 20 29 20 29 0a 20 |rds( phone ) ). | -00001310 20 20 20 20 20 20 20 20 20 20 20 77 72 69 74 65 | write| -00001320 66 6c 6e 28 70 68 6f 6e 65 2c 20 22 3a 20 22 2c |fln(phone, ": ",| -00001330 20 61 6c 74 65 72 6e 61 74 69 76 65 20 29 3b 0a | alternative );.| -00001340 7d 0a 0a |}..| -00001343 diff --git a/third_party/pygments/tests/examplefiles/hexdump_hexcat b/third_party/pygments/tests/examplefiles/hexdump_hexcat deleted file mode 100644 index 522074cff..000000000 --- a/third_party/pygments/tests/examplefiles/hexdump_hexcat +++ /dev/null @@ -1,247 +0,0 @@ -00000000 2F 2F 20 43 72 65 61 74 65 64 20 62 79 20 4C 69 6F 6E 65 6C //.Created.by.Lionel -00000014 6C 6F 20 4C 75 6E 65 73 75 20 61 6E 64 20 70 6C 61 63 65 64 lo.Lunesu.and.placed -00000028 20 69 6E 20 74 68 65 20 70 75 62 6C 69 63 20 64 6F 6D 61 69 .in.the.public.domai -0000003C 6E 2E 0A 2F 2F 20 54 68 69 73 20 66 69 6C 65 20 68 61 73 20 n..//.This.file.has. -00000050 62 65 65 6E 20 6D 6F 64 69 66 69 65 64 20 66 72 6F 6D 20 69 been.modified.from.i -00000064 74 73 20 6F 72 69 67 69 6E 61 6C 20 76 65 72 73 69 6F 6E 2E ts.original.version. -00000078 0A 2F 2F 20 49 74 20 68 61 73 20 62 65 65 6E 20 66 6F 72 6D .//.It.has.been.form -0000008C 61 74 74 65 64 20 74 6F 20 66 69 74 20 79 6F 75 72 20 73 63 atted.to.fit.your.sc -000000A0 72 65 65 6E 2E 0A 6D 6F 64 75 6C 65 20 70 68 6F 6E 65 6E 6F reen..module.phoneno -000000B4 3B 20 20 20 20 20 2F 2F 20 6F 70 74 69 6F 6E 61 6C 0A 69 6D ;.....//.optional.im -000000C8 70 6F 72 74 20 73 74 64 2E 73 74 64 69 6F 3B 20 20 20 2F 2F port.std.stdio;...// -000000DC 20 77 72 69 74 65 66 6C 6E 20 20 20 20 20 0A 69 6D 70 6F 72 .writefln......impor -000000F0 74 20 73 74 64 2E 63 74 79 70 65 3B 20 20 20 2F 2F 20 69 73 t.std.ctype;...//.is -00000104 64 69 67 69 74 20 20 20 20 20 0A 69 6D 70 6F 72 74 20 73 74 digit......import.st -00000118 64 2E 73 74 72 65 61 6D 3B 20 20 2F 2F 20 42 75 66 66 65 72 d.stream;..//.Buffer -0000012C 65 64 46 69 6C 65 0A 0A 2F 2F 20 4A 75 73 74 20 66 6F 72 20 edFile..//.Just.for. -00000140 72 65 61 64 61 62 69 6C 69 74 79 20 28 69 6D 61 67 69 6E 65 readability.(imagine -00000154 20 63 68 61 72 5B 5D 5B 5D 5B 63 68 61 72 5B 5D 5D 29 20 20 .char[][][char[]]).. -00000168 20 20 0A 61 6C 69 61 73 20 63 68 61 72 5B 5D 20 73 74 72 69 ...alias.char[].stri -0000017C 6E 67 3B 0A 61 6C 69 61 73 20 73 74 72 69 6E 67 5B 5D 20 73 ng;.alias.string[].s -00000190 74 72 69 6E 67 61 72 72 61 79 3B 0A 0A 2F 2F 2F 20 53 74 72 tringarray;..///.Str -000001A4 69 70 73 20 6E 6F 6E 2D 64 69 67 69 74 20 63 68 61 72 61 63 ips.non-digit.charac -000001B8 74 65 72 73 20 66 72 6F 6D 20 74 68 65 20 73 74 72 69 6E 67 ters.from.the.string -000001CC 20 28 43 4F 57 29 0A 73 74 72 69 6E 67 20 73 74 72 69 70 4E .(COW).string.stripN -000001E0 6F 6E 44 69 67 69 74 28 20 69 6E 20 73 74 72 69 6E 67 20 6C onDigit(.in.string.l -000001F4 69 6E 65 20 29 20 0A 7B 0A 20 20 20 20 73 74 72 69 6E 67 20 ine.)..{.....string. -00000208 72 65 74 3B 0A 20 20 20 20 66 6F 72 65 61 63 68 28 75 69 6E ret;.....foreach(uin -0000021C 74 20 69 2C 20 63 3B 20 6C 69 6E 65 29 20 7B 0A 20 20 20 20 t.i,.c;.line).{..... -00000230 20 20 20 20 2F 2F 20 45 72 72 6F 72 3A 20 73 74 64 2E 63 74 ....//.Error:.std.ct -00000244 79 70 65 2E 69 73 64 69 67 69 74 20 61 74 20 43 3A 5C 64 6D ype.isdigit.at.C:\dm -00000258 64 5C 73 72 63 5C 70 68 6F 62 6F 73 5C 73 74 64 5C 63 74 79 d\src\phobos\std\cty -0000026C 70 65 2E 64 28 33 37 29 20 0A 20 20 20 20 20 20 20 20 2F 2F pe.d(37)..........// -00000280 20 63 6F 6E 66 6C 69 63 74 73 20 77 69 74 68 20 73 74 64 2E .conflicts.with.std. -00000294 73 74 72 65 61 6D 2E 69 73 64 69 67 69 74 20 61 74 20 43 3A stream.isdigit.at.C: -000002A8 5C 64 6D 64 5C 73 72 63 5C 70 68 6F 62 6F 73 5C 73 74 64 5C \dmd\src\phobos\std\ -000002BC 73 74 72 65 61 6D 2E 64 28 32 39 32 34 29 0A 20 20 20 20 20 stream.d(2924)...... -000002D0 20 20 20 69 66 20 28 21 73 74 64 2E 63 74 79 70 65 2E 69 73 ...if.(!std.ctype.is -000002E4 64 69 67 69 74 28 63 29 29 20 7B 0A 20 20 20 20 20 20 20 20 digit(c)).{......... -000002F8 20 20 20 20 69 66 20 28 21 72 65 74 29 0A 20 20 20 20 20 20 ....if.(!ret)....... -0000030C 20 20 20 20 20 20 20 20 20 20 72 65 74 20 3D 20 6C 69 6E 65 ..........ret.=.line -00000320 5B 30 2E 2E 69 5D 3B 20 20 20 20 0A 20 20 20 20 20 20 20 20 [0..i];............. -00000334 7D 20 20 20 20 0A 20 20 20 20 20 20 20 20 65 6C 73 65 20 69 }.............else.i -00000348 66 20 28 72 65 74 29 0A 20 20 20 20 20 20 20 20 20 20 20 20 f.(ret)............. -0000035C 72 65 74 20 7E 3D 20 63 3B 20 20 20 20 0A 20 20 20 20 7D 20 ret.~=.c;.........}. -00000370 20 20 20 0A 20 20 20 20 72 65 74 75 72 6E 20 72 65 74 3F 72 ........return.ret?r -00000384 65 74 3A 6C 69 6E 65 3B 0A 7D 0A 0A 75 6E 69 74 74 65 73 74 et:line;.}..unittest -00000398 20 7B 0A 20 20 20 20 61 73 73 65 72 74 28 20 73 74 72 69 70 .{.....assert(.strip -000003AC 4E 6F 6E 44 69 67 69 74 28 22 61 73 64 66 22 29 20 3D 3D 20 NonDigit("asdf").==. -000003C0 22 22 20 20 29 3B 0A 20 20 20 20 61 73 73 65 72 74 28 20 73 ""..);.....assert(.s -000003D4 74 72 69 70 4E 6F 6E 44 69 67 69 74 28 22 5C 27 31 33 2D 3D tripNonDigit("\'13-= -000003E8 32 20 34 6B 6F 70 22 29 20 3D 3D 20 20 22 31 33 32 34 22 20 2.4kop").==.."1324". -000003FC 20 29 3B 0A 7D 0A 0A 2F 2F 2F 20 43 6F 6E 76 65 72 74 73 20 .);.}..///.Converts. -00000410 61 20 77 6F 72 64 20 69 6E 74 6F 20 61 20 6E 75 6D 62 65 72 a.word.into.a.number -00000424 2C 20 69 67 6E 6F 72 69 6E 67 20 61 6C 6C 20 6E 6F 6E 20 61 ,.ignoring.all.non.a -00000438 6C 70 68 61 20 63 68 61 72 61 63 74 65 72 73 20 20 0A 73 74 lpha.characters...st -0000044C 72 69 6E 67 20 77 6F 72 64 54 6F 4E 75 6D 28 20 69 6E 20 73 ring.wordToNum(.in.s -00000460 74 72 69 6E 67 20 77 6F 72 64 20 29 0A 7B 0A 2F 2F 20 74 72 tring.word.).{.//.tr -00000474 61 6E 73 6C 61 74 69 6F 6E 20 74 61 62 6C 65 20 66 6F 72 20 anslation.table.for. -00000488 74 68 65 20 74 61 73 6B 20 61 74 20 68 61 6E 64 0A 63 6F 6E the.task.at.hand.con -0000049C 73 74 20 63 68 61 72 5B 32 35 36 5D 20 54 52 41 4E 53 4C 41 st.char[256].TRANSLA -000004B0 54 45 20 3D 20 20 20 20 0A 20 20 20 20 22 20 20 20 20 20 20 TE.=........."...... -000004C4 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 .................... -000004D8 20 20 20 20 20 20 22 20 20 2F 2F 20 30 20 20 20 0A 20 20 20 ......"..//.0....... -000004EC 20 22 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 31 ."................01 -00000500 32 33 34 35 36 37 38 39 20 20 20 20 20 20 22 20 20 2F 2F 20 23456789......"..//. -00000514 33 32 20 20 20 20 20 0A 20 20 20 20 22 20 35 37 36 33 30 34 32..........".576304 -00000528 39 39 36 31 37 38 35 31 38 38 31 32 33 34 37 36 32 32 33 39 99617851881234762239 -0000053C 20 20 20 20 20 22 20 20 2F 2F 20 36 34 20 20 20 0A 20 20 20 ....."..//.64....... -00000550 20 22 20 35 37 36 33 30 34 39 39 36 31 37 38 35 31 38 38 31 .".57630499617851881 -00000564 32 33 34 37 36 32 32 33 39 20 20 20 20 20 22 0A 20 20 20 20 234762239....."..... -00000578 22 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "................... -0000058C 20 20 20 20 20 20 20 20 20 20 20 20 20 22 0A 20 20 20 20 22 ............."....." -000005A0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 .................... -000005B4 20 20 20 20 20 20 20 20 20 20 20 20 22 0A 20 20 20 20 22 20 ............".....". -000005C8 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 .................... -000005DC 20 20 20 20 20 20 20 20 20 20 20 22 20 20 20 20 0A 20 20 20 ..........."........ -000005F0 20 22 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 .".................. -00000604 20 20 20 20 20 20 20 20 20 20 20 20 20 20 22 3B 0A 20 20 20 ..............";.... -00000618 20 73 74 72 69 6E 67 20 72 65 74 3B 0A 20 20 20 20 66 6F 72 .string.ret;.....for -0000062C 65 61 63 68 28 63 3B 20 63 61 73 74 28 75 62 79 74 65 5B 5D each(c;.cast(ubyte[] -00000640 29 77 6F 72 64 29 0A 20 20 20 20 20 20 20 20 69 66 20 28 54 )word).........if.(T -00000654 52 41 4E 53 4C 41 54 45 5B 63 5D 20 21 3D 20 27 20 27 29 0A RANSLATE[c].!=.'.'). -00000668 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 20 7E 3D 20 54 ............ret.~=.T -0000067C 52 41 4E 53 4C 41 54 45 5B 63 5D 3B 0A 20 20 20 20 72 65 74 RANSLATE[c];.....ret -00000690 75 72 6E 20 72 65 74 3B 0A 7D 0A 0A 75 6E 69 74 74 65 73 74 urn.ret;.}..unittest -000006A4 20 7B 0A 20 2F 2F 20 54 65 73 74 20 77 6F 72 64 54 6F 4E 75 .{..//.Test.wordToNu -000006B8 6D 20 75 73 69 6E 67 20 74 68 65 20 74 61 62 6C 65 20 66 72 m.using.the.table.fr -000006CC 6F 6D 20 74 68 65 20 74 61 73 6B 20 64 65 73 63 72 69 70 74 om.the.task.descript -000006E0 69 6F 6E 2E 0A 20 61 73 73 65 72 74 28 20 22 30 31 31 31 32 ion...assert(."01112 -000006F4 32 32 33 33 33 34 34 35 35 36 36 36 37 37 37 38 38 38 39 39 22333445566677788899 -00000708 39 22 20 3D 3D 0A 20 20 20 77 6F 72 64 54 6F 4E 75 6D 28 22 9".==....wordToNum(" -0000071C 45 20 7C 20 4A 20 4E 20 51 20 7C 20 52 20 57 20 58 20 7C 20 E.|.J.N.Q.|.R.W.X.|. -00000730 44 20 53 20 59 20 7C 20 46 20 54 20 7C 20 41 20 4D 20 7C 20 D.S.Y.|.F.T.|.A.M.|. -00000744 43 20 49 20 56 20 7C 20 42 20 4B 20 55 20 7C 20 4C 20 4F 20 C.I.V.|.B.K.U.|.L.O. -00000758 50 20 7C 20 47 20 48 20 5A 22 29 29 3B 0A 20 61 73 73 65 72 P.|.G.H.Z"));..asser -0000076C 74 28 20 22 30 31 31 31 32 32 32 33 33 33 34 34 35 35 36 36 t(."0111222333445566 -00000780 36 37 37 37 38 38 38 39 39 39 22 20 3D 3D 20 0A 20 20 20 77 6777888999".==.....w -00000794 6F 72 64 54 6F 4E 75 6D 28 22 65 20 7C 20 6A 20 6E 20 71 20 ordToNum("e.|.j.n.q. -000007A8 7C 20 72 20 77 20 78 20 7C 20 64 20 73 20 79 20 7C 20 66 20 |.r.w.x.|.d.s.y.|.f. -000007BC 74 20 7C 20 61 20 6D 20 7C 20 63 20 69 20 76 20 7C 20 62 20 t.|.a.m.|.c.i.v.|.b. -000007D0 6B 20 75 20 7C 20 6C 20 6F 20 70 20 7C 20 67 20 68 20 7A 22 k.u.|.l.o.p.|.g.h.z" -000007E4 29 29 3B 0A 20 61 73 73 65 72 74 28 20 22 30 31 32 33 34 35 ));..assert(."012345 -000007F8 36 37 38 39 22 20 3D 3D 20 0A 20 20 20 77 6F 72 64 54 6F 4E 6789".==.....wordToN -0000080C 75 6D 28 22 30 20 7C 20 20 20 31 20 20 20 7C 20 20 20 32 20 um("0.|...1...|...2. -00000820 20 20 7C 20 20 20 33 20 20 20 7C 20 20 34 20 20 7C 20 20 35 ..|...3...|..4..|..5 -00000834 20 20 7C 20 20 20 36 20 20 20 7C 20 20 20 37 20 20 20 7C 20 ..|...6...|...7...|. -00000848 20 20 38 20 20 20 7C 20 20 20 39 22 29 29 3B 0A 7D 0A 0A 76 ..8...|...9"));.}..v -0000085C 6F 69 64 20 6D 61 69 6E 28 20 73 74 72 69 6E 67 5B 5D 20 61 oid.main(.string[].a -00000870 72 67 73 20 29 0A 7B 0A 20 20 20 20 2F 2F 20 54 68 69 73 20 rgs.).{.....//.This. -00000884 61 73 73 6F 63 69 61 74 69 76 65 20 61 72 72 61 79 20 6D 61 associative.array.ma -00000898 70 73 20 61 20 6E 75 6D 62 65 72 20 74 6F 20 61 6E 20 61 72 ps.a.number.to.an.ar -000008AC 72 61 79 20 6F 66 20 77 6F 72 64 73 2E 20 20 20 20 0A 20 20 ray.of.words........ -000008C0 20 20 73 74 72 69 6E 67 61 72 72 61 79 5B 73 74 72 69 6E 67 ..stringarray[string -000008D4 5D 20 20 20 20 6E 75 6D 32 77 6F 72 64 73 3B 0A 0A 20 20 20 ]....num2words;..... -000008E8 20 66 6F 72 65 61 63 68 28 73 74 72 69 6E 67 20 77 6F 72 64 .foreach(string.word -000008FC 3B 20 6E 65 77 20 42 75 66 66 65 72 65 64 46 69 6C 65 28 22 ;.new.BufferedFile(" -00000910 64 69 63 74 69 6F 6E 61 72 79 2E 74 78 74 22 20 29 20 29 0A dictionary.txt".).). -00000924 20 20 20 20 20 20 20 20 6E 75 6D 32 77 6F 72 64 73 5B 20 77 ........num2words[.w -00000938 6F 72 64 54 6F 4E 75 6D 28 77 6F 72 64 29 20 5D 20 7E 3D 20 ordToNum(word).].~=. -0000094C 77 6F 72 64 2E 64 75 70 3B 20 20 20 20 20 20 20 20 2F 2F 20 word.dup;........//. -00000960 6D 75 73 74 20 64 75 70 0A 0A 20 20 20 20 2F 2F 2F 20 46 69 must.dup......///.Fi -00000974 6E 64 73 20 61 6C 6C 20 61 6C 74 65 72 6E 61 74 69 76 65 73 nds.all.alternatives -00000988 20 66 6F 72 20 74 68 65 20 67 69 76 65 6E 20 6E 75 6D 62 65 .for.the.given.numbe -0000099C 72 0A 20 20 20 20 2F 2F 2F 20 28 73 68 6F 75 6C 64 20 68 61 r.....///.(should.ha -000009B0 76 65 20 62 65 65 6E 20 73 74 72 69 70 70 65 64 20 66 72 6F ve.been.stripped.fro -000009C4 6D 20 6E 6F 6E 2D 64 69 67 69 74 20 63 68 61 72 61 63 74 65 m.non-digit.characte -000009D8 72 73 29 0A 20 20 20 20 73 74 72 69 6E 67 61 72 72 61 79 20 rs).....stringarray. -000009EC 5F 46 69 6E 64 57 6F 72 64 73 28 20 73 74 72 69 6E 67 20 6E _FindWords(.string.n -00000A00 75 6D 62 65 72 73 2C 20 62 6F 6F 6C 20 64 69 67 69 74 6F 6B umbers,.bool.digitok -00000A14 20 29 0A 20 20 20 20 69 6E 20 7B 0A 20 20 20 20 20 20 20 20 .).....in.{......... -00000A28 61 73 73 65 72 74 28 6E 75 6D 62 65 72 73 2E 6C 65 6E 67 74 assert(numbers.lengt -00000A3C 68 20 3E 20 20 30 29 3B 20 20 20 20 0A 20 20 20 20 7D 20 20 h.>..0);.........}.. -00000A50 20 20 0A 20 20 20 20 6F 75 74 28 72 65 73 75 6C 74 29 20 7B .......out(result).{ -00000A64 0A 20 20 20 20 20 20 20 20 66 6F 72 65 61 63 68 20 28 61 3B .........foreach.(a; -00000A78 20 72 65 73 75 6C 74 29 0A 20 20 20 20 20 20 20 20 20 20 20 .result)............ -00000A8C 20 61 73 73 65 72 74 28 20 77 6F 72 64 54 6F 4E 75 6D 28 61 .assert(.wordToNum(a -00000AA0 29 20 3D 3D 20 6E 75 6D 62 65 72 73 20 29 3B 0A 20 20 20 20 ).==.numbers.);..... -00000AB4 7D 20 20 20 20 0A 20 20 20 20 62 6F 64 79 20 7B 0A 20 20 20 }.........body.{.... -00000AC8 20 20 20 20 20 73 74 72 69 6E 67 61 72 72 61 79 20 72 65 74 .....stringarray.ret -00000ADC 3B 0A 20 20 20 20 20 20 20 20 62 6F 6F 6C 20 66 6F 75 6E 64 ;.........bool.found -00000AF0 77 6F 72 64 20 3D 20 66 61 6C 73 65 3B 0A 20 20 20 20 20 20 word.=.false;....... -00000B04 20 20 66 6F 72 20 28 75 69 6E 74 20 74 3D 31 3B 20 74 3C 3D ..for.(uint.t=1;.t<= -00000B18 6E 75 6D 62 65 72 73 2E 6C 65 6E 67 74 68 3B 20 2B 2B 74 29 numbers.length;.++t) -00000B2C 20 7B 0A 20 20 20 20 20 20 20 20 20 20 20 20 61 75 74 6F 20 .{.............auto. -00000B40 61 6C 74 65 72 6E 61 74 69 76 65 73 20 3D 20 6E 75 6D 62 65 alternatives.=.numbe -00000B54 72 73 5B 30 2E 2E 74 5D 20 69 6E 20 6E 75 6D 32 77 6F 72 64 rs[0..t].in.num2word -00000B68 73 3B 0A 20 20 20 20 20 20 20 20 20 20 20 20 69 66 20 28 21 s;.............if.(! -00000B7C 61 6C 74 65 72 6E 61 74 69 76 65 73 29 0A 20 20 20 20 20 20 alternatives)....... -00000B90 20 20 20 20 20 20 20 20 20 20 63 6F 6E 74 69 6E 75 65 3B 0A ..........continue;. -00000BA4 20 20 20 20 20 20 20 20 20 20 20 20 66 6F 75 6E 64 77 6F 72 ............foundwor -00000BB8 64 20 3D 20 74 72 75 65 3B 0A 20 20 20 20 20 20 20 20 20 20 d.=.true;........... -00000BCC 20 20 69 66 20 28 6E 75 6D 62 65 72 73 2E 6C 65 6E 67 74 68 ..if.(numbers.length -00000BE0 20 3E 20 20 74 29 20 7B 0A 20 20 20 20 20 20 20 20 20 20 20 .>..t).{............ -00000BF4 20 20 20 20 20 2F 2F 20 43 6F 6D 62 69 6E 65 20 61 6C 6C 20 .....//.Combine.all. -00000C08 63 75 72 72 65 6E 74 20 61 6C 74 65 72 6E 61 74 69 76 65 73 current.alternatives -00000C1C 20 77 69 74 68 20 61 6C 6C 20 61 6C 74 65 72 6E 61 74 69 76 .with.all.alternativ -00000C30 65 73 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 es.................. -00000C44 20 20 20 20 2F 2F 20 6F 66 20 74 68 65 20 72 65 73 74 20 28 ....//.of.the.rest.( -00000C58 6E 65 78 74 20 70 69 65 63 65 20 63 61 6E 20 73 74 61 72 74 next.piece.can.start -00000C6C 20 77 69 74 68 20 61 20 64 69 67 69 74 29 20 20 20 20 20 20 .with.a.digit)...... -00000C80 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 .................... -00000C94 20 20 20 20 20 66 6F 72 65 61 63 68 20 28 61 32 3B 20 5F 46 .....foreach.(a2;._F -00000CA8 69 6E 64 57 6F 72 64 73 28 20 6E 75 6D 62 65 72 73 5B 74 2E indWords(.numbers[t. -00000CBC 2E 24 5D 2C 20 74 72 75 65 20 20 20 20 20 29 20 29 0A 20 20 .$],.true.....).)... -00000CD0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 66 6F ..................fo -00000CE4 72 65 61 63 68 28 61 31 3B 20 2A 61 6C 74 65 72 6E 61 74 69 reach(a1;.*alternati -00000CF8 76 65 73 29 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 ves)................ -00000D0C 20 20 20 20 20 20 20 20 72 65 74 20 7E 3D 20 61 31 20 7E 20 ........ret.~=.a1.~. -00000D20 22 20 22 20 7E 20 61 32 3B 0A 20 20 20 20 20 20 20 20 20 20 ".".~.a2;........... -00000D34 20 20 7D 0A 20 20 20 20 20 20 20 20 20 20 20 20 65 6C 73 65 ..}.............else -00000D48 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 .................... -00000D5C 20 72 65 74 20 7E 3D 20 2A 61 6C 74 65 72 6E 61 74 69 76 65 .ret.~=.*alternative -00000D70 73 3B 20 20 20 20 2F 2F 20 61 70 70 65 6E 64 20 74 68 65 73 s;....//.append.thes -00000D84 65 20 61 6C 74 65 72 6E 61 74 69 76 65 73 0A 20 20 20 20 20 e.alternatives...... -00000D98 20 20 20 7D 0A 20 20 20 20 20 20 20 20 2F 2F 20 54 72 79 20 ...}.........//.Try. -00000DAC 74 6F 20 6B 65 65 70 20 31 20 64 69 67 69 74 2C 20 6F 6E 6C to.keep.1.digit,.onl -00000DC0 79 20 69 66 20 77 65 27 72 65 20 61 6C 6C 6F 77 65 64 20 61 y.if.we're.allowed.a -00000DD4 6E 64 20 6E 6F 20 6F 74 68 65 72 0A 20 20 20 20 20 20 20 20 nd.no.other......... -00000DE8 2F 2F 20 61 6C 74 65 72 6E 61 74 69 76 65 73 20 77 65 72 65 //.alternatives.were -00000DFC 20 66 6F 75 6E 64 0A 20 20 20 20 20 20 20 20 2F 2F 20 54 65 .found.........//.Te -00000E10 73 74 69 6E 67 20 22 72 65 74 2E 6C 65 6E 67 74 68 22 20 6D sting."ret.length".m -00000E24 61 6B 65 73 20 6D 6F 72 65 20 73 65 6E 73 65 20 74 68 61 6E akes.more.sense.than -00000E38 20 74 65 73 74 69 6E 67 20 22 66 6F 75 6E 64 77 6F 72 64 22 .testing."foundword" -00000E4C 2C 0A 20 20 20 20 20 20 20 20 2F 2F 20 62 75 74 20 74 68 65 ,.........//.but.the -00000E60 20 6F 74 68 65 72 20 69 6D 70 6C 65 6D 65 6E 74 61 74 69 6F .other.implementatio -00000E74 6E 73 20 73 65 65 6D 20 74 6F 20 64 6F 20 6A 75 73 74 20 74 ns.seem.to.do.just.t -00000E88 68 69 73 2E 0A 20 20 20 20 20 20 20 20 69 66 20 28 64 69 67 his..........if.(dig -00000E9C 69 74 6F 6B 20 26 26 20 21 66 6F 75 6E 64 77 6F 72 64 29 20 itok.&&.!foundword). -00000EB0 7B 20 2F 2F 72 65 74 2E 6C 65 6E 67 74 68 20 3D 3D 20 30 20 {.//ret.length.==.0. -00000EC4 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 69 66 28 6E 75 6D ..............if(num -00000ED8 62 65 72 73 2E 6C 65 6E 67 74 68 20 3E 20 20 31 29 20 7B 0A bers.length.>..1).{. -00000EEC 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 2F 2F 20 43 ................//.C -00000F00 6F 6D 62 69 6E 65 20 31 20 64 69 67 69 74 20 77 69 74 68 20 ombine.1.digit.with. -00000F14 61 6C 6C 20 61 6C 74 65 6E 61 74 69 76 65 73 20 66 72 6F 6D all.altenatives.from -00000F28 20 74 68 65 20 72 65 73 74 20 20 20 20 0A 20 20 20 20 20 20 .the.rest........... -00000F3C 20 20 20 20 20 20 20 20 20 20 2F 2F 20 28 6E 65 78 74 20 70 ..........//.(next.p -00000F50 69 65 63 65 20 63 61 6E 20 6E 6F 74 20 73 74 61 72 74 20 77 iece.can.not.start.w -00000F64 69 74 68 20 61 20 64 69 67 69 74 29 20 20 20 20 20 20 20 20 ith.a.digit)........ -00000F78 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 66 ...................f -00000F8C 6F 72 65 61 63 68 20 28 61 3B 20 5F 46 69 6E 64 57 6F 72 64 oreach.(a;._FindWord -00000FA0 73 28 20 6E 75 6D 62 65 72 73 5B 31 2E 2E 24 5D 2C 20 66 61 s(.numbers[1..$],.fa -00000FB4 6C 73 65 20 29 20 29 0A 20 20 20 20 20 20 20 20 20 20 20 20 lse.).)............. -00000FC8 20 20 20 20 20 20 20 20 72 65 74 20 7E 3D 20 6E 75 6D 62 65 ........ret.~=.numbe -00000FDC 72 73 5B 30 2E 2E 31 5D 20 7E 20 22 20 22 20 7E 20 61 3B 0A rs[0..1].~.".".~.a;. -00000FF0 20 20 20 20 20 20 20 20 20 20 20 20 7D 20 20 20 20 0A 20 20 ............}....... -00001004 20 20 20 20 20 20 20 20 20 20 65 6C 73 65 20 20 20 20 0A 20 ..........else...... -00001018 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 20 7E ...............ret.~ -0000102C 3D 20 6E 75 6D 62 65 72 73 5B 30 2E 2E 31 5D 3B 20 20 20 20 =.numbers[0..1];.... -00001040 2F 2F 20 6A 75 73 74 20 61 70 70 65 6E 64 20 74 68 69 73 20 //.just.append.this. -00001054 64 69 67 69 74 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 digit............... -00001068 20 20 20 20 20 20 20 7D 20 20 20 20 0A 20 20 20 20 20 20 20 .......}............ -0000107C 20 72 65 74 75 72 6E 20 72 65 74 3B 0A 20 20 20 20 7D 0A 0A .return.ret;.....}.. -00001090 20 20 20 20 2F 2F 2F 20 28 54 68 69 73 20 66 75 6E 63 74 69 ....///.(This.functi -000010A4 6F 6E 20 77 61 73 20 69 6E 6C 69 6E 65 64 20 69 6E 20 74 68 on.was.inlined.in.th -000010B8 65 20 6F 72 69 67 69 6E 61 6C 20 70 72 6F 67 72 61 6D 29 20 e.original.program). -000010CC 0A 20 20 20 20 2F 2F 2F 20 46 69 6E 64 73 20 61 6C 6C 20 61 .....///.Finds.all.a -000010E0 6C 74 65 72 6E 61 74 69 76 65 73 20 66 6F 72 20 74 68 65 20 lternatives.for.the. -000010F4 67 69 76 65 6E 20 70 68 6F 6E 65 20 6E 75 6D 62 65 72 20 0A given.phone.number.. -00001108 20 20 20 20 2F 2F 2F 20 52 65 74 75 72 6E 73 3A 20 61 72 72 ....///.Returns:.arr -0000111C 61 79 20 6F 66 20 73 74 72 69 6E 67 73 20 0A 20 20 20 20 73 ay.of.strings......s -00001130 74 72 69 6E 67 61 72 72 61 79 20 46 69 6E 64 57 6F 72 64 73 tringarray.FindWords -00001144 28 20 73 74 72 69 6E 67 20 70 68 6F 6E 65 5F 6E 75 6D 62 65 (.string.phone_numbe -00001158 72 20 29 0A 20 20 20 20 7B 0A 20 20 20 20 20 20 20 20 69 66 r.).....{.........if -0000116C 20 28 21 70 68 6F 6E 65 5F 6E 75 6D 62 65 72 2E 6C 65 6E 67 .(!phone_number.leng -00001180 74 68 29 0A 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 75 th).............retu -00001194 72 6E 20 6E 75 6C 6C 3B 0A 20 20 20 20 20 20 20 20 2F 2F 20 rn.null;.........//. -000011A8 53 74 72 69 70 20 74 68 65 20 6E 6F 6E 2D 64 69 67 69 74 20 Strip.the.non-digit. -000011BC 63 68 61 72 61 63 74 65 72 73 20 66 72 6F 6D 20 74 68 65 20 characters.from.the. -000011D0 70 68 6F 6E 65 20 6E 75 6D 62 65 72 2C 20 61 6E 64 0A 20 20 phone.number,.and... -000011E4 20 20 20 20 20 20 2F 2F 20 70 61 73 73 20 69 74 20 74 6F 20 ......//.pass.it.to. -000011F8 74 68 65 20 72 65 63 75 72 73 69 76 65 20 66 75 6E 63 74 69 the.recursive.functi -0000120C 6F 6E 20 28 6C 65 61 64 69 6E 67 20 64 69 67 69 74 20 69 73 on.(leading.digit.is -00001220 20 61 6C 6C 6F 77 65 64 29 0A 20 20 20 20 20 20 20 20 72 65 .allowed).........re -00001234 74 75 72 6E 20 5F 46 69 6E 64 57 6F 72 64 73 28 20 73 74 72 turn._FindWords(.str -00001248 69 70 4E 6F 6E 44 69 67 69 74 28 70 68 6F 6E 65 5F 6E 75 6D ipNonDigit(phone_num -0000125C 62 65 72 29 2C 20 74 72 75 65 20 29 3B 20 20 20 20 0A 20 20 ber),.true.);....... -00001270 20 20 7D 20 20 20 20 0A 20 20 20 20 0A 20 20 20 20 2F 2F 20 ..}..............//. -00001284 52 65 61 64 20 74 68 65 20 70 68 6F 6E 65 20 6E 75 6D 62 65 Read.the.phone.numbe -00001298 72 73 20 20 20 20 20 0A 20 20 20 20 66 6F 72 65 61 63 68 28 rs..........foreach( -000012AC 73 74 72 69 6E 67 20 70 68 6F 6E 65 3B 20 6E 65 77 20 42 75 string.phone;.new.Bu -000012C0 66 66 65 72 65 64 46 69 6C 65 28 22 69 6E 70 75 74 2E 74 78 fferedFile("input.tx -000012D4 74 22 20 20 20 29 20 29 0A 20 20 20 20 20 20 20 20 66 6F 72 t"...).).........for -000012E8 65 61 63 68 28 61 6C 74 65 72 6E 61 74 69 76 65 3B 20 46 69 each(alternative;.Fi -000012FC 6E 64 57 6F 72 64 73 28 20 70 68 6F 6E 65 20 29 20 29 0A 20 ndWords(.phone.).).. -00001310 20 20 20 20 20 20 20 20 20 20 20 77 72 69 74 65 66 6C 6E 28 ...........writefln( -00001324 70 68 6F 6E 65 2C 20 22 3A 20 22 2C 20 61 6C 74 65 72 6E 61 phone,.":.",.alterna -00001338 74 69 76 65 20 29 3B 0A 7D 0A 0A tive.);.}.. diff --git a/third_party/pygments/tests/examplefiles/hexdump_hexdump b/third_party/pygments/tests/examplefiles/hexdump_hexdump deleted file mode 100644 index 06c2e861f..000000000 --- a/third_party/pygments/tests/examplefiles/hexdump_hexdump +++ /dev/null @@ -1,310 +0,0 @@ -0000000 2f2f 4320 6572 7461 6465 6220 2079 694c -0000010 6e6f 6c65 6f6c 4c20 6e75 7365 2075 6e61 -0000020 2064 6c70 6361 6465 6920 206e 6874 2065 -0000030 7570 6c62 6369 6420 6d6f 6961 2e6e 2f0a -0000040 202f 6854 7369 6620 6c69 2065 6168 2073 -0000050 6562 6e65 6d20 646f 6669 6569 2064 7266 -0000060 6d6f 6920 7374 6f20 6972 6967 616e 206c -0000070 6576 7372 6f69 2e6e 2f0a 202f 7449 6820 -0000080 7361 6220 6565 206e 6f66 6d72 7461 6574 -0000090 2064 6f74 6620 7469 7920 756f 2072 6373 -00000a0 6572 6e65 0a2e 6f6d 7564 656c 7020 6f68 -00000b0 656e 6f6e 203b 2020 2020 2f2f 6f20 7470 -00000c0 6f69 616e 0a6c 6d69 6f70 7472 7320 6474 -00000d0 732e 6474 6f69 203b 2020 2f2f 7720 6972 -00000e0 6574 6c66 206e 2020 2020 690a 706d 726f -00000f0 2074 7473 2e64 7463 7079 3b65 2020 2f20 -0000100 202f 7369 6964 6967 2074 2020 2020 690a -0000110 706d 726f 2074 7473 2e64 7473 6572 6d61 -0000120 203b 2f20 202f 7542 6666 7265 6465 6946 -0000130 656c 0a0a 2f2f 4a20 7375 2074 6f66 2072 -0000140 6572 6461 6261 6c69 7469 2079 6928 616d -0000150 6967 656e 6320 6168 5b72 5b5d 5b5d 6863 -0000160 7261 5d5b 295d 2020 2020 610a 696c 7361 -0000170 6320 6168 5b72 205d 7473 6972 676e 0a3b -0000180 6c61 6169 2073 7473 6972 676e 5d5b 7320 -0000190 7274 6e69 6167 7272 7961 0a3b 2f0a 2f2f -00001a0 5320 7274 7069 2073 6f6e 2d6e 6964 6967 -00001b0 2074 6863 7261 6361 6574 7372 6620 6f72 -00001c0 206d 6874 2065 7473 6972 676e 2820 4f43 -00001d0 2957 730a 7274 6e69 2067 7473 6972 4e70 -00001e0 6e6f 6944 6967 2874 6920 206e 7473 6972 -00001f0 676e 6c20 6e69 2065 2029 7b0a 200a 2020 -0000200 7320 7274 6e69 2067 6572 3b74 200a 2020 -0000210 6620 726f 6165 6863 7528 6e69 2074 2c69 -0000220 6320 203b 696c 656e 2029 0a7b 2020 2020 -0000230 2020 2020 2f2f 4520 7272 726f 203a 7473 -0000240 2e64 7463 7079 2e65 7369 6964 6967 2074 -0000250 7461 4320 5c3a 6d64 5c64 7273 5c63 6870 -0000260 626f 736f 735c 6474 635c 7974 6570 642e -0000270 3328 2937 0a20 2020 2020 2020 2020 2f2f -0000280 6320 6e6f 6c66 6369 7374 7720 7469 2068 -0000290 7473 2e64 7473 6572 6d61 692e 6473 6769 -00002a0 7469 6120 2074 3a43 645c 646d 735c 6372 -00002b0 705c 6f68 6f62 5c73 7473 5c64 7473 6572 -00002c0 6d61 642e 3228 3239 2934 200a 2020 2020 -00002d0 2020 6920 2066 2128 7473 2e64 7463 7079 -00002e0 2e65 7369 6964 6967 2874 2963 2029 0a7b -00002f0 2020 2020 2020 2020 2020 2020 6669 2820 -0000300 7221 7465 0a29 2020 2020 2020 2020 2020 -0000310 2020 2020 2020 6572 2074 203d 696c 656e -0000320 305b 2e2e 5d69 203b 2020 0a20 2020 2020 -0000330 2020 2020 207d 2020 0a20 2020 2020 2020 -0000340 2020 6c65 6573 6920 2066 7228 7465 0a29 -0000350 2020 2020 2020 2020 2020 2020 6572 2074 -0000360 3d7e 6320 203b 2020 0a20 2020 2020 207d -0000370 2020 0a20 2020 2020 6572 7574 6e72 7220 -0000380 7465 723f 7465 6c3a 6e69 3b65 7d0a 0a0a -0000390 6e75 7469 6574 7473 7b20 200a 2020 6120 -00003a0 7373 7265 2874 7320 7274 7069 6f4e 446e -00003b0 6769 7469 2228 7361 6664 2922 3d20 203d -00003c0 2222 2020 3b29 200a 2020 6120 7373 7265 -00003d0 2874 7320 7274 7069 6f4e 446e 6769 7469 -00003e0 2228 275c 3331 3d2d 2032 6b34 706f 2922 -00003f0 3d20 203d 2220 3331 3432 2022 2920 0a3b -0000400 0a7d 2f0a 2f2f 4320 6e6f 6576 7472 2073 -0000410 2061 6f77 6472 6920 746e 206f 2061 756e -0000420 626d 7265 202c 6769 6f6e 6972 676e 6120 -0000430 6c6c 6e20 6e6f 6120 706c 6168 6320 6168 -0000440 6172 7463 7265 2073 0a20 7473 6972 676e -0000450 7720 726f 5464 4e6f 6d75 2028 6e69 7320 -0000460 7274 6e69 2067 6f77 6472 2920 7b0a 2f0a -0000470 202f 7274 6e61 6c73 7461 6f69 206e 6174 -0000480 6c62 2065 6f66 2072 6874 2065 6174 6b73 -0000490 6120 2074 6168 646e 630a 6e6f 7473 6320 -00004a0 6168 5b72 3532 5d36 5420 4152 534e 414c -00004b0 4554 3d20 2020 2020 200a 2020 2220 2020 -00004c0 2020 2020 2020 2020 2020 2020 2020 2020 -00004d0 2020 2020 2020 2020 2020 2020 2020 2022 -00004e0 2f20 202f 2030 2020 200a 2020 2220 2020 -00004f0 2020 2020 2020 2020 2020 2020 2020 3130 -0000500 3332 3534 3736 3938 2020 2020 2020 2022 -0000510 2f20 202f 3233 2020 2020 0a20 2020 2020 -0000520 2022 3735 3336 3430 3939 3136 3837 3135 -0000530 3838 3231 3433 3637 3232 3933 2020 2020 -0000540 2220 2020 2f2f 3620 2034 2020 200a 2020 -0000550 2220 3520 3637 3033 3934 3639 3731 3538 -0000560 3831 3138 3332 3734 3236 3332 2039 2020 -0000570 2020 0a22 2020 2020 2022 2020 2020 2020 -0000580 2020 2020 2020 2020 2020 2020 2020 2020 -0000590 2020 2020 2020 2020 2220 200a 2020 2220 -00005a0 2020 2020 2020 2020 2020 2020 2020 2020 -* -00005c0 0a22 2020 2020 2022 2020 2020 2020 2020 -00005d0 2020 2020 2020 2020 2020 2020 2020 2020 -00005e0 2020 2020 2020 2220 2020 2020 200a 2020 -00005f0 2220 2020 2020 2020 2020 2020 2020 2020 -0000600 2020 2020 2020 2020 2020 2020 2020 2020 -0000610 2020 3b22 200a 2020 7320 7274 6e69 2067 -0000620 6572 3b74 200a 2020 6620 726f 6165 6863 -0000630 6328 203b 6163 7473 7528 7962 6574 5d5b -0000640 7729 726f 2964 200a 2020 2020 2020 6920 -0000650 2066 5428 4152 534e 414c 4554 635b 205d -0000660 3d21 2720 2720 0a29 2020 2020 2020 2020 -0000670 2020 2020 6572 2074 3d7e 5420 4152 534e -0000680 414c 4554 635b 3b5d 200a 2020 7220 7465 -0000690 7275 206e 6572 3b74 7d0a 0a0a 6e75 7469 -00006a0 6574 7473 7b20 200a 2f2f 5420 7365 2074 -00006b0 6f77 6472 6f54 754e 206d 7375 6e69 2067 -00006c0 6874 2065 6174 6c62 2065 7266 6d6f 7420 -00006d0 6568 7420 7361 206b 6564 6373 6972 7470 -00006e0 6f69 2e6e 200a 7361 6573 7472 2028 3022 -00006f0 3131 3231 3232 3333 3433 3534 3635 3636 -0000700 3737 3837 3838 3939 2239 3d20 0a3d 2020 -0000710 7720 726f 5464 4e6f 6d75 2228 2045 207c -0000720 204a 204e 2051 207c 2052 2057 2058 207c -0000730 2044 2053 2059 207c 2046 2054 207c 2041 -0000740 204d 207c 2043 2049 2056 207c 2042 204b -0000750 2055 207c 204c 204f 2050 207c 2047 2048 -0000760 225a 2929 0a3b 6120 7373 7265 2874 2220 -0000770 3130 3131 3232 3332 3333 3434 3535 3636 -0000780 3736 3737 3838 3938 3939 2022 3d3d 0a20 -0000790 2020 7720 726f 5464 4e6f 6d75 2228 2065 -00007a0 207c 206a 206e 2071 207c 2072 2077 2078 -00007b0 207c 2064 2073 2079 207c 2066 2074 207c -00007c0 2061 206d 207c 2063 2069 2076 207c 2062 -00007d0 206b 2075 207c 206c 206f 2070 207c 2067 -00007e0 2068 227a 2929 0a3b 6120 7373 7265 2874 -00007f0 2220 3130 3332 3534 3736 3938 2022 3d3d -0000800 0a20 2020 7720 726f 5464 4e6f 6d75 2228 -0000810 2030 207c 2020 2031 2020 207c 2020 2032 -0000820 2020 207c 2020 2033 2020 207c 3420 2020 -0000830 207c 3520 2020 207c 2020 2036 2020 207c -0000840 2020 2037 2020 207c 2020 2038 2020 207c -0000850 2020 2239 2929 0a3b 0a7d 760a 696f 2064 -0000860 616d 6e69 2028 7473 6972 676e 5d5b 6120 -0000870 6772 2073 0a29 0a7b 2020 2020 2f2f 5420 -0000880 6968 2073 7361 6f73 6963 7461 7669 2065 -0000890 7261 6172 2079 616d 7370 6120 6e20 6d75 -00008a0 6562 2072 6f74 6120 206e 7261 6172 2079 -00008b0 666f 7720 726f 7364 202e 2020 0a20 2020 -00008c0 2020 7473 6972 676e 7261 6172 5b79 7473 -00008d0 6972 676e 205d 2020 6e20 6d75 7732 726f -00008e0 7364 0a3b 200a 2020 6620 726f 6165 6863 -00008f0 7328 7274 6e69 2067 6f77 6472 203b 656e -0000900 2077 7542 6666 7265 6465 6946 656c 2228 -0000910 6964 7463 6f69 616e 7972 742e 7478 2022 -0000920 2029 0a29 2020 2020 2020 2020 756e 326d -0000930 6f77 6472 5b73 7720 726f 5464 4e6f 6d75 -0000940 7728 726f 2964 5d20 7e20 203d 6f77 6472 -0000950 642e 7075 203b 2020 2020 2020 2f20 202f -0000960 756d 7473 6420 7075 0a0a 2020 2020 2f2f -0000970 202f 6946 646e 2073 6c61 206c 6c61 6574 -0000980 6e72 7461 7669 7365 6620 726f 7420 6568 -0000990 6720 7669 6e65 6e20 6d75 6562 0a72 2020 -00009a0 2020 2f2f 202f 7328 6f68 6c75 2064 6168 -00009b0 6576 6220 6565 206e 7473 6972 7070 6465 -00009c0 6620 6f72 206d 6f6e 2d6e 6964 6967 2074 -00009d0 6863 7261 6361 6574 7372 0a29 2020 2020 -00009e0 7473 6972 676e 7261 6172 2079 465f 6e69 -00009f0 5764 726f 7364 2028 7473 6972 676e 6e20 -0000a00 6d75 6562 7372 202c 6f62 6c6f 6420 6769 -0000a10 7469 6b6f 2920 200a 2020 6920 206e 0a7b -0000a20 2020 2020 2020 2020 7361 6573 7472 6e28 -0000a30 6d75 6562 7372 6c2e 6e65 7467 2068 203e -0000a40 3020 3b29 2020 2020 200a 2020 7d20 2020 -0000a50 2020 200a 2020 6f20 7475 7228 7365 6c75 -0000a60 2974 7b20 200a 2020 2020 2020 6620 726f -0000a70 6165 6863 2820 3b61 7220 7365 6c75 2974 -0000a80 200a 2020 2020 2020 2020 2020 6120 7373 -0000a90 7265 2874 7720 726f 5464 4e6f 6d75 6128 -0000aa0 2029 3d3d 6e20 6d75 6562 7372 2920 0a3b -0000ab0 2020 2020 207d 2020 0a20 2020 2020 6f62 -0000ac0 7964 7b20 200a 2020 2020 2020 7320 7274 -0000ad0 6e69 6167 7272 7961 7220 7465 0a3b 2020 -0000ae0 2020 2020 2020 6f62 6c6f 6620 756f 646e -0000af0 6f77 6472 3d20 6620 6c61 6573 0a3b 2020 -0000b00 2020 2020 2020 6f66 2072 7528 6e69 2074 -0000b10 3d74 3b31 7420 3d3c 756e 626d 7265 2e73 -0000b20 656c 676e 6874 203b 2b2b 2974 7b20 200a -0000b30 2020 2020 2020 2020 2020 6120 7475 206f -0000b40 6c61 6574 6e72 7461 7669 7365 3d20 6e20 -0000b50 6d75 6562 7372 305b 2e2e 5d74 6920 206e -0000b60 756e 326d 6f77 6472 3b73 200a 2020 2020 -0000b70 2020 2020 2020 6920 2066 2128 6c61 6574 -0000b80 6e72 7461 7669 7365 0a29 2020 2020 2020 -0000b90 2020 2020 2020 2020 2020 6f63 746e 6e69 -0000ba0 6575 0a3b 2020 2020 2020 2020 2020 2020 -0000bb0 6f66 6e75 7764 726f 2064 203d 7274 6575 -0000bc0 0a3b 2020 2020 2020 2020 2020 2020 6669 -0000bd0 2820 756e 626d 7265 2e73 656c 676e 6874 -0000be0 3e20 2020 2974 7b20 200a 2020 2020 2020 -0000bf0 2020 2020 2020 2020 2f20 202f 6f43 626d -0000c00 6e69 2065 6c61 206c 7563 7272 6e65 2074 -0000c10 6c61 6574 6e72 7461 7669 7365 7720 7469 -0000c20 2068 6c61 206c 6c61 6574 6e72 7461 7669 -0000c30 7365 2020 2020 0a20 2020 2020 2020 2020 -0000c40 2020 2020 2020 2020 2f2f 6f20 2066 6874 -0000c50 2065 6572 7473 2820 656e 7478 7020 6569 -0000c60 6563 6320 6e61 7320 6174 7472 7720 7469 -0000c70 2068 2061 6964 6967 2974 2020 2020 2020 -0000c80 2020 2020 2020 2020 200a 2020 2020 2020 -0000c90 2020 2020 2020 2020 6620 726f 6165 6863 -0000ca0 2820 3261 203b 465f 6e69 5764 726f 7364 -0000cb0 2028 756e 626d 7265 5b73 2e74 242e 2c5d -0000cc0 7420 7572 2065 2020 2020 2029 0a29 2020 -0000cd0 2020 2020 2020 2020 2020 2020 2020 2020 -0000ce0 2020 6f66 6572 6361 2868 3161 203b 612a -0000cf0 746c 7265 616e 6974 6576 2973 200a 2020 -0000d00 2020 2020 2020 2020 2020 2020 2020 2020 -0000d10 2020 2020 6572 2074 3d7e 6120 2031 207e -0000d20 2022 2022 207e 3261 0a3b 2020 2020 2020 -0000d30 2020 2020 2020 0a7d 2020 2020 2020 2020 -0000d40 2020 2020 6c65 6573 2020 2020 200a 2020 -0000d50 2020 2020 2020 2020 2020 2020 7220 7465 -0000d60 7e20 203d 612a 746c 7265 616e 6974 6576 -0000d70 3b73 2020 2020 2f2f 6120 7070 6e65 2064 -0000d80 6874 7365 2065 6c61 6574 6e72 7461 7669 -0000d90 7365 200a 2020 2020 2020 7d20 200a 2020 -0000da0 2020 2020 2f20 202f 7254 2079 6f74 6b20 -0000db0 6565 2070 2031 6964 6967 2c74 6f20 6c6e -0000dc0 2079 6669 7720 2765 6572 6120 6c6c 776f -0000dd0 6465 6120 646e 6e20 206f 746f 6568 0a72 -0000de0 2020 2020 2020 2020 2f2f 6120 746c 7265 -0000df0 616e 6974 6576 2073 6577 6572 6620 756f -0000e00 646e 200a 2020 2020 2020 2f20 202f 6554 -0000e10 7473 6e69 2067 7222 7465 6c2e 6e65 7467 -0000e20 2268 6d20 6b61 7365 6d20 726f 2065 6573 -0000e30 736e 2065 6874 6e61 7420 7365 6974 676e -0000e40 2220 6f66 6e75 7764 726f 2264 0a2c 2020 -0000e50 2020 2020 2020 2f2f 6220 7475 7420 6568 -0000e60 6f20 6874 7265 6920 706d 656c 656d 746e -0000e70 7461 6f69 736e 7320 6565 206d 6f74 6420 -0000e80 206f 756a 7473 7420 6968 2e73 200a 2020 -0000e90 2020 2020 6920 2066 6428 6769 7469 6b6f -0000ea0 2620 2026 6621 756f 646e 6f77 6472 2029 -0000eb0 207b 2f2f 6572 2e74 656c 676e 6874 3d20 -0000ec0 203d 2030 0a20 2020 2020 2020 2020 2020 -0000ed0 2020 6669 6e28 6d75 6562 7372 6c2e 6e65 -0000ee0 7467 2068 203e 3120 2029 0a7b 2020 2020 -0000ef0 2020 2020 2020 2020 2020 2020 2f2f 4320 -0000f00 6d6f 6962 656e 3120 6420 6769 7469 7720 -0000f10 7469 2068 6c61 206c 6c61 6574 616e 6974 -0000f20 6576 2073 7266 6d6f 7420 6568 7220 7365 -0000f30 2074 2020 0a20 2020 2020 2020 2020 2020 -0000f40 2020 2020 2020 2f2f 2820 656e 7478 7020 -0000f50 6569 6563 6320 6e61 6e20 746f 7320 6174 -0000f60 7472 7720 7469 2068 2061 6964 6967 2974 -0000f70 2020 2020 2020 2020 2020 200a 2020 2020 -0000f80 2020 2020 2020 2020 2020 6620 726f 6165 -0000f90 6863 2820 3b61 5f20 6946 646e 6f57 6472 -0000fa0 2873 6e20 6d75 6562 7372 315b 2e2e 5d24 -0000fb0 202c 6166 736c 2065 2029 0a29 2020 2020 -0000fc0 2020 2020 2020 2020 2020 2020 2020 2020 -0000fd0 6572 2074 3d7e 6e20 6d75 6562 7372 305b -0000fe0 2e2e 5d31 7e20 2220 2220 7e20 6120 0a3b -0000ff0 2020 2020 2020 2020 2020 2020 207d 2020 -0001000 0a20 2020 2020 2020 2020 2020 2020 6c65 -0001010 6573 2020 2020 200a 2020 2020 2020 2020 -0001020 2020 2020 2020 7220 7465 7e20 203d 756e -0001030 626d 7265 5b73 2e30 312e 3b5d 2020 2020 -0001040 2f2f 6a20 7375 2074 7061 6570 646e 7420 -0001050 6968 2073 6964 6967 2074 2020 2020 2020 -0001060 2020 2020 2020 200a 2020 2020 2020 7d20 -0001070 2020 2020 200a 2020 2020 2020 7220 7465 -0001080 7275 206e 6572 3b74 200a 2020 7d20 0a0a -0001090 2020 2020 2f2f 202f 5428 6968 2073 7566 -00010a0 636e 6974 6e6f 7720 7361 6920 6c6e 6e69 -00010b0 6465 6920 206e 6874 2065 726f 6769 6e69 -00010c0 6c61 7020 6f72 7267 6d61 2029 200a 2020 -00010d0 2f20 2f2f 4620 6e69 7364 6120 6c6c 6120 -00010e0 746c 7265 616e 6974 6576 2073 6f66 2072 -00010f0 6874 2065 6967 6576 206e 6870 6e6f 2065 -0001100 756e 626d 7265 0a20 2020 2020 2f2f 202f -0001110 6552 7574 6e72 3a73 6120 7272 7961 6f20 -0001120 2066 7473 6972 676e 2073 200a 2020 7320 -0001130 7274 6e69 6167 7272 7961 4620 6e69 5764 -0001140 726f 7364 2028 7473 6972 676e 7020 6f68 -0001150 656e 6e5f 6d75 6562 2072 0a29 2020 2020 -0001160 0a7b 2020 2020 2020 2020 6669 2820 7021 -0001170 6f68 656e 6e5f 6d75 6562 2e72 656c 676e -0001180 6874 0a29 2020 2020 2020 2020 2020 2020 -0001190 6572 7574 6e72 6e20 6c75 3b6c 200a 2020 -00011a0 2020 2020 2f20 202f 7453 6972 2070 6874 -00011b0 2065 6f6e 2d6e 6964 6967 2074 6863 7261 -00011c0 6361 6574 7372 6620 6f72 206d 6874 2065 -00011d0 6870 6e6f 2065 756e 626d 7265 202c 6e61 -00011e0 0a64 2020 2020 2020 2020 2f2f 7020 7361 -00011f0 2073 7469 7420 206f 6874 2065 6572 7563 -0001200 7372 7669 2065 7566 636e 6974 6e6f 2820 -0001210 656c 6461 6e69 2067 6964 6967 2074 7369 -0001220 6120 6c6c 776f 6465 0a29 2020 2020 2020 -0001230 2020 6572 7574 6e72 5f20 6946 646e 6f57 -0001240 6472 2873 7320 7274 7069 6f4e 446e 6769 -0001250 7469 7028 6f68 656e 6e5f 6d75 6562 2972 -0001260 202c 7274 6575 2920 203b 2020 0a20 2020 -0001270 2020 207d 2020 0a20 2020 2020 200a 2020 -0001280 2f20 202f 6552 6461 7420 6568 7020 6f68 -0001290 656e 6e20 6d75 6562 7372 2020 2020 0a20 -00012a0 2020 2020 6f66 6572 6361 2868 7473 6972 -00012b0 676e 7020 6f68 656e 203b 656e 2077 7542 -00012c0 6666 7265 6465 6946 656c 2228 6e69 7570 -00012d0 2e74 7874 2274 2020 2920 2920 200a 2020 -00012e0 2020 2020 6620 726f 6165 6863 6128 746c -00012f0 7265 616e 6974 6576 203b 6946 646e 6f57 -0001300 6472 2873 7020 6f68 656e 2920 2920 200a -0001310 2020 2020 2020 2020 2020 7720 6972 6574 -0001320 6c66 286e 6870 6e6f 2c65 2220 203a 2c22 -0001330 6120 746c 7265 616e 6974 6576 2920 0a3b -0001340 0a7d 000a -0001343 diff --git a/third_party/pygments/tests/examplefiles/hexdump_od b/third_party/pygments/tests/examplefiles/hexdump_od deleted file mode 100644 index a407aef0e..000000000 --- a/third_party/pygments/tests/examplefiles/hexdump_od +++ /dev/null @@ -1,310 +0,0 @@ -0000000 2f 2f 20 43 72 65 61 74 65 64 20 62 79 20 4c 69 >// Created by Li< -0000020 6f 6e 65 6c 6c 6f 20 4c 75 6e 65 73 75 20 61 6e >onello Lunesu an< -0000040 64 20 70 6c 61 63 65 64 20 69 6e 20 74 68 65 20 >d placed in the < -0000060 70 75 62 6c 69 63 20 64 6f 6d 61 69 6e 2e 0a 2f >public domain../< -0000100 2f 20 54 68 69 73 20 66 69 6c 65 20 68 61 73 20 >/ This file has < -0000120 62 65 65 6e 20 6d 6f 64 69 66 69 65 64 20 66 72 >been modified fr< -0000140 6f 6d 20 69 74 73 20 6f 72 69 67 69 6e 61 6c 20 >om its original < -0000160 76 65 72 73 69 6f 6e 2e 0a 2f 2f 20 49 74 20 68 >version..// It h< -0000200 61 73 20 62 65 65 6e 20 66 6f 72 6d 61 74 74 65 >as been formatte< -0000220 64 20 74 6f 20 66 69 74 20 79 6f 75 72 20 73 63 >d to fit your sc< -0000240 72 65 65 6e 2e 0a 6d 6f 64 75 6c 65 20 70 68 6f >reen..module pho< -0000260 6e 65 6e 6f 3b 20 20 20 20 20 2f 2f 20 6f 70 74 >neno; // opt< -0000300 69 6f 6e 61 6c 0a 69 6d 70 6f 72 74 20 73 74 64 >ional.import std< -0000320 2e 73 74 64 69 6f 3b 20 20 20 2f 2f 20 77 72 69 >.stdio; // wri< -0000340 74 65 66 6c 6e 20 20 20 20 20 0a 69 6d 70 6f 72 >tefln .impor< -0000360 74 20 73 74 64 2e 63 74 79 70 65 3b 20 20 20 2f >t std.ctype; /< -0000400 2f 20 69 73 64 69 67 69 74 20 20 20 20 20 0a 69 >/ isdigit .i< -0000420 6d 70 6f 72 74 20 73 74 64 2e 73 74 72 65 61 6d >mport std.stream< -0000440 3b 20 20 2f 2f 20 42 75 66 66 65 72 65 64 46 69 >; // BufferedFi< -0000460 6c 65 0a 0a 2f 2f 20 4a 75 73 74 20 66 6f 72 20 >le..// Just for < -0000500 72 65 61 64 61 62 69 6c 69 74 79 20 28 69 6d 61 >readability (ima< -0000520 67 69 6e 65 20 63 68 61 72 5b 5d 5b 5d 5b 63 68 >gine char[][][ch< -0000540 61 72 5b 5d 5d 29 20 20 20 20 0a 61 6c 69 61 73 >ar[]]) .alias< -0000560 20 63 68 61 72 5b 5d 20 73 74 72 69 6e 67 3b 0a > char[] string;.< -0000600 61 6c 69 61 73 20 73 74 72 69 6e 67 5b 5d 20 73 >alias string[] s< -0000620 74 72 69 6e 67 61 72 72 61 79 3b 0a 0a 2f 2f 2f >tringarray;..///< -0000640 20 53 74 72 69 70 73 20 6e 6f 6e 2d 64 69 67 69 > Strips non-digi< -0000660 74 20 63 68 61 72 61 63 74 65 72 73 20 66 72 6f >t characters fro< -0000700 6d 20 74 68 65 20 73 74 72 69 6e 67 20 28 43 4f >m the string (CO< -0000720 57 29 0a 73 74 72 69 6e 67 20 73 74 72 69 70 4e >W).string stripN< -0000740 6f 6e 44 69 67 69 74 28 20 69 6e 20 73 74 72 69 >onDigit( in stri< -0000760 6e 67 20 6c 69 6e 65 20 29 20 0a 7b 0a 20 20 20 >ng line ) .{. < -0001000 20 73 74 72 69 6e 67 20 72 65 74 3b 0a 20 20 20 > string ret;. < -0001020 20 66 6f 72 65 61 63 68 28 75 69 6e 74 20 69 2c > foreach(uint i,< -0001040 20 63 3b 20 6c 69 6e 65 29 20 7b 0a 20 20 20 20 > c; line) {. < -0001060 20 20 20 20 2f 2f 20 45 72 72 6f 72 3a 20 73 74 > // Error: st< -0001100 64 2e 63 74 79 70 65 2e 69 73 64 69 67 69 74 20 >d.ctype.isdigit < -0001120 61 74 20 43 3a 5c 64 6d 64 5c 73 72 63 5c 70 68 >at C:\dmd\src\ph< -0001140 6f 62 6f 73 5c 73 74 64 5c 63 74 79 70 65 2e 64 >obos\std\ctype.d< -0001160 28 33 37 29 20 0a 20 20 20 20 20 20 20 20 2f 2f >(37) . //< -0001200 20 63 6f 6e 66 6c 69 63 74 73 20 77 69 74 68 20 > conflicts with < -0001220 73 74 64 2e 73 74 72 65 61 6d 2e 69 73 64 69 67 >std.stream.isdig< -0001240 69 74 20 61 74 20 43 3a 5c 64 6d 64 5c 73 72 63 >it at C:\dmd\src< -0001260 5c 70 68 6f 62 6f 73 5c 73 74 64 5c 73 74 72 65 >\phobos\std\stre< -0001300 61 6d 2e 64 28 32 39 32 34 29 0a 20 20 20 20 20 >am.d(2924). < -0001320 20 20 20 69 66 20 28 21 73 74 64 2e 63 74 79 70 > if (!std.ctyp< -0001340 65 2e 69 73 64 69 67 69 74 28 63 29 29 20 7b 0a >e.isdigit(c)) {.< -0001360 20 20 20 20 20 20 20 20 20 20 20 20 69 66 20 28 > if (< -0001400 21 72 65 74 29 0a 20 20 20 20 20 20 20 20 20 20 >!ret). < -0001420 20 20 20 20 20 20 72 65 74 20 3d 20 6c 69 6e 65 > ret = line< -0001440 5b 30 2e 2e 69 5d 3b 20 20 20 20 0a 20 20 20 20 >[0..i]; . < -0001460 20 20 20 20 7d 20 20 20 20 0a 20 20 20 20 20 20 > } . < -0001500 20 20 65 6c 73 65 20 69 66 20 28 72 65 74 29 0a > else if (ret).< -0001520 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 20 > ret < -0001540 7e 3d 20 63 3b 20 20 20 20 0a 20 20 20 20 7d 20 >~= c; . } < -0001560 20 20 20 0a 20 20 20 20 72 65 74 75 72 6e 20 72 > . return r< -0001600 65 74 3f 72 65 74 3a 6c 69 6e 65 3b 0a 7d 0a 0a >et?ret:line;.}..< -0001620 75 6e 69 74 74 65 73 74 20 7b 0a 20 20 20 20 61 >unittest {. a< -0001640 73 73 65 72 74 28 20 73 74 72 69 70 4e 6f 6e 44 >ssert( stripNonD< -0001660 69 67 69 74 28 22 61 73 64 66 22 29 20 3d 3d 20 >igit("asdf") == < -0001700 22 22 20 20 29 3b 0a 20 20 20 20 61 73 73 65 72 >"" );. asser< -0001720 74 28 20 73 74 72 69 70 4e 6f 6e 44 69 67 69 74 >t( stripNonDigit< -0001740 28 22 5c 27 31 33 2d 3d 32 20 34 6b 6f 70 22 29 >("\'13-=2 4kop")< -0001760 20 3d 3d 20 20 22 31 33 32 34 22 20 20 29 3b 0a > == "1324" );.< -0002000 7d 0a 0a 2f 2f 2f 20 43 6f 6e 76 65 72 74 73 20 >}../// Converts < -0002020 61 20 77 6f 72 64 20 69 6e 74 6f 20 61 20 6e 75 >a word into a nu< -0002040 6d 62 65 72 2c 20 69 67 6e 6f 72 69 6e 67 20 61 >mber, ignoring a< -0002060 6c 6c 20 6e 6f 6e 20 61 6c 70 68 61 20 63 68 61 >ll non alpha cha< -0002100 72 61 63 74 65 72 73 20 20 0a 73 74 72 69 6e 67 >racters .string< -0002120 20 77 6f 72 64 54 6f 4e 75 6d 28 20 69 6e 20 73 > wordToNum( in s< -0002140 74 72 69 6e 67 20 77 6f 72 64 20 29 0a 7b 0a 2f >tring word ).{./< -0002160 2f 20 74 72 61 6e 73 6c 61 74 69 6f 6e 20 74 61 >/ translation ta< -0002200 62 6c 65 20 66 6f 72 20 74 68 65 20 74 61 73 6b >ble for the task< -0002220 20 61 74 20 68 61 6e 64 0a 63 6f 6e 73 74 20 63 > at hand.const c< -0002240 68 61 72 5b 32 35 36 5d 20 54 52 41 4e 53 4c 41 >har[256] TRANSLA< -0002260 54 45 20 3d 20 20 20 20 0a 20 20 20 20 22 20 20 >TE = . " < -0002300 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0002320 20 20 20 20 20 20 20 20 20 20 20 20 20 20 22 20 > " < -0002340 20 2f 2f 20 30 20 20 20 0a 20 20 20 20 22 20 20 > // 0 . " < -0002360 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 31 > 01< -0002400 32 33 34 35 36 37 38 39 20 20 20 20 20 20 22 20 >23456789 " < -0002420 20 2f 2f 20 33 32 20 20 20 20 20 0a 20 20 20 20 > // 32 . < -0002440 22 20 35 37 36 33 30 34 39 39 36 31 37 38 35 31 >" 57630499617851< -0002460 38 38 31 32 33 34 37 36 32 32 33 39 20 20 20 20 >881234762239 < -0002500 20 22 20 20 2f 2f 20 36 34 20 20 20 0a 20 20 20 > " // 64 . < -0002520 20 22 20 35 37 36 33 30 34 39 39 36 31 37 38 35 > " 5763049961785< -0002540 31 38 38 31 32 33 34 37 36 32 32 33 39 20 20 20 >1881234762239 < -0002560 20 20 22 0a 20 20 20 20 22 20 20 20 20 20 20 20 > ". " < -0002600 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0002620 20 20 20 20 20 20 20 20 20 22 0a 20 20 20 20 22 > ". "< -0002640 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -* -0002700 22 0a 20 20 20 20 22 20 20 20 20 20 20 20 20 20 >". " < -0002720 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0002740 20 20 20 20 20 20 20 22 20 20 20 20 0a 20 20 20 > " . < -0002760 20 22 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > " < -0003000 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0003020 20 20 22 3b 0a 20 20 20 20 73 74 72 69 6e 67 20 > ";. string < -0003040 72 65 74 3b 0a 20 20 20 20 66 6f 72 65 61 63 68 >ret;. foreach< -0003060 28 63 3b 20 63 61 73 74 28 75 62 79 74 65 5b 5d >(c; cast(ubyte[]< -0003100 29 77 6f 72 64 29 0a 20 20 20 20 20 20 20 20 69 >)word). i< -0003120 66 20 28 54 52 41 4e 53 4c 41 54 45 5b 63 5d 20 >f (TRANSLATE[c] < -0003140 21 3d 20 27 20 27 29 0a 20 20 20 20 20 20 20 20 >!= ' '). < -0003160 20 20 20 20 72 65 74 20 7e 3d 20 54 52 41 4e 53 > ret ~= TRANS< -0003200 4c 41 54 45 5b 63 5d 3b 0a 20 20 20 20 72 65 74 >LATE[c];. ret< -0003220 75 72 6e 20 72 65 74 3b 0a 7d 0a 0a 75 6e 69 74 >urn ret;.}..unit< -0003240 74 65 73 74 20 7b 0a 20 2f 2f 20 54 65 73 74 20 >test {. // Test < -0003260 77 6f 72 64 54 6f 4e 75 6d 20 75 73 69 6e 67 20 >wordToNum using < -0003300 74 68 65 20 74 61 62 6c 65 20 66 72 6f 6d 20 74 >the table from t< -0003320 68 65 20 74 61 73 6b 20 64 65 73 63 72 69 70 74 >he task descript< -0003340 69 6f 6e 2e 0a 20 61 73 73 65 72 74 28 20 22 30 >ion.. assert( "0< -0003360 31 31 31 32 32 32 33 33 33 34 34 35 35 36 36 36 >1112223334455666< -0003400 37 37 37 38 38 38 39 39 39 22 20 3d 3d 0a 20 20 >777888999" ==. < -0003420 20 77 6f 72 64 54 6f 4e 75 6d 28 22 45 20 7c 20 > wordToNum("E | < -0003440 4a 20 4e 20 51 20 7c 20 52 20 57 20 58 20 7c 20 >J N Q | R W X | < -0003460 44 20 53 20 59 20 7c 20 46 20 54 20 7c 20 41 20 >D S Y | F T | A < -0003500 4d 20 7c 20 43 20 49 20 56 20 7c 20 42 20 4b 20 >M | C I V | B K < -0003520 55 20 7c 20 4c 20 4f 20 50 20 7c 20 47 20 48 20 >U | L O P | G H < -0003540 5a 22 29 29 3b 0a 20 61 73 73 65 72 74 28 20 22 >Z"));. assert( "< -0003560 30 31 31 31 32 32 32 33 33 33 34 34 35 35 36 36 >0111222333445566< -0003600 36 37 37 37 38 38 38 39 39 39 22 20 3d 3d 20 0a >6777888999" == .< -0003620 20 20 20 77 6f 72 64 54 6f 4e 75 6d 28 22 65 20 > wordToNum("e < -0003640 7c 20 6a 20 6e 20 71 20 7c 20 72 20 77 20 78 20 >| j n q | r w x < -0003660 7c 20 64 20 73 20 79 20 7c 20 66 20 74 20 7c 20 >| d s y | f t | < -0003700 61 20 6d 20 7c 20 63 20 69 20 76 20 7c 20 62 20 >a m | c i v | b < -0003720 6b 20 75 20 7c 20 6c 20 6f 20 70 20 7c 20 67 20 >k u | l o p | g < -0003740 68 20 7a 22 29 29 3b 0a 20 61 73 73 65 72 74 28 >h z"));. assert(< -0003760 20 22 30 31 32 33 34 35 36 37 38 39 22 20 3d 3d > "0123456789" ==< -0004000 20 0a 20 20 20 77 6f 72 64 54 6f 4e 75 6d 28 22 > . wordToNum("< -0004020 30 20 7c 20 20 20 31 20 20 20 7c 20 20 20 32 20 >0 | 1 | 2 < -0004040 20 20 7c 20 20 20 33 20 20 20 7c 20 20 34 20 20 > | 3 | 4 < -0004060 7c 20 20 35 20 20 7c 20 20 20 36 20 20 20 7c 20 >| 5 | 6 | < -0004100 20 20 37 20 20 20 7c 20 20 20 38 20 20 20 7c 20 > 7 | 8 | < -0004120 20 20 39 22 29 29 3b 0a 7d 0a 0a 76 6f 69 64 20 > 9"));.}..void < -0004140 6d 61 69 6e 28 20 73 74 72 69 6e 67 5b 5d 20 61 >main( string[] a< -0004160 72 67 73 20 29 0a 7b 0a 20 20 20 20 2f 2f 20 54 >rgs ).{. // T< -0004200 68 69 73 20 61 73 73 6f 63 69 61 74 69 76 65 20 >his associative < -0004220 61 72 72 61 79 20 6d 61 70 73 20 61 20 6e 75 6d >array maps a num< -0004240 62 65 72 20 74 6f 20 61 6e 20 61 72 72 61 79 20 >ber to an array < -0004260 6f 66 20 77 6f 72 64 73 2e 20 20 20 20 0a 20 20 >of words. . < -0004300 20 20 73 74 72 69 6e 67 61 72 72 61 79 5b 73 74 > stringarray[st< -0004320 72 69 6e 67 5d 20 20 20 20 6e 75 6d 32 77 6f 72 >ring] num2wor< -0004340 64 73 3b 0a 0a 20 20 20 20 66 6f 72 65 61 63 68 >ds;.. foreach< -0004360 28 73 74 72 69 6e 67 20 77 6f 72 64 3b 20 6e 65 >(string word; ne< -0004400 77 20 42 75 66 66 65 72 65 64 46 69 6c 65 28 22 >w BufferedFile("< -0004420 64 69 63 74 69 6f 6e 61 72 79 2e 74 78 74 22 20 >dictionary.txt" < -0004440 29 20 29 0a 20 20 20 20 20 20 20 20 6e 75 6d 32 >) ). num2< -0004460 77 6f 72 64 73 5b 20 77 6f 72 64 54 6f 4e 75 6d >words[ wordToNum< -0004500 28 77 6f 72 64 29 20 5d 20 7e 3d 20 77 6f 72 64 >(word) ] ~= word< -0004520 2e 64 75 70 3b 20 20 20 20 20 20 20 20 2f 2f 20 >.dup; // < -0004540 6d 75 73 74 20 64 75 70 0a 0a 20 20 20 20 2f 2f >must dup.. //< -0004560 2f 20 46 69 6e 64 73 20 61 6c 6c 20 61 6c 74 65 >/ Finds all alte< -0004600 72 6e 61 74 69 76 65 73 20 66 6f 72 20 74 68 65 >rnatives for the< -0004620 20 67 69 76 65 6e 20 6e 75 6d 62 65 72 0a 20 20 > given number. < -0004640 20 20 2f 2f 2f 20 28 73 68 6f 75 6c 64 20 68 61 > /// (should ha< -0004660 76 65 20 62 65 65 6e 20 73 74 72 69 70 70 65 64 >ve been stripped< -0004700 20 66 72 6f 6d 20 6e 6f 6e 2d 64 69 67 69 74 20 > from non-digit < -0004720 63 68 61 72 61 63 74 65 72 73 29 0a 20 20 20 20 >characters). < -0004740 73 74 72 69 6e 67 61 72 72 61 79 20 5f 46 69 6e >stringarray _Fin< -0004760 64 57 6f 72 64 73 28 20 73 74 72 69 6e 67 20 6e >dWords( string n< -0005000 75 6d 62 65 72 73 2c 20 62 6f 6f 6c 20 64 69 67 >umbers, bool dig< -0005020 69 74 6f 6b 20 29 0a 20 20 20 20 69 6e 20 7b 0a >itok ). in {.< -0005040 20 20 20 20 20 20 20 20 61 73 73 65 72 74 28 6e > assert(n< -0005060 75 6d 62 65 72 73 2e 6c 65 6e 67 74 68 20 3e 20 >umbers.length > < -0005100 20 30 29 3b 20 20 20 20 0a 20 20 20 20 7d 20 20 > 0); . } < -0005120 20 20 0a 20 20 20 20 6f 75 74 28 72 65 73 75 6c > . out(resul< -0005140 74 29 20 7b 0a 20 20 20 20 20 20 20 20 66 6f 72 >t) {. for< -0005160 65 61 63 68 20 28 61 3b 20 72 65 73 75 6c 74 29 >each (a; result)< -0005200 0a 20 20 20 20 20 20 20 20 20 20 20 20 61 73 73 >. ass< -0005220 65 72 74 28 20 77 6f 72 64 54 6f 4e 75 6d 28 61 >ert( wordToNum(a< -0005240 29 20 3d 3d 20 6e 75 6d 62 65 72 73 20 29 3b 0a >) == numbers );.< -0005260 20 20 20 20 7d 20 20 20 20 0a 20 20 20 20 62 6f > } . bo< -0005300 64 79 20 7b 0a 20 20 20 20 20 20 20 20 73 74 72 >dy {. str< -0005320 69 6e 67 61 72 72 61 79 20 72 65 74 3b 0a 20 20 >ingarray ret;. < -0005340 20 20 20 20 20 20 62 6f 6f 6c 20 66 6f 75 6e 64 > bool found< -0005360 77 6f 72 64 20 3d 20 66 61 6c 73 65 3b 0a 20 20 >word = false;. < -0005400 20 20 20 20 20 20 66 6f 72 20 28 75 69 6e 74 20 > for (uint < -0005420 74 3d 31 3b 20 74 3c 3d 6e 75 6d 62 65 72 73 2e >t=1; t<=numbers.< -0005440 6c 65 6e 67 74 68 3b 20 2b 2b 74 29 20 7b 0a 20 >length; ++t) {. < -0005460 20 20 20 20 20 20 20 20 20 20 20 61 75 74 6f 20 > auto < -0005500 61 6c 74 65 72 6e 61 74 69 76 65 73 20 3d 20 6e >alternatives = n< -0005520 75 6d 62 65 72 73 5b 30 2e 2e 74 5d 20 69 6e 20 >umbers[0..t] in < -0005540 6e 75 6d 32 77 6f 72 64 73 3b 0a 20 20 20 20 20 >num2words;. < -0005560 20 20 20 20 20 20 20 69 66 20 28 21 61 6c 74 65 > if (!alte< -0005600 72 6e 61 74 69 76 65 73 29 0a 20 20 20 20 20 20 >rnatives). < -0005620 20 20 20 20 20 20 20 20 20 20 63 6f 6e 74 69 6e > contin< -0005640 75 65 3b 0a 20 20 20 20 20 20 20 20 20 20 20 20 >ue;. < -0005660 66 6f 75 6e 64 77 6f 72 64 20 3d 20 74 72 75 65 >foundword = true< -0005700 3b 0a 20 20 20 20 20 20 20 20 20 20 20 20 69 66 >;. if< -0005720 20 28 6e 75 6d 62 65 72 73 2e 6c 65 6e 67 74 68 > (numbers.length< -0005740 20 3e 20 20 74 29 20 7b 0a 20 20 20 20 20 20 20 > > t) {. < -0005760 20 20 20 20 20 20 20 20 20 2f 2f 20 43 6f 6d 62 > // Comb< -0006000 69 6e 65 20 61 6c 6c 20 63 75 72 72 65 6e 74 20 >ine all current < -0006020 61 6c 74 65 72 6e 61 74 69 76 65 73 20 77 69 74 >alternatives wit< -0006040 68 20 61 6c 6c 20 61 6c 74 65 72 6e 61 74 69 76 >h all alternativ< -0006060 65 73 20 20 20 20 20 0a 20 20 20 20 20 20 20 20 >es . < -0006100 20 20 20 20 20 20 20 20 2f 2f 20 6f 66 20 74 68 > // of th< -0006120 65 20 72 65 73 74 20 28 6e 65 78 74 20 70 69 65 >e rest (next pie< -0006140 63 65 20 63 61 6e 20 73 74 61 72 74 20 77 69 74 >ce can start wit< -0006160 68 20 61 20 64 69 67 69 74 29 20 20 20 20 20 20 >h a digit) < -0006200 20 20 20 20 20 20 20 20 0a 20 20 20 20 20 20 20 > . < -0006220 20 20 20 20 20 20 20 20 20 66 6f 72 65 61 63 68 > foreach< -0006240 20 28 61 32 3b 20 5f 46 69 6e 64 57 6f 72 64 73 > (a2; _FindWords< -0006260 28 20 6e 75 6d 62 65 72 73 5b 74 2e 2e 24 5d 2c >( numbers[t..$],< -0006300 20 74 72 75 65 20 20 20 20 20 29 20 29 0a 20 20 > true ) ). < -0006320 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0006340 20 20 66 6f 72 65 61 63 68 28 61 31 3b 20 2a 61 > foreach(a1; *a< -0006360 6c 74 65 72 6e 61 74 69 76 65 73 29 0a 20 20 20 >lternatives). < -0006400 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0006420 20 20 20 20 72 65 74 20 7e 3d 20 61 31 20 7e 20 > ret ~= a1 ~ < -0006440 22 20 22 20 7e 20 61 32 3b 0a 20 20 20 20 20 20 >" " ~ a2;. < -0006460 20 20 20 20 20 20 7d 0a 20 20 20 20 20 20 20 20 > }. < -0006500 20 20 20 20 65 6c 73 65 20 20 20 20 0a 20 20 20 > else . < -0006520 20 20 20 20 20 20 20 20 20 20 20 20 20 72 65 74 > ret< -0006540 20 7e 3d 20 2a 61 6c 74 65 72 6e 61 74 69 76 65 > ~= *alternative< -0006560 73 3b 20 20 20 20 2f 2f 20 61 70 70 65 6e 64 20 >s; // append < -0006600 74 68 65 73 65 20 61 6c 74 65 72 6e 61 74 69 76 >these alternativ< -0006620 65 73 0a 20 20 20 20 20 20 20 20 7d 0a 20 20 20 >es. }. < -0006640 20 20 20 20 20 2f 2f 20 54 72 79 20 74 6f 20 6b > // Try to k< -0006660 65 65 70 20 31 20 64 69 67 69 74 2c 20 6f 6e 6c >eep 1 digit, onl< -0006700 79 20 69 66 20 77 65 27 72 65 20 61 6c 6c 6f 77 >y if we're allow< -0006720 65 64 20 61 6e 64 20 6e 6f 20 6f 74 68 65 72 0a >ed and no other.< -0006740 20 20 20 20 20 20 20 20 2f 2f 20 61 6c 74 65 72 > // alter< -0006760 6e 61 74 69 76 65 73 20 77 65 72 65 20 66 6f 75 >natives were fou< -0007000 6e 64 0a 20 20 20 20 20 20 20 20 2f 2f 20 54 65 >nd. // Te< -0007020 73 74 69 6e 67 20 22 72 65 74 2e 6c 65 6e 67 74 >sting "ret.lengt< -0007040 68 22 20 6d 61 6b 65 73 20 6d 6f 72 65 20 73 65 >h" makes more se< -0007060 6e 73 65 20 74 68 61 6e 20 74 65 73 74 69 6e 67 >nse than testing< -0007100 20 22 66 6f 75 6e 64 77 6f 72 64 22 2c 0a 20 20 > "foundword",. < -0007120 20 20 20 20 20 20 2f 2f 20 62 75 74 20 74 68 65 > // but the< -0007140 20 6f 74 68 65 72 20 69 6d 70 6c 65 6d 65 6e 74 > other implement< -0007160 61 74 69 6f 6e 73 20 73 65 65 6d 20 74 6f 20 64 >ations seem to d< -0007200 6f 20 6a 75 73 74 20 74 68 69 73 2e 0a 20 20 20 >o just this.. < -0007220 20 20 20 20 20 69 66 20 28 64 69 67 69 74 6f 6b > if (digitok< -0007240 20 26 26 20 21 66 6f 75 6e 64 77 6f 72 64 29 20 > && !foundword) < -0007260 7b 20 2f 2f 72 65 74 2e 6c 65 6e 67 74 68 20 3d >{ //ret.length =< -0007300 3d 20 30 20 20 0a 20 20 20 20 20 20 20 20 20 20 >= 0 . < -0007320 20 20 69 66 28 6e 75 6d 62 65 72 73 2e 6c 65 6e > if(numbers.len< -0007340 67 74 68 20 3e 20 20 31 29 20 7b 0a 20 20 20 20 >gth > 1) {. < -0007360 20 20 20 20 20 20 20 20 20 20 20 20 2f 2f 20 43 > // C< -0007400 6f 6d 62 69 6e 65 20 31 20 64 69 67 69 74 20 77 >ombine 1 digit w< -0007420 69 74 68 20 61 6c 6c 20 61 6c 74 65 6e 61 74 69 >ith all altenati< -0007440 76 65 73 20 66 72 6f 6d 20 74 68 65 20 72 65 73 >ves from the res< -0007460 74 20 20 20 20 0a 20 20 20 20 20 20 20 20 20 20 >t . < -0007500 20 20 20 20 20 20 2f 2f 20 28 6e 65 78 74 20 70 > // (next p< -0007520 69 65 63 65 20 63 61 6e 20 6e 6f 74 20 73 74 61 >iece can not sta< -0007540 72 74 20 77 69 74 68 20 61 20 64 69 67 69 74 29 >rt with a digit)< -0007560 20 20 20 20 20 20 20 20 20 20 0a 20 20 20 20 20 > . < -0007600 20 20 20 20 20 20 20 20 20 20 20 66 6f 72 65 61 > forea< -0007620 63 68 20 28 61 3b 20 5f 46 69 6e 64 57 6f 72 64 >ch (a; _FindWord< -0007640 73 28 20 6e 75 6d 62 65 72 73 5b 31 2e 2e 24 5d >s( numbers[1..$]< -0007660 2c 20 66 61 6c 73 65 20 29 20 29 0a 20 20 20 20 >, false ) ). < -0007700 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 > < -0007720 72 65 74 20 7e 3d 20 6e 75 6d 62 65 72 73 5b 30 >ret ~= numbers[0< -0007740 2e 2e 31 5d 20 7e 20 22 20 22 20 7e 20 61 3b 0a >..1] ~ " " ~ a;.< -0007760 20 20 20 20 20 20 20 20 20 20 20 20 7d 20 20 20 > } < -0010000 20 0a 20 20 20 20 20 20 20 20 20 20 20 20 65 6c > . el< -0010020 73 65 20 20 20 20 0a 20 20 20 20 20 20 20 20 20 >se . < -0010040 20 20 20 20 20 20 20 72 65 74 20 7e 3d 20 6e 75 > ret ~= nu< -0010060 6d 62 65 72 73 5b 30 2e 2e 31 5d 3b 20 20 20 20 >mbers[0..1]; < -0010100 2f 2f 20 6a 75 73 74 20 61 70 70 65 6e 64 20 74 >// just append t< -0010120 68 69 73 20 64 69 67 69 74 20 20 20 20 20 20 20 >his digit < -0010140 20 20 20 20 20 20 0a 20 20 20 20 20 20 20 20 7d > . }< -0010160 20 20 20 20 0a 20 20 20 20 20 20 20 20 72 65 74 > . ret< -0010200 75 72 6e 20 72 65 74 3b 0a 20 20 20 20 7d 0a 0a >urn ret;. }..< -0010220 20 20 20 20 2f 2f 2f 20 28 54 68 69 73 20 66 75 > /// (This fu< -0010240 6e 63 74 69 6f 6e 20 77 61 73 20 69 6e 6c 69 6e >nction was inlin< -0010260 65 64 20 69 6e 20 74 68 65 20 6f 72 69 67 69 6e >ed in the origin< -0010300 61 6c 20 70 72 6f 67 72 61 6d 29 20 0a 20 20 20 >al program) . < -0010320 20 2f 2f 2f 20 46 69 6e 64 73 20 61 6c 6c 20 61 > /// Finds all a< -0010340 6c 74 65 72 6e 61 74 69 76 65 73 20 66 6f 72 20 >lternatives for < -0010360 74 68 65 20 67 69 76 65 6e 20 70 68 6f 6e 65 20 >the given phone < -0010400 6e 75 6d 62 65 72 20 0a 20 20 20 20 2f 2f 2f 20 >number . /// < -0010420 52 65 74 75 72 6e 73 3a 20 61 72 72 61 79 20 6f >Returns: array o< -0010440 66 20 73 74 72 69 6e 67 73 20 0a 20 20 20 20 73 >f strings . s< -0010460 74 72 69 6e 67 61 72 72 61 79 20 46 69 6e 64 57 >tringarray FindW< -0010500 6f 72 64 73 28 20 73 74 72 69 6e 67 20 70 68 6f >ords( string pho< -0010520 6e 65 5f 6e 75 6d 62 65 72 20 29 0a 20 20 20 20 >ne_number ). < -0010540 7b 0a 20 20 20 20 20 20 20 20 69 66 20 28 21 70 >{. if (!p< -0010560 68 6f 6e 65 5f 6e 75 6d 62 65 72 2e 6c 65 6e 67 >hone_number.leng< -0010600 74 68 29 0a 20 20 20 20 20 20 20 20 20 20 20 20 >th). < -0010620 72 65 74 75 72 6e 20 6e 75 6c 6c 3b 0a 20 20 20 >return null;. < -0010640 20 20 20 20 20 2f 2f 20 53 74 72 69 70 20 74 68 > // Strip th< -0010660 65 20 6e 6f 6e 2d 64 69 67 69 74 20 63 68 61 72 >e non-digit char< -0010700 61 63 74 65 72 73 20 66 72 6f 6d 20 74 68 65 20 >acters from the < -0010720 70 68 6f 6e 65 20 6e 75 6d 62 65 72 2c 20 61 6e >phone number, an< -0010740 64 0a 20 20 20 20 20 20 20 20 2f 2f 20 70 61 73 >d. // pas< -0010760 73 20 69 74 20 74 6f 20 74 68 65 20 72 65 63 75 >s it to the recu< -0011000 72 73 69 76 65 20 66 75 6e 63 74 69 6f 6e 20 28 >rsive function (< -0011020 6c 65 61 64 69 6e 67 20 64 69 67 69 74 20 69 73 >leading digit is< -0011040 20 61 6c 6c 6f 77 65 64 29 0a 20 20 20 20 20 20 > allowed). < -0011060 20 20 72 65 74 75 72 6e 20 5f 46 69 6e 64 57 6f > return _FindWo< -0011100 72 64 73 28 20 73 74 72 69 70 4e 6f 6e 44 69 67 >rds( stripNonDig< -0011120 69 74 28 70 68 6f 6e 65 5f 6e 75 6d 62 65 72 29 >it(phone_number)< -0011140 2c 20 74 72 75 65 20 29 3b 20 20 20 20 0a 20 20 >, true ); . < -0011160 20 20 7d 20 20 20 20 0a 20 20 20 20 0a 20 20 20 > } . . < -0011200 20 2f 2f 20 52 65 61 64 20 74 68 65 20 70 68 6f > // Read the pho< -0011220 6e 65 20 6e 75 6d 62 65 72 73 20 20 20 20 20 0a >ne numbers .< -0011240 20 20 20 20 66 6f 72 65 61 63 68 28 73 74 72 69 > foreach(stri< -0011260 6e 67 20 70 68 6f 6e 65 3b 20 6e 65 77 20 42 75 >ng phone; new Bu< -0011300 66 66 65 72 65 64 46 69 6c 65 28 22 69 6e 70 75 >fferedFile("inpu< -0011320 74 2e 74 78 74 22 20 20 20 29 20 29 0a 20 20 20 >t.txt" ) ). < -0011340 20 20 20 20 20 66 6f 72 65 61 63 68 28 61 6c 74 > foreach(alt< -0011360 65 72 6e 61 74 69 76 65 3b 20 46 69 6e 64 57 6f >ernative; FindWo< -0011400 72 64 73 28 20 70 68 6f 6e 65 20 29 20 29 0a 20 >rds( phone ) ). < -0011420 20 20 20 20 20 20 20 20 20 20 20 77 72 69 74 65 > write< -0011440 66 6c 6e 28 70 68 6f 6e 65 2c 20 22 3a 20 22 2c >fln(phone, ": ",< -0011460 20 61 6c 74 65 72 6e 61 74 69 76 65 20 29 3b 0a > alternative );.< -0011500 7d 0a 0a >}..< -0011503 diff --git a/third_party/pygments/tests/examplefiles/hexdump_xxd b/third_party/pygments/tests/examplefiles/hexdump_xxd deleted file mode 100644 index 33a8a6e1d..000000000 --- a/third_party/pygments/tests/examplefiles/hexdump_xxd +++ /dev/null @@ -1,309 +0,0 @@ -0000000: 2f2f 2043 7265 6174 6564 2062 7920 4c69 // Created by Li -0000010: 6f6e 656c 6c6f 204c 756e 6573 7520 616e onello Lunesu an -0000020: 6420 706c 6163 6564 2069 6e20 7468 6520 d placed in the -0000030: 7075 626c 6963 2064 6f6d 6169 6e2e 0a2f public domain../ -0000040: 2f20 5468 6973 2066 696c 6520 6861 7320 / This file has -0000050: 6265 656e 206d 6f64 6966 6965 6420 6672 been modified fr -0000060: 6f6d 2069 7473 206f 7269 6769 6e61 6c20 om its original -0000070: 7665 7273 696f 6e2e 0a2f 2f20 4974 2068 version..// It h -0000080: 6173 2062 6565 6e20 666f 726d 6174 7465 as been formatte -0000090: 6420 746f 2066 6974 2079 6f75 7220 7363 d to fit your sc -00000a0: 7265 656e 2e0a 6d6f 6475 6c65 2070 686f reen..module pho -00000b0: 6e65 6e6f 3b20 2020 2020 2f2f 206f 7074 neno; // opt -00000c0: 696f 6e61 6c0a 696d 706f 7274 2073 7464 ional.import std -00000d0: 2e73 7464 696f 3b20 2020 2f2f 2077 7269 .stdio; // wri -00000e0: 7465 666c 6e20 2020 2020 0a69 6d70 6f72 tefln .impor -00000f0: 7420 7374 642e 6374 7970 653b 2020 202f t std.ctype; / -0000100: 2f20 6973 6469 6769 7420 2020 2020 0a69 / isdigit .i -0000110: 6d70 6f72 7420 7374 642e 7374 7265 616d mport std.stream -0000120: 3b20 202f 2f20 4275 6666 6572 6564 4669 ; // BufferedFi -0000130: 6c65 0a0a 2f2f 204a 7573 7420 666f 7220 le..// Just for -0000140: 7265 6164 6162 696c 6974 7920 2869 6d61 readability (ima -0000150: 6769 6e65 2063 6861 725b 5d5b 5d5b 6368 gine char[][][ch -0000160: 6172 5b5d 5d29 2020 2020 0a61 6c69 6173 ar[]]) .alias -0000170: 2063 6861 725b 5d20 7374 7269 6e67 3b0a char[] string;. -0000180: 616c 6961 7320 7374 7269 6e67 5b5d 2073 alias string[] s -0000190: 7472 696e 6761 7272 6179 3b0a 0a2f 2f2f tringarray;../// -00001a0: 2053 7472 6970 7320 6e6f 6e2d 6469 6769 Strips non-digi -00001b0: 7420 6368 6172 6163 7465 7273 2066 726f t characters fro -00001c0: 6d20 7468 6520 7374 7269 6e67 2028 434f m the string (CO -00001d0: 5729 0a73 7472 696e 6720 7374 7269 704e W).string stripN -00001e0: 6f6e 4469 6769 7428 2069 6e20 7374 7269 onDigit( in stri -00001f0: 6e67 206c 696e 6520 2920 0a7b 0a20 2020 ng line ) .{. -0000200: 2073 7472 696e 6720 7265 743b 0a20 2020 string ret;. -0000210: 2066 6f72 6561 6368 2875 696e 7420 692c foreach(uint i, -0000220: 2063 3b20 6c69 6e65 2920 7b0a 2020 2020 c; line) {. -0000230: 2020 2020 2f2f 2045 7272 6f72 3a20 7374 // Error: st -0000240: 642e 6374 7970 652e 6973 6469 6769 7420 d.ctype.isdigit -0000250: 6174 2043 3a5c 646d 645c 7372 635c 7068 at C:\dmd\src\ph -0000260: 6f62 6f73 5c73 7464 5c63 7479 7065 2e64 obos\std\ctype.d -0000270: 2833 3729 200a 2020 2020 2020 2020 2f2f (37) . // -0000280: 2063 6f6e 666c 6963 7473 2077 6974 6820 conflicts with -0000290: 7374 642e 7374 7265 616d 2e69 7364 6967 std.stream.isdig -00002a0: 6974 2061 7420 433a 5c64 6d64 5c73 7263 it at C:\dmd\src -00002b0: 5c70 686f 626f 735c 7374 645c 7374 7265 \phobos\std\stre -00002c0: 616d 2e64 2832 3932 3429 0a20 2020 2020 am.d(2924). -00002d0: 2020 2069 6620 2821 7374 642e 6374 7970 if (!std.ctyp -00002e0: 652e 6973 6469 6769 7428 6329 2920 7b0a e.isdigit(c)) {. -00002f0: 2020 2020 2020 2020 2020 2020 6966 2028 if ( -0000300: 2172 6574 290a 2020 2020 2020 2020 2020 !ret). -0000310: 2020 2020 2020 7265 7420 3d20 6c69 6e65 ret = line -0000320: 5b30 2e2e 695d 3b20 2020 200a 2020 2020 [0..i]; . -0000330: 2020 2020 7d20 2020 200a 2020 2020 2020 } . -0000340: 2020 656c 7365 2069 6620 2872 6574 290a else if (ret). -0000350: 2020 2020 2020 2020 2020 2020 7265 7420 ret -0000360: 7e3d 2063 3b20 2020 200a 2020 2020 7d20 ~= c; . } -0000370: 2020 200a 2020 2020 7265 7475 726e 2072 . return r -0000380: 6574 3f72 6574 3a6c 696e 653b 0a7d 0a0a et?ret:line;.}.. -0000390: 756e 6974 7465 7374 207b 0a20 2020 2061 unittest {. a -00003a0: 7373 6572 7428 2073 7472 6970 4e6f 6e44 ssert( stripNonD -00003b0: 6967 6974 2822 6173 6466 2229 203d 3d20 igit("asdf") == -00003c0: 2222 2020 293b 0a20 2020 2061 7373 6572 "" );. asser -00003d0: 7428 2073 7472 6970 4e6f 6e44 6967 6974 t( stripNonDigit -00003e0: 2822 5c27 3133 2d3d 3220 346b 6f70 2229 ("\'13-=2 4kop") -00003f0: 203d 3d20 2022 3133 3234 2220 2029 3b0a == "1324" );. -0000400: 7d0a 0a2f 2f2f 2043 6f6e 7665 7274 7320 }../// Converts -0000410: 6120 776f 7264 2069 6e74 6f20 6120 6e75 a word into a nu -0000420: 6d62 6572 2c20 6967 6e6f 7269 6e67 2061 mber, ignoring a -0000430: 6c6c 206e 6f6e 2061 6c70 6861 2063 6861 ll non alpha cha -0000440: 7261 6374 6572 7320 200a 7374 7269 6e67 racters .string -0000450: 2077 6f72 6454 6f4e 756d 2820 696e 2073 wordToNum( in s -0000460: 7472 696e 6720 776f 7264 2029 0a7b 0a2f tring word ).{./ -0000470: 2f20 7472 616e 736c 6174 696f 6e20 7461 / translation ta -0000480: 626c 6520 666f 7220 7468 6520 7461 736b ble for the task -0000490: 2061 7420 6861 6e64 0a63 6f6e 7374 2063 at hand.const c -00004a0: 6861 725b 3235 365d 2054 5241 4e53 4c41 har[256] TRANSLA -00004b0: 5445 203d 2020 2020 0a20 2020 2022 2020 TE = . " -00004c0: 2020 2020 2020 2020 2020 2020 2020 2020 -00004d0: 2020 2020 2020 2020 2020 2020 2020 2220 " -00004e0: 202f 2f20 3020 2020 0a20 2020 2022 2020 // 0 . " -00004f0: 2020 2020 2020 2020 2020 2020 2020 3031 01 -0000500: 3233 3435 3637 3839 2020 2020 2020 2220 23456789 " -0000510: 202f 2f20 3332 2020 2020 200a 2020 2020 // 32 . -0000520: 2220 3537 3633 3034 3939 3631 3738 3531 " 57630499617851 -0000530: 3838 3132 3334 3736 3232 3339 2020 2020 881234762239 -0000540: 2022 2020 2f2f 2036 3420 2020 0a20 2020 " // 64 . -0000550: 2022 2035 3736 3330 3439 3936 3137 3835 " 5763049961785 -0000560: 3138 3831 3233 3437 3632 3233 3920 2020 1881234762239 -0000570: 2020 220a 2020 2020 2220 2020 2020 2020 ". " -0000580: 2020 2020 2020 2020 2020 2020 2020 2020 -0000590: 2020 2020 2020 2020 2022 0a20 2020 2022 ". " -00005a0: 2020 2020 2020 2020 2020 2020 2020 2020 -00005b0: 2020 2020 2020 2020 2020 2020 2020 2020 -00005c0: 220a 2020 2020 2220 2020 2020 2020 2020 ". " -00005d0: 2020 2020 2020 2020 2020 2020 2020 2020 -00005e0: 2020 2020 2020 2022 2020 2020 0a20 2020 " . -00005f0: 2022 2020 2020 2020 2020 2020 2020 2020 " -0000600: 2020 2020 2020 2020 2020 2020 2020 2020 -0000610: 2020 223b 0a20 2020 2073 7472 696e 6720 ";. string -0000620: 7265 743b 0a20 2020 2066 6f72 6561 6368 ret;. foreach -0000630: 2863 3b20 6361 7374 2875 6279 7465 5b5d (c; cast(ubyte[] -0000640: 2977 6f72 6429 0a20 2020 2020 2020 2069 )word). i -0000650: 6620 2854 5241 4e53 4c41 5445 5b63 5d20 f (TRANSLATE[c] -0000660: 213d 2027 2027 290a 2020 2020 2020 2020 != ' '). -0000670: 2020 2020 7265 7420 7e3d 2054 5241 4e53 ret ~= TRANS -0000680: 4c41 5445 5b63 5d3b 0a20 2020 2072 6574 LATE[c];. ret -0000690: 7572 6e20 7265 743b 0a7d 0a0a 756e 6974 urn ret;.}..unit -00006a0: 7465 7374 207b 0a20 2f2f 2054 6573 7420 test {. // Test -00006b0: 776f 7264 546f 4e75 6d20 7573 696e 6720 wordToNum using -00006c0: 7468 6520 7461 626c 6520 6672 6f6d 2074 the table from t -00006d0: 6865 2074 6173 6b20 6465 7363 7269 7074 he task descript -00006e0: 696f 6e2e 0a20 6173 7365 7274 2820 2230 ion.. assert( "0 -00006f0: 3131 3132 3232 3333 3334 3435 3536 3636 1112223334455666 -0000700: 3737 3738 3838 3939 3922 203d 3d0a 2020 777888999" ==. -0000710: 2077 6f72 6454 6f4e 756d 2822 4520 7c20 wordToNum("E | -0000720: 4a20 4e20 5120 7c20 5220 5720 5820 7c20 J N Q | R W X | -0000730: 4420 5320 5920 7c20 4620 5420 7c20 4120 D S Y | F T | A -0000740: 4d20 7c20 4320 4920 5620 7c20 4220 4b20 M | C I V | B K -0000750: 5520 7c20 4c20 4f20 5020 7c20 4720 4820 U | L O P | G H -0000760: 5a22 2929 3b0a 2061 7373 6572 7428 2022 Z"));. assert( " -0000770: 3031 3131 3232 3233 3333 3434 3535 3636 0111222333445566 -0000780: 3637 3737 3838 3839 3939 2220 3d3d 200a 6777888999" == . -0000790: 2020 2077 6f72 6454 6f4e 756d 2822 6520 wordToNum("e -00007a0: 7c20 6a20 6e20 7120 7c20 7220 7720 7820 | j n q | r w x -00007b0: 7c20 6420 7320 7920 7c20 6620 7420 7c20 | d s y | f t | -00007c0: 6120 6d20 7c20 6320 6920 7620 7c20 6220 a m | c i v | b -00007d0: 6b20 7520 7c20 6c20 6f20 7020 7c20 6720 k u | l o p | g -00007e0: 6820 7a22 2929 3b0a 2061 7373 6572 7428 h z"));. assert( -00007f0: 2022 3031 3233 3435 3637 3839 2220 3d3d "0123456789" == -0000800: 200a 2020 2077 6f72 6454 6f4e 756d 2822 . wordToNum(" -0000810: 3020 7c20 2020 3120 2020 7c20 2020 3220 0 | 1 | 2 -0000820: 2020 7c20 2020 3320 2020 7c20 2034 2020 | 3 | 4 -0000830: 7c20 2035 2020 7c20 2020 3620 2020 7c20 | 5 | 6 | -0000840: 2020 3720 2020 7c20 2020 3820 2020 7c20 7 | 8 | -0000850: 2020 3922 2929 3b0a 7d0a 0a76 6f69 6420 9"));.}..void -0000860: 6d61 696e 2820 7374 7269 6e67 5b5d 2061 main( string[] a -0000870: 7267 7320 290a 7b0a 2020 2020 2f2f 2054 rgs ).{. // T -0000880: 6869 7320 6173 736f 6369 6174 6976 6520 his associative -0000890: 6172 7261 7920 6d61 7073 2061 206e 756d array maps a num -00008a0: 6265 7220 746f 2061 6e20 6172 7261 7920 ber to an array -00008b0: 6f66 2077 6f72 6473 2e20 2020 200a 2020 of words. . -00008c0: 2020 7374 7269 6e67 6172 7261 795b 7374 stringarray[st -00008d0: 7269 6e67 5d20 2020 206e 756d 3277 6f72 ring] num2wor -00008e0: 6473 3b0a 0a20 2020 2066 6f72 6561 6368 ds;.. foreach -00008f0: 2873 7472 696e 6720 776f 7264 3b20 6e65 (string word; ne -0000900: 7720 4275 6666 6572 6564 4669 6c65 2822 w BufferedFile(" -0000910: 6469 6374 696f 6e61 7279 2e74 7874 2220 dictionary.txt" -0000920: 2920 290a 2020 2020 2020 2020 6e75 6d32 ) ). num2 -0000930: 776f 7264 735b 2077 6f72 6454 6f4e 756d words[ wordToNum -0000940: 2877 6f72 6429 205d 207e 3d20 776f 7264 (word) ] ~= word -0000950: 2e64 7570 3b20 2020 2020 2020 202f 2f20 .dup; // -0000960: 6d75 7374 2064 7570 0a0a 2020 2020 2f2f must dup.. // -0000970: 2f20 4669 6e64 7320 616c 6c20 616c 7465 / Finds all alte -0000980: 726e 6174 6976 6573 2066 6f72 2074 6865 rnatives for the -0000990: 2067 6976 656e 206e 756d 6265 720a 2020 given number. -00009a0: 2020 2f2f 2f20 2873 686f 756c 6420 6861 /// (should ha -00009b0: 7665 2062 6565 6e20 7374 7269 7070 6564 ve been stripped -00009c0: 2066 726f 6d20 6e6f 6e2d 6469 6769 7420 from non-digit -00009d0: 6368 6172 6163 7465 7273 290a 2020 2020 characters). -00009e0: 7374 7269 6e67 6172 7261 7920 5f46 696e stringarray _Fin -00009f0: 6457 6f72 6473 2820 7374 7269 6e67 206e dWords( string n -0000a00: 756d 6265 7273 2c20 626f 6f6c 2064 6967 umbers, bool dig -0000a10: 6974 6f6b 2029 0a20 2020 2069 6e20 7b0a itok ). in {. -0000a20: 2020 2020 2020 2020 6173 7365 7274 286e assert(n -0000a30: 756d 6265 7273 2e6c 656e 6774 6820 3e20 umbers.length > -0000a40: 2030 293b 2020 2020 0a20 2020 207d 2020 0); . } -0000a50: 2020 0a20 2020 206f 7574 2872 6573 756c . out(resul -0000a60: 7429 207b 0a20 2020 2020 2020 2066 6f72 t) {. for -0000a70: 6561 6368 2028 613b 2072 6573 756c 7429 each (a; result) -0000a80: 0a20 2020 2020 2020 2020 2020 2061 7373 . ass -0000a90: 6572 7428 2077 6f72 6454 6f4e 756d 2861 ert( wordToNum(a -0000aa0: 2920 3d3d 206e 756d 6265 7273 2029 3b0a ) == numbers );. -0000ab0: 2020 2020 7d20 2020 200a 2020 2020 626f } . bo -0000ac0: 6479 207b 0a20 2020 2020 2020 2073 7472 dy {. str -0000ad0: 696e 6761 7272 6179 2072 6574 3b0a 2020 ingarray ret;. -0000ae0: 2020 2020 2020 626f 6f6c 2066 6f75 6e64 bool found -0000af0: 776f 7264 203d 2066 616c 7365 3b0a 2020 word = false;. -0000b00: 2020 2020 2020 666f 7220 2875 696e 7420 for (uint -0000b10: 743d 313b 2074 3c3d 6e75 6d62 6572 732e t=1; t<=numbers. -0000b20: 6c65 6e67 7468 3b20 2b2b 7429 207b 0a20 length; ++t) {. -0000b30: 2020 2020 2020 2020 2020 2061 7574 6f20 auto -0000b40: 616c 7465 726e 6174 6976 6573 203d 206e alternatives = n -0000b50: 756d 6265 7273 5b30 2e2e 745d 2069 6e20 umbers[0..t] in -0000b60: 6e75 6d32 776f 7264 733b 0a20 2020 2020 num2words;. -0000b70: 2020 2020 2020 2069 6620 2821 616c 7465 if (!alte -0000b80: 726e 6174 6976 6573 290a 2020 2020 2020 rnatives). -0000b90: 2020 2020 2020 2020 2020 636f 6e74 696e contin -0000ba0: 7565 3b0a 2020 2020 2020 2020 2020 2020 ue;. -0000bb0: 666f 756e 6477 6f72 6420 3d20 7472 7565 foundword = true -0000bc0: 3b0a 2020 2020 2020 2020 2020 2020 6966 ;. if -0000bd0: 2028 6e75 6d62 6572 732e 6c65 6e67 7468 (numbers.length -0000be0: 203e 2020 7429 207b 0a20 2020 2020 2020 > t) {. -0000bf0: 2020 2020 2020 2020 202f 2f20 436f 6d62 // Comb -0000c00: 696e 6520 616c 6c20 6375 7272 656e 7420 ine all current -0000c10: 616c 7465 726e 6174 6976 6573 2077 6974 alternatives wit -0000c20: 6820 616c 6c20 616c 7465 726e 6174 6976 h all alternativ -0000c30: 6573 2020 2020 200a 2020 2020 2020 2020 es . -0000c40: 2020 2020 2020 2020 2f2f 206f 6620 7468 // of th -0000c50: 6520 7265 7374 2028 6e65 7874 2070 6965 e rest (next pie -0000c60: 6365 2063 616e 2073 7461 7274 2077 6974 ce can start wit -0000c70: 6820 6120 6469 6769 7429 2020 2020 2020 h a digit) -0000c80: 2020 2020 2020 2020 0a20 2020 2020 2020 . -0000c90: 2020 2020 2020 2020 2066 6f72 6561 6368 foreach -0000ca0: 2028 6132 3b20 5f46 696e 6457 6f72 6473 (a2; _FindWords -0000cb0: 2820 6e75 6d62 6572 735b 742e 2e24 5d2c ( numbers[t..$], -0000cc0: 2074 7275 6520 2020 2020 2920 290a 2020 true ) ). -0000cd0: 2020 2020 2020 2020 2020 2020 2020 2020 -0000ce0: 2020 666f 7265 6163 6828 6131 3b20 2a61 foreach(a1; *a -0000cf0: 6c74 6572 6e61 7469 7665 7329 0a20 2020 lternatives). -0000d00: 2020 2020 2020 2020 2020 2020 2020 2020 -0000d10: 2020 2020 7265 7420 7e3d 2061 3120 7e20 ret ~= a1 ~ -0000d20: 2220 2220 7e20 6132 3b0a 2020 2020 2020 " " ~ a2;. -0000d30: 2020 2020 2020 7d0a 2020 2020 2020 2020 }. -0000d40: 2020 2020 656c 7365 2020 2020 0a20 2020 else . -0000d50: 2020 2020 2020 2020 2020 2020 2072 6574 ret -0000d60: 207e 3d20 2a61 6c74 6572 6e61 7469 7665 ~= *alternative -0000d70: 733b 2020 2020 2f2f 2061 7070 656e 6420 s; // append -0000d80: 7468 6573 6520 616c 7465 726e 6174 6976 these alternativ -0000d90: 6573 0a20 2020 2020 2020 207d 0a20 2020 es. }. -0000da0: 2020 2020 202f 2f20 5472 7920 746f 206b // Try to k -0000db0: 6565 7020 3120 6469 6769 742c 206f 6e6c eep 1 digit, onl -0000dc0: 7920 6966 2077 6527 7265 2061 6c6c 6f77 y if we're allow -0000dd0: 6564 2061 6e64 206e 6f20 6f74 6865 720a ed and no other. -0000de0: 2020 2020 2020 2020 2f2f 2061 6c74 6572 // alter -0000df0: 6e61 7469 7665 7320 7765 7265 2066 6f75 natives were fou -0000e00: 6e64 0a20 2020 2020 2020 202f 2f20 5465 nd. // Te -0000e10: 7374 696e 6720 2272 6574 2e6c 656e 6774 sting "ret.lengt -0000e20: 6822 206d 616b 6573 206d 6f72 6520 7365 h" makes more se -0000e30: 6e73 6520 7468 616e 2074 6573 7469 6e67 nse than testing -0000e40: 2022 666f 756e 6477 6f72 6422 2c0a 2020 "foundword",. -0000e50: 2020 2020 2020 2f2f 2062 7574 2074 6865 // but the -0000e60: 206f 7468 6572 2069 6d70 6c65 6d65 6e74 other implement -0000e70: 6174 696f 6e73 2073 6565 6d20 746f 2064 ations seem to d -0000e80: 6f20 6a75 7374 2074 6869 732e 0a20 2020 o just this.. -0000e90: 2020 2020 2069 6620 2864 6967 6974 6f6b if (digitok -0000ea0: 2026 2620 2166 6f75 6e64 776f 7264 2920 && !foundword) -0000eb0: 7b20 2f2f 7265 742e 6c65 6e67 7468 203d { //ret.length = -0000ec0: 3d20 3020 200a 2020 2020 2020 2020 2020 = 0 . -0000ed0: 2020 6966 286e 756d 6265 7273 2e6c 656e if(numbers.len -0000ee0: 6774 6820 3e20 2031 2920 7b0a 2020 2020 gth > 1) {. -0000ef0: 2020 2020 2020 2020 2020 2020 2f2f 2043 // C -0000f00: 6f6d 6269 6e65 2031 2064 6967 6974 2077 ombine 1 digit w -0000f10: 6974 6820 616c 6c20 616c 7465 6e61 7469 ith all altenati -0000f20: 7665 7320 6672 6f6d 2074 6865 2072 6573 ves from the res -0000f30: 7420 2020 200a 2020 2020 2020 2020 2020 t . -0000f40: 2020 2020 2020 2f2f 2028 6e65 7874 2070 // (next p -0000f50: 6965 6365 2063 616e 206e 6f74 2073 7461 iece can not sta -0000f60: 7274 2077 6974 6820 6120 6469 6769 7429 rt with a digit) -0000f70: 2020 2020 2020 2020 2020 0a20 2020 2020 . -0000f80: 2020 2020 2020 2020 2020 2066 6f72 6561 forea -0000f90: 6368 2028 613b 205f 4669 6e64 576f 7264 ch (a; _FindWord -0000fa0: 7328 206e 756d 6265 7273 5b31 2e2e 245d s( numbers[1..$] -0000fb0: 2c20 6661 6c73 6520 2920 290a 2020 2020 , false ) ). -0000fc0: 2020 2020 2020 2020 2020 2020 2020 2020 -0000fd0: 7265 7420 7e3d 206e 756d 6265 7273 5b30 ret ~= numbers[0 -0000fe0: 2e2e 315d 207e 2022 2022 207e 2061 3b0a ..1] ~ " " ~ a;. -0000ff0: 2020 2020 2020 2020 2020 2020 7d20 2020 } -0001000: 200a 2020 2020 2020 2020 2020 2020 656c . el -0001010: 7365 2020 2020 0a20 2020 2020 2020 2020 se . -0001020: 2020 2020 2020 2072 6574 207e 3d20 6e75 ret ~= nu -0001030: 6d62 6572 735b 302e 2e31 5d3b 2020 2020 mbers[0..1]; -0001040: 2f2f 206a 7573 7420 6170 7065 6e64 2074 // just append t -0001050: 6869 7320 6469 6769 7420 2020 2020 2020 his digit -0001060: 2020 2020 2020 0a20 2020 2020 2020 207d . } -0001070: 2020 2020 0a20 2020 2020 2020 2072 6574 . ret -0001080: 7572 6e20 7265 743b 0a20 2020 207d 0a0a urn ret;. }.. -0001090: 2020 2020 2f2f 2f20 2854 6869 7320 6675 /// (This fu -00010a0: 6e63 7469 6f6e 2077 6173 2069 6e6c 696e nction was inlin -00010b0: 6564 2069 6e20 7468 6520 6f72 6967 696e ed in the origin -00010c0: 616c 2070 726f 6772 616d 2920 0a20 2020 al program) . -00010d0: 202f 2f2f 2046 696e 6473 2061 6c6c 2061 /// Finds all a -00010e0: 6c74 6572 6e61 7469 7665 7320 666f 7220 lternatives for -00010f0: 7468 6520 6769 7665 6e20 7068 6f6e 6520 the given phone -0001100: 6e75 6d62 6572 200a 2020 2020 2f2f 2f20 number . /// -0001110: 5265 7475 726e 733a 2061 7272 6179 206f Returns: array o -0001120: 6620 7374 7269 6e67 7320 0a20 2020 2073 f strings . s -0001130: 7472 696e 6761 7272 6179 2046 696e 6457 tringarray FindW -0001140: 6f72 6473 2820 7374 7269 6e67 2070 686f ords( string pho -0001150: 6e65 5f6e 756d 6265 7220 290a 2020 2020 ne_number ). -0001160: 7b0a 2020 2020 2020 2020 6966 2028 2170 {. if (!p -0001170: 686f 6e65 5f6e 756d 6265 722e 6c65 6e67 hone_number.leng -0001180: 7468 290a 2020 2020 2020 2020 2020 2020 th). -0001190: 7265 7475 726e 206e 756c 6c3b 0a20 2020 return null;. -00011a0: 2020 2020 202f 2f20 5374 7269 7020 7468 // Strip th -00011b0: 6520 6e6f 6e2d 6469 6769 7420 6368 6172 e non-digit char -00011c0: 6163 7465 7273 2066 726f 6d20 7468 6520 acters from the -00011d0: 7068 6f6e 6520 6e75 6d62 6572 2c20 616e phone number, an -00011e0: 640a 2020 2020 2020 2020 2f2f 2070 6173 d. // pas -00011f0: 7320 6974 2074 6f20 7468 6520 7265 6375 s it to the recu -0001200: 7273 6976 6520 6675 6e63 7469 6f6e 2028 rsive function ( -0001210: 6c65 6164 696e 6720 6469 6769 7420 6973 leading digit is -0001220: 2061 6c6c 6f77 6564 290a 2020 2020 2020 allowed). -0001230: 2020 7265 7475 726e 205f 4669 6e64 576f return _FindWo -0001240: 7264 7328 2073 7472 6970 4e6f 6e44 6967 rds( stripNonDig -0001250: 6974 2870 686f 6e65 5f6e 756d 6265 7229 it(phone_number) -0001260: 2c20 7472 7565 2029 3b20 2020 200a 2020 , true ); . -0001270: 2020 7d20 2020 200a 2020 2020 0a20 2020 } . . -0001280: 202f 2f20 5265 6164 2074 6865 2070 686f // Read the pho -0001290: 6e65 206e 756d 6265 7273 2020 2020 200a ne numbers . -00012a0: 2020 2020 666f 7265 6163 6828 7374 7269 foreach(stri -00012b0: 6e67 2070 686f 6e65 3b20 6e65 7720 4275 ng phone; new Bu -00012c0: 6666 6572 6564 4669 6c65 2822 696e 7075 fferedFile("inpu -00012d0: 742e 7478 7422 2020 2029 2029 0a20 2020 t.txt" ) ). -00012e0: 2020 2020 2066 6f72 6561 6368 2861 6c74 foreach(alt -00012f0: 6572 6e61 7469 7665 3b20 4669 6e64 576f ernative; FindWo -0001300: 7264 7328 2070 686f 6e65 2029 2029 0a20 rds( phone ) ). -0001310: 2020 2020 2020 2020 2020 2077 7269 7465 write -0001320: 666c 6e28 7068 6f6e 652c 2022 3a20 222c fln(phone, ": ", -0001330: 2061 6c74 6572 6e61 7469 7665 2029 3b0a alternative );. -0001340: 7d0a 0a }.. diff --git a/third_party/pygments/tests/examplefiles/html+php_faulty.php b/third_party/pygments/tests/examplefiles/html+php_faulty.php deleted file mode 100644 index b3d9bbc7f..000000000 --- a/third_party/pygments/tests/examplefiles/html+php_faulty.php +++ /dev/null @@ -1 +0,0 @@ - - * - * Hybris 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. - * - * Hybris 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 Hybris. If not, see . -*/ -import std.io.file; - -class File { - - protected file, fileName, mode; - - public method File( fileName, mode ){ - me.fileName = fileName; - me.mode = mode; - me.file = fopen ( me.fileName, me.mode); - } - - private method isBinary(){ - return me.mode.find("b") != false; - } - - public method File ( file ){ - me.file = file; - } - - private method __expire() { - me.close(); - } - - public method close(){ - fclose( me.file ); - } - - public method readLine(){ - return line = fgets( me.file ); - } - - public method getFileName(){ - return me.fileName; - } - - public method getSize(){ - return fsize( me.fileName ); - } - - public method getPosition(){ - return ftell( me.file ); - } - - public method readAll(){ - text = ""; - line = ""; - while ( ( line = fgets(me.file) ) != 0 ){ - text += line; - } - return text; - } - - public method read(){ - byte = ' '; - if ( fread( me.file, byte) > 0 ) { - return byte; - } - else { - return -1; - } - } - - public method read( bytes ) { - word = ""; - byte = ' '; - if ( fread( me.file, byte, bytes) > 0 ) { - word += byte; - } - else { - return -1; - } - return word; - } - - public method read ( seek, seekType ){ - if ( me.seek( seek, seekType) == 0 ) { - return -1; - } - - return me.read(); - } - - public method read ( bytes, seek, seekType ){ - if ( me.seek( seek, seekType) == 0 ) { - return -1; - } - - return me.read( bytes ); - } - - public method readType ( type ){ - if ( me.isBinary() == false ) { - return -1; - } - if ( fread (me.file, type ) > 0 ) { - return type; - } - else { - return -1; - } - } - - operator >> ( object ){ - return me.readType(object); - } - - public method readType ( type, bytes ){ - if ( me.isBinary() == false ) { - return -1; - } - if ( fread (me.file, type, bytes ) > 0){ - return type; - } - else { - return -1; - } - } - - public method readType ( type, seek, seekType ){ - if ( ( me.isBinary() == false ) | ( me.seek( seek, seekType) == 0 ) ) { - return -1; - } - - return me.readType( type ); - } - - public method readType( type, bytes, seek, seekType){ - if ( ( me.isBinary() == false ) | ( me.seek( seek, seekType) == 0 ) ) { - return -1; - } - - return me.readType( type, bytes ); - } - - public method write( data ){ - return fwrite( me.file, data ); - } - - operator << ( object ){ - return me.write(object); - } - - public method write ( data, bytes ){ - return fwrite( me.file, data, bytes); - } - - public method seek( pos, mode ){ - return fseek( me.file, pos, mode ); - } - - public method merge ( fileName ){ - text = file ( fileName ); - return me.write ( me.file, text ); - } -} diff --git a/third_party/pygments/tests/examplefiles/idl_sample.pro b/third_party/pygments/tests/examplefiles/idl_sample.pro deleted file mode 100644 index 814d510d5..000000000 --- a/third_party/pygments/tests/examplefiles/idl_sample.pro +++ /dev/null @@ -1,73 +0,0 @@ -; docformat = 'rst' - -; Example IDL (Interactive Data Language) source code. - -;+ -; Get `nIndices` random indices for an array of size `nValues` (without -; repeating an index). -; -; :Examples: -; Try:: -; -; IDL> r = randomu(seed, 10) -; IDL> print, r, format='(4F)' -; 0.6297589 0.7815896 0.2508559 0.7546844 -; 0.1353382 0.1245834 0.8733745 0.0753110 -; 0.8054136 0.9513228 -; IDL> ind = mg_sample(10, 3, seed=seed) -; IDL> print, ind -; 2 4 7 -; IDL> print, r[ind] -; 0.250856 0.135338 0.0753110 -; -; :Returns: -; lonarr(`nIndices`) -; -; :Params: -; nValues : in, required, type=long -; size of array to choose indices from -; nIndices : in, required, type=long -; number of indices needed -; -; :Keywords: -; seed : in, out, optional, type=integer or lonarr(36) -; seed to use for random number generation, leave undefined to use a -; seed generated from the system clock; new seed will be output -;- -function mg_sample, nValues, nIndices, seed=seed - compile_opt strictarr - - ; get random nIndices by finding the indices of the smallest nIndices in a - ; array of random values - values = randomu(seed, nValues) - - ; our random values are uniformly distributed, so ideally the nIndices - ; smallest values are in the first bin of the below histogram - nBins = nValues / nIndices - h = histogram(values, nbins=nBins, reverse_indices=ri) - - ; the candidates for being in the first nIndices will live in bins 0..bin - nCandidates = 0L - for bin = 0L, nBins - 1L do begin - nCandidates += h[bin] - if (nCandidates ge nIndices) then break - endfor - - ; get the candidates and sort them - candidates = ri[ri[0] : ri[bin + 1L] - 1L] - sortedCandidates = sort(values[candidates]) - - ; return the first nIndices of them - return, (candidates[sortedCandidates])[0:nIndices-1L] -end - - -; main-level example program - -r = randomu(seed, 10) -print, r -ind = mg_sample(10, 3, seed=seed) -print, ind -print, r[ind] - -end \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/iex_example b/third_party/pygments/tests/examplefiles/iex_example deleted file mode 100644 index 22407e4e5..000000000 --- a/third_party/pygments/tests/examplefiles/iex_example +++ /dev/null @@ -1,23 +0,0 @@ -iex> :" multi -...> line ' \s \123 \x20 -...> atom" -:" multi\n line ' S \natom" - -iex(1)> <<"hello"::binary, c :: utf8, x::[4, unit(2)]>> = "hello™1" -"hello™1" - -iex(2)> c -8482 - -iex> 1 + :atom -** (ArithmeticError) bad argument in arithmetic expression - :erlang.+(1, :atom) - -iex(3)> 1 + -...(3)> 2 + -...(3)> 3 -6 - -iex> IO.puts "Hello world" -Hello world -:ok diff --git a/third_party/pygments/tests/examplefiles/inet_pton6.dg b/third_party/pygments/tests/examplefiles/inet_pton6.dg deleted file mode 100644 index 3813d5b87..000000000 --- a/third_party/pygments/tests/examplefiles/inet_pton6.dg +++ /dev/null @@ -1,71 +0,0 @@ -import '/re' -import '/sys' - - -# IPv6address = hexpart [ ":" IPv4address ] -# IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT -# hexpart = [ hexseq ] [ "::" [ hexseq ] ] -# hexseq = hex4 *( ":" hex4) -# hex4 = 1*4HEXDIG -hexpart = r'({0}|)(?:::({0}|)|)'.format r'(?:[\da-f]{1,4})(?::[\da-f]{1,4})*' -addrv4 = r'(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})' -addrv6 = re.compile $ r'(?i)(?:{})(?::{})?$'.format hexpart addrv4 - - -# Parse a base-N number given a list of its digits. -# -# :param q: the number of digits in that numeral system -# -# :param digits: an iterable of integers in range [0..q] -# -# :return: a decimal integer -# -base_n = q digits -> foldl (x y -> x * q + y) 0 digits - - -# Parse a sequence of hexadecimal numbers -# -# :param q: a string of colon-separated base-16 integers -# -# :return: an iterable of Python ints -# -unhex = q -> q and map (p -> int p 16) (q.split ':') - - -# Parse an IPv6 address as specified in RFC 4291. -# -# :param address: a string, obviously. -# -# :return: an integer which, written in binary form, points to the same node. -# -inet_pton6 = address -> - not (match = addrv6.match address) => raise $ ValueError 'not a valid IPv6 address' - start, end, *ipv4 = match.groups! - - is_ipv4 = not $ None in ipv4 - shift = (7 - start.count ':' - 2 * is_ipv4) * 16 - - (end is None and shift) or shift < 0 => raise $ ValueError 'not a valid IPv6 address' - hexaddr = (base_n 0x10000 (unhex start) << shift) + base_n 0x10000 (unhex $ end or '') - if (is_ipv4 => (hexaddr << 32) + base_n 0x100 (map int ipv4)) (otherwise => hexaddr) - - -inet6_type = q -> if - q == 0 => 'unspecified' - q == 1 => 'loopback' - (q >> 32) == 0x000000000000ffff => 'IPv4-mapped' - (q >> 64) == 0xfe80000000000000 => 'link-local' - (q >> 120) != 0x00000000000000ff => 'general unicast' - (q >> 112) % (1 << 4) == 0x0000000000000000 => 'multicast w/ reserved scope value' - (q >> 112) % (1 << 4) == 0x000000000000000f => 'multicast w/ reserved scope value' - (q >> 112) % (1 << 4) == 0x0000000000000001 => 'interface-local multicast' - (q >> 112) % (1 << 4) == 0x0000000000000004 => 'admin-local multicast' - (q >> 112) % (1 << 4) == 0x0000000000000005 => 'site-local multicast' - (q >> 112) % (1 << 4) == 0x0000000000000008 => 'organization-local multicast' - (q >> 112) % (1 << 4) == 0x000000000000000e => 'global multicast' - (q >> 112) % (1 << 4) != 0x0000000000000002 => 'multicast w/ unknown scope value' - (q >> 24) % (1 << 112) == 0x00000000000001ff => 'solicited-node multicast' - otherwise => 'link-local multicast' - - -print $ (x -> inet6_type x, hex x) $ inet_pton6 $ sys.stdin.read!.strip! diff --git a/third_party/pygments/tests/examplefiles/inform6_example b/third_party/pygments/tests/examplefiles/inform6_example deleted file mode 100644 index 6fa1fe5ba..000000000 --- a/third_party/pygments/tests/examplefiles/inform6_example +++ /dev/null @@ -1,375 +0,0 @@ -!% $SMALL ! This is ICL, not a comment. -!% -w - -!% A comprehensive test of Inform6Lexer. - -Switches d2SDq; - -Constant Story "Informal Testing"; -Constant Headline "^Not a game.^";!% This is a comment, not ICL. - -Release 3; -Serial "151213"; -Version 5; - -Ifndef TARGET_ZCODE; -Ifndef TARGET_GLULX; -Ifndef WORDSIZE; -Default WORDSIZE 2; -Constant TARGET_ZCODE; -Endif; -Endif; -Endif; - -Ifv3; Message "Compiling to version 3"; Endif; -Ifv5; Message "Not compiling to version 3"; endif; -ifdef TARGET_ZCODE; -#IFTRUE (#version_number == 5); -Message "Compiling to version 5"; -#ENDIF; -endif ; - -Replace CreatureTest; - -Include "Parser"; -Include "VerbLib"; - -# ! A hash is optional at the top level. -Object kitchen "Kitchen" - with description "You are in a kitchen.", - arr 1 2 3 4, - has light; - -#[ Initialise; - location = kitchen; - print "v"; inversion; "^"; -]; - -Ifdef VN_1633; -Replace IsSeeThrough IsSeeThroughOrig; -[ IsSeeThrough * o; - return o hasnt opaque || IsSeeThroughOrig(o); -]; -Endif; - -Abbreviate "test"; - -Array table buffer 260; - -Attribute reversed; -Attribute opaque alias locked; -Constant to reversed; - -Property long additive additive long alias; -Property long long long wingspan alias alias; - -Class Flier with wingspan 5; -Class Bird(10) has animate class Flier with wingspan 2; - -Constant Constant1; -Constant Constant2 Constant1; -Constant Constant3 = Constant2; -Ifdef VN_1633; Undef Constant; Endif; - -Ifdef VN_1633; -Dictionary 'word' 1 2; -Ifnot; -Dictionary dict_word "word"; -Endif; - -Fake_action NotReal; - -Global global1; -Global global2 = 69105; - -Lowstring low_string "low string"; - -Iftrue false; -Message error "Uh-oh!^~false~ shouldn't be ~true~."; -Endif; -Iffalse true; -Message fatalerror "Uh-oh!^~true~ shouldn't be ~false~."; -Endif; - -Nearby person "person" - with name 'person', - description "This person is barely implemented.", - life [ * x y z; - Ask: print_ret (The) self, " says nothing."; - Answer: print (The) self, " didn't say anything.^"; rfalse; - ] - has has animate transparent; - -Object -> -> test_tube "test tube" - with name 'test' "tube" 'testtube', - has ~openable ~opaque container; - -Bird -> pigeon - with name 'pigeon', - description [; - "The pigeon has a wingspan of ", self.&wingspan-->0, " wing units."; - ]; - -Object -> "thimble" with name 'thimble'; - -Object -> pebble "pebble" with name 'pebble'; - -Ifdef TARGET_ZCODE; Trace objects; Endif; - -Statusline score; - -Stub StubR 3; - -Ifdef TARGET_ZCODE; -Zcharacter "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "123456789.,!?_#'0/@{005C}-:()"; -Zcharacter table '@!!' '@<<' '@'A'; -Zcharacter table + '@AE' '@{dc}' '@et' '@:y'; -Ifnot; -Ifdef TARGET_GLULX; -Message "Glulx doesn't use ~Zcharacter~.^Oh well."; ! '~' and '^' work here. -Ifnot; -Message warning "Uh-oh! ^~^"; ! They don't work in other Messages. -Endif; -Endif; - -Include "Grammar"; - -Verb"acquire"'collect'='take'; - -[ NounFilter; return noun ofclass Bird; ]; - -[ ScopeFilter obj; - switch (scope_stage) { - 1: rtrue; - 2: objectloop (obj in compass) PlaceInScope(obj); - 3: "Nothing is in scope."; - } -]; - -Verb meta "t" 'test' - * 'held' held -> TestHeld - * number -> TestNumber - * reversed -> TestAttribute - * 'creature' creature -> TestCreature - * 'multiheld' multiheld -> TestMultiheld - * 'm' multiexcept 'into'/"in" noun -> TestMultiexcept - * 'm' multiinside 'from' noun -> TestMultiinside - * multi -> TestMulti - * 'filter'/'f' noun=NounFilter -> TestNounFilter - * 'filter'/'f' scope=ScopeFilter -> TestScopeFilter - * 'special' special -> TestSpecial - * topic -> TestTopic; - -Verb 'reverse' 'swap' 'exchange' - * held 'for' noun -> reverse - * noun 'with' noun -> reverse reverse; - -Extend "t" last * noun -> TestNoun; - -Extend 't' first * -> Test; - -Extend 'wave' replace * -> NewWave; - -Extend only 'feel' 'touch' replace * noun -> Feel; - -[ TestSub "a\ - " b o "@@98"; ! Not an escape sequence. - string 25 low_string; - print "Test what?> "; - table->0 = 260; - parse->0 = 61; - #Ifdef TARGET_ZCODE; - read buffer parse; - #Ifnot; ! TARGET_GLULX - KeyboardPrimitive(buffer, parse); - #Endif; ! TARGET_ - switch (parse-->1) { - 'save': - #Ifdef TARGET_ZCODE; - #Ifv3; - @save ?saved; - #Ifnot; - save saved; - #Endif; - #Endif; - print "Saving failed.^"; - 'restore': - #Ifdef TARGET_ZCODE; - restore saved; - #Endif; - print "Restoring failed.^"; - 'restart': - @restart; - 'quit', 'q//': - quit; - return 2; rtrue; rfalse; return; - 'print', 'p//': - print "Print:^", - " (string): ", (string) "xyzzy^", - " (number): ", (number) 123, "^", - " (char): ", (char) 'x', "^", - " (address): ", (address) 'plugh//p', "^", - " (The): ", (The) person, "^", - " (the): ", (the) person, "^", - " (A): ", (A) person, "^", - " (a): ", (a) person, "^", - " (an): ", (an) person, "^", - " (name): ", (name) person, "^", - " (object): ", (object) person, "^", - " (property): ", (property) alias, "^", - " (): ", (LanguageNumber) 123, "^", - " : ", a * 2 - 1, "^", - " (): ", (a + person), "^"; - print "Escapes:^", - " by mnemonic: @!! @<< @'A @AE @et @:y^", - " by decimal value: @@64 @@126^", - " by Unicode value: @{DC}@{002b}^", - " by string variable: @25^"; - 'font', 'style': - font off; print "font off^"; - font on; print "font on^"; - style reverse; print "style reverse^"; style roman; - style bold; print "style bold^"; - style underline; print "style underline^"; - style fixed; print "style fixed^"; - style roman; print "style roman^"; - 'statements': - spaces 8; - objectloop (o) { - print "objectloop (o): ", (the) o, "^"; - } - objectloop (o in compass) { ! 'in' is a keyword - print "objectloop (o in compass): ", (the) o, "^"; - } - objectloop (o in compass && true) { ! 'in' is an operator - print "objectloop (o in compass && true): ", (the) o, "^"; - } - objectloop (o from se_obj) { - print "objectloop (o from se_obj): ", (the) o, "^"; - } - objectloop (o near person) { - print "objectloop (o near person): ", (the) o, "^"; - } - #Ifdef TARGET_ZCODE; - #Trace assembly on; -@ ! This is assembly. - add -4 ($$1+$3)*2 -> b; - @get_sibling test_tube -> b ?saved; - @inc [b]; - @je sp (1+3*0) ? equal; - @je 1 ((sp)) ?~ different; - .! This is a label: - equal; - print "sp == 1^"; - jump label; - .different; - print "sp @@126= 1^"; - .label; - #Trace off; #Endif; ! TARGET_ZCODE - a = random(10); - switch (a) { - 1, 9: - box "Testing oneself is best when done alone." - " -- Jimmy Carter"; - 2, 6, to, 3 to 5, to to to: - ; - #Ifdef VN_1633; - ; - #Endif; - a = ##Drop; - < ! The angle brackets may be separated by whitespace. - < (a) pigeon > >; - default: - do { - give person general ~general; - } until (person provides life && ~~false); - if (a == 7) a = 4; - else a = 5; - } - 'expressions': - a = 1+1-1*1/1%1&1|1&&1||1==(1~=(1>(1<(1>=(1<=1))))); - a++; ++a; a--; --a; - a = person.life; - a = kitchen.&arr; - a = kitchen.#arr; - a = Bird::wingspan; - a = kitchen has general; - a = kitchen hasnt general; - a = kitchen provides arr; - a = person in kitchen; - a = person notin kitchen; - a = person ofclass Bird; - a = a == 0 or 1; - a = StubR(); - a = StubR(a); - a = StubR(, a); - a = "string"; - a = 'word'; - a = '''; ! character - a = $09afAF; - a = $$01; - a = ##Eat; a = #a$Eat; - a = #g$self; - a = #n$!word; - a = #r$StubR; - a = #dict_par1; - default: - for (a = 2, b = a; (a < buffer->1 + 2) && (Bird::wingspan): ++a, b--) { - print (char) buffer->a; - } - new_line; - for (::) break; - } - .saved;; -]; - -[ TestNumberSub; - print_ret parsed_number, " is ", (number) parsed_number, "."; -]; - -[ TestAttributeSub; print_ret (The) noun, " has been reversed."; ]; - -[ CreatureTest obj; return obj has animate; ]; - -[ TestCreatureSub; print_ret (The) noun, " is a creature."; ]; - -[ TestMultiheldSub; print_ret "You are holding ", (the) noun, "."; ]; - -[ TestMultiexceptSub; "You test ", (the) noun, " with ", (the) second, "."; ]; - -[ TestMultiinsideSub; "You test ", (the) noun, " from ", (the) second, "."; ]; - -[ TestMultiSub; print_ret (The) noun, " is a thing."; ]; - -[ TestNounFilterSub; print_ret (The) noun, " is a bird."; ]; - -[ TestScopeFilterSub; print_ret (The) noun, " is a direction."; ]; - -[ TestSpecialSub; "Your lucky number is ", parsed_number, "."; ]; - -[ TestTopicSub; "You discuss a topic."; ]; - -[ TestNounSub; "That is ", (a) noun, "."; ]; - -[ TestHeldSub; "You are holding ", (a) noun, "."; ]; - -[ NewWaveSub; "That would be foolish."; ]; - -[ FeelSub; print_ret (The) noun, " feels normal."; ]; - -[ ReverseSub from; - from = parent(noun); - move noun to parent(second); - if (from == to) - move second to to; - else - move second to from; - give noun to; - from = to; - give second from; - "You swap ", (the) noun, " and ", (the) second, "."; -]; - -End: The End directive ends the source code. diff --git a/third_party/pygments/tests/examplefiles/interp.scala b/third_party/pygments/tests/examplefiles/interp.scala deleted file mode 100644 index 4131b75e3..000000000 --- a/third_party/pygments/tests/examplefiles/interp.scala +++ /dev/null @@ -1,10 +0,0 @@ -val n = 123; -val a = s"n=$n"; -val a2 = s"n=$n''"; -val b = s"""n=$n"""; -val c = f"n=$n%f"; -val d = f"""n=$n%f"""; -val d2 = s"""a""""; -val e = s"abc\u00e9"; -val f = s"a${n}b"; -val g = s"a${n + 1}b"; diff --git a/third_party/pygments/tests/examplefiles/intro.ik b/third_party/pygments/tests/examplefiles/intro.ik deleted file mode 100644 index 03fcee390..000000000 --- a/third_party/pygments/tests/examplefiles/intro.ik +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/ioke - -Ioke = LanguageExperiment with( - goal: :expressiveness, - data: as(code), - code: as(data), - features: [ - :dynamic, - :object_oriented, - :prototype_based, - :homoiconic, - :macros - ], - runtimes:(JVM, CLR), - inspirations: set(Io, Smalltalk, Ruby, Lisp) -) - -hello = method("Every example needs a hello world!", - name, - "hello, #{name}!" println) - -Ioke inspirations select( - features include?(:object_oriented) -) each(x, hello(x name)) diff --git a/third_party/pygments/tests/examplefiles/ints.php b/third_party/pygments/tests/examplefiles/ints.php deleted file mode 100644 index 516ab2c82..000000000 --- a/third_party/pygments/tests/examplefiles/ints.php +++ /dev/null @@ -1,10 +0,0 @@ - - diff --git a/third_party/pygments/tests/examplefiles/intsyn.fun b/third_party/pygments/tests/examplefiles/intsyn.fun deleted file mode 100644 index 777b0fdb1..000000000 --- a/third_party/pygments/tests/examplefiles/intsyn.fun +++ /dev/null @@ -1,675 +0,0 @@ -(* Internal Syntax *) -(* Author: Frank Pfenning, Carsten Schuermann *) -(* Modified: Roberto Virga *) - -functor IntSyn (structure Global : GLOBAL) :> INTSYN = -struct - - type cid = int (* Constant identifier *) - type name = string (* Variable name *) - type mid = int (* Structure identifier *) - type csid = int (* CS module identifier *) - - - (* Contexts *) - datatype 'a Ctx = (* Contexts *) - Null (* G ::= . *) - | Decl of 'a Ctx * 'a (* | G, D *) - - (* ctxPop (G) => G' - Invariant: G = G',D - *) - fun ctxPop (Decl (G, D)) = G - - exception Error of string (* raised if out of space *) - (* ctxLookup (G, k) = D, kth declaration in G from right to left - Invariant: 1 <= k <= |G|, where |G| is length of G - *) - - fun ctxLookup (Decl (G', D), 1) = D - | ctxLookup (Decl (G', _), k') = ctxLookup (G', k'-1) -(* | ctxLookup (Null, k') = (print ("Looking up k' = " ^ Int.toString k' ^ "\n"); raise Error "Out of Bounce\n")*) - (* ctxLookup (Null, k') should not occur by invariant *) - - (* ctxLength G = |G|, the number of declarations in G *) - fun ctxLength G = - let - fun ctxLength' (Null, n) = n - | ctxLength' (Decl(G, _), n)= ctxLength' (G, n+1) - in - ctxLength' (G, 0) - end - - type FgnExp = exn (* foreign expression representation *) - exception UnexpectedFgnExp of FgnExp - (* raised by a constraint solver - if passed an incorrect arg *) - - type FgnCnstr = exn (* foreign unification constraint - representation *) - exception UnexpectedFgnCnstr of FgnCnstr - (* raised by a constraint solver - if passed an incorrect arg *) - - datatype Depend = (* Dependency information *) - No (* P ::= No *) - | Maybe (* | Maybe *) - | Meta (* | Meta *) - - (* Expressions *) - - datatype Uni = (* Universes: *) - Kind (* L ::= Kind *) - | Type (* | Type *) - - datatype Exp = (* Expressions: *) - Uni of Uni (* U ::= L *) - | Pi of (Dec * Depend) * Exp (* | bPi (D, P). V *) - | Root of Head * Spine (* | C @ S *) - | Redex of Exp * Spine (* | U @ S *) - | Lam of Dec * Exp (* | lam D. U *) - | EVar of Exp option ref * Dec Ctx * Exp * (Cnstr ref) list ref - (* | X : G|-V, Cnstr *) - - | EClo of Exp * Sub (* | U[s] *) - | AVar of Exp option ref (* | A *) - | NVar of int (* | n (linear, fully applied) *) - (* grafting variable *) - - | FgnExp of csid * FgnExp - (* | (foreign expression) *) - - and Head = (* Heads: *) - BVar of int (* H ::= k *) - | Const of cid (* | c *) - | Proj of Block * int (* | #k(b) *) - | Skonst of cid (* | c# *) - | Def of cid (* | d *) - | NSDef of cid (* | d (non strict) *) - | FVar of name * Exp * Sub (* | F[s] *) - | FgnConst of csid * ConDec (* | (foreign constant) *) - - and Spine = (* Spines: *) - Nil (* S ::= Nil *) - | App of Exp * Spine (* | U ; S *) - | SClo of Spine * Sub (* | S[s] *) - - and Sub = (* Explicit substitutions: *) - Shift of int (* s ::= ^n *) - | Dot of Front * Sub (* | Ft.s *) - - and Front = (* Fronts: *) - Idx of int (* Ft ::= k *) - | Exp of Exp (* | U *) - | Axp of Exp (* | U (assignable) *) - | Block of Block (* | _x *) - | Undef (* | _ *) - - and Dec = (* Declarations: *) - Dec of name option * Exp (* D ::= x:V *) - | BDec of name option * (cid * Sub) (* | v:l[s] *) - | ADec of name option * int (* | v[^-d] *) - | NDec of name option - - and Block = (* Blocks: *) - Bidx of int (* b ::= v *) - | LVar of Block option ref * Sub * (cid * Sub) - (* | L(l[^k],t) *) - | Inst of Exp list (* | u1, ..., Un *) - - - (* Constraints *) - - and Cnstr = (* Constraint: *) - Solved (* Cnstr ::= solved *) - | Eqn of Dec Ctx * Exp * Exp (* | G|-(U1 == U2) *) - | FgnCnstr of csid * FgnCnstr (* | (foreign) *) - - and Status = (* Status of a constant: *) - Normal (* inert *) - | Constraint of csid * (Dec Ctx * Spine * int -> Exp option) - (* acts as constraint *) - | Foreign of csid * (Spine -> Exp) (* is converted to foreign *) - - and FgnUnify = (* Result of foreign unify *) - Succeed of FgnUnifyResidual list - (* succeed with a list of residual operations *) - | Fail - - and FgnUnifyResidual = (* Residual of foreign unify *) - Assign of Dec Ctx * Exp * Exp * Sub - (* perform the assignment G |- X = U [ss] *) - | Delay of Exp * Cnstr ref - (* delay cnstr, associating it with all the rigid EVars in U *) - - (* Global signature *) - - and ConDec = (* Constant declaration *) - ConDec of string * mid option * int * Status - (* a : K : kind or *) - * Exp * Uni (* c : A : type *) - | ConDef of string * mid option * int (* a = A : K : kind or *) - * Exp * Exp * Uni (* d = M : A : type *) - * Ancestor (* Ancestor info for d or a *) - | AbbrevDef of string * mid option * int - (* a = A : K : kind or *) - * Exp * Exp * Uni (* d = M : A : type *) - | BlockDec of string * mid option (* %block l : SOME G1 PI G2 *) - * Dec Ctx * Dec list - - | BlockDef of string * mid option * cid list - (* %block l = (l1 | ... | ln) *) - - | SkoDec of string * mid option * int (* sa: K : kind or *) - * Exp * Uni (* sc: A : type *) - - and Ancestor = (* Ancestor of d or a *) - Anc of cid option * int * cid option (* head(expand(d)), height, head(expand[height](d)) *) - (* NONE means expands to {x:A}B *) - - datatype StrDec = (* Structure declaration *) - StrDec of string * mid option - - (* Form of constant declaration *) - datatype ConDecForm = - FromCS (* from constraint domain *) - | Ordinary (* ordinary declaration *) - | Clause (* %clause declaration *) - - (* Type abbreviations *) - type dctx = Dec Ctx (* G = . | G,D *) - type eclo = Exp * Sub (* Us = U[s] *) - type bclo = Block * Sub (* Bs = B[s] *) - type cnstr = Cnstr ref - -(* exception Error of string (* raised if out of space *) *) - - - structure FgnExpStd = struct - - structure ToInternal = FgnOpnTable (type arg = unit - type result = Exp) - - structure Map = FgnOpnTable (type arg = Exp -> Exp - type result = Exp) - - structure App = FgnOpnTable (type arg = Exp -> unit - type result = unit) - - structure EqualTo = FgnOpnTable (type arg = Exp - type result = bool) - - structure UnifyWith = FgnOpnTable (type arg = Dec Ctx * Exp - type result = FgnUnify) - - - - fun fold csfe f b = let - val r = ref b - fun g U = r := f (U,!r) - in - App.apply csfe g ; !r - end - - end - - structure FgnCnstrStd = struct - - structure ToInternal = FgnOpnTable (type arg = unit - type result = (Dec Ctx * Exp) list) - - structure Awake = FgnOpnTable (type arg = unit - type result = bool) - - structure Simplify = FgnOpnTable (type arg = unit - type result = bool) - - end - - fun conDecName (ConDec (name, _, _, _, _, _)) = name - | conDecName (ConDef (name, _, _, _, _, _, _)) = name - | conDecName (AbbrevDef (name, _, _, _, _, _)) = name - | conDecName (SkoDec (name, _, _, _, _)) = name - | conDecName (BlockDec (name, _, _, _)) = name - | conDecName (BlockDef (name, _, _)) = name - - fun conDecParent (ConDec (_, parent, _, _, _, _)) = parent - | conDecParent (ConDef (_, parent, _, _, _, _, _)) = parent - | conDecParent (AbbrevDef (_, parent, _, _, _, _)) = parent - | conDecParent (SkoDec (_, parent, _, _, _)) = parent - | conDecParent (BlockDec (_, parent, _, _)) = parent - | conDecParent (BlockDef (_, parent, _)) = parent - - - (* conDecImp (CD) = k - - Invariant: - If CD is either a declaration, definition, abbreviation, or - a Skolem constant - then k stands for the number of implicit elements. - *) - fun conDecImp (ConDec (_, _, i, _, _, _)) = i - | conDecImp (ConDef (_, _, i, _, _, _, _)) = i - | conDecImp (AbbrevDef (_, _, i, _, _, _)) = i - | conDecImp (SkoDec (_, _, i, _, _)) = i - | conDecImp (BlockDec (_, _, _, _)) = 0 (* watch out -- carsten *) - - fun conDecStatus (ConDec (_, _, _, status, _, _)) = status - | conDecStatus _ = Normal - - (* conDecType (CD) = V - - Invariant: - If CD is either a declaration, definition, abbreviation, or - a Skolem constant - then V is the respective type - *) - fun conDecType (ConDec (_, _, _, _, V, _)) = V - | conDecType (ConDef (_, _, _, _, V, _, _)) = V - | conDecType (AbbrevDef (_, _, _, _, V, _)) = V - | conDecType (SkoDec (_, _, _, V, _)) = V - - - (* conDecBlock (CD) = (Gsome, Lpi) - - Invariant: - If CD is block definition - then Gsome is the context of some variables - and Lpi is the list of pi variables - *) - fun conDecBlock (BlockDec (_, _, Gsome, Lpi)) = (Gsome, Lpi) - - (* conDecUni (CD) = L - - Invariant: - If CD is either a declaration, definition, abbreviation, or - a Skolem constant - then L is the respective universe - *) - fun conDecUni (ConDec (_, _, _, _, _, L)) = L - | conDecUni (ConDef (_, _, _, _, _, L, _)) = L - | conDecUni (AbbrevDef (_, _, _, _, _, L)) = L - | conDecUni (SkoDec (_, _, _, _, L)) = L - - - fun strDecName (StrDec (name, _)) = name - - fun strDecParent (StrDec (_, parent)) = parent - - local - val maxCid = Global.maxCid - val dummyEntry = ConDec("", NONE, 0, Normal, Uni (Kind), Kind) - val sgnArray = Array.array (maxCid+1, dummyEntry) - : ConDec Array.array - val nextCid = ref(0) - - val maxMid = Global.maxMid - val sgnStructArray = Array.array (maxMid+1, StrDec("", NONE)) - : StrDec Array.array - val nextMid = ref (0) - - in - (* Invariants *) - (* Constant declarations are all well-typed *) - (* Constant declarations are stored in beta-normal form *) - (* All definitions are strict in all their arguments *) - (* If Const(cid) is valid, then sgnArray(cid) = ConDec _ *) - (* If Def(cid) is valid, then sgnArray(cid) = ConDef _ *) - - fun sgnClean (i) = if i >= !nextCid then () - else (Array.update (sgnArray, i, dummyEntry); - sgnClean (i+1)) - - fun sgnReset () = ((* Fri Dec 20 12:04:24 2002 -fp *) - (* this circumvents a space leak *) - sgnClean (0); - nextCid := 0; nextMid := 0) - fun sgnSize () = (!nextCid, !nextMid) - - fun sgnAdd (conDec) = - let - val cid = !nextCid - in - if cid > maxCid - then raise Error ("Global signature size " ^ Int.toString (maxCid+1) ^ " exceeded") - else (Array.update (sgnArray, cid, conDec) ; - nextCid := cid + 1; - cid) - end - - (* 0 <= cid < !nextCid *) - fun sgnLookup (cid) = Array.sub (sgnArray, cid) - - fun sgnApp (f) = - let - fun sgnApp' (cid) = - if cid = !nextCid then () else (f cid; sgnApp' (cid+1)) - in - sgnApp' (0) - end - - fun sgnStructAdd (strDec) = - let - val mid = !nextMid - in - if mid > maxMid - then raise Error ("Global signature size " ^ Int.toString (maxMid+1) ^ " exceeded") - else (Array.update (sgnStructArray, mid, strDec) ; - nextMid := mid + 1; - mid) - end - - (* 0 <= mid < !nextMid *) - fun sgnStructLookup (mid) = Array.sub (sgnStructArray, mid) - - (* A hack used in Flit - jcreed 6/05 *) - fun rename (cid, new) = - let - val newConDec = case sgnLookup cid of - ConDec (n,m,i,s,e,u) => ConDec(new,m,i,s,e,u) - | ConDef (n,m,i,e,e',u,a) => ConDef(new,m,i,e,e',u,a) - | AbbrevDef (n,m,i,e,e',u) => AbbrevDef (new,m,i,e,e',u) - | BlockDec (n,m,d,d') => BlockDec (new,m,d,d') - | SkoDec (n,m,i,e,u) => SkoDec (new,m,i,e,u) - in - Array.update (sgnArray, cid, newConDec) - end - - end - - fun constDef (d) = - (case sgnLookup (d) - of ConDef(_, _, _, U,_, _, _) => U - | AbbrevDef (_, _, _, U,_, _) => U) - - fun constType (c) = conDecType (sgnLookup c) - fun constImp (c) = conDecImp (sgnLookup c) - fun constUni (c) = conDecUni (sgnLookup c) - fun constBlock (c) = conDecBlock (sgnLookup c) - - fun constStatus (c) = - (case sgnLookup (c) - of ConDec (_, _, _, status, _, _) => status - | _ => Normal) - - - (* Explicit Substitutions *) - - (* id = ^0 - - Invariant: - G |- id : G id is patsub - *) - val id = Shift(0) - - (* shift = ^1 - - Invariant: - G, V |- ^ : G ^ is patsub - *) - val shift = Shift(1) - - (* invShift = ^-1 = _.^0 - Invariant: - G |- ^-1 : G, V ^-1 is patsub - *) - val invShift = Dot(Undef, id) - - - (* comp (s1, s2) = s' - - Invariant: - If G' |- s1 : G - and G'' |- s2 : G' - then s' = s1 o s2 - and G'' |- s1 o s2 : G - - If s1, s2 patsub - then s' patsub - *) - fun comp (Shift (0), s) = s - (* next line is an optimization *) - (* roughly 15% on standard suite for Twelf 1.1 *) - (* Sat Feb 14 10:15:16 1998 -fp *) - | comp (s, Shift (0)) = s - | comp (Shift (n), Dot (Ft, s)) = comp (Shift (n-1), s) - | comp (Shift (n), Shift (m)) = Shift (n+m) - | comp (Dot (Ft, s), s') = Dot (frontSub (Ft, s'), comp (s, s')) - - (* bvarSub (n, s) = Ft' - - Invariant: - If G |- s : G' G' |- n : V - then Ft' = Ftn if s = Ft1 .. Ftn .. ^k - or Ft' = ^(n+k) if s = Ft1 .. Ftm ^k and m Bidx k' - | Block B => B) - | blockSub (LVar (ref (SOME B), sk, _), s) = - blockSub (B, comp (sk, s)) - (* -fp Sun Dec 1 21:18:30 2002 *) - (* --cs Sun Dec 1 11:25:41 2002 *) - (* Since always . |- t : Gsome, discard s *) - (* where is this needed? *) - (* Thu Dec 6 20:30:26 2001 -fp !!! *) - | blockSub (LVar (r as ref NONE, sk, (l, t)), s) = - LVar(r, comp(sk, s), (l, t)) - (* was: - LVar (r, comp(sk, s), (l, comp (t, s))) - July 22, 2010 -fp -cs - *) - (* comp(^k, s) = ^k' for some k' by invariant *) - | blockSub (L as Inst ULs, s') = Inst (map (fn U => EClo (U, s')) ULs) - (* this should be right but somebody should verify *) - - (* frontSub (Ft, s) = Ft' - - Invariant: - If G |- s : G' G' |- Ft : V - then Ft' = Ft [s] - and G |- Ft' : V [s] - - NOTE: EClo (U, s) might be undefined, so if this is ever - computed eagerly, we must introduce an "Undefined" exception, - raise it in whnf and handle it here so Exp (EClo (U, s)) => Undef - *) - and frontSub (Idx (n), s) = bvarSub (n, s) - | frontSub (Exp (U), s) = Exp (EClo (U, s)) - | frontSub (Undef, s) = Undef - | frontSub (Block (B), s) = Block (blockSub (B, s)) - - (* decSub (x:V, s) = D' - - Invariant: - If G |- s : G' G' |- V : L - then D' = x:V[s] - and G |- V[s] : L - *) - (* First line is an optimization suggested by cs *) - (* D[id] = D *) - (* Sat Feb 14 18:37:44 1998 -fp *) - (* seems to have no statistically significant effect *) - (* undo for now Sat Feb 14 20:22:29 1998 -fp *) - (* - fun decSub (D, Shift(0)) = D - | decSub (Dec (x, V), s) = Dec (x, EClo (V, s)) - *) - fun decSub (Dec (x, V), s) = Dec (x, EClo (V, s)) - | decSub (NDec x, s) = NDec x - | decSub (BDec (n, (l, t)), s) = BDec (n, (l, comp (t, s))) - - (* dot1 (s) = s' - - Invariant: - If G |- s : G' - then s' = 1. (s o ^) - and for all V s.t. G' |- V : L - G, V[s] |- s' : G', V - - If s patsub then s' patsub - *) - (* first line is an optimization *) - (* roughly 15% on standard suite for Twelf 1.1 *) - (* Sat Feb 14 10:16:16 1998 -fp *) - fun dot1 (s as Shift (0)) = s - | dot1 s = Dot (Idx(1), comp(s, shift)) - - (* invDot1 (s) = s' - invDot1 (1. s' o ^) = s' - - Invariant: - s = 1 . s' o ^ - If G' |- s' : G - (so G',V[s] |- s : G,V) - *) - fun invDot1 (s) = comp (comp(shift, s), invShift) - - - (* Declaration Contexts *) - - (* ctxDec (G, k) = x:V - Invariant: - If |G| >= k, where |G| is size of G, - then G |- k : V and G |- V : L - *) - fun ctxDec (G, k) = - let (* ctxDec' (G'', k') = x:V - where G |- ^(k-k') : G'', 1 <= k' <= k - *) - fun ctxDec' (Decl (G', Dec (x, V')), 1) = Dec (x, EClo (V', Shift (k))) - | ctxDec' (Decl (G', BDec (n, (l, s))), 1) = BDec (n, (l, comp (s, Shift (k)))) - | ctxDec' (Decl (G', _), k') = ctxDec' (G', k'-1) - (* ctxDec' (Null, k') should not occur by invariant *) - in - ctxDec' (G, k) - end - - (* blockDec (G, v, i) = V - - Invariant: - If G (v) = l[s] - and Sigma (l) = SOME Gsome BLOCK Lblock - and G |- s : Gsome - then G |- pi (v, i) : V - *) - - fun blockDec (G, v as (Bidx k), i) = - let - val BDec (_, (l, s)) = ctxDec (G, k) - (* G |- s : Gsome *) - val (Gsome, Lblock) = conDecBlock (sgnLookup l) - fun blockDec' (t, D :: L, 1, j) = decSub (D, t) - | blockDec' (t, _ :: L, n, j) = - blockDec' (Dot (Exp (Root (Proj (v, j), Nil)), t), - L, n-1, j+1) - in - blockDec' (s, Lblock, i, 1) - end - - - (* EVar related functions *) - - (* newEVar (G, V) = newEVarCnstr (G, V, nil) *) - fun newEVar (G, V) = EVar(ref NONE, G, V, ref nil) - - (* newAVar G = new AVar (assignable variable) *) - (* AVars carry no type, ctx, or cnstr *) - fun newAVar () = AVar(ref NONE) - - (* newTypeVar (G) = X, X new - where G |- X : type - *) - fun newTypeVar (G) = EVar(ref NONE, G, Uni(Type), ref nil) - - (* newLVar (l, s) = (l[s]) *) - fun newLVar (sk, (cid, t)) = LVar (ref NONE, sk, (cid, t)) - - (* Definition related functions *) - (* headOpt (U) = SOME(H) or NONE, U should be strict, normal *) - fun headOpt (Root (H, _)) = SOME(H) - | headOpt (Lam (_, U)) = headOpt U - | headOpt _ = NONE - - fun ancestor' (NONE) = Anc(NONE, 0, NONE) - | ancestor' (SOME(Const(c))) = Anc(SOME(c), 1, SOME(c)) - | ancestor' (SOME(Def(d))) = - (case sgnLookup(d) - of ConDef(_, _, _, _, _, _, Anc(_, height, cOpt)) - => Anc(SOME(d), height+1, cOpt)) - | ancestor' (SOME _) = (* FgnConst possible, BVar impossible by strictness *) - Anc(NONE, 0, NONE) - (* ancestor(U) = ancestor info for d = U *) - fun ancestor (U) = ancestor' (headOpt U) - - (* defAncestor(d) = ancestor of d, d must be defined *) - fun defAncestor (d) = - (case sgnLookup(d) - of ConDef(_, _, _, _, _, _, anc) => anc) - - (* Type related functions *) - - (* targetHeadOpt (V) = SOME(H) or NONE - where H is the head of the atomic target type of V, - NONE if V is a kind or object or have variable type. - Does not expand type definitions. - *) - (* should there possibly be a FgnConst case? also targetFamOpt -kw *) - fun targetHeadOpt (Root (H, _)) = SOME(H) - | targetHeadOpt (Pi(_, V)) = targetHeadOpt V - | targetHeadOpt (Redex (V, S)) = targetHeadOpt V - | targetHeadOpt (Lam (_, V)) = targetHeadOpt V - | targetHeadOpt (EVar (ref (SOME(V)),_,_,_)) = targetHeadOpt V - | targetHeadOpt (EClo (V, s)) = targetHeadOpt V - | targetHeadOpt _ = NONE - (* Root(Bvar _, _), Root(FVar _, _), Root(FgnConst _, _), - EVar(ref NONE,..), Uni, FgnExp _ - *) - (* Root(Skonst _, _) can't occur *) - (* targetHead (A) = a - as in targetHeadOpt, except V must be a valid type - *) - fun targetHead (A) = valOf (targetHeadOpt A) - - (* targetFamOpt (V) = SOME(cid) or NONE - where cid is the type family of the atomic target type of V, - NONE if V is a kind or object or have variable type. - Does expand type definitions. - *) - fun targetFamOpt (Root (Const(cid), _)) = SOME(cid) - | targetFamOpt (Pi(_, V)) = targetFamOpt V - | targetFamOpt (Root (Def(cid), _)) = targetFamOpt (constDef cid) - | targetFamOpt (Redex (V, S)) = targetFamOpt V - | targetFamOpt (Lam (_, V)) = targetFamOpt V - | targetFamOpt (EVar (ref (SOME(V)),_,_,_)) = targetFamOpt V - | targetFamOpt (EClo (V, s)) = targetFamOpt V - | targetFamOpt _ = NONE - (* Root(Bvar _, _), Root(FVar _, _), Root(FgnConst _, _), - EVar(ref NONE,..), Uni, FgnExp _ - *) - (* Root(Skonst _, _) can't occur *) - (* targetFam (A) = a - as in targetFamOpt, except V must be a valid type - *) - fun targetFam (A) = valOf (targetFamOpt A) - -end; (* functor IntSyn *) - -structure IntSyn :> INTSYN = - IntSyn (structure Global = Global); diff --git a/third_party/pygments/tests/examplefiles/intsyn.sig b/third_party/pygments/tests/examplefiles/intsyn.sig deleted file mode 100644 index ea505362b..000000000 --- a/third_party/pygments/tests/examplefiles/intsyn.sig +++ /dev/null @@ -1,286 +0,0 @@ -(* Internal Syntax *) -(* Author: Frank Pfenning, Carsten Schuermann *) -(* Modified: Roberto Virga *) - -signature INTSYN = -sig - - type cid = int (* Constant identifier *) - type mid = int (* Structure identifier *) - type csid = int (* CS module identifier *) - - - type FgnExp = exn (* foreign expression representation *) - exception UnexpectedFgnExp of FgnExp - (* raised by a constraint solver - if passed an incorrect arg *) - type FgnCnstr = exn (* foreign constraint representation *) - exception UnexpectedFgnCnstr of FgnCnstr - (* raised by a constraint solver - if passed an incorrect arg *) - - (* Contexts *) - - datatype 'a Ctx = (* Contexts *) - Null (* G ::= . *) - | Decl of 'a Ctx * 'a (* | G, D *) - - val ctxPop : 'a Ctx -> 'a Ctx - val ctxLookup: 'a Ctx * int -> 'a - val ctxLength: 'a Ctx -> int - - datatype Depend = (* Dependency information *) - No (* P ::= No *) - | Maybe (* | Maybe *) - | Meta (* | Meta *) - - (* expressions *) - - datatype Uni = (* Universes: *) - Kind (* L ::= Kind *) - | Type (* | Type *) - - datatype Exp = (* Expressions: *) - Uni of Uni (* U ::= L *) - | Pi of (Dec * Depend) * Exp (* | Pi (D, P). V *) - | Root of Head * Spine (* | H @ S *) - | Redex of Exp * Spine (* | U @ S *) - | Lam of Dec * Exp (* | lam D. U *) - | EVar of Exp option ref * Dec Ctx * Exp * (Cnstr ref) list ref - (* | X : G|-V, Cnstr *) - | EClo of Exp * Sub (* | U[s] *) - | AVar of Exp option ref (* | A *) - - | FgnExp of csid * FgnExp (* | (foreign expression) *) - - | NVar of int (* | n (linear, - fully applied variable - used in indexing *) - - and Head = (* Head: *) - BVar of int (* H ::= k *) - | Const of cid (* | c *) - | Proj of Block * int (* | #k(b) *) - | Skonst of cid (* | c# *) - | Def of cid (* | d (strict) *) - | NSDef of cid (* | d (non strict) *) - | FVar of string * Exp * Sub (* | F[s] *) - | FgnConst of csid * ConDec (* | (foreign constant) *) - - and Spine = (* Spines: *) - Nil (* S ::= Nil *) - | App of Exp * Spine (* | U ; S *) - | SClo of Spine * Sub (* | S[s] *) - - and Sub = (* Explicit substitutions: *) - Shift of int (* s ::= ^n *) - | Dot of Front * Sub (* | Ft.s *) - - and Front = (* Fronts: *) - Idx of int (* Ft ::= k *) - | Exp of Exp (* | U *) - | Axp of Exp (* | U *) - | Block of Block (* | _x *) - | Undef (* | _ *) - - and Dec = (* Declarations: *) - Dec of string option * Exp (* D ::= x:V *) - | BDec of string option * (cid * Sub) (* | v:l[s] *) - | ADec of string option * int (* | v[^-d] *) - | NDec of string option - - and Block = (* Blocks: *) - Bidx of int (* b ::= v *) - | LVar of Block option ref * Sub * (cid * Sub) - (* | L(l[^k],t) *) - | Inst of Exp list (* | U1, ..., Un *) - (* It would be better to consider having projections count - like substitutions, then we could have Inst of Sub here, - which would simplify a lot of things. - - I suggest however to wait until the next big overhaul - of the system -- cs *) - - -(* | BClo of Block * Sub (* | b[s] *) *) - - (* constraints *) - - and Cnstr = (* Constraint: *) - Solved (* Cnstr ::= solved *) - | Eqn of Dec Ctx * Exp * Exp (* | G|-(U1 == U2) *) - | FgnCnstr of csid * FgnCnstr (* | (foreign) *) - - and Status = (* Status of a constant: *) - Normal (* inert *) - | Constraint of csid * (Dec Ctx * Spine * int -> Exp option) - (* acts as constraint *) - | Foreign of csid * (Spine -> Exp) (* is converted to foreign *) - - and FgnUnify = (* Result of foreign unify *) - Succeed of FgnUnifyResidual list - (* succeed with a list of residual operations *) - | Fail - - and FgnUnifyResidual = - Assign of Dec Ctx * Exp * Exp * Sub - (* perform the assignment G |- X = U [ss] *) - | Delay of Exp * Cnstr ref - (* delay cnstr, associating it with all the rigid EVars in U *) - - (* Global signature *) - - and ConDec = (* Constant declaration *) - ConDec of string * mid option * int * Status - (* a : K : kind or *) - * Exp * Uni (* c : A : type *) - | ConDef of string * mid option * int (* a = A : K : kind or *) - * Exp * Exp * Uni (* d = M : A : type *) - * Ancestor (* Ancestor info for d or a *) - | AbbrevDef of string * mid option * int - (* a = A : K : kind or *) - * Exp * Exp * Uni (* d = M : A : type *) - | BlockDec of string * mid option (* %block l : SOME G1 PI G2 *) - * Dec Ctx * Dec list - | BlockDef of string * mid option * cid list - (* %block l = (l1 | ... | ln) *) - | SkoDec of string * mid option * int (* sa: K : kind or *) - * Exp * Uni (* sc: A : type *) - - and Ancestor = (* Ancestor of d or a *) - Anc of cid option * int * cid option (* head(expand(d)), height, head(expand[height](d)) *) - (* NONE means expands to {x:A}B *) - - datatype StrDec = (* Structure declaration *) - StrDec of string * mid option - - (* Form of constant declaration *) - datatype ConDecForm = - FromCS (* from constraint domain *) - | Ordinary (* ordinary declaration *) - | Clause (* %clause declaration *) - - (* Type abbreviations *) - type dctx = Dec Ctx (* G = . | G,D *) - type eclo = Exp * Sub (* Us = U[s] *) - type bclo = Block * Sub (* Bs = B[s] *) - type cnstr = Cnstr ref - - exception Error of string (* raised if out of space *) - - (* standard operations on foreign expressions *) - structure FgnExpStd : sig - (* convert to internal syntax *) - structure ToInternal : FGN_OPN where type arg = unit - where type result = Exp - - (* apply function to subterms *) - structure Map : FGN_OPN where type arg = Exp -> Exp - where type result = Exp - - (* apply function to subterms, for effect *) - structure App : FGN_OPN where type arg = Exp -> unit - where type result = unit - - (* test for equality *) - structure EqualTo : FGN_OPN where type arg = Exp - where type result = bool - - (* unify with another term *) - structure UnifyWith : FGN_OPN where type arg = Dec Ctx * Exp - where type result = FgnUnify - - (* fold a function over the subterms *) - val fold : (csid * FgnExp) -> (Exp * 'a -> 'a) -> 'a -> 'a - end - - (* standard operations on foreign constraints *) - structure FgnCnstrStd : sig - (* convert to internal syntax *) - structure ToInternal : FGN_OPN where type arg = unit - where type result = (Dec Ctx * Exp) list - - (* awake *) - structure Awake : FGN_OPN where type arg = unit - where type result = bool - - (* simplify *) - structure Simplify : FGN_OPN where type arg = unit - where type result = bool - end - - val conDecName : ConDec -> string - val conDecParent : ConDec -> mid option - val conDecImp : ConDec -> int - val conDecStatus : ConDec -> Status - val conDecType : ConDec -> Exp - val conDecBlock : ConDec -> dctx * Dec list - val conDecUni : ConDec -> Uni - - val strDecName : StrDec -> string - val strDecParent : StrDec -> mid option - - val sgnReset : unit -> unit - val sgnSize : unit -> cid * mid - - val sgnAdd : ConDec -> cid - val sgnLookup: cid -> ConDec - val sgnApp : (cid -> unit) -> unit - - val sgnStructAdd : StrDec -> mid - val sgnStructLookup : mid -> StrDec - - val constType : cid -> Exp (* type of c or d *) - val constDef : cid -> Exp (* definition of d *) - val constImp : cid -> int - val constStatus : cid -> Status - val constUni : cid -> Uni - val constBlock : cid -> dctx * Dec list - - (* Declaration Contexts *) - - val ctxDec : dctx * int -> Dec (* get variable declaration *) - val blockDec : dctx * Block * int -> Dec - - (* Explicit substitutions *) - - val id : Sub (* id *) - val shift : Sub (* ^ *) - val invShift : Sub (* ^-1 *) - - val bvarSub : int * Sub -> Front (* k[s] *) - val frontSub : Front * Sub -> Front (* H[s] *) - val decSub : Dec * Sub -> Dec (* x:V[s] *) - val blockSub : Block * Sub -> Block (* B[s] *) - - val comp : Sub * Sub -> Sub (* s o s' *) - val dot1 : Sub -> Sub (* 1 . (s o ^) *) - val invDot1 : Sub -> Sub (* (^ o s) o ^-1) *) - - (* EVar related functions *) - - val newEVar : dctx * Exp -> Exp (* creates X:G|-V, [] *) - val newAVar : unit -> Exp (* creates A (bare) *) - val newTypeVar : dctx -> Exp (* creates X:G|-type, [] *) - val newLVar : Sub * (cid * Sub) -> Block - (* creates B:(l[^k],t) *) - - (* Definition related functions *) - val headOpt : Exp -> Head option - val ancestor : Exp -> Ancestor - val defAncestor : cid -> Ancestor - - (* Type related functions *) - - (* Not expanding type definitions *) - val targetHeadOpt : Exp -> Head option (* target type family or NONE *) - val targetHead : Exp -> Head (* target type family *) - - (* Expanding type definitions *) - val targetFamOpt : Exp -> cid option (* target type family or NONE *) - val targetFam : Exp -> cid (* target type family *) - - (* Used in Flit *) - val rename : cid * string -> unit - -end; (* signature INTSYN *) diff --git a/third_party/pygments/tests/examplefiles/irb_heredoc b/third_party/pygments/tests/examplefiles/irb_heredoc deleted file mode 100644 index 3dc205e3e..000000000 --- a/third_party/pygments/tests/examplefiles/irb_heredoc +++ /dev/null @@ -1,8 +0,0 @@ -irb(main):001:0> puts < nil -irb(main):005:0> diff --git a/third_party/pygments/tests/examplefiles/irc.lsp b/third_party/pygments/tests/examplefiles/irc.lsp deleted file mode 100644 index 6f45976ae..000000000 --- a/third_party/pygments/tests/examplefiles/irc.lsp +++ /dev/null @@ -1,214 +0,0 @@ -#!/usr/bin/env newlisp - -;; @module IRC -;; @description a basic irc library -;; @version early alpha! 0.1 2011-10-31 14:21:26 -;; @author cormullion -;; Usage: -;; (IRC:init "newlithper") ; a username/nick (not that one obviously :-) -;; (IRC:connect "irc.freenode.net" 6667) ; irc/server -;; (IRC:join-channel {#newlisp}) ; join a room -;; either (IRC:read-irc-loop) ; loop - monitor only, no input -;; or (IRC:session) ; a command-line session, end with /QUIT - -(context 'IRC) - (define Inickname) - (define Ichannels) - (define Iserver) - (define Iconnected) - (define Icallbacks '()) - (define Idle-time 400) ; seconds - (define Itime-stamp) ; time since last message was processed - -(define (register-callback callback-name callback-function) - (println {registering callback for } callback-name { : } (sym (term callback-function) (prefix callback-function))) - (push (list callback-name (sym (term callback-function) (prefix callback-function))) Icallbacks)) - -(define (do-callback callback-name data) - (when (set 'func (lookup callback-name Icallbacks)) ; find first callback - (if-not (catch (apply func (list data)) 'error) - (println {error in callback } callback-name {: } error)))) - -(define (do-callbacks callback-name data) - (dolist (rf (ref-all callback-name Icallbacks)) - (set 'callback-entry (Icallbacks (first rf))) - (when (set 'func (last callback-entry)) - (if-not (catch (apply func (list data)) 'error) - (println {error in callback } callback-name {: } error))))) - -(define (init str) - (set 'Inickname str) - (set 'Iconnected nil) - (set 'Ichannels '()) - (set 'Itime-stamp (time-of-day))) - -(define (connect server port) - (set 'Iserver (net-connect server port)) - (net-send Iserver (format "USER %s %s %s :%s\r\n" Inickname Inickname Inickname Inickname)) - (net-send Iserver (format "NICK %s \r\n" Inickname)) - (set 'Iconnected true) - (do-callbacks "connect" (list (list "server" server) (list "port" port)))) - -(define (identify password) - (net-send Iserver (format "PRIVMSG nickserv :identify %s\r\n" password))) - -(define (join-channel channel) - (when (net-send Iserver (format "JOIN %s \r\n" channel)) - (push channel Ichannels) - (do-callbacks "join-channel" (list (list "channel" channel) (list "nickname" Inickname))))) - -(define (part chan) - (if-not (empty? chan) - ; leave specified - (begin - (net-send Iserver (format "PART %s\r\n" chan)) - (replace channel Ichannels) - (do-callbacks "part" (list (list "channel" channel)))) - ; leave all - (begin - (dolist (channel Ichannels) - (net-send Iserver (format "PART %s\r\n" channel)) - (replace channel Ichannels) - (do-callbacks "part" (list (list "channel" channel))))))) - -(define (do-quit message) - (do-callbacks "quit" '()) ; chance to do stuff before quit... - (net-send Iserver (format "QUIT :%s\r\n" message)) - (sleep 1000) - (set 'Ichannels '()) - (close Iserver) - (set 'Iconnected nil)) - -(define (privmsg user message) - (net-send Iserver (format "PRIVMSG %s :%s\r\n" user message))) - -(define (notice user message) - (net-send Iserver (format "NOTICE %s :%s\r\n" user message))) - -(define (send-to-server message (channel nil)) - (cond - ((starts-with message {/}) ; default command character - (set 'the-message (replace "^/" (copy message) {} 0)) ; keep original - (net-send Iserver (format "%s \r\n" the-message)) ; send it - ; do a quit - (if (starts-with (lower-case the-message) "quit") - (do-quit { enough}))) - (true - (if (nil? channel) - ; say to all channels - (dolist (c Ichannels) - (net-send Iserver (format "PRIVMSG %s :%s\r\n" c message))) - ; say to specified channel - (if (find channel Ichannels) - (net-send Iserver (format "PRIVMSG %s :%s\r\n" channel message)))))) - (do-callbacks "send-to-server" (list (list "channel" channel) (list "message" message)))) - -(define (process-command sender command text) - (cond - ((= sender "PING") - (net-send Iserver (format "PONG %s\r\n" command))) - ((or (= command "NOTICE") (= command "PRIVMSG")) - (process-message sender command text)) - ((= command "JOIN") - (set 'username (first (clean empty? (parse sender {!|:} 0)))) - (set 'channel (last (clean empty? (parse sender {!|:} 0)))) - (println {username } username { joined } channel) - (do-callbacks "join" (list (list "channel" channel) (list "username" username)))) - (true - nil))) - -(define (process-message sender command text) - (let ((username {} target {} message {})) - (set 'username (first (clean empty? (parse sender {!|:} 0)))) - (set 'target (trim (first (clean empty? (parse text {!|:} 0))))) - (set 'message (slice text (+ (find {:} text) 1))) - (cond - ((starts-with message "\001") - (process-ctcp username target message)) - ((find target Ichannels) - (cond - ((= command {PRIVMSG}) - (do-callbacks "channel-message" (list (list "channel" target) (list "username" username) (list "message" message)))) - ((= command {NOTICE}) - (do-callbacks "channel-notice" (list (list "channel" target) (list "username" username) (list "message" message)))))) - ((= target Inickname) - (cond - ((= command {PRIVMSG}) - (do-callbacks "private-message" (list (list "username" username) (list "message" message)))) - ((= command {NOTICE}) - (do-callbacks "private-notice" (list (list "username" username) (list "message" message)))))) - (true - nil)))) - -(define (process-ctcp username target message) - (cond - ((starts-with message "\001VERSION\001") - (net-send Iserver (format "NOTICE %s :\001VERSION %s\001\r\n" username version))) - ((starts-with message "\001PING") - (set 'data (first (rest (clean empty? (parse message { } 0))))) - (set 'data (trim data "\001" "\001")) - (net-send Iserver (format "NOTICE %s :\001PING %s\001\r\n" username data))) - ((starts-with message "\001ACTION") - (set 'data (first (rest (clean empty? (parse message { } 0))))) - (set 'data (join data { })) - (set 'data (trim data "\001" "\001")) - (if (find target Ichannels) - (do-callbacks "channel-action" (list (list "username" username) (list "message" message)))) - (if (= target Inickname) - (do-callbacks "private-action" (list (list "username" username) (list "message" message))))) - ((starts-with message "\001TIME\001") - (net-send Iserver (format "NOTICE %s:\001TIME :%s\001\r\n" username (date)))))) - -(define (parse-buffer raw-buffer) - (let ((messages (clean empty? (parse raw-buffer "\r\n" 0))) - (sender {} command {} text {})) - ; check for elapsed time since last activity - (when (> (sub (time-of-day) Itime-stamp) (mul Idle-time 1000)) - (do-callbacks "idle-event") - (set 'Itime-stamp (time-of-day))) - (dolist (message messages) - (set 'message-parts (parse message { })) - (unless (empty? message-parts) - (set 'sender (first message-parts)) - (catch (set 'command (first (rest message-parts))) 'error) - (catch (set 'text (join (rest (rest message-parts)) { })) 'error)) - (process-command sender command text)))) - -(define (read-irc) - (let ((buffer {})) - (when (!= (net-peek Iserver) 0) - (net-receive Iserver buffer 8192 "\n") - (unless (empty? buffer) - (parse-buffer buffer))))) - -(define (read-irc-loop) ; monitoring - (let ((buffer {})) - (while Iconnected - (read-irc) - (sleep 1000)))) - -(define (print-raw-message data) ; example of using a callback - (set 'raw-data (lookup "message" data)) - (set 'channel (lookup "channel" data)) - (set 'message-text raw-data) - (println (date (date-value) 0 {%H:%M:%S }) username {> } message-text)) - -(define (print-outgoing-message data) - (set 'raw-data (lookup "message" data)) - (set 'channel (lookup "channel" data)) - (set 'message-text raw-data) - (println (date (date-value) 0 {%H:%M:%S }) Inickname {> } message-text)) - -(define (session); interactive terminal - ; must add callbacks to display messages - (register-callback "channel-message" 'print-raw-message) - (register-callback "send-to-server" 'print-outgoing-message) - (while Iconnected - (while (zero? (peek 0)) - (read-irc)) - (send-to-server (string (read-line 0)))) - (println {finished session } (date)) - (exit)) - -; end of IRC code - diff --git a/third_party/pygments/tests/examplefiles/java.properties b/third_party/pygments/tests/examplefiles/java.properties deleted file mode 100644 index 72ad0f964..000000000 --- a/third_party/pygments/tests/examplefiles/java.properties +++ /dev/null @@ -1,16 +0,0 @@ -foo = bar -foo: bar -foo.oof: \ - bar=baz; \ - asdf - -// comment -# comment -; comment - -x:a\ -b -x: a \ - b - -x = \ diff --git a/third_party/pygments/tests/examplefiles/jbst_example1.jbst b/third_party/pygments/tests/examplefiles/jbst_example1.jbst deleted file mode 100644 index 0e7d014f0..000000000 --- a/third_party/pygments/tests/examplefiles/jbst_example1.jbst +++ /dev/null @@ -1,28 +0,0 @@ -<%@ Control Name="MyApp.MyJbstControl" Language="JavaScript" %> - - - -<%! - /* initialization code block, executed only once as control is loaded */ - /* alternate syntax to script block above */ - this.myInitTime = this.generateValue(); -%> - -<% - /* data binding code block, executed each time as control is data bound */ - this.myBindTime = this.generateValue(); -%> - -<%-- JBST Comment --%> -<%= this.myBindTime /* data binding expression */ %> -<%= this.myInitTime /* data binding expression */ %> - - -<%$ Resources: localizationKey %><%-- JBST globalization--%> \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/jbst_example2.jbst b/third_party/pygments/tests/examplefiles/jbst_example2.jbst deleted file mode 100644 index 2b5e0489b..000000000 --- a/third_party/pygments/tests/examplefiles/jbst_example2.jbst +++ /dev/null @@ -1,45 +0,0 @@ -<%@ Control Name="Foo.MyZebraList" Language="JavaScript" %> - - - -
    -

    <%= this.data.title %> as of <%= this.formatTime(this.data.timestamp) %>!

    -

    <%= this.data.description %>

    -
      - - - - -
    • - <%= this.data.label %> (<%= this.index+1 %> of <%= this.count %>) -
    • -
      - -
    -
    \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/jinjadesignerdoc.rst b/third_party/pygments/tests/examplefiles/jinjadesignerdoc.rst deleted file mode 100644 index b4b6c44b1..000000000 --- a/third_party/pygments/tests/examplefiles/jinjadesignerdoc.rst +++ /dev/null @@ -1,713 +0,0 @@ -====================== -Designer Documentation -====================== - -This part of the Jinja documentaton is meant for template designers. - -Basics -====== - -The Jinja template language is designed to strike a balance between content -and application logic. Nevertheless you can use a python like statement -language. You don't have to know how Python works to create Jinja templates, -but if you know it you can use some additional statements you may know from -Python. - -Here is a small example template: - -.. sourcecode:: html+jinja - - - - - My Webpage - - - - -

    My Webpage

    - {{ variable }} - - - -This covers the default settings. The application developer might have changed -the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar. This -documentation just covers the default values. - -A variable looks like ``{{ foobar }}`` where foobar is the variable name. Inside -of statements (``{% some content here %}``) variables are just normal names -without the braces around it. In fact ``{{ foobar }}`` is just an alias for -the statement ``{% print foobar %}``. - -Variables are coming from the context provided by the application. Normally there -should be a documentation regarding the context contents but if you want to know -the content of the current context, you can add this to your template: - -.. sourcecode:: html+jinja - -
    {{ debug()|e }}
    - -A context isn't flat which means that each variable can has subvariables, as long -as it is representable as python data structure. You can access attributes of -a variable using the dot and bracket operators. The following examples show -this: - -.. sourcecode:: jinja - - {{ user.username }} - is the same as - {{ user['username'] }} - you can also use a variable to access an attribute: - {{ users[current_user].username }} - If you have numerical indices you have to use the [] syntax: - {{ users[0].username }} - -Filters -======= - -In the examples above you might have noticed the pipe symbols. Pipe symbols tell -the engine that it has to apply a filter on the variable. Here is a small example: - -.. sourcecode:: jinja - - {{ variable|replace('foo', 'bar')|escape }} - -If you want, you can also put whitespace between the filters. - -This will look for a variable `variable`, pass it to the filter `replace` -with the arguments ``'foo'`` and ``'bar'``, and pass the result to the filter -`escape` that automatically XML-escapes the value. The `e` filter is an alias for -`escape`. Here is the complete list of supported filters: - -[[list_of_filters]] - -.. admonition:: note - - Filters have a pretty low priority. If you want to add fitered values - you have to put them into parentheses. The same applies if you want to access - attributes: - - .. sourcecode:: jinja - - correct: - {{ (foo|filter) + (bar|filter) }} - wrong: - {{ foo|filter + bar|filter }} - - correct: - {{ (foo|filter).attribute }} - wrong: - {{ foo|filter.attribute }} - -Tests -===== - -You can use the `is` operator to perform tests on a value: - -.. sourcecode:: jinja - - {{ 42 is numeric }} -> true - {{ "foobar" is numeric }} -> false - {{ 'FOO' is upper }} -> true - -These tests are especially useful when used in `if` conditions. - -[[list_of_tests]] - -Global Functions -================ - -Test functions and filter functions live in their own namespace. Global -functions not. They behave like normal objects in the context. Beside the -functions added by the application or framewhere there are two functions -available per default: - -`range` - - Works like the python `range function`_ just that it doesn't support - ranges greater than ``1000000``. - -`debug` - - Function that outputs the contents of the context. - -Loops -===== - -To iterate over a sequence, you can use the `for` loop. It basically looks like a -normal Python `for` loop and works pretty much the same: - -.. sourcecode:: html+jinja - -

    Members

    -
      - {% for user in users %} -
    • {{ loop.index }} / {{ loop.length }} - {{ user.username|escape }}
    • - {% else %} -
    • no users found
    • - {% endfor %} -
    - -*Important* Contrary to Python is the optional ``else`` block only -executed if there was no iteration because the sequence was empty. - -Inside of a `for` loop block you can access some special variables: - -+----------------------+----------------------------------------+ -| Variable | Description | -+======================+========================================+ -| `loop.index` | The current iteration of the loop. | -+----------------------+----------------------------------------+ -| `loop.index0` | The current iteration of the loop, | -| | starting counting by 0. | -+----------------------+----------------------------------------+ -| `loop.revindex` | The number of iterations from the end | -| | of the loop. | -+----------------------+----------------------------------------+ -| `loop.revindex0` | The number of iterations from the end | -| | of the loop, starting counting by 0. | -+----------------------+----------------------------------------+ -| `loop.first` | True if first iteration. | -+----------------------+----------------------------------------+ -| `loop.last` | True if last iteration. | -+----------------------+----------------------------------------+ -| `loop.even` | True if current iteration is even. | -+----------------------+----------------------------------------+ -| `loop.odd` | True if current iteration is odd. | -+----------------------+----------------------------------------+ -| `loop.length` | Total number of items in the sequence. | -+----------------------+----------------------------------------+ -| `loop.parent` | The context of the parent loop. | -+----------------------+----------------------------------------+ - -Loops also support recursion. Let's assume you have a sitemap where each item -might have a number of child items. A template for that could look like this: - -.. sourcecode:: html+jinja - -

    Sitemap -
      - {% for item in sitemap recursive %} -
    • {{ item.title|e }} - {% if item.children %}
        {{ loop(item.children) }}
      {% endif %}
    • - {% endfor %} -
    - -What happens here? Basically the first thing that is different to a normal -loop is the additional ``recursive`` modifier in the `for`-loop declaration. -It tells the template engine that we want recursion. If recursion is enabled -the special `loop` variable is callable. If you call it with a sequence it will -automatically render the loop at that position with the new sequence as argument. - -Cycling -======= - -Sometimes you might want to have different text snippets for each row in a list, -for example to have alternating row colors. You can easily do this by using the -``{% cycle %}`` tag: - -.. sourcecode:: html+jinja - -
      - {% for message in messages %} -
    • {{ message|e }}
    • - {% endfor %} -
    - -Each time Jinja encounters a `cycle` tag it will cycle through the list -of given items and return the next one. If you pass it one item jinja assumes -that this item is a sequence from the context and uses this: - -.. sourcecode:: html+jinja - -
  • ...
  • - -Conditions -========== - -Jinja supports Python-like `if` / `elif` / `else` constructs: - -.. sourcecode:: jinja - - {% if user.active %} - user {{ user.name|e }} is active. - {% elif user.deleted %} - user {{ user.name|e }} was deleted some time ago. - {% else %} - i don't know what's wrong with {{ user.username|e }} - {% endif %} - -If the user is active the first block is rendered. If not and the user was -deleted the second one, in all other cases the third one. - -You can also use comparison operators: - -.. sourcecode:: html+jinja - - {% if amount < 0 %} - {{ amount }} - {% else %} - {{ amount }} - {% endif %} - -.. admonition:: Note - - Of course you can use `or` / `and` and parentheses to create more complex - conditions, but usually the logic is already handled in the application and - you don't have to create such complex constructs in the template code. However - in some situations it might be a good thing to have the abilities to create - them. - -Operators -========= - -Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can -can use expressions. In expressions you can use any of the following operators: - - ======= =================================================================== - ``+`` add the right operand to the left one. - ``{{ 1 + 2 }}`` would return ``3``. - ``-`` subtract the right operand from the left one. - ``{{ 1 - 1 }}`` would return ``0``. - ``/`` divide the left operand by the right one. - ``{{ 1 / 2 }}`` would return ``0.5``. - ``*`` multiply the left operand with the right one. - ``{{ 2 * 2 }}`` would return ``4``. - ``**`` raise the left operand to the power of the right - operand. ``{{ 2**3 }}`` would return ``8``. - ``in`` perform sequence membership test. ``{{ 1 in [1,2,3] }}`` would - return true. - ``is`` perform a test on the value. See the section about - tests for more information. - ``|`` apply a filter on the value. See the section about - filters for more information. - ``and`` return true if the left and the right operand is true. - ``or`` return true if the left or the right operand is true. - ``not`` negate a statement (see below) - ``()`` call a callable: ``{{ user.get_username() }}``. Inside of the - parentheses you can use variables: ``{{ user.get(username) }}``. - ======= =================================================================== - -Note that there is no support for any bit operations or something similar. - -* special note regarding `not`: The `is` and `in` operators support negation - using an infix notation too: ``foo is not bar`` and ``foo not in bar`` - instead of ``not foo is bar`` and ``not foo in bar``. All other expressions - require a prefix notation: ``not (foo and bar)``. - -Boolean Values -============== - -In If-Conditions Jinja performs a boolean check. All empty values (eg: empty -lists ``[]``, empty dicts ``{}`` etc) evaluate to `false`. Numbers that are -equal to `0`/`0.00` are considered `false` too. The boolean value of other -objects depends on the behavior the application developer gave it. Usually -items are `true`. - -Here some examples that should explain it: - -.. sourcecode:: jinja - - {% if [] %} - will always be false because it's an empty list - - {% if {} %} - false too. - - {% if ['foo'] %} - this is true. Because the list is not empty. - - {% if "foobar" %} - this is also true because the string is not empty. - -Slicing -======= - -Some objects support slicing operations. For example lists: - -.. sourcecode:: jinja - - {% for item in items[:5] %} - This will only iterate over the first 5 items of the list - - {% for item in items[5:10] %} - This will only iterate from item 5 to 10. - - {% for item in items[:10:2] %} - This will only yield items from start to ten and only returing - even items. - -For more informations about slicing have a look at the `slicing chapter`_ -in the "Dive into Python" e-book. - -Macros -====== - -If you want to use a partial template in more than one place, you might want to -create a macro from it: - -.. sourcecode:: html+jinja - - {% macro show_user user %} -

    {{ user.name|e }}

    -
    - {{ user.description }} -
    - {% endmacro %} - -Now you can use it from everywhere in the code by passing it an item: - -.. sourcecode:: jinja - - {% for user in users %} - {{ show_user(user) }} - {% endfor %} - -You can also specify more than one value: - -.. sourcecode:: html+jinja - - {% macro show_dialog title, text %} -
    -

    {{ title|e }}

    -
    {{ text|e }}
    -
    - {% endmacro %} - - {{ show_dialog('Warning', 'something went wrong i guess') }} - -Inheritance -=========== - -The most powerful part of Jinja is template inheritance. Template inheritance -allows you to build a base "skeleton" template that contains all the common -elements of your site and defines **blocks** that child templates can override. - -Sounds complicated but is very basic. It's easiest to understand it by starting -with an example. - -Base Template -------------- - -This template, which we'll call ``base.html``, defines a simple HTML skeleton -document that you might use for a simple two-column page. It's the job of -"child" templates to fill the empty blocks with content: - -.. sourcecode:: html+jinja - - - - - - {% block title %}{% endblock %} - My Webpage - {% block html_head %}{% endblock %} - - -
    - {% block content %}{% endblock %} -
    - - - - -In this example, the ``{% block %}`` tags define four blocks that child templates -can fill in. All the `block` tag does is to tell the template engine that a -child template may override those portions of the template. - -Child Template --------------- - -A child template might look like this: - -.. sourcecode:: html+jinja - - {% extends "base.html" %} - {% block title %}Index{% endblock %} - - {% block html_head %} - - {% endblock %} - - {% block content %} -

    Index

    -

    - Welcome on my awsome homepage. -

    - {% endblock %} - -The ``{% extends %}`` tag is the key here. It tells the template engine that -this template "extends" another template. When the template system evaluates -this template, first it locates the parent. - -The filename of the template depends on the template loader. For example the -``FileSystemLoader`` allows you to access other templates by giving the -filename. You can access templates in subdirectories with an slash: - -.. sourcecode:: jinja - - {% extends "layout/default.html" %} - -But this behavior can depend on the application using Jinja. - -Note that since the child template didn't define the ``footer`` block, the -value from the parent template is used instead. - -.. admonition:: Note - - You can't define multiple ``{% block %}`` tags with the same name in the - same template. This limitation exists because a block tag works in "both" - directions. That is, a block tag doesn't just provide a hole to fill - it - also defines the content that fills the hole in the *parent*. If there were - two similarly-named ``{% block %}`` tags in a template, that template's - parent wouldn't know which one of the blocks' content to use. - -Template Inclusion -================== - -You can load another template at a given position using ``{% include %}``. -Usually it's a better idea to use inheritance but if you for example want to -load macros, `include` works better than `extends`: - -.. sourcecode:: jinja - - {% include "myhelpers.html" %} - {{ my_helper("foo") }} - -If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now -use it from the template as shown above. - -Filtering Blocks -================ - -Sometimes it could be a good idea to filter a complete block of text. For -example, if you want to escape some html code: - -.. sourcecode:: jinja - - {% filter escape %} - - goes here - - {% endfilter %} - -Of course you can chain filters too: - -.. sourcecode:: jinja - - {% filter lower|escape %} - SOME TEXT - {% endfilter %} - -returns ``"<b>some text</b>"``. - -Defining Variables -================== - -You can also define variables in the namespace using the ``{% set %}`` tag: - -.. sourcecode:: jinja - - {% set foo = 'foobar' %} - {{ foo }} - -This should ouput ``foobar``. - -Scopes -====== - -Jinja has multiple scopes. A scope is something like a new transparent foil on -a stack of foils. You can only write to the outermost foil but read all of them -since you can look through them. If you remove the top foil all data on that -foil disappears. Some tags in Jinja add a new layer to the stack. Currently -these are `block`, `for`, `macro` and `filter`. This means that variables and -other elements defined inside a macro, loop or some of the other tags listed -above will be only available in that block. Here an example: - -.. sourcecode:: jinja - - {% macro angryhello name %} - {% set angryname = name|upper %} - Hello {{ name }}. Hello {{ name }}! - HELLO {{ angryname }}!!!!!!111 - {% endmacro %} - -The variable ``angryname`` just exists inside the macro, not outside it. - -Defined macros appear on the context as variables. Because of this, they are -affected by the scoping too. A macro defined inside of a macro is just available -in those two macros (the macro itself and the macro it's defined in). For `set` -and `macro` two additional rules exist: If a macro is defined in an extended -template but outside of a visible block (thus outside of any block) will be -available in all blocks below. This allows you to use `include` statements to -load often used macros at once. - -Undefined Variables -=================== - -If you have already worked with python you probably know about the fact that -undefined variables raise an exception. This is different in Jinja. There is a -special value called `undefined` that represents values that do not exist. - -This special variable works complete different from any variables you maybe -know. If you print it using ``{{ variable }}`` it will not appear because it's -literally empty. If you try to iterate over it, it will work. But no items -are returned. Comparing this value to any other value results in `false`. -Even if you compare it to itself: - -.. sourcecode:: jinja - - {{ undefined == undefined }} - will return false. Not even undefined is undefined :) - Use `is defined` / `is not defined`: - - {{ undefined is not defined }} - will return true. - -There are also some additional rules regarding this special value. Any -mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand -as result: - -.. sourcecode:: jinja - - {{ undefined + "foo" }} - returns "foo" - - {{ undefined - 42 }} - returns 42. Note: not -42! - -In any expression `undefined` evaluates to `false`. It has no length, all -attribute calls return undefined, calling too: - -.. sourcecode:: jinja - - {{ undefined.attribute().attribute_too[42] }} - still returns `undefined`. - -Escaping -======== - -Sometimes you might want to add Jinja syntax elements into the template -without executing them. In that case you have quite a few possibilities. - -For small parts this might be a good way: - -.. sourcecode:: jinja - - {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }} - -When you have multiple elements you can use the ``raw`` block: - -.. sourcecode:: jinja - - {% raw %} - Filtering blocks works like this in Jinja: - {% filter escape %} - - goes here - - {% endfilter %} - {% endraw %} - -Reserved Keywords -================= - -Jinja has some keywords you cannot use a variable names. This limitation -exists to make look coherent. Syntax highlighters won't mess things up and -you will don't have unexpected output. - -The following keywords exist and cannot be used as identifiers: - - `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`, - `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`, - `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`, - `raw`, `recursive`, `set`, `trans` - -If you want to use such a name you have to prefix or suffix it or use -alternative names: - -.. sourcecode:: jinja - - {% for macro_ in macros %} - {{ macro_('foo') }} - {% endfor %} - -If future Jinja releases add new keywords those will be "light" keywords which -means that they won't raise an error for several releases but yield warnings -on the application side. But it's very unlikely that new keywords will be -added. - -Internationalization -==================== - -If the application is configured for i18n, you can define translatable blocks -for translators using the `trans` tag or the special underscore function: - -.. sourcecode:: jinja - - {% trans %} - this is a translatable block - {% endtrans %} - - {% trans "This is a translatable string" %} - - {{ _("This is a translatable string") }} - -The latter one is useful if you want translatable arguments for filters etc. - -If you want to have plural forms too, use the `pluralize` block: - -.. sourcecode:: jinja - - {% trans users=users %} - One user found. - {% pluralize %} - {{ users }} users found. - {% endtrans %} - - {% trans first=(users|first).username|escape, user=users|length %} - one user {{ first }} found. - {% pluralize users %} - {{ users }} users found, the first one is called {{ first }}. - {% endtrans %} - -If you have multiple arguments, the first one is assumed to be the indicator (the -number that is used to determine the correct singular or plural form. If you -don't have the indicator variable on position 1 you have to tell the `pluralize` -tag the correct variable name. - -Inside translatable blocks you cannot use blocks or expressions (however you can -still use the ``raw`` block which will work as expected). The variable -print syntax (``{{ variablename }}``) is the only way to insert the variables -defined in the ``trans`` header. Filters must be applied in the header. - -.. admonition:: note - - Please make sure that you always use pluralize blocks where required. - Many languages have more complex plural forms than the English language. - - Never try to workaround that issue by using something like this: - - .. sourcecode:: jinja - - {% if count != 1 %} - {{ count }} users found. - {% else %} - one user found. - {% endif %} - -.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice -.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000 diff --git a/third_party/pygments/tests/examplefiles/json.lasso b/third_party/pygments/tests/examplefiles/json.lasso deleted file mode 100644 index 72926112e..000000000 --- a/third_party/pygments/tests/examplefiles/json.lasso +++ /dev/null @@ -1,301 +0,0 @@ - - // - // - // - -If: (Lasso_TagExists: 'Encode_JSON') == False; - - Define_Tag: 'JSON', -Namespace='Encode_', -Required='value', -Optional='options'; - - Local: 'escapes' = Map('\\' = '\\', '"' = '"', '\r' = 'r', '\n' = 'n', '\t' = 't', '\f' = 'f', '\b' = 'b'); - Local: 'output' = ''; - Local: 'newoptions' = (Array: -Internal); - If: !(Local_Defined: 'options') || (#options->(IsA: 'array') == False); - Local: 'options' = (Array); - /If; - If: (#options >> -UseNative) || (Params >> -UseNative); - #newoptions->(Insert: -UseNative); - /If; - If: (#options >> -NoNative) || (Params >> -NoNative); - #newoptions->(Insert: -NoNative); - /If; - If: (#options !>> -UseNative) && ((#value->(IsA: 'set')) || (#value->(IsA: 'list')) || (#value->(IsA: 'queue')) || (#value->(IsA: 'priorityqueue')) || (#value->(IsA: 'stack'))); - #output += (Encode_JSON: Array->(insertfrom: #value->iterator) &, -Options=#newoptions); - Else: (#options !>> -UseNative) && (#value->(IsA: 'pair')); - #output += (Encode_JSON: (Array: #value->First, #value->Second)); - Else: (#options !>> -Internal) && (#value->(Isa: 'array') == False) && (#value->(IsA: 'map') == False); - #output += '[' + (Encode_JSON: #value, -Options=#newoptions) + ']'; - Else: (#value->(IsA: 'literal')); - #output += #value; - Else: (#value->(IsA: 'string')); - #output += '"'; - Loop: (#value->Length); - Local('character' = #value->(Get: Loop_Count)); - #output->(Append: - (Match_RegExp('[\\x{0020}-\\x{21}\\x{23}-\\x{5b}\\x{5d}-\\x{10fff}]') == #character) ? #character | - '\\' + (#escapes->(Contains: #character) ? #escapes->(Find: #character) | 'u' + String(Encode_Hex(#character))->PadLeading(4, '0')&) - ); - /Loop; - #output += '"'; - Else: (#value->(IsA: 'integer')) || (#value->(IsA: 'decimal')) || (#value->(IsA: 'boolean')); - #output += (String: #value); - Else: (#value->(IsA: 'null')); - #output += 'null'; - Else: (#value->(IsA: 'date')); - If: #value->gmt; - #output += '"' + #value->(format: '%QT%TZ') + '"'; - Else; - #output += '"' + #value->(format: '%QT%T') + '"'; - /If; - Else: (#value->(IsA: 'array')); - #output += '['; - Iterate: #value, (Local: 'temp'); - #output += (Encode_JSON: #temp, -Options=#newoptions); - If: #value->Size != Loop_Count; - #output += ', '; - /If; - /Iterate; - #output += ']'; - Else: (#value->(IsA: 'object')); - #output += '{'; - Iterate: #value, (Local: 'temp'); - #output += #temp->First + ': ' + (Encode_JSON: #temp->Second, -Options=#newoptions); - If: (#value->Size != Loop_Count); - #output += ', '; - /If; - /Iterate; - #output += '}'; - Else: (#value->(IsA: 'map')); - #output += '{'; - Iterate: #value, (Local: 'temp'); - #output += (Encode_JSON: #temp->First, -Options=#newoptions) + ': ' + (Encode_JSON: #temp->Second, -Options=#newoptions); - If: (#value->Size != Loop_Count); - #output += ', '; - /If; - /Iterate; - #output += '}'; - Else: (#value->(IsA: 'client_ip')) || (#value->(IsA: 'client_address')); - #output += (Encode_JSON: (String: #value), -Options=#newoptions); - Else: (#options !>> -UseNative) && (#value->(IsA: 'set')) || (#value->(IsA: 'list')) || (#value->(IsA: 'queue')) || (#value->(IsA: 'priorityqueue')) || (#value->(IsA: 'stack')); - #output += (Encode_JSON: Array->(insertfrom: #value->iterator) &, -Options=#newoptions); - Else: (#options !>> -NoNative); - #output += (Encode_JSON: (Map: '__jsonclass__'=(Array:'deserialize',(Array:'' + #value->Serialize + '')))); - /If; - Return: @#output; - - /Define_Tag; - -/If; - -If: (Lasso_TagExists: 'Decode_JSON') == False; - - Define_Tag: 'JSON', -Namespace='Decode_', -Required='value'; - - (#value == '') ? Return: Null; - - Define_Tag: 'consume_string', -Required='ibytes'; - Local: 'unescapes' = (map: 34 = '"', 92 = '\\', 98 = '\b', 102 = '\f', 110 = '\n', 114 = '\r', 116 = '\t'); - Local: 'temp' = 0, 'obytes' = Bytes; - While: ((#temp := #ibytes->export8bits) != 34); // '"' - If: (#temp === 92); // '\' - #temp = #ibytes->export8bits; - If: (#temp === 117); // 'u' - #obytes->(ImportString: (Decode_Hex: (String: #ibytes->(GetRange: #ibytes->Position + 1, 4)))->(ExportString: 'UTF-16'), 'UTF-8'); - #ibytes->(SetPosition: #ibytes->Position + 4); - Else; - If: (#unescapes->(Contains: #temp)); - #obytes->(ImportString: #unescapes->(Find: #temp), 'UTF-8'); - Else; - #obytes->(Import8Bits: #temp); - /If; - /If; - Else; - #obytes->(Import8Bits: #temp); - /If; - /While; - Local('output' = #obytes->(ExportString: 'UTF-8')); - If: #output->(BeginsWith: '') && #output->(EndsWith: ''); - Local: 'temp' = #output - '' - ''; - Local: 'output' = null; - Protect; - #output->(Deserialize: #temp); - /Protect; - Else: (Valid_Date: #output, -Format='%QT%TZ'); - Local: 'output' = (Date: #output, -Format='%QT%TZ'); - Else: (Valid_Date: #output, -Format='%QT%T'); - Local: 'output' = (Date: #output, -Format='%QT%T'); - /If; - Return: @#output; - /Define_Tag; - - Define_Tag: 'consume_token', -Required='ibytes', -required='temp'; - Local: 'obytes' = bytes->(import8bits: #temp) &; - local: 'delimit' = (array: 9, 10, 13, 32, 44, 58, 93, 125); // \t\r\n ,:]} - While: (#delimit !>> (#temp := #ibytes->export8bits)); - #obytes->(import8bits: #temp); - /While; - Local: 'output' = (String: #obytes); - If: (#output == 'true') || (#output == 'false'); - Return: (Boolean: #output); - Else: (#output == 'null'); - Return: Null; - Else: (String_IsNumeric: #output); - Return: (#output >> '.') ? (Decimal: #output) | (Integer: #output); - /If; - Return: @#output; - /Define_Tag; - - Define_Tag: 'consume_array', -Required='ibytes'; - Local: 'output' = array; - local: 'delimit' = (array: 9, 10, 13, 32, 44); // \t\r\n , - local: 'temp' = 0; - While: ((#temp := #ibytes->export8bits) != 93); // ] - If: (#delimit >> #temp); - // Discard whitespace - Else: (#temp == 34); // " - #output->(insert: (consume_string: @#ibytes)); - Else: (#temp == 91); // [ - #output->(insert: (consume_array: @#ibytes)); - Else: (#temp == 123); // { - #output->(insert: (consume_object: @#ibytes)); - Else; - #output->(insert: (consume_token: @#ibytes, @#temp)); - (#temp == 93) ? Loop_Abort; - /If; - /While; - Return: @#output; - /Define_Tag; - - Define_Tag: 'consume_object', -Required='ibytes'; - Local: 'output' = map; - local: 'delimit' = (array: 9, 10, 13, 32, 44); // \t\r\n , - local: 'temp' = 0; - local: 'key' = null; - local: 'val' = null; - While: ((#temp := #ibytes->export8bits) != 125); // } - If: (#delimit >> #temp); - // Discard whitespace - Else: (#key !== null) && (#temp == 34); // " - #output->(insert: #key = (consume_string: @#ibytes)); - #key = null; - Else: (#key !== null) && (#temp == 91); // [ - #output->(insert: #key = (consume_array: @#ibytes)); - #key = null; - Else: (#key !== null) && (#temp == 123); // { - #output->(insert: #key = (consume_object: @#ibytes)); - #key = null; - Else: (#key !== null); - #output->(insert: #key = (consume_token: @#ibytes, @#temp)); - (#temp == 125) ? Loop_abort; - #key = null; - Else; - #key = (consume_string: @#ibytes); - while(#delimit >> (#temp := #ibytes->export8bits)); - /while; - #temp != 58 ? Loop_Abort; - /If; - /While; - If: (#output >> '__jsonclass__') && (#output->(Find: '__jsonclass__')->(isa: 'array')) && (#output->(Find: '__jsonclass__')->size >= 2) && (#output->(Find: '__jsonclass__')->First == 'deserialize'); - Return: #output->(find: '__jsonclass__')->Second->First; - Else: (#output >> 'native') && (#output >> 'comment') && (#output->(find: 'comment') == 'http://www.lassosoft.com/json'); - Return: #output->(find: 'native'); - /If; - Return: @#output; - /Define_Tag; - - Local: 'ibytes' = (bytes: #value); - Local: 'start' = 1; - #ibytes->removeLeading(BOM_UTF8); - Local: 'temp' = #ibytes->export8bits; - If: (#temp == 91); // [ - Local: 'output' = (consume_array: @#ibytes); - Return: @#output; - Else: (#temp == 123); // { - Local: 'output' = (consume_object: @#ibytes); - Return: @#output; - /If; - - /Define_Tag; - -/If; - -If: (Lasso_TagExists: 'Literal') == False; - - Define_Type: 'Literal', 'String'; - /Define_Type; - -/If; - -If: (Lasso_TagExists: 'Object') == False; - - Define_Type: 'Object', 'Map'; - /Define_Type; - -/If; - -If: (Lasso_TagExists: 'JSON_RPCCall') == False; - - Define_Tag: 'RPCCall', -Namespace='JSON_', - -Required='method', - -Optional='params', - -Optional='id', - -Optional='host'; - - !(Local_Defined: 'host') ? Local: 'host' = 'http://localhost/lassoapps.8/rpc/rpc.lasso'; - !(Local_Defined: 'id') ? Local: 'id' = Lasso_UniqueID; - Local: 'request' = (Map: 'method' = #method, 'params' = #params, 'id' = #id); - Local: 'request' = (Encode_JSON: #request); - Local: 'result' = (Include_URL: #host, -PostParams=#request); - Local: 'result' = (Decode_JSON: #result); - Return: @#result; - - /Define_Tag; - -/If; - -If: (Lasso_TagExists: 'JSON_Records') == False; - - Define_Tag: 'JSON_Records', - -Optional='KeyField', - -Optional='ReturnField', - -Optional='ExcludeField', - -Optional='Fields'; - - Local: '_fields' = (Local_Defined: 'fields') && #fields->(IsA: 'array') ? #fields | Field_Names; - Fail_If: #_fields->size == 0, -1, 'No fields found for [JSON_Records]'; - Local: '_keyfield' = (Local: 'keyfield'); - If: #_fields !>> #_keyfield; - Local: '_keyfield' = (KeyField_Name); - If: #_fields !>> #_keyfield; - Local: '_keyfield' = 'ID'; - If: #_fields !>> #_keyfield; - Local: '_keyfield' = #_fields->First; - /If; - /If; - /If; - Local: '_index' = #_fields->(FindPosition: #_keyfield)->First; - Local: '_return' = (Local_Defined: 'returnfield') ? (Params->(Find: -ReturnField)->(ForEach: {Params->First = Params->First->Second; Return: True}) &) | @#_fields; - Local: '_exclude' = (Local_Defined: 'excludefield') ? (Params->(Find: -ExcludeField)->(ForEach: {Params->First = Params->First->Second; Return: True}) &) | Array; - Local: '_records' = Array; - Iterate: Records_Array, (Local: '_record'); - Local: '_temp' = Map; - Iterate: #_fields, (Local: '_field'); - ((#_return >> #_field) && (#_exclude !>> #_field)) ? #_temp->Insert(#_field = #_record->(Get: Loop_Count)); - /Iterate; - #_records->Insert(#_temp); - /Iterate; - Local: '_output' = (Encode_JSON: (Object: 'error_msg'=Error_Msg, 'error_code'=Error_Code, 'found_count'=Found_Count, 'keyfield'=#_keyfield, 'rows'=#_records)); - Return: @#_output; - - /Define_Tag; - -/If; - -?> diff --git a/third_party/pygments/tests/examplefiles/json.lasso9 b/third_party/pygments/tests/examplefiles/json.lasso9 deleted file mode 100644 index 732ab2afb..000000000 --- a/third_party/pygments/tests/examplefiles/json.lasso9 +++ /dev/null @@ -1,213 +0,0 @@ - -/** - trait_json_serialize - Objects with this trait will be assumed to convert to json data - when its ->asString method is called -*/ -define trait_json_serialize => trait { - require asString() -} - -define json_serialize(e::bytes)::string => ('"' + (string(#e)->Replace(`\`, `\\`) & Replace('\"', '\\"') & Replace('\r', '\\r') & Replace('\n', '\\n') & Replace('\t', '\\t') & Replace('\f', '\\f') & Replace('\b', '\\b') &) + '"') -define json_serialize(e::string)::string => ('"' + (string(#e)->Replace(`\`, `\\`) & Replace('\"', '\\"') & Replace('\r', '\\r') & Replace('\n', '\\n') & Replace('\t', '\\t') & Replace('\f', '\\f') & Replace('\b', '\\b') &) + '"') -define json_serialize(e::json_literal)::string => (#e->asstring) -define json_serialize(e::integer)::string => (#e->asstring) -define json_serialize(e::decimal)::string => (#e->asstring) -define json_serialize(e::boolean)::string => (#e->asstring) -define json_serialize(e::null)::string => ('null') -define json_serialize(e::date)::string => ('"' + #e->format(#e->gmt ? '%QT%TZ' | '%Q%T') + '"') -/* -define json_serialize(e::array)::string => { - local(output) = ''; - local(delimit) = ''; - #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } - return('[' + #output + ']'); -} -define json_serialize(e::staticarray)::string => { - local(output) = ''; - local(delimit) = ''; - #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } - return('[' + #output + ']'); -} -*/ -define json_serialize(e::trait_forEach)::string => { - local(output) = ''; - local(delimit) = ''; - #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } - return('[' + #output + ']'); -} -define json_serialize(e::map)::string => { - local(output = with pr in #e->eachPair - select json_serialize(#pr->first->asString) + ': ' + json_serialize(#pr->second)) - return '{' + #output->join(',') + '}' -} -define json_serialize(e::json_object)::string => { - local(output) = ''; - local(delimit) = ''; - #e->foreachpair => { #output += #delimit + #1->first + ': ' + json_serialize(#1->second); #delimit = ', '; } - return('{' + #output + '}'); -} -define json_serialize(e::trait_json_serialize) => #e->asString -define json_serialize(e::any)::string => json_serialize('' + #e->serialize + '') - -// Bil Corry fixes for decoding json -define json_consume_string(ibytes::bytes) => { - local(obytes) = bytes; - local(temp) = 0; - while((#temp := #ibytes->export8bits) != 34); - #obytes->import8bits(#temp); - (#temp == 92) ? #obytes->import8bits(#ibytes->export8bits); // Escape \ - /while; - local(output = string(#obytes)->unescape) - //Replace('\\"', '\"') & Replace('\\r', '\r') & Replace('\\n', '\n') & Replace('\\t', '\t') & Replace('\\f', '\f') & Replace('\\b', '\b') &; - if(#output->BeginsWith('') && #output->EndsWith('')); - Protect; - return serialization_reader(xml(#output - '' - ''))->read - /Protect; - else( (#output->size == 16 or #output->size == 15) and regexp(`\d{8}T\d{6}Z?`, '', #output)->matches) - return date(#output, -Format=#output->size == 16?`yyyyMMdd'T'HHmmssZ`|`yyyyMMdd'T'HHmmss`) - /if - return #output -} - -// Bil Corry fix + Ke fix -define json_consume_token(ibytes::bytes, temp::integer) => { - - local(obytes = bytes->import8bits(#temp) &, - delimit = array(9, 10, 13, 32, 44, 58, 93, 125)) // \t\r\n ,:]} - - while(#delimit !>> (#temp := #ibytes->export8bits)) - #obytes->import8bits(#temp) - /while - - #temp == 125? // } - #ibytes->marker -= 1 -//============================================================================ -// Is also end of token if end of array[] - #temp == 93? // ] - #ibytes->marker -= 1 -//............................................................................ - - local(output = string(#obytes)) - #output == 'true'? - return true - #output == 'false'? - return false - #output == 'null'? - return null - string_IsNumeric(#output)? - return (#output >> '.')? decimal(#output) | integer(#output) - - return #output -} - -// Bil Corry fix -define json_consume_array(ibytes::bytes)::array => { - Local(output) = array; - local(delimit) = array( 9, 10, 13, 32, 44); // \t\r\n , - local(temp) = 0; - While((#temp := #ibytes->export8bits) != 93); // ] - If(#delimit >> #temp); - // Discard whitespace - Else(#temp == 34); // " - #output->insert(json_consume_string(#ibytes)); - Else(#temp == 91); // [ - #output->insert(json_consume_array(#ibytes)); - Else(#temp == 123); // { - #output->insert(json_consume_object(#ibytes)); - Else; - #output->insert(json_consume_token(#ibytes, #temp)); - (#temp == 93) ? Loop_Abort; - /If; - /While; - Return(#output); -} - -// Bil Corry fix -define json_consume_object(ibytes::bytes)::map => { - Local('output' = map, - 'delimit' = array( 9, 10, 13, 32, 44), // \t\r\n , - 'temp' = 0, - 'key' = null, - 'val' = null); - While((#temp := #ibytes->export8bits) != 125); // } - If(#delimit >> #temp); - // Discard whitespace - Else((#key !== null) && (#temp == 34)); // " - #output->insert(#key = json_consume_string(#ibytes)); - #key = null; - Else((#key !== null) && (#temp == 91)); // [ - #output->insert(#key = json_consume_array(#ibytes)); - #key = null; - Else((#key !== null) && (#temp == 123)); // { - #output->insert(#key = json_consume_object(#ibytes)); - #key = null; - Else((#key !== null)); - #output->insert(#key = json_consume_token(#ibytes, #temp)); - #key = null; - Else; - #key = json_consume_string(#ibytes); - while(#delimit >> (#temp := #ibytes->export8bits)); - /while; - #temp != 58 ? Loop_Abort; - /If; - /While; - - If((#output >> '__jsonclass__') && (#output->Find('__jsonclass__')->isa('array')) && (#output->Find('__jsonclass__')->size >= 2) && (#output->Find('__jsonclass__')->First == 'deserialize')); - Return(#output->find('__jsonclass__')->Second->First); - Else((#output >> 'native') && (#output >> 'comment') && (#output->find('comment') == 'http://www.lassosoft.com/json')); - Return(#output->find('native')); - /If; - Return(#output); -} - -// Bil Corry fix + Ke fix -define json_deserialize(ibytes::bytes)::any => { - #ibytes->removeLeading(bom_utf8); - -//============================================================================ -// Reset marker on provided bytes - #ibytes->marker = 0 -//............................................................................ - - Local(temp) = #ibytes->export8bits; - If(#temp == 91); // [ - Return(json_consume_array(#ibytes)); - Else(#temp == 123); // { - Return(json_consume_object(#ibytes)); - else(#temp == 34) // " - return json_consume_string(#ibytes) - /If; -} - -define json_deserialize(s::string) => json_deserialize(bytes(#s)) - -/**! json_literal - This is a subclass of String used for JSON encoding. - - A json_literal works exactly like a string, but will be inserted directly - rather than being encoded into JSON. This allows JavaScript elements - like functions to be inserted into JSON objects. This is most useful - when the JSON object will be used within a JavaScript on the local page. - [Map: 'fn'=Literal('function(){ ...})] => {'fn': function(){ ...}} -**/ -define json_literal => type { - parent string -} - -/**! json_object - This is a subclass of Map used for JSON encoding. - - An object works exactly like a map, but when it is encoded into JSON all - of the keys will be inserted literally. This makes it easy to create a - JavaScript object without extraneous quote marks. - Object('name'='value') => {name: "value"} -**/ -define json_object => type { - parent map - public onCreate(...) => ..onCreate(:#rest or (:)) -} - -define json_rpccall(method::string, params=map, id='', host='') => { - #id == '' ? #host = Lasso_UniqueID; - #host == '' ? #host = 'http://localhost/lassoapps.8/rpc/rpc.lasso'; - Return(Decode_JSON(Include_URL(#host, -PostParams=Encode_JSON(Map('method' = #method, 'params' = #params, 'id' = #id))))); -} diff --git a/third_party/pygments/tests/examplefiles/language.hy b/third_party/pygments/tests/examplefiles/language.hy deleted file mode 100644 index 9768c39c7..000000000 --- a/third_party/pygments/tests/examplefiles/language.hy +++ /dev/null @@ -1,165 +0,0 @@ -;;;; This contains some of the core Hy functions used -;;;; to make functional programming slightly easier. -;;;; - - -(defn _numeric-check [x] - (if (not (numeric? x)) - (raise (TypeError (.format "{0!r} is not a number" x))))) - -(defn cycle [coll] - "Yield an infinite repetition of the items in coll" - (setv seen []) - (for [x coll] - (yield x) - (.append seen x)) - (while seen - (for [x seen] - (yield x)))) - -(defn dec [n] - "Decrement n by 1" - (_numeric-check n) - (- n 1)) - -(defn distinct [coll] - "Return a generator from the original collection with duplicates - removed" - (let [[seen []] [citer (iter coll)]] - (for [val citer] - (if (not_in val seen) - (do - (yield val) - (.append seen val)))))) - -(defn drop [count coll] - "Drop `count` elements from `coll` and yield back the rest" - (let [[citer (iter coll)]] - (try (for [i (range count)] - (next citer)) - (catch [StopIteration])) - citer)) - -(defn even? [n] - "Return true if n is an even number" - (_numeric-check n) - (= (% n 2) 0)) - -(defn filter [pred coll] - "Return all elements from `coll` that pass `pred`" - (let [[citer (iter coll)]] - (for [val citer] - (if (pred val) - (yield val))))) - -(defn inc [n] - "Increment n by 1" - (_numeric-check n) - (+ n 1)) - -(defn instance? [klass x] - (isinstance x klass)) - -(defn iterable? [x] - "Return true if x is iterable" - (try (do (iter x) true) - (catch [Exception] false))) - -(defn iterate [f x] - (setv val x) - (while true - (yield val) - (setv val (f val)))) - -(defn iterator? [x] - "Return true if x is an iterator" - (try (= x (iter x)) - (catch [TypeError] false))) - -(defn neg? [n] - "Return true if n is < 0" - (_numeric-check n) - (< n 0)) - -(defn none? [x] - "Return true if x is None" - (is x None)) - -(defn numeric? [x] - (import numbers) - (instance? numbers.Number x)) - -(defn nth [coll index] - "Return nth item in collection or sequence, counting from 0" - (if (not (neg? index)) - (if (iterable? coll) - (try (first (list (take 1 (drop index coll)))) - (catch [IndexError] None)) - (try (get coll index) - (catch [IndexError] None))) - None)) - -(defn odd? [n] - "Return true if n is an odd number" - (_numeric-check n) - (= (% n 2) 1)) - -(defn pos? [n] - "Return true if n is > 0" - (_numeric_check n) - (> n 0)) - -(defn remove [pred coll] - "Return coll with elements removed that pass `pred`" - (let [[citer (iter coll)]] - (for [val citer] - (if (not (pred val)) - (yield val))))) - -(defn repeat [x &optional n] - "Yield x forever or optionally n times" - (if (none? n) - (setv dispatch (fn [] (while true (yield x)))) - (setv dispatch (fn [] (for [_ (range n)] (yield x))))) - (dispatch)) - -(defn repeatedly [func] - "Yield result of running func repeatedly" - (while true - (yield (func)))) - -(defn take [count coll] - "Take `count` elements from `coll`, or the whole set if the total - number of entries in `coll` is less than `count`." - (let [[citer (iter coll)]] - (for [_ (range count)] - (yield (next citer))))) - -(defn take-nth [n coll] - "Return every nth member of coll - raises ValueError for (not (pos? n))" - (if (pos? n) - (let [[citer (iter coll)] [skip (dec n)]] - (for [val citer] - (yield val) - (for [_ (range skip)] - (next citer)))) - (raise (ValueError "n must be positive")))) - -(defn take-while [pred coll] - "Take all elements while `pred` is true" - (let [[citer (iter coll)]] - (for [val citer] - (if (pred val) - (yield val) - (break))))) - -(defn zero? [n] - "Return true if n is 0" - (_numeric_check n) - (= n 0)) - -(def *exports* ["cycle" "dec" "distinct" "drop" "even?" "filter" "inc" - "instance?" "iterable?" "iterate" "iterator?" "neg?" - "none?" "nth" "numeric?" "odd?" "pos?" "remove" "repeat" - "repeatedly" "take" "take_nth" "take_while" "zero?"]) diff --git a/third_party/pygments/tests/examplefiles/lighttpd_config.conf b/third_party/pygments/tests/examplefiles/lighttpd_config.conf deleted file mode 100644 index 8475f378e..000000000 --- a/third_party/pygments/tests/examplefiles/lighttpd_config.conf +++ /dev/null @@ -1,13 +0,0 @@ -fastcgi.server = ( ".php" => (( - "bin-path" => "/path/to/php-cgi", - "socket" => "/tmp/php.socket", - "max-procs" => 2, - "bin-environment" => ( - "PHP_FCGI_CHILDREN" => "16", - "PHP_FCGI_MAX_REQUESTS" => "10000" - ), - "bin-copy-environment" => ( - "PATH", "SHELL", "USER" - ), - "broken-scriptfilename" => "enable" - ))) diff --git a/third_party/pygments/tests/examplefiles/limbo.b b/third_party/pygments/tests/examplefiles/limbo.b deleted file mode 100644 index e55a0a620..000000000 --- a/third_party/pygments/tests/examplefiles/limbo.b +++ /dev/null @@ -1,456 +0,0 @@ -implement Ninewin; -include "sys.m"; - sys: Sys; -include "draw.m"; - draw: Draw; - Image, Display, Pointer: import draw; -include "arg.m"; -include "keyboard.m"; -include "tk.m"; -include "wmclient.m"; - wmclient: Wmclient; - Window: import wmclient; -include "sh.m"; - sh: Sh; - -# run a p9 graphics program (default rio) under inferno wm, -# making available to it: -# /dev/winname - naming the current inferno window (changing on resize) -# /dev/mouse - pointer file + resize events; write to change position -# /dev/cursor - change appearance of cursor. -# /dev/draw - inferno draw device -# /dev/cons - read keyboard events, write to 9win stdout. - -Ninewin: module { - init: fn(ctxt: ref Draw->Context, argv: list of string); -}; -winname: string; - -init(ctxt: ref Draw->Context, argv: list of string) -{ - size := Draw->Point(500, 500); - sys = load Sys Sys->PATH; - draw = load Draw Draw->PATH; - wmclient = load Wmclient Wmclient->PATH; - wmclient->init(); - sh = load Sh Sh->PATH; - - buts := Wmclient->Resize; - if(ctxt == nil){ - ctxt = wmclient->makedrawcontext(); - buts = Wmclient->Plain; - } - arg := load Arg Arg->PATH; - arg->init(argv); - arg->setusage("9win [-s] [-x width] [-y height]"); - exportonly := 0; - while(((opt := arg->opt())) != 0){ - case opt { - 's' => - exportonly = 1; - 'x' => - size.x = int arg->earg(); - 'y' => - size.y = int arg->earg(); - * => - arg->usage(); - } - } - if(size.x < 1 || size.y < 1) - arg->usage(); - argv = arg->argv(); - if(argv != nil && hd argv == "-s"){ - exportonly = 1; - argv = tl argv; - } - if(argv == nil && !exportonly) - argv = "rio" :: nil; - if(argv != nil && exportonly){ - sys->fprint(sys->fildes(2), "9win: no command allowed with -s flag\n"); - raise "fail:usage"; - } - title := "9win"; - if(!exportonly) - title += " " + hd argv; - w := wmclient->window(ctxt, title, buts); - w.reshape(((0, 0), size)); - w.onscreen(nil); - if(w.image == nil){ - sys->fprint(sys->fildes(2), "9win: cannot get image to draw on\n"); - raise "fail:no window"; - } - - sys->pctl(Sys->FORKNS|Sys->NEWPGRP, nil); - ld := "/n/9win"; - if(sys->bind("#s", ld, Sys->MREPL) == -1 && - sys->bind("#s", ld = "/n/local", Sys->MREPL) == -1){ - sys->fprint(sys->fildes(2), "9win: cannot bind files: %r\n"); - raise "fail:error"; - } - w.startinput("kbd" :: "ptr" :: nil); - spawn ptrproc(rq := chan of Sys->Rread, ptr := chan[10] of ref Pointer, reshape := chan[1] of int); - - - fwinname := sys->file2chan(ld, "winname"); - fconsctl := sys->file2chan(ld, "consctl"); - fcons := sys->file2chan(ld, "cons"); - fmouse := sys->file2chan(ld, "mouse"); - fcursor := sys->file2chan(ld, "cursor"); - if(!exportonly){ - spawn run(sync := chan of string, w.ctl, ld, argv); - if((e := <-sync) != nil){ - sys->fprint(sys->fildes(2), "9win: %s", e); - raise "fail:error"; - } - } - spawn serveproc(w, rq, fwinname, fconsctl, fcons, fmouse, fcursor); - if(!exportonly){ - # handle events synchronously so that we don't get a "killed" message - # from the shell. - handleevents(w, ptr, reshape); - }else{ - spawn handleevents(w, ptr, reshape); - sys->bind(ld, "/dev", Sys->MBEFORE); - export(sys->fildes(0), w.ctl); - } -} - -handleevents(w: ref Window, ptr: chan of ref Pointer, reshape: chan of int) -{ - for(;;)alt{ - c := <-w.ctxt.ctl or - c = <-w.ctl => - e := w.wmctl(c); - if(e != nil) - sys->fprint(sys->fildes(2), "9win: ctl error: %s\n", e); - if(e == nil && c != nil && c[0] == '!'){ - alt{ - reshape <-= 1 => - ; - * => - ; - } - winname = nil; - } - p := <-w.ctxt.ptr => - if(w.pointer(*p) == 0){ - # XXX would block here if client isn't reading mouse... but we do want to - # extert back-pressure, which conflicts. - alt{ - ptr <-= p => - ; - * => - ; # sys->fprint(sys->fildes(2), "9win: discarding mouse event\n"); - } - } - } -} - -serveproc(w: ref Window, mouserq: chan of Sys->Rread, fwinname, fconsctl, fcons, fmouse, fcursor: ref Sys->FileIO) -{ - winid := 0; - krc: list of Sys->Rread; - ks: string; - - for(;;)alt { - c := <-w.ctxt.kbd => - ks[len ks] = inf2p9key(c); - if(krc != nil){ - hd krc <-= (array of byte ks, nil); - ks = nil; - krc = tl krc; - } - (nil, d, nil, wc) := <-fcons.write => - if(wc != nil){ - sys->write(sys->fildes(1), d, len d); - wc <-= (len d, nil); - } - (nil, nil, nil, rc) := <-fcons.read => - if(rc != nil){ - if(ks != nil){ - rc <-= (array of byte ks, nil); - ks = nil; - }else - krc = rc :: krc; - } - (offset, nil, nil, rc) := <-fwinname.read => - if(rc != nil){ - if(winname == nil){ - winname = sys->sprint("noborder.9win.%d", winid++); - if(w.image.name(winname, 1) == -1){ - sys->fprint(sys->fildes(2), "9win: namewin %q failed: %r", winname); - rc <-= (nil, "namewin failure"); - break; - } - } - d := array of byte winname; - if(offset < len d) - d = d[offset:]; - else - d = nil; - rc <-= (d, nil); - } - (nil, nil, nil, wc) := <-fwinname.write => - if(wc != nil) - wc <-= (-1, "permission denied"); - (nil, nil, nil, rc) := <-fconsctl.read => - if(rc != nil) - rc <-= (nil, "permission denied"); - (nil, d, nil, wc) := <-fconsctl.write => - if(wc != nil){ - if(string d != "rawon") - wc <-= (-1, "cannot change console mode"); - else - wc <-= (len d, nil); - } - (nil, nil, nil, rc) := <-fmouse.read => - if(rc != nil) - mouserq <-= rc; - (nil, d, nil, wc) := <-fmouse.write => - if(wc != nil){ - e := cursorset(w, string d); - if(e == nil) - wc <-= (len d, nil); - else - wc <-= (-1, e); - } - (nil, nil, nil, rc) := <-fcursor.read => - if(rc != nil) - rc <-= (nil, "permission denied"); - (nil, d, nil, wc) := <-fcursor.write => - if(wc != nil){ - e := cursorswitch(w, d); - if(e == nil) - wc <-= (len d, nil); - else - wc <-= (-1, e); - } - } -} - -ptrproc(rq: chan of Sys->Rread, ptr: chan of ref Pointer, reshape: chan of int) -{ - rl: list of Sys->Rread; - c := ref Pointer(0, (0, 0), 0); - for(;;){ - ch: int; - alt{ - p := <-ptr => - ch = 'm'; - c = p; - <-reshape => - ch = 'r'; - rc := <-rq => - rl = rc :: rl; - continue; - } - if(rl == nil) - rl = <-rq :: rl; - hd rl <-= (sys->aprint("%c%11d %11d %11d %11d ", ch, c.xy.x, c.xy.y, c.buttons, c.msec), nil); - rl = tl rl; - } -} - -cursorset(w: ref Window, m: string): string -{ - if(m == nil || m[0] != 'm') - return "invalid mouse message"; - x := int m[1:]; - for(i := 1; i < len m; i++) - if(m[i] == ' '){ - while(m[i] == ' ') - i++; - break; - } - if(i == len m) - return "invalid mouse message"; - y := int m[i:]; - return w.wmctl(sys->sprint("ptr %d %d", x, y)); -} - -cursorswitch(w: ref Window, d: array of byte): string -{ - Hex: con "0123456789abcdef"; - if(len d != 2*4+64) - return w.wmctl("cursor"); - hot := Draw->Point(bglong(d, 0*4), bglong(d, 1*4)); - s := sys->sprint("cursor %d %d 16 32 ", hot.x, hot.y); - for(i := 2*4; i < len d; i++){ - c := int d[i]; - s[len s] = Hex[c >> 4]; - s[len s] = Hex[c & 16rf]; - } - return w.wmctl(s); -} - -run(sync, ctl: chan of string, ld: string, argv: list of string) -{ - Rcmeta: con "|<>&^*[]?();"; - sys->pctl(Sys->FORKNS, nil); - if(sys->bind("#₪", "/srv", Sys->MCREATE) == -1){ - sync <-= sys->sprint("cannot bind srv device: %r"); - exit; - } - srvname := "/srv/9win."+string sys->pctl(0, nil); # XXX do better. - fd := sys->create(srvname, Sys->ORDWR, 8r600); - if(fd == nil){ - sync <-= sys->sprint("cannot create %s: %r", srvname); - exit; - } - sync <-= nil; - spawn export(fd, ctl); - sh->run(nil, "os" :: - "rc" :: "-c" :: - "mount "+srvname+" /mnt/term;"+ - "rm "+srvname+";"+ - "bind -b /mnt/term"+ld+" /dev;"+ - "bind /mnt/term/dev/draw /dev/draw ||"+ - "bind -a /mnt/term/dev /dev;"+ - quotedc("cd"::"/mnt/term"+cwd()::nil, Rcmeta)+";"+ - quotedc(argv, Rcmeta)+";":: - nil - ); -} - -export(fd: ref Sys->FD, ctl: chan of string) -{ - sys->export(fd, "/", Sys->EXPWAIT); - ctl <-= "exit"; -} - -inf2p9key(c: int): int -{ - KF: import Keyboard; - - P9KF: con 16rF000; - Spec: con 16rF800; - Khome: con P9KF|16r0D; - Kup: con P9KF|16r0E; - Kpgup: con P9KF|16r0F; - Kprint: con P9KF|16r10; - Kleft: con P9KF|16r11; - Kright: con P9KF|16r12; - Kdown: con Spec|16r00; - Kview: con Spec|16r00; - Kpgdown: con P9KF|16r13; - Kins: con P9KF|16r14; - Kend: con P9KF|16r18; - Kalt: con P9KF|16r15; - Kshift: con P9KF|16r16; - Kctl: con P9KF|16r17; - - case c { - Keyboard->LShift => - return Kshift; - Keyboard->LCtrl => - return Kctl; - Keyboard->LAlt => - return Kalt; - Keyboard->Home => - return Khome; - Keyboard->End => - return Kend; - Keyboard->Up => - return Kup; - Keyboard->Down => - return Kdown; - Keyboard->Left => - return Kleft; - Keyboard->Right => - return Kright; - Keyboard->Pgup => - return Kpgup; - Keyboard->Pgdown => - return Kpgdown; - Keyboard->Ins => - return Kins; - - # function keys - KF|1 or - KF|2 or - KF|3 or - KF|4 or - KF|5 or - KF|6 or - KF|7 or - KF|8 or - KF|9 or - KF|10 or - KF|11 or - KF|12 => - return (c - KF) + P9KF; - } - return c; -} - -cwd(): string -{ - return sys->fd2path(sys->open(".", Sys->OREAD)); -} - -# from string.b, waiting for declaration to be uncommented. -quotedc(argv: list of string, cl: string): string -{ - s := ""; - while (argv != nil) { - arg := hd argv; - for (i := 0; i < len arg; i++) { - c := arg[i]; - if (c == ' ' || c == '\t' || c == '\n' || c == '\'' || in(c, cl)) - break; - } - if (i < len arg || arg == nil) { - s += "'" + arg[0:i]; - for (; i < len arg; i++) { - if (arg[i] == '\'') - s[len s] = '\''; - s[len s] = arg[i]; - } - s[len s] = '\''; - } else - s += arg; - if (tl argv != nil) - s[len s] = ' '; - argv = tl argv; - } - return s; -} - -in(c: int, s: string): int -{ - n := len s; - if(n == 0) - return 0; - ans := 0; - negate := 0; - if(s[0] == '^') { - negate = 1; - s = s[1:]; - n--; - } - for(i := 0; i < n; i++) { - if(s[i] == '-' && i > 0 && i < n-1) { - if(c >= s[i-1] && c <= s[i+1]) { - ans = 1; - break; - } - i++; - } - else - if(c == s[i]) { - ans = 1; - break; - } - } - if(negate) - ans = !ans; - - # just to showcase labels -skip: - return ans; -} - -bglong(d: array of byte, i: int): int -{ - return int d[i] | (int d[i+1]<<8) | (int d[i+2]<<16) | (int d[i+3]<<24); -} diff --git a/third_party/pygments/tests/examplefiles/linecontinuation.py b/third_party/pygments/tests/examplefiles/linecontinuation.py deleted file mode 100644 index 2a41c31c6..000000000 --- a/third_party/pygments/tests/examplefiles/linecontinuation.py +++ /dev/null @@ -1,47 +0,0 @@ -apple.filter(x, y) -apple.\ - filter(x, y) - -1 \ - . \ - __str__ - -from os import path -from \ - os \ - import \ - path - -import os.path as something - -import \ - os.path \ - as \ - something - -class \ - Spam: - pass - -class Spam: pass - -class Spam(object): - pass - -class \ - Spam \ - ( - object - ) \ - : - pass - - -def \ - spam \ - ( \ - ) \ - : \ - pass - - diff --git a/third_party/pygments/tests/examplefiles/livescript-demo.ls b/third_party/pygments/tests/examplefiles/livescript-demo.ls deleted file mode 100644 index 03cbcc99d..000000000 --- a/third_party/pygments/tests/examplefiles/livescript-demo.ls +++ /dev/null @@ -1,43 +0,0 @@ -a = -> [1 to 50] -const b = --> [2 til 5] -var c = ~~> 10_000_000km * 500ms - 16~ff / 32~lol -e = (a) -> (b) ~> (c) --> (d, e) ~~> <[list of words]> -dashes-identifiers = -> - a - a b -- c 1-1 1- -1 a- a a -a -underscores_i$d = -> - /regexp1/ - //regexp2//g - 'strings' and "strings" and \strings and \#$-"\'strings - -another-word-list = <[ more words ]> - -[2 til 10] - |> map (* 2) - |> filter (> 5) - |> fold (+) - -obj = - prop1: 1 - prop2: 2 - -class Class extends Anc-est-or - (args) -> - <- # Comment - <~ /* Comment */ - void undefined yes no on off - a.void b.undefined c.off d.if f.no g.not - avoid bundefined coff dif fno gnot - "inter #{2 + 2} #variable" - '''HELLO 'world' ''' - -copy = (from, to, callback) --> - error, data <- read file - return callback error if error? - error <~ write file, data - return callback error if error? - callback() - -take(n, [x, ...xs]:list) = - | n <= 0 => [] - | empty list => [] - | otherwise => [x] +++ take n - 1, xs diff --git a/third_party/pygments/tests/examplefiles/logos_example.xm b/third_party/pygments/tests/examplefiles/logos_example.xm deleted file mode 100644 index 39753e236..000000000 --- a/third_party/pygments/tests/examplefiles/logos_example.xm +++ /dev/null @@ -1,28 +0,0 @@ -%hook ABC -- (id)a:(B)b { - %log; - return %orig(nil); -} -%end - -%subclass DEF: NSObject -- (id)init { - [%c(RuntimeAccessibleClass) alloc]; - return nil; -} -%end - -%group OptionalHooks -%hook ABC -- (void)release { - [self retain]; - %orig; -} -%end -%end - -%ctor { - %init; - if(OptionalCondition) - %init(OptionalHooks); -} diff --git a/third_party/pygments/tests/examplefiles/ltmain.sh b/third_party/pygments/tests/examplefiles/ltmain.sh deleted file mode 100644 index 5b5f845f2..000000000 --- a/third_party/pygments/tests/examplefiles/ltmain.sh +++ /dev/null @@ -1,2849 +0,0 @@ -# ltmain.sh - Provide generalized library-building support services. -# NOTE: Changing this file will not affect anything until you rerun configure. -# -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005 -# Free Software Foundation, Inc. -# Originally by Gordon Matzigkeit , 1996 -# -# 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 2 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, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - -basename="s,^.*/,,g" - -# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh -# is ksh but when the shell is invoked as "sh" and the current value of -# the _XPG environment variable is not equal to 1 (one), the special -# positional parameter $0, within a function call, is the name of the -# function. -progpath="$0" - -# define SED for historic ltconfig's generated by Libtool 1.3 -test -z "$SED" && SED=sed - -# The name of this program: -progname=`echo "$progpath" | $SED $basename` -modename="$progname" - -# Global variables: -EXIT_SUCCESS=0 -EXIT_FAILURE=1 - -PROGRAM=ltmain.sh -PACKAGE=libtool -VERSION=1.5.22 -TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)" - -# See if we are running on zsh, and set the options which allow our -# commands through without removal of \ escapes. -if test -n "${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST -fi -# Same for EGREP, and just to be sure, do LTCC as well -if test "X$EGREP" = X ; then - EGREP=egrep -fi -if test "X$LTCC" = X ; then - LTCC=${CC-gcc} -fi - -# Check that we have a working $echo. -if test "X$1" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift -elif test "X$1" = X--fallback-echo; then - # Avoid inline document here, it may be left over - : -elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then - # Yippee, $echo works! - : -else - # Restart under the correct shell, and then maybe $echo will work. - exec $SHELL "$progpath" --no-reexec ${1+"$@"} -fi - -if test "X$1" = X--fallback-echo; then - # used as fallback echo - shift - cat <&2 - $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 - exit $EXIT_FAILURE -fi - -# Global variables. -mode=$default_mode -nonopt= -prev= -prevopt= -run= -show="$echo" -show_help= -execute_dlfiles= -duplicate_deps=no -preserve_args= -lo2o="s/\\.lo\$/.${objext}/" -o2lo="s/\\.${objext}\$/.lo/" - -if test -z "$max_cmd_len"; then - i=0 - testring="ABCD" - new_result= - - # If test is not a shell built-in, we'll probably end up computing a - # maximum length that is only half of the actual maximum length, but - # we can't tell. - while (test "X"`$SHELL $0 --fallback-echo "X$testring" 2>/dev/null` \ - = "XX$testring") >/dev/null 2>&1 && - new_result=`expr "X$testring" : ".*" 2>&1` && - max_cmd_len="$new_result" && - test "$i" != 17 # 1/2 MB should be enough - do - i=`expr $i + 1` - testring="$testring$testring" - done - testring= - # Add a significant safety factor because C++ compilers can tack on massive - # amounts of additional arguments before passing them to the linker. - # It appears as though 1/2 is a usable value. - max_cmd_len=`expr $max_cmd_len \/ 2` -fi - -##################################### -# Shell function definitions: -# This seems to be the best place for them - -# func_mktempdir [string] -# Make a temporary directory that won't clash with other running -# libtool processes, and avoids race conditions if possible. If -# given, STRING is the basename for that directory. -func_mktempdir () -{ - my_template="${TMPDIR-/tmp}/${1-$progname}" - - if test "$run" = ":"; then - # Return a directory name, but don't create it in dry-run mode - my_tmpdir="${my_template}-$$" - else - - # If mktemp works, use that first and foremost - my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` - - if test ! -d "$my_tmpdir"; then - # Failing that, at least try and use $RANDOM to avoid a race - my_tmpdir="${my_template}-${RANDOM-0}$$" - - save_mktempdir_umask=`umask` - umask 0077 - $mkdir "$my_tmpdir" - umask $save_mktempdir_umask - fi - - # If we're not in dry-run mode, bomb out on failure - test -d "$my_tmpdir" || { - $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2 - exit $EXIT_FAILURE - } - fi - - $echo "X$my_tmpdir" | $Xsed -} - - -# func_win32_libid arg -# return the library type of file 'arg' -# -# Need a lot of goo to handle *both* DLLs and import libs -# Has to be a shell function in order to 'eat' the argument -# that is supplied when $file_magic_command is called. -func_win32_libid () -{ - win32_libid_type="unknown" - win32_fileres=`file -L $1 2>/dev/null` - case $win32_fileres in - *ar\ archive\ import\ library*) # definitely import - win32_libid_type="x86 archive import" - ;; - *ar\ archive*) # could be an import, or static - if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \ - $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then - win32_nmres=`eval $NM -f posix -A $1 | \ - $SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'` - case $win32_nmres in - import*) win32_libid_type="x86 archive import";; - *) win32_libid_type="x86 archive static";; - esac - fi - ;; - *DLL*) - win32_libid_type="x86 DLL" - ;; - *executable*) # but shell scripts are "executable" too... - case $win32_fileres in - *MS\ Windows\ PE\ Intel*) - win32_libid_type="x86 DLL" - ;; - esac - ;; - esac - $echo $win32_libid_type -} - - -# func_infer_tag arg -# Infer tagged configuration to use if any are available and -# if one wasn't chosen via the "--tag" command line option. -# Only attempt this if the compiler in the base compile -# command doesn't match the default compiler. -# arg is usually of the form 'gcc ...' -func_infer_tag () -{ - if test -n "$available_tags" && test -z "$tagname"; then - CC_quoted= - for arg in $CC; do - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - CC_quoted="$CC_quoted $arg" - done - case $@ in - # Blanks in the command may have been stripped by the calling shell, - # but not from the CC environment variable when configure was run. - " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;; - # Blanks at the start of $base_compile will cause this to fail - # if we don't check for them as well. - *) - for z in $available_tags; do - if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then - # Evaluate the configuration. - eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" - CC_quoted= - for arg in $CC; do - # Double-quote args containing other shell metacharacters. - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - CC_quoted="$CC_quoted $arg" - done - # user sometimes does CC=-gcc so we need to match that to 'gcc' - trimedcc=`echo ${CC} | $SED -e "s/${host}-//g"` - # and sometimes libtool has CC=-gcc but user does CC=gcc - extendcc=${host}-${CC} - # and sometimes libtool has CC=-gcc but user has CC=-gcc - # (Gentoo-specific hack because we always export $CHOST) - mungedcc=${CHOST-${host}}-${trimedcc} - case "$@ " in - "cc "* | " cc "* | "${host}-cc "* | " ${host}-cc "*|\ - "gcc "* | " gcc "* | "${host}-gcc "* | " ${host}-gcc "*) - tagname=CC - break ;; - "$trimedcc "* | " $trimedcc "* | "`$echo $trimedcc` "* | " `$echo $trimedcc` "*|\ - "$extendcc "* | " $extendcc "* | "`$echo $extendcc` "* | " `$echo $extendcc` "*|\ - "$mungedcc "* | " $mungedcc "* | "`$echo $mungedcc` "* | " `$echo $mungedcc` "*|\ - " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) - # The compiler in the base compile command matches - # the one in the tagged configuration. - # Assume this is the tagged configuration we want. - tagname=$z - break - ;; - esac - fi - done - # If $tagname still isn't set, then no tagged configuration - # was found and let the user know that the "--tag" command - # line option must be used. - if test -z "$tagname"; then - $echo "$modename: unable to infer tagged configuration" - $echo "$modename: specify a tag with \`--tag'" 1>&2 - exit $EXIT_FAILURE -# else -# $echo "$modename: using $tagname tagged configuration" - fi - ;; - esac - fi -} - - -# func_extract_an_archive dir oldlib -func_extract_an_archive () -{ - f_ex_an_ar_dir="$1"; shift - f_ex_an_ar_oldlib="$1" - - $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)" - $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $? - if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then - : - else - $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2 - exit $EXIT_FAILURE - fi -} - -# func_extract_archives gentop oldlib ... -func_extract_archives () -{ - my_gentop="$1"; shift - my_oldlibs=${1+"$@"} - my_oldobjs="" - my_xlib="" - my_xabs="" - my_xdir="" - my_status="" - - $show "${rm}r $my_gentop" - $run ${rm}r "$my_gentop" - $show "$mkdir $my_gentop" - $run $mkdir "$my_gentop" - my_status=$? - if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then - exit $my_status - fi - - for my_xlib in $my_oldlibs; do - # Extract the objects. - case $my_xlib in - [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; - *) my_xabs=`pwd`"/$my_xlib" ;; - esac - my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'` - my_xdir="$my_gentop/$my_xlib" - - $show "${rm}r $my_xdir" - $run ${rm}r "$my_xdir" - $show "$mkdir $my_xdir" - $run $mkdir "$my_xdir" - exit_status=$? - if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then - exit $exit_status - fi - case $host in - *-darwin*) - $show "Extracting $my_xabs" - # Do not bother doing anything if just a dry run - if test -z "$run"; then - darwin_orig_dir=`pwd` - cd $my_xdir || exit $? - darwin_archive=$my_xabs - darwin_curdir=`pwd` - darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'` - darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null` - if test -n "$darwin_arches"; then - darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'` - darwin_arch= - $show "$darwin_base_archive has multiple architectures $darwin_arches" - for darwin_arch in $darwin_arches ; do - mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}" - lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" - cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" - func_extract_an_archive "`pwd`" "${darwin_base_archive}" - cd "$darwin_curdir" - $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" - done # $darwin_arches - ## Okay now we have a bunch of thin objects, gotta fatten them up :) - darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP` - darwin_file= - darwin_files= - for darwin_file in $darwin_filelist; do - darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` - lipo -create -output "$darwin_file" $darwin_files - done # $darwin_filelist - ${rm}r unfat-$$ - cd "$darwin_orig_dir" - else - cd "$darwin_orig_dir" - func_extract_an_archive "$my_xdir" "$my_xabs" - fi # $darwin_arches - fi # $run - ;; - *) - func_extract_an_archive "$my_xdir" "$my_xabs" - ;; - esac - my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` - done - func_extract_archives_result="$my_oldobjs" -} -# End of Shell function definitions -##################################### - -# Darwin sucks -eval std_shrext=\"$shrext_cmds\" - -disable_libs=no - -# Parse our command line options once, thoroughly. -while test "$#" -gt 0 -do - arg="$1" - shift - - case $arg in - -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;; - *) optarg= ;; - esac - - # If the previous option needs an argument, assign it. - if test -n "$prev"; then - case $prev in - execute_dlfiles) - execute_dlfiles="$execute_dlfiles $arg" - ;; - tag) - tagname="$arg" - preserve_args="${preserve_args}=$arg" - - # Check whether tagname contains only valid characters - case $tagname in - *[!-_A-Za-z0-9,/]*) - $echo "$progname: invalid tag name: $tagname" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - case $tagname in - CC) - # Don't test for the "default" C tag, as we know, it's there, but - # not specially marked. - ;; - *) - if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then - taglist="$taglist $tagname" - # Evaluate the configuration. - eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`" - else - $echo "$progname: ignoring unknown tag $tagname" 1>&2 - fi - ;; - esac - ;; - *) - eval "$prev=\$arg" - ;; - esac - - prev= - prevopt= - continue - fi - - # Have we seen a non-optional argument yet? - case $arg in - --help) - show_help=yes - ;; - - --version) - $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP" - $echo - $echo "Copyright (C) 2005 Free Software Foundation, Inc." - $echo "This is free software; see the source for copying conditions. There is NO" - $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." - exit $? - ;; - - --config) - ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath - # Now print the configurations for the tags. - for tagname in $taglist; do - ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath" - done - exit $? - ;; - - --debug) - $echo "$progname: enabling shell trace mode" - set -x - preserve_args="$preserve_args $arg" - ;; - - --dry-run | -n) - run=: - ;; - - --features) - $echo "host: $host" - if test "$build_libtool_libs" = yes; then - $echo "enable shared libraries" - else - $echo "disable shared libraries" - fi - if test "$build_old_libs" = yes; then - $echo "enable static libraries" - else - $echo "disable static libraries" - fi - exit $? - ;; - - --finish) mode="finish" ;; - - --mode) prevopt="--mode" prev=mode ;; - --mode=*) mode="$optarg" ;; - - --preserve-dup-deps) duplicate_deps="yes" ;; - - --quiet | --silent) - show=: - preserve_args="$preserve_args $arg" - ;; - - --tag) - prevopt="--tag" - prev=tag - preserve_args="$preserve_args --tag" - ;; - --tag=*) - set tag "$optarg" ${1+"$@"} - shift - prev=tag - preserve_args="$preserve_args --tag" - ;; - - -dlopen) - prevopt="-dlopen" - prev=execute_dlfiles - ;; - - -*) - $echo "$modename: unrecognized option \`$arg'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; - - *) - nonopt="$arg" - break - ;; - esac -done - -if test -n "$prevopt"; then - $echo "$modename: option \`$prevopt' requires an argument" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE -fi - -case $disable_libs in -no) - ;; -shared) - build_libtool_libs=no - build_old_libs=yes - ;; -static) - build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` - ;; -esac - -# If this variable is set in any of the actions, the command in it -# will be execed at the end. This prevents here-documents from being -# left over by shells. -exec_cmd= - -if test -z "$show_help"; then - - # Infer the operation mode. - if test -z "$mode"; then - $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2 - $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2 - case $nonopt in - *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*) - mode=link - for arg - do - case $arg in - -c) - mode=compile - break - ;; - esac - done - ;; - *db | *dbx | *strace | *truss) - mode=execute - ;; - *install*|cp|mv) - mode=install - ;; - *rm) - mode=uninstall - ;; - *) - # If we have no mode, but dlfiles were specified, then do execute mode. - test -n "$execute_dlfiles" && mode=execute - - # Just use the default operation mode. - if test -z "$mode"; then - if test -n "$nonopt"; then - $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2 - else - $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2 - fi - fi - ;; - esac - fi - - # Only execute mode is allowed to have -dlopen flags. - if test -n "$execute_dlfiles" && test "$mode" != execute; then - $echo "$modename: unrecognized option \`-dlopen'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Change the help message to a mode-specific one. - generic_help="$help" - help="Try \`$modename --help --mode=$mode' for more information." - - # These modes are in order of execution frequency so that they run quickly. - case $mode in - # libtool compile mode - compile) - modename="$modename: compile" - # Get the compilation command and the source file. - base_compile= - srcfile="$nonopt" # always keep a non-empty value in "srcfile" - suppress_opt=yes - suppress_output= - arg_mode=normal - libobj= - later= - - for arg - do - case $arg_mode in - arg ) - # do not "continue". Instead, add this to base_compile - lastarg="$arg" - arg_mode=normal - ;; - - target ) - libobj="$arg" - arg_mode=normal - continue - ;; - - normal ) - # Accept any command-line options. - case $arg in - -o) - if test -n "$libobj" ; then - $echo "$modename: you cannot specify \`-o' more than once" 1>&2 - exit $EXIT_FAILURE - fi - arg_mode=target - continue - ;; - - -static | -prefer-pic | -prefer-non-pic) - later="$later $arg" - continue - ;; - - -no-suppress) - suppress_opt=no - continue - ;; - - -Xcompiler) - arg_mode=arg # the next one goes into the "base_compile" arg list - continue # The current "srcfile" will either be retained or - ;; # replaced later. I would guess that would be a bug. - - -Wc,*) - args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"` - lastarg= - save_ifs="$IFS"; IFS=',' - for arg in $args; do - IFS="$save_ifs" - - # Double-quote args containing other shell metacharacters. - # Many Bourne shells cannot handle close brackets correctly - # in scan sets, so we specify it separately. - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - lastarg="$lastarg $arg" - done - IFS="$save_ifs" - lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"` - - # Add the arguments to base_compile. - base_compile="$base_compile $lastarg" - continue - ;; - - * ) - # Accept the current argument as the source file. - # The previous "srcfile" becomes the current argument. - # - lastarg="$srcfile" - srcfile="$arg" - ;; - esac # case $arg - ;; - esac # case $arg_mode - - # Aesthetically quote the previous argument. - lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"` - - case $lastarg in - # Double-quote args containing other shell metacharacters. - # Many Bourne shells cannot handle close brackets correctly - # in scan sets, and some SunOS ksh mistreat backslash-escaping - # in scan sets (worked around with variable expansion), - # and furthermore cannot handle '|' '&' '(' ')' in scan sets - # at all, so we specify them separately. - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - lastarg="\"$lastarg\"" - ;; - esac - - base_compile="$base_compile $lastarg" - done # for arg - - case $arg_mode in - arg) - $echo "$modename: you must specify an argument for -Xcompile" - exit $EXIT_FAILURE - ;; - target) - $echo "$modename: you must specify a target with \`-o'" 1>&2 - exit $EXIT_FAILURE - ;; - *) - # Get the name of the library object. - [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'` - ;; - esac - - # Recognize several different file suffixes. - # If the user specifies -o file.o, it is replaced with file.lo - xform='[cCFSifmso]' - case $libobj in - *.ada) xform=ada ;; - *.adb) xform=adb ;; - *.ads) xform=ads ;; - *.asm) xform=asm ;; - *.c++) xform=c++ ;; - *.cc) xform=cc ;; - *.ii) xform=ii ;; - *.class) xform=class ;; - *.cpp) xform=cpp ;; - *.cxx) xform=cxx ;; - *.f90) xform=f90 ;; - *.for) xform=for ;; - *.java) xform=java ;; - esac - - libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` - - case $libobj in - *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;; - *) - $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - func_infer_tag $base_compile - - for arg in $later; do - case $arg in - -static) - build_old_libs=yes - continue - ;; - - -prefer-pic) - pic_mode=yes - continue - ;; - - -prefer-non-pic) - pic_mode=no - continue - ;; - esac - done - - qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"` - case $qlibobj in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - qlibobj="\"$qlibobj\"" ;; - esac - test "X$libobj" != "X$qlibobj" \ - && $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \ - && $echo "$modename: libobj name \`$libobj' may not contain shell special characters." - objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'` - xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$obj"; then - xdir= - else - xdir=$xdir/ - fi - lobj=${xdir}$objdir/$objname - - if test -z "$base_compile"; then - $echo "$modename: you must specify a compilation command" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Delete any leftover library objects. - if test "$build_old_libs" = yes; then - removelist="$obj $lobj $libobj ${libobj}T" - else - removelist="$lobj $libobj ${libobj}T" - fi - - $run $rm $removelist - trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 - - # On Cygwin there's no "real" PIC flag so we must build both object types - case $host_os in - cygwin* | mingw* | pw32* | os2*) - pic_mode=default - ;; - esac - if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then - # non-PIC code in shared libraries is not supported - pic_mode=default - fi - - # Calculate the filename of the output object if compiler does - # not support -o with -c - if test "$compiler_c_o" = no; then - output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} - lockfile="$output_obj.lock" - removelist="$removelist $output_obj $lockfile" - trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 - else - output_obj= - need_locks=no - lockfile= - fi - - # Lock this critical section if it is needed - # We use this script file to make the link, it avoids creating a new file - if test "$need_locks" = yes; then - until $run ln "$srcfile" "$lockfile" 2>/dev/null; do - $show "Waiting for $lockfile to be removed" - sleep 2 - done - elif test "$need_locks" = warn; then - if test -f "$lockfile"; then - $echo "\ -*** ERROR, $lockfile exists and contains: -`cat $lockfile 2>/dev/null` - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $run $rm $removelist - exit $EXIT_FAILURE - fi - $echo "$srcfile" > "$lockfile" - fi - - if test -n "$fix_srcfile_path"; then - eval srcfile=\"$fix_srcfile_path\" - fi - qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"` - case $qsrcfile in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - qsrcfile="\"$qsrcfile\"" ;; - esac - - $run $rm "$libobj" "${libobj}T" - - # Create a libtool object file (analogous to a ".la" file), - # but don't create it if we're doing a dry run. - test -z "$run" && cat > ${libobj}T </dev/null`" != "X$srcfile"; then - $echo "\ -*** ERROR, $lockfile contains: -`cat $lockfile 2>/dev/null` - -but it should contain: -$srcfile - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $run $rm $removelist - exit $EXIT_FAILURE - fi - - # Just move the object if needed, then go on to compile the next one - if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then - $show "$mv $output_obj $lobj" - if $run $mv $output_obj $lobj; then : - else - error=$? - $run $rm $removelist - exit $error - fi - fi - - # Append the name of the PIC object to the libtool object file. - test -z "$run" && cat >> ${libobj}T <> ${libobj}T </dev/null`" != "X$srcfile"; then - $echo "\ -*** ERROR, $lockfile contains: -`cat $lockfile 2>/dev/null` - -but it should contain: -$srcfile - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $run $rm $removelist - exit $EXIT_FAILURE - fi - - # Just move the object if needed - if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then - $show "$mv $output_obj $obj" - if $run $mv $output_obj $obj; then : - else - error=$? - $run $rm $removelist - exit $error - fi - fi - - # Append the name of the non-PIC object the libtool object file. - # Only append if the libtool object file exists. - test -z "$run" && cat >> ${libobj}T <> ${libobj}T <&2 - fi - if test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=yes - else - if test -z "$pic_flag" && test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=built - fi - build_libtool_libs=no - build_old_libs=yes - break - ;; - esac - done - - # See if our shared archives depend on static archives. - test -n "$old_archive_from_new_cmds" && build_old_libs=yes - - # Go through the arguments, transforming them on the way. - while test "$#" -gt 0; do - arg="$1" - shift - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test - ;; - *) qarg=$arg ;; - esac - libtool_args="$libtool_args $qarg" - - # If the previous option needs an argument, assign it. - if test -n "$prev"; then - case $prev in - output) - compile_command="$compile_command @OUTPUT@" - finalize_command="$finalize_command @OUTPUT@" - ;; - esac - - case $prev in - dlfiles|dlprefiles) - if test "$preload" = no; then - # Add the symbol object into the linking commands. - compile_command="$compile_command @SYMFILE@" - finalize_command="$finalize_command @SYMFILE@" - preload=yes - fi - case $arg in - *.la | *.lo) ;; # We handle these cases below. - force) - if test "$dlself" = no; then - dlself=needless - export_dynamic=yes - fi - prev= - continue - ;; - self) - if test "$prev" = dlprefiles; then - dlself=yes - elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then - dlself=yes - else - dlself=needless - export_dynamic=yes - fi - prev= - continue - ;; - *) - if test "$prev" = dlfiles; then - dlfiles="$dlfiles $arg" - else - dlprefiles="$dlprefiles $arg" - fi - prev= - continue - ;; - esac - ;; - expsyms) - export_symbols="$arg" - if test ! -f "$arg"; then - $echo "$modename: symbol file \`$arg' does not exist" - exit $EXIT_FAILURE - fi - prev= - continue - ;; - expsyms_regex) - export_symbols_regex="$arg" - prev= - continue - ;; - inst_prefix) - inst_prefix_dir="$arg" - prev= - continue - ;; - precious_regex) - precious_files_regex="$arg" - prev= - continue - ;; - release) - release="-$arg" - prev= - continue - ;; - objectlist) - if test -f "$arg"; then - save_arg=$arg - moreargs= - for fil in `cat $save_arg` - do -# moreargs="$moreargs $fil" - arg=$fil - # A libtool-controlled object. - - # Check to see that this really is a libtool object. - if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - pic_object= - non_pic_object= - - # Read the .lo file - # If there is no directory component, then add one. - case $arg in - */* | *\\*) . $arg ;; - *) . ./$arg ;; - esac - - if test -z "$pic_object" || \ - test -z "$non_pic_object" || - test "$pic_object" = none && \ - test "$non_pic_object" = none; then - $echo "$modename: cannot find name of object for \`$arg'" 1>&2 - exit $EXIT_FAILURE - fi - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - if test "$pic_object" != none; then - # Prepend the subdirectory the object is found in. - pic_object="$xdir$pic_object" - - if test "$prev" = dlfiles; then - if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then - dlfiles="$dlfiles $pic_object" - prev= - continue - else - # If libtool objects are unsupported, then we need to preload. - prev=dlprefiles - fi - fi - - # CHECK ME: I think I busted this. -Ossama - if test "$prev" = dlprefiles; then - # Preload the old-style object. - dlprefiles="$dlprefiles $pic_object" - prev= - fi - - # A PIC object. - libobjs="$libobjs $pic_object" - arg="$pic_object" - fi - - # Non-PIC object. - if test "$non_pic_object" != none; then - # Prepend the subdirectory the object is found in. - non_pic_object="$xdir$non_pic_object" - - # A standard non-PIC object - non_pic_objects="$non_pic_objects $non_pic_object" - if test -z "$pic_object" || test "$pic_object" = none ; then - arg="$non_pic_object" - fi - else - # If the PIC object exists, use it instead. - # $xdir was prepended to $pic_object above. - non_pic_object="$pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - else - # Only an error if not doing a dry-run. - if test -z "$run"; then - $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 - exit $EXIT_FAILURE - else - # Dry-run case. - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` - non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` - libobjs="$libobjs $pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - fi - done - else - $echo "$modename: link input file \`$save_arg' does not exist" - exit $EXIT_FAILURE - fi - arg=$save_arg - prev= - continue - ;; - rpath | xrpath) - # We need an absolute path. - case $arg in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - $echo "$modename: only absolute run-paths are allowed" 1>&2 - exit $EXIT_FAILURE - ;; - esac - if test "$prev" = rpath; then - case "$rpath " in - *" $arg "*) ;; - *) rpath="$rpath $arg" ;; - esac - else - case "$xrpath " in - *" $arg "*) ;; - *) xrpath="$xrpath $arg" ;; - esac - fi - prev= - continue - ;; - xcompiler) - compiler_flags="$compiler_flags $qarg" - prev= - compile_command="$compile_command $qarg" - finalize_command="$finalize_command $qarg" - continue - ;; - xlinker) - linker_flags="$linker_flags $qarg" - compiler_flags="$compiler_flags $wl$qarg" - prev= - compile_command="$compile_command $wl$qarg" - finalize_command="$finalize_command $wl$qarg" - continue - ;; - xcclinker) - linker_flags="$linker_flags $qarg" - compiler_flags="$compiler_flags $qarg" - prev= - compile_command="$compile_command $qarg" - finalize_command="$finalize_command $qarg" - continue - ;; - shrext) - shrext_cmds="$arg" - prev= - continue - ;; - darwin_framework|darwin_framework_skip) - test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg" - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - prev= - continue - ;; - *) - eval "$prev=\"\$arg\"" - prev= - continue - ;; - esac - fi # test -n "$prev" - - prevarg="$arg" - - case $arg in - -all-static) - if test -n "$link_static_flag"; then - compile_command="$compile_command $link_static_flag" - finalize_command="$finalize_command $link_static_flag" - fi - continue - ;; - - -allow-undefined) - # FIXME: remove this flag sometime in the future. - $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2 - continue - ;; - - -avoid-version) - avoid_version=yes - continue - ;; - - -dlopen) - prev=dlfiles - continue - ;; - - -dlpreopen) - prev=dlprefiles - continue - ;; - - -export-dynamic) - export_dynamic=yes - continue - ;; - - -export-symbols | -export-symbols-regex) - if test -n "$export_symbols" || test -n "$export_symbols_regex"; then - $echo "$modename: more than one -exported-symbols argument is not allowed" - exit $EXIT_FAILURE - fi - if test "X$arg" = "X-export-symbols"; then - prev=expsyms - else - prev=expsyms_regex - fi - continue - ;; - - -framework|-arch|-isysroot) - case " $CC " in - *" ${arg} ${1} "* | *" ${arg} ${1} "*) - prev=darwin_framework_skip ;; - *) compiler_flags="$compiler_flags $arg" - prev=darwin_framework ;; - esac - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - continue - ;; - - -inst-prefix-dir) - prev=inst_prefix - continue - ;; - - # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* - # so, if we see these flags be careful not to treat them like -L - -L[A-Z][A-Z]*:*) - case $with_gcc/$host in - no/*-*-irix* | /*-*-irix*) - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - ;; - esac - continue - ;; - - -L*) - dir=`$echo "X$arg" | $Xsed -e 's/^-L//'` - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - absdir=`cd "$dir" && pwd` - if test -z "$absdir"; then - $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2 - absdir="$dir" - notinst_path="$notinst_path $dir" - fi - dir="$absdir" - ;; - esac - case "$deplibs " in - *" -L$dir "*) ;; - *) - deplibs="$deplibs -L$dir" - lib_search_path="$lib_search_path $dir" - ;; - esac - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'` - case :$dllsearchpath: in - *":$dir:"*) ;; - *) dllsearchpath="$dllsearchpath:$dir";; - esac - case :$dllsearchpath: in - *":$testbindir:"*) ;; - *) dllsearchpath="$dllsearchpath:$testbindir";; - esac - ;; - esac - continue - ;; - - -l*) - if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*) - # These systems don't actually have a C or math library (as such) - continue - ;; - *-*-os2*) - # These systems don't actually have a C library (as such) - test "X$arg" = "X-lc" && continue - ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc due to us having libc/libc_r. - test "X$arg" = "X-lc" && continue - ;; - *-*-rhapsody* | *-*-darwin1.[012]) - # Rhapsody C and math libraries are in the System framework - deplibs="$deplibs -framework System" - continue - ;; - *-*-sco3.2v5* | *-*-sco5v6*) - # Causes problems with __ctype - test "X$arg" = "X-lc" && continue - ;; - *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) - # Compiler inserts libc in the correct place for threads to work - test "X$arg" = "X-lc" && continue - ;; - esac - elif test "X$arg" = "X-lc_r"; then - case $host in - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc_r directly, use -pthread flag. - continue - ;; - esac - fi - deplibs="$deplibs $arg" - continue - ;; - - # Tru64 UNIX uses -model [arg] to determine the layout of C++ - # classes, name mangling, and exception handling. - -model) - compile_command="$compile_command $arg" - compiler_flags="$compiler_flags $arg" - finalize_command="$finalize_command $arg" - prev=xcompiler - continue - ;; - - -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) - compiler_flags="$compiler_flags $arg" - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - continue - ;; - - -module) - module=yes - continue - ;; - - # -64, -mips[0-9] enable 64-bit mode on the SGI compiler - # -r[0-9][0-9]* specifies the processor on the SGI compiler - # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler - # +DA*, +DD* enable 64-bit mode on the HP compiler - # -q* pass through compiler args for the IBM compiler - # -m* pass through architecture-specific compiler args for GCC - # -m*, -t[45]*, -txscale* pass through architecture-specific - # compiler args for GCC - # -pg pass through profiling flag for GCC - # @file GCC response files - -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \ - -t[45]*|-txscale*|@*) - - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - compiler_flags="$compiler_flags $arg" - continue - ;; - - -shrext) - prev=shrext - continue - ;; - - -no-fast-install) - fast_install=no - continue - ;; - - -no-install) - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - # The PATH hackery in wrapper scripts is required on Windows - # in order for the loader to find any dlls it needs. - $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2 - $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2 - fast_install=no - ;; - *) no_install=yes ;; - esac - continue - ;; - - -no-undefined) - allow_undefined=no - continue - ;; - - -objectlist) - prev=objectlist - continue - ;; - - -o) prev=output ;; - - -precious-files-regex) - prev=precious_regex - continue - ;; - - -release) - prev=release - continue - ;; - - -rpath) - prev=rpath - continue - ;; - - -R) - prev=xrpath - continue - ;; - - -R*) - dir=`$echo "X$arg" | $Xsed -e 's/^-R//'` - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - $echo "$modename: only absolute run-paths are allowed" 1>&2 - exit $EXIT_FAILURE - ;; - esac - case "$xrpath " in - *" $dir "*) ;; - *) xrpath="$xrpath $dir" ;; - esac - continue - ;; - - -static) - # The effects of -static are defined in a previous loop. - # We used to do the same as -all-static on platforms that - # didn't have a PIC flag, but the assumption that the effects - # would be equivalent was wrong. It would break on at least - # Digital Unix and AIX. - continue - ;; - - -thread-safe) - thread_safe=yes - continue - ;; - - -version-info) - prev=vinfo - continue - ;; - -version-number) - prev=vinfo - vinfo_number=yes - continue - ;; - - -Wc,*) - args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'` - arg= - save_ifs="$IFS"; IFS=',' - for flag in $args; do - IFS="$save_ifs" - case $flag in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - flag="\"$flag\"" - ;; - esac - arg="$arg $wl$flag" - compiler_flags="$compiler_flags $flag" - done - IFS="$save_ifs" - arg=`$echo "X$arg" | $Xsed -e "s/^ //"` - ;; - - -Wl,*) - args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'` - arg= - save_ifs="$IFS"; IFS=',' - for flag in $args; do - IFS="$save_ifs" - case $flag in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - flag="\"$flag\"" - ;; - esac - arg="$arg $wl$flag" - compiler_flags="$compiler_flags $wl$flag" - linker_flags="$linker_flags $flag" - done - IFS="$save_ifs" - arg=`$echo "X$arg" | $Xsed -e "s/^ //"` - ;; - - -Xcompiler) - prev=xcompiler - continue - ;; - - -Xlinker) - prev=xlinker - continue - ;; - - -XCClinker) - prev=xcclinker - continue - ;; - - # Some other compiler flag. - -* | +*) - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - ;; - - *.$objext) - # A standard object. - objs="$objs $arg" - ;; - - *.lo) - # A libtool-controlled object. - - # Check to see that this really is a libtool object. - if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - pic_object= - non_pic_object= - - # Read the .lo file - # If there is no directory component, then add one. - case $arg in - */* | *\\*) . $arg ;; - *) . ./$arg ;; - esac - - if test -z "$pic_object" || \ - test -z "$non_pic_object" || - test "$pic_object" = none && \ - test "$non_pic_object" = none; then - $echo "$modename: cannot find name of object for \`$arg'" 1>&2 - exit $EXIT_FAILURE - fi - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - if test "$pic_object" != none; then - # Prepend the subdirectory the object is found in. - pic_object="$xdir$pic_object" - - if test "$prev" = dlfiles; then - if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then - dlfiles="$dlfiles $pic_object" - prev= - continue - else - # If libtool objects are unsupported, then we need to preload. - prev=dlprefiles - fi - fi - - # CHECK ME: I think I busted this. -Ossama - if test "$prev" = dlprefiles; then - # Preload the old-style object. - dlprefiles="$dlprefiles $pic_object" - prev= - fi - - # A PIC object. - libobjs="$libobjs $pic_object" - arg="$pic_object" - fi - - # Non-PIC object. - if test "$non_pic_object" != none; then - # Prepend the subdirectory the object is found in. - non_pic_object="$xdir$non_pic_object" - - # A standard non-PIC object - non_pic_objects="$non_pic_objects $non_pic_object" - if test -z "$pic_object" || test "$pic_object" = none ; then - arg="$non_pic_object" - fi - else - # If the PIC object exists, use it instead. - # $xdir was prepended to $pic_object above. - non_pic_object="$pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - else - # Only an error if not doing a dry-run. - if test -z "$run"; then - $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 - exit $EXIT_FAILURE - else - # Dry-run case. - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` - non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` - libobjs="$libobjs $pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - fi - ;; - - *.$libext) - # An archive. - deplibs="$deplibs $arg" - old_deplibs="$old_deplibs $arg" - continue - ;; - - *.la) - # A libtool-controlled library. - - if test "$prev" = dlfiles; then - # This library was specified with -dlopen. - dlfiles="$dlfiles $arg" - prev= - elif test "$prev" = dlprefiles; then - # The library was specified with -dlpreopen. - dlprefiles="$dlprefiles $arg" - prev= - else - deplibs="$deplibs $arg" - fi - continue - ;; - - # Some other compiler argument. - *) - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - ;; - esac # arg - - # Now actually substitute the argument into the commands. - if test -n "$arg"; then - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - fi - done # argument parsing loop - - if test -n "$prev"; then - $echo "$modename: the \`$prevarg' option requires an argument" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then - eval arg=\"$export_dynamic_flag_spec\" - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - fi - - oldlibs= - # calculate the name of the file, without its directory - outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'` - libobjs_save="$libobjs" - - if test -n "$shlibpath_var"; then - # get the directories listed in $shlibpath_var - eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` - else - shlib_search_path= - fi - eval sys_lib_search_path=\"$sys_lib_search_path_spec\" - eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" - - output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'` - if test "X$output_objdir" = "X$output"; then - output_objdir="$objdir" - else - output_objdir="$output_objdir/$objdir" - fi - # Create the object directory. - if test ! -d "$output_objdir"; then - $show "$mkdir $output_objdir" - $run $mkdir $output_objdir - exit_status=$? - if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then - exit $exit_status - fi - fi - - # Determine the type of output - case $output in - "") - $echo "$modename: you must specify an output file" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; - *.$libext) linkmode=oldlib ;; - *.lo | *.$objext) linkmode=obj ;; - *.la) linkmode=lib ;; - *) linkmode=prog ;; # Anything else should be a program. - esac - - case $host in - *cygwin* | *mingw* | *pw32*) - # don't eliminate duplications in $postdeps and $predeps - duplicate_compiler_generated_deps=yes - ;; - *) - duplicate_compiler_generated_deps=$duplicate_deps - ;; - esac - specialdeplibs= - - libs= - # Find all interdependent deplibs by searching for libraries - # that are linked more than once (e.g. -la -lb -la) - for deplib in $deplibs; do - if test "X$duplicate_deps" = "Xyes" ; then - case "$libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - libs="$libs $deplib" - done - - if test "$linkmode" = lib; then - libs="$predeps $libs $compiler_lib_search_path $postdeps" - - # Compute libraries that are listed more than once in $predeps - # $postdeps and mark them as special (i.e., whose duplicates are - # not to be eliminated). - pre_post_deps= - if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then - for pre_post_dep in $predeps $postdeps; do - case "$pre_post_deps " in - *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; - esac - pre_post_deps="$pre_post_deps $pre_post_dep" - done - fi - pre_post_deps= - fi - - deplibs= - newdependency_libs= - newlib_search_path= - need_relink=no # whether we're linking any uninstalled libtool libraries - notinst_deplibs= # not-installed libtool libraries - case $linkmode in - lib) - passes="conv link" - for file in $dlfiles $dlprefiles; do - case $file in - *.la) ;; - *) - $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2 - exit $EXIT_FAILURE - ;; - esac - done - ;; - prog) - compile_deplibs= - finalize_deplibs= - alldeplibs=no - newdlfiles= - newdlprefiles= - passes="conv scan dlopen dlpreopen link" - ;; - *) passes="conv" - ;; - esac - for pass in $passes; do - if test "$linkmode,$pass" = "lib,link" || - test "$linkmode,$pass" = "prog,scan"; then - libs="$deplibs" - deplibs= - fi - if test "$linkmode" = prog; then - case $pass in - dlopen) libs="$dlfiles" ;; - dlpreopen) libs="$dlprefiles" ;; - link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; - esac - fi - if test "$pass" = dlopen; then - # Collect dlpreopened libraries - save_deplibs="$deplibs" - deplibs= - fi - for deplib in $libs; do - lib= - found=no - case $deplib in - -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - compiler_flags="$compiler_flags $deplib" - fi - continue - ;; - -l*) - if test "$linkmode" != lib && test "$linkmode" != prog; then - $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2 - continue - fi - name=`$echo "X$deplib" | $Xsed -e 's/^-l//'` - for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do - for search_ext in .la $std_shrext .so .a; do - # Search the libtool library - lib="$searchdir/lib${name}${search_ext}" - if test -f "$lib"; then - if test "$search_ext" = ".la"; then - found=yes - else - found=no - fi - break 2 - fi - done - done - if test "$found" != yes; then - # deplib doesn't seem to be a libtool library - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" - fi - continue - else # deplib is a libtool library - # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, - # We need to do some special things here, and not later. - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - case " $predeps $postdeps " in - *" $deplib "*) - if (${SED} -e '2q' $lib | - grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - library_names= - old_library= - case $lib in - */* | *\\*) . $lib ;; - *) . ./$lib ;; - esac - for l in $old_library $library_names; do - ll="$l" - done - if test "X$ll" = "X$old_library" ; then # only static version available - found=no - ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` - test "X$ladir" = "X$lib" && ladir="." - lib=$ladir/$old_library - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" - fi - continue - fi - fi - ;; - *) ;; - esac - fi - fi - ;; # -l - -L*) - case $linkmode in - lib) - deplibs="$deplib $deplibs" - test "$pass" = conv && continue - newdependency_libs="$deplib $newdependency_libs" - newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` - ;; - prog) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - continue - fi - if test "$pass" = scan; then - deplibs="$deplib $deplibs" - else - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - fi - newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` - ;; - *) - $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2 - ;; - esac # linkmode - continue - ;; # -L - -R*) - if test "$pass" = link; then - dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'` - # Make sure the xrpath contains only unique directories. - case "$xrpath " in - *" $dir "*) ;; - *) xrpath="$xrpath $dir" ;; - esac - fi - deplibs="$deplib $deplibs" - continue - ;; - *.la) lib="$deplib" ;; - *.$libext) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - continue - fi - case $linkmode in - lib) - valid_a_lib=no - case $deplibs_check_method in - match_pattern*) - set dummy $deplibs_check_method - match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"` - if eval $echo \"$deplib\" 2>/dev/null \ - | $SED 10q \ - | $EGREP "$match_pattern_regex" > /dev/null; then - valid_a_lib=yes - fi - ;; - pass_all) - valid_a_lib=yes - ;; - esac - if test "$valid_a_lib" != yes; then - $echo - $echo "*** Warning: Trying to link with static lib archive $deplib." - $echo "*** I have the capability to make that library automatically link in when" - $echo "*** you link to this library. But I can only do this if you have a" - $echo "*** shared version of the library, which you do not appear to have" - $echo "*** because the file extensions .$libext of this argument makes me believe" - $echo "*** that it is just a static archive that I should not used here." - else - $echo - $echo "*** Warning: Linking the shared library $output against the" - $echo "*** static library $deplib is not portable!" - deplibs="$deplib $deplibs" - fi - continue - ;; - prog) - if test "$pass" != link; then - deplibs="$deplib $deplibs" - else - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - fi - continue - ;; - esac # linkmode - ;; # *.$libext - *.lo | *.$objext) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - elif test "$linkmode" = prog; then - if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then - # If there is no dlopen support or we're linking statically, - # we need to preload. - newdlprefiles="$newdlprefiles $deplib" - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - newdlfiles="$newdlfiles $deplib" - fi - fi - continue - ;; - %DEPLIBS%) - alldeplibs=yes - continue - ;; - esac # case $deplib - if test "$found" = yes || test -f "$lib"; then : - else - $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2 - exit $EXIT_FAILURE - fi - - # Check to see that this really is a libtool archive. - if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : - else - $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 - exit $EXIT_FAILURE - fi - - ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` - test "X$ladir" = "X$lib" && ladir="." - - dlname= - dlopen= - dlpreopen= - libdir= - library_names= - old_library= - # If the library was installed with an old release of libtool, - # it will not redefine variables installed, or shouldnotlink - installed=yes - shouldnotlink=no - avoidtemprpath= - - - # Read the .la file - case $lib in - */* | *\\*) . $lib ;; - *) . ./$lib ;; - esac - - if test "$linkmode,$pass" = "lib,link" || - test "$linkmode,$pass" = "prog,scan" || - { test "$linkmode" != prog && test "$linkmode" != lib; }; then - test -n "$dlopen" && dlfiles="$dlfiles $dlopen" - test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" - fi - - if test "$pass" = conv; then - # Only check for convenience libraries - deplibs="$lib $deplibs" - if test -z "$libdir"; then - if test -z "$old_library"; then - $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - # It is a libtool convenience library, so add in its objects. - convenience="$convenience $ladir/$objdir/$old_library" - old_convenience="$old_convenience $ladir/$objdir/$old_library" - tmp_libs= - for deplib in $dependency_libs; do - deplibs="$deplib $deplibs" - if test "X$duplicate_deps" = "Xyes" ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done - elif test "$linkmode" != prog && test "$linkmode" != lib; then - $echo "$modename: \`$lib' is not a convenience library" 1>&2 - exit $EXIT_FAILURE - fi - continue - fi # $pass = conv - - - # Get the name of the library we link against. - linklib= - for l in $old_library $library_names; do - linklib="$l" - done - if test -z "$linklib"; then - $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - - # This library was specified with -dlopen. - if test "$pass" = dlopen; then - if test -z "$libdir"; then - $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - if test -z "$dlname" || - test "$dlopen_support" != yes || - test "$build_libtool_libs" = no; then - # If there is no dlname, no dlopen support or we're linking - # statically, we need to preload. We also need to preload any - # dependent libraries so libltdl's deplib preloader doesn't - # bomb out in the load deplibs phase. - dlprefiles="$dlprefiles $lib $dependency_libs" - else - newdlfiles="$newdlfiles $lib" - fi - continue - fi # $pass = dlopen - - # We need an absolute path. - case $ladir in - [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; - *) - abs_ladir=`cd "$ladir" && pwd` - if test -z "$abs_ladir"; then - $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2 - $echo "$modename: passing it literally to the linker, although it might fail" 1>&2 - abs_ladir="$ladir" - fi - ;; - esac - laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` - - # Find the relevant object directory and library name. - if test "X$installed" = Xyes; then - if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then - $echo "$modename: warning: library \`$lib' was moved." 1>&2 - dir="$ladir" - absdir="$abs_ladir" - libdir="$abs_ladir" - else - dir="$libdir" - absdir="$libdir" - fi - test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes - else - if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then - dir="$ladir" - absdir="$abs_ladir" - # Remove this search path later - notinst_path="$notinst_path $abs_ladir" - else - dir="$ladir/$objdir" - absdir="$abs_ladir/$objdir" - # Remove this search path later - notinst_path="$notinst_path $abs_ladir" - fi - fi # $installed = yes - name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` - - # This library was specified with -dlpreopen. - if test "$pass" = dlpreopen; then - if test -z "$libdir"; then - $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - # Prefer using a static library (so that no silly _DYNAMIC symbols - # are required to link). - if test -n "$old_library"; then - newdlprefiles="$newdlprefiles $dir/$old_library" - # Otherwise, use the dlname, so that lt_dlopen finds it. - elif test -n "$dlname"; then - newdlprefiles="$newdlprefiles $dir/$dlname" - else - newdlprefiles="$newdlprefiles $dir/$linklib" - fi - fi # $pass = dlpreopen - - if test -z "$libdir"; then - # Link the convenience library - if test "$linkmode" = lib; then - deplibs="$dir/$old_library $deplibs" - elif test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$dir/$old_library $compile_deplibs" - finalize_deplibs="$dir/$old_library $finalize_deplibs" - else - deplibs="$lib $deplibs" # used for prog,scan pass - fi - continue - fi - - - if test "$linkmode" = prog && test "$pass" != link; then - newlib_search_path="$newlib_search_path $ladir" - deplibs="$lib $deplibs" - - linkalldeplibs=no - if test "$link_all_deplibs" != no || test -z "$library_names" || - test "$build_libtool_libs" = no; then - linkalldeplibs=yes - fi - - tmp_libs= - for deplib in $dependency_libs; do - case $deplib in - -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test - esac - # Need to link against all dependency_libs? - if test "$linkalldeplibs" = yes; then - deplibs="$deplib $deplibs" - else - # Need to hardcode shared library paths - # or/and link against static libraries - newdependency_libs="$deplib $newdependency_libs" - fi - if test "X$duplicate_deps" = "Xyes" ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done # for deplib - continue - fi # $linkmode = prog... - - if test "$linkmode,$pass" = "prog,link"; then - if test -n "$library_names" && - { test "$prefer_static_libs" = no || test -z "$old_library"; }; then - # We need to hardcode the library path - if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then - # Make sure the rpath contains only unique directories. - case "$temp_rpath " in - *" $dir "*) ;; - *" $absdir "*) ;; - *) temp_rpath="$temp_rpath $absdir" ;; - esac - fi - - # Hardcode the library path. - # Skip directories that are in the system default run-time - # search path. - case " $sys_lib_dlsearch_path " in - *" $absdir "*) ;; - *) - case "$compile_rpath " in - *" $absdir "*) ;; - *) compile_rpath="$compile_rpath $absdir" - esac - ;; - esac - case " $sys_lib_dlsearch_path " in - *" $libdir "*) ;; - *) - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" - esac - ;; - esac - fi # $linkmode,$pass = prog,link... - - if test "$alldeplibs" = yes && - { test "$deplibs_check_method" = pass_all || - { test "$build_libtool_libs" = yes && - test -n "$library_names"; }; }; then - # We only need to search for static libraries - continue - fi - fi - - link_static=no # Whether the deplib will be linked statically - use_static_libs=$prefer_static_libs - if test "$use_static_libs" = built && test "$installed" = yes ; then - use_static_libs=no - fi - if test -n "$library_names" && - { test "$use_static_libs" = no || test -z "$old_library"; }; then - if test "$installed" = no; then - notinst_deplibs="$notinst_deplibs $lib" - need_relink=yes - fi - # This is a shared library - - # Warn about portability, can't link against -module's on - # some systems (darwin) - if test "$shouldnotlink" = yes && test "$pass" = link ; then - $echo - if test "$linkmode" = prog; then - $echo "*** Warning: Linking the executable $output against the loadable module" - else - $echo "*** Warning: Linking the shared library $output against the loadable module" - fi - $echo "*** $linklib is not portable!" - fi - if test "$linkmode" = lib && - test "$hardcode_into_libs" = yes; then - # Hardcode the library path. - # Skip directories that are in the system default run-time - # search path. - case " $sys_lib_dlsearch_path " in - *" $absdir "*) ;; - *) - case "$compile_rpath " in - *" $absdir "*) ;; - *) compile_rpath="$compile_rpath $absdir" - esac - ;; - esac - case " $sys_lib_dlsearch_path " in - *" $libdir "*) ;; - *) - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" - esac - ;; - esac - fi - - if test -n "$old_archive_from_expsyms_cmds"; then - # figure out the soname - set dummy $library_names - realname="$2" - shift; shift - libname=`eval \\$echo \"$libname_spec\"` - # use dlname if we got it. it's perfectly good, no? - if test -n "$dlname"; then - soname="$dlname" - elif test -n "$soname_spec"; then - # bleh windows - case $host in - *cygwin* | mingw*) - major=`expr $current - $age` - versuffix="-$major" - ;; - esac - eval soname=\"$soname_spec\" - else - soname="$realname" - fi - - # Make a new name for the extract_expsyms_cmds to use - soroot="$soname" - soname=`$echo $soroot | ${SED} -e 's/^.*\///'` - newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a" - - # If the library has no export list, then create one now - if test -f "$output_objdir/$soname-def"; then : - else - $show "extracting exported symbol list from \`$soname'" - save_ifs="$IFS"; IFS='~' - cmds=$extract_expsyms_cmds - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - fi - - # Create $newlib - if test -f "$output_objdir/$newlib"; then :; else - $show "generating import library for \`$soname'" - save_ifs="$IFS"; IFS='~' - cmds=$old_archive_from_expsyms_cmds - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - fi - # make sure the library variables are pointing to the new library - dir=$output_objdir - linklib=$newlib - fi # test -n "$old_archive_from_expsyms_cmds" - - if test "$linkmode" = prog || test "$mode" != relink; then - add_shlibpath= - add_dir= - add= - lib_linked=yes - case $hardcode_action in - immediate | unsupported) - if test "$hardcode_direct" = no; then - add="$dir/$linklib" - case $host in - *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; - *-*-sysv4*uw2*) add_dir="-L$dir" ;; - *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ - *-*-unixware7*) add_dir="-L$dir" ;; - *-*-darwin* ) - # if the lib is a module then we can not link against - # it, someone is ignoring the new warnings I added - if /usr/bin/file -L $add 2> /dev/null | - $EGREP ": [^:]* bundle" >/dev/null ; then - $echo "** Warning, lib $linklib is a module, not a shared library" - if test -z "$old_library" ; then - $echo - $echo "** And there doesn't seem to be a static archive available" - $echo "** The link will probably fail, sorry" - else - add="$dir/$old_library" - fi - fi - esac - elif test "$hardcode_minus_L" = no; then - case $host in - *-*-sunos*) add_shlibpath="$dir" ;; - esac - add_dir="-L$dir" - add="-l$name" - elif test "$hardcode_shlibpath_var" = no; then - add_shlibpath="$dir" - add="-l$name" - else - lib_linked=no - fi - ;; - relink) - if test "$hardcode_direct" = yes; then - add="$dir/$linklib" - elif test "$hardcode_minus_L" = yes; then - add_dir="-L$dir" - # Try looking first in the location we're being installed to. - if test -n "$inst_prefix_dir"; then - case $libdir in - [\\/]*) - add_dir="$add_dir -L$inst_prefix_dir$libdir" - ;; - esac - fi - add="-l$name" - elif test "$hardcode_shlibpath_var" = yes; then - add_shlibpath="$dir" - add="-l$name" - else - lib_linked=no - fi - ;; - *) lib_linked=no ;; - esac - - if test "$lib_linked" != yes; then - $echo "$modename: configuration error: unsupported hardcode properties" - exit $EXIT_FAILURE - fi - - if test -n "$add_shlibpath"; then - case :$compile_shlibpath: in - *":$add_shlibpath:"*) ;; - *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; - esac - fi - if test "$linkmode" = prog; then - test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" - test -n "$add" && compile_deplibs="$add $compile_deplibs" - else - test -n "$add_dir" && deplibs="$add_dir $deplibs" - test -n "$add" && deplibs="$add $deplibs" - if test "$hardcode_direct" != yes && \ - test "$hardcode_minus_L" != yes && \ - test "$hardcode_shlibpath_var" = yes; then - case :$finalize_shlibpath: in - *":$libdir:"*) ;; - *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; - esac - fi - fi - fi - - if test "$linkmode" = prog || test "$mode" = relink; then - add_shlibpath= - add_dir= - add= - # Finalize command for both is simple: just hardcode it. - if test "$hardcode_direct" = yes; then - add="$libdir/$linklib" - elif test "$hardcode_minus_L" = yes; then - add_dir="-L$libdir" - add="-l$name" - elif test "$hardcode_shlibpath_var" = yes; then - case :$finalize_shlibpath: in - *":$libdir:"*) ;; - *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; - esac - add="-l$name" - elif test "$hardcode_automatic" = yes; then - if test -n "$inst_prefix_dir" && - test -f "$inst_prefix_dir$libdir/$linklib" ; then - add="$inst_prefix_dir$libdir/$linklib" - else - add="$libdir/$linklib" - fi - else - # We cannot seem to hardcode it, guess we'll fake it. - add_dir="-L$libdir" - # Try looking first in the location we're being installed to. - if test -n "$inst_prefix_dir"; then - case $libdir in - [\\/]*) - add_dir="$add_dir -L$inst_prefix_dir$libdir" - ;; - esac - fi - add="-l$name" - fi - - if test "$linkmode" = prog; then - test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" - test -n "$add" && finalize_deplibs="$add $finalize_deplibs" - else - test -n "$add_dir" && deplibs="$add_dir $deplibs" - test -n "$add" && deplibs="$add $deplibs" - fi - fi - elif test "$linkmode" = prog; then - # Here we assume that one of hardcode_direct or hardcode_minus_L - # is not unsupported. This is valid on all known static and - # shared platforms. - if test "$hardcode_direct" != unsupported; then - test -n "$old_library" && linklib="$old_library" - compile_deplibs="$dir/$linklib $compile_deplibs" - finalize_deplibs="$dir/$linklib $finalize_deplibs" - else - compile_deplibs="-l$name -L$dir $compile_deplibs" - finalize_deplibs="-l$name -L$dir $finalize_deplibs" - fi - elif test "$build_libtool_libs" = yes; then - # Not a shared library - if test "$deplibs_check_method" != pass_all; then - # We're trying link a shared library against a static one - # but the system doesn't support it. - diff --git a/third_party/pygments/tests/examplefiles/main.cmake b/third_party/pygments/tests/examplefiles/main.cmake deleted file mode 100644 index 6dfcab102..000000000 --- a/third_party/pygments/tests/examplefiles/main.cmake +++ /dev/null @@ -1,45 +0,0 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 2.6 FATAL_ERROR) - -SET( SOURCES back.c io.c main.c ) -SET( PATH $ENV{PATH} ) -MESSAGE( ${SOURCES} ) # three arguments, prints "back.cio.cmain.c" -MESSAGE( "${SOURCES}" ) # one argument, prints "back.c;io.c;main.c" -MESSAGE( "" ) # one argument, prints "" an empty line -MESSAGE( "${EMPTY_STRING}" ) # one argument, prints "" an empty line -MESSAGE( ${EMPTY_STRING} ) # zero arguments, causes CMake Error - # "MESSAGE called with incorrect number of arguments" -MESSAGE( \\\"\ \(\)\#\$\^ ) # this message contains literal characters - -MESSAGE( "This is practice." ) # prints "This is practice." -MESSAGE( "This;is;practice." ) # prints "This;is;practice." -MESSAGE( "Hi. ) MESSAGE( x )" ) # prints "Hi. ) MESSAGE( x )" - -MESSAGE( "Welc"ome ) # rule 1 -MESSAGE( Welc"ome" ) # rule 3 -MESSAGE( Welc"ome)" ) # rule 2 -MESSAGE( ""Thanks ) # rule 1 -MESSAGE( Thanks"" ) # rule 3 - -SET( x y A B C ) # stores "y;A;B;C" in x (without quote) -SET( ${x} ) # => SET( y;A;B;C ) => SET( y A B C) -MESSAGE( ${y} ) # prints "ABC" to stdout (without quotes) -SET( y x ) # stores "x" in y (without quotes) -SET( ${y} y = x ) # => SET( x y ) -MESSAGE( "\${x} = '${x}'" ) # prints "${x} = 'y;=;x'" to stdout (without quotes) -SET( y ${x} ) # => SET( y y = x ) => stores "y;=;x" in y (without quotes) -MESSAGE( ${y} ) # prints "y=x" to stdout (without quotes) - -SET( x a b c ) # stores "a;b;c" in x (without quotes) -SET( y "a b c" ) # stores "a b c" in y (without quotes) -MESSAGE( a b c ) # prints "abc" to stdout (without quotes) -MESSAGE( ${x} ) # prints "abc" to stdout (without quotes) -MESSAGE("${x}") # prints "a;b;c" to stdout (without quotes) -MESSAGE( ${y} ) # prints "a b c" to stdout (without quotes) -MESSAGE("${y}") # prints "a b c" to stdout (without quotes) - -# This is a comment. -COMMAND( arguments go here ) -ANOTHER_COMMAND() # this command has no arguments -YET_ANOTHER_COMMAND( these - arguments are spread # another comment - over several lines ) diff --git a/third_party/pygments/tests/examplefiles/markdown.lsp b/third_party/pygments/tests/examplefiles/markdown.lsp deleted file mode 100644 index 8159082be..000000000 --- a/third_party/pygments/tests/examplefiles/markdown.lsp +++ /dev/null @@ -1,679 +0,0 @@ -#!/usr/bin/env newlisp - -;; @module markdown -;; @author cormullion -;; @description a port of John Gruber's Markdown to newLISP -;; @location http://unbalanced-parentheses.nfshost.com/ -;; @version of date 2011-10-02 22:36:02 -;; version history: at the end -;; a port of John Gruber's Markdown.pl (http://daringfireball.net/markdown) script to newLISP... -;; see his original Perl script for explanations of the fearsome regexen and -;; byzantine logic, etc... -;; TODO: -;; the following Markdown tests fail: -;; Inline HTML (Advanced) ... FAILED -;; Links, reference style ... FAILED -- nested brackets -;; Links, shortcut references ... FAILED -;; Markdown Documentation - Syntax ... FAILED -;; Ordered and unordered lists ... FAILED -- a nested ordered list error -;; parens in url : ![this is a stupid URL](http://example.com/(parens).jpg) see (Images.text) -;; Add: email address scrambling - -(context 'Hash) -(define HashTable:HashTable) - -(define (build-escape-table) - (set '*escape-chars* [text]\`*_{}[]()>#+-.![/text]) - (dolist (c (explode *escape-chars*)) - (HashTable c (hash c)))) - -(define (init-hash txt) - ; finds a hash identifier that doesn't occur anywhere in the text - (set 'counter 0) - (set 'hash-prefix "HASH") - (set 'hash-id (string hash-prefix counter)) - (do-while (find hash-id txt) - (set 'hash-id (string hash-prefix (inc counter)))) - (Hash:build-escape-table)) - -(define (hash s) - (HashTable s (string hash-id (inc counter)))) - -(context 'markdown) - -(define (markdown:markdown txt) - (initialize) - (Hash:init-hash txt) - (unescape-special-chars - (block-transforms - (strip-link-definitions - (protect - (cleanup txt)))))) - -(define (initialize) - (set '*escape-pairs* '( - ({\\\\} {\}) - ({\\`} {`}) - ({\\\*} {*}) - ({\\_} {_}) - ([text]\\\{[/text] [text]{[/text]) - ([text]\\\}[/text] [text]}[/text]) - ({\\\[} {[}) - ({\\\]} {]}) - ({\\\(} {(}) - ({\\\)} {)}) - ({\\>} {>}) - ({\\\#} {#}) - ({\\\+} {+}) - ({\\\-} {-}) - ({\\\.} {.}) - ({\\!} {!}))) - (set '*hashed-html-blocks* '()) - (set '*list-level* 0)) - -(define (block-transforms txt) - (form-paragraphs - (protect - (block-quotes - (code-blocks - (lists - (horizontal-rules - (headers txt)))))))) - -(define (span-transforms txt) - (line-breaks - (emphasis - (amps-and-angles - (auto-links - (anchors - (images - (escape-special-chars - (escape-special-chars (code-spans txt) 'inside-attributes))))))))) - -(define (tokenize-html xhtml) -; return list of tag/text portions of xhtml text - (letn ( - (tag-match [text]((?s:)| -(?s:<\?.*?\?>)| -(?:<[a-z/!$](?:[^<>]| -(?:<[a-z/!$](?:[^<>]| -(?:<[a-z/!$](?:[^<>]| -(?:<[a-z/!$](?:[^<>]| -(?:<[a-z/!$](?:[^<>]| -(?:<[a-z/!$](?:[^<>])*>))*>))*>))*>))*>))*>))[/text]) ; yeah, well... - (str xhtml) - (len (length str)) - (pos 0) - (tokens '())) - (while (set 'tag-start (find tag-match str 8)) - (if (< pos tag-start) - (push (list 'text (slice str pos (- tag-start pos))) tokens -1)) - (push (list 'tag $0) tokens -1) - (set 'str (slice str (+ tag-start (length $0)))) - (set 'pos 0)) - ; leftovers - (if (< pos len) - (push (list 'text (slice str pos (- len pos))) tokens -1)) - tokens)) - -(define (escape-special-chars txt (within-tag-attributes nil)) - (let ((temp (tokenize-html txt)) - (new-text {})) - (dolist (pair temp) - (if (= (first pair) 'tag) - ; 'tag - (begin - (set 'new-text (replace {\\} (last pair) (HashTable {\\}) 0)) - (replace [text](?<=.)(?=.)[/text] new-text (HashTable {`}) 0) - (replace {\*} new-text (HashTable {*}) 0) - (replace {_} new-text (HashTable {_} ) 0)) - ; 'text - (if within-tag-attributes - (set 'new-text (last pair)) - (set 'new-text (encode-backslash-escapes (last pair))))) - (setf (temp $idx) (list (first pair) new-text))) - ; return as text - (join (map last temp)))) - -(define (encode-backslash-escapes t) - (dolist (pair *escape-pairs*) - (replace (first pair) t (HashTable (last pair)) 14))) - -(define (encode-code s) - ; encode/escape certain characters inside Markdown code runs - (replace {&} s "&" 0) - (replace {<} s "<" 0) - (replace {>} s ">" 0) - (replace {\*} s (HashTable {\\}) 0) - (replace {_} s (HashTable {_}) 0) - (replace "{" s (HashTable "{") 0) - (replace {\[} s (HashTable {[}) 0) - (replace {\]} s (HashTable {]}) 0) - (replace {\\} s (HashTable "\\") 0)) - -(define (code-spans s) - (replace - {(?} (encode-code (trim $2)) {
    }) - 2)) - -(define (encode-alt s) - (replace {&} s "&" 0) - (replace {"} s """ 0)) - -(define (images txt) - (let ((alt-text {}) - (url {}) - (title {}) - (ref-regex {(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])}) - (inline-regex {(!\[(.*?)\]\([ \t]*?[ \t]*((['"])(.*?)\5[ \t]*)?\))}) - (whole-match {}) - (result {}) - (id-ref {}) - (url {})) - ; reference links ![alt text][id] - (replace - ref-regex - txt - (begin - (set 'whole-match $1 'alt-text $2 'id-ref $3) - (if alt-text - (replace {"} alt-text {"} 0)) - (if (empty? id-ref) - (set 'id-ref (lower-case alt-text))) - (if (lookup id-ref *link-database*) - (set 'url (first (lookup id-ref *link-database*))) - (set 'url nil)) - (if url - (begin - (replace {\*} url (HashTable {*}) 0) - (replace {_} url (HashTable {_}) 0) - )) - (if (last (lookup id-ref *link-database*)) - ; title - (begin - (set 'title (last (lookup id-ref *link-database*))) - (replace {"} title {"} 0) - (replace {\*} title (HashTable {*}) 0) - (replace {_} title (HashTable {_}) 0)) - ; no title - (set 'title {}) - ) - (if url - (set 'result (string - {} 
-          alt-text {})) - (set 'result whole-match)) - ) - 0 - ) - ; inline image refs: ![alt text](url "optional title") - (replace - inline-regex - txt - (begin - (set 'whole-match $1) - (set 'alt-text $2) - (set 'url $3) - (set 'title $6) - (if alt-text - (replace {"} alt-text {"} 0) - (set 'alt-text {})) - (if title - (begin - (replace {"} title {"} 0) - (replace {\*} title (HashTable {*}) 0) - (replace {_} title (HashTable {_}) 0)) - (set 'title {})) - (replace {\*} url (HashTable {*}) 0) - (replace {_} url (HashTable {_}) 0) - (string - {} 
-           alt-text {}) - ) - 0 - ) - ; empty ones are possible - (set '$1 {}) - (replace {!\[(.*?)\]\([ \t]*\)} - txt - (string {} $1 {}) - 0))) - -(define (make-anchor link-text id-ref ) -; Link defs are in the form: ^[id]: url "optional title" -; stored in link db list as (id (url title)) -; params are text to be linked and the id of the link in the db -; eg bar 1 for [bar][1] - - (let ((title {}) - (id id-ref) - (url nil)) - (if link-text - (begin - (replace {"} link-text {"} 0) - (replace {\n} link-text { } 0) - (replace {[ ]?\n} link-text { } 0))) - (if (null? id ) (set 'id (lower-case link-text))) - (if (not (nil? (lookup id *link-database*))) - (begin - (set 'url (first (lookup id *link-database*))) - (replace {\*} url (HashTable {*}) 0) - (replace {_} url (HashTable {_}) 0) - (if (set 'title (last (lookup id *link-database*))) - (begin - (replace {"} title {"} 0) - (replace {\*} title (HashTable {*}) 0) - (replace {_} title (HashTable {_}) 0)) - (set 'title {}))) - (set 'url nil)) - (if url - (string {} link-text {}) - (string {[} link-text {][} id-ref {]})))) - -(define (anchors txt) - (letn ((nested-brackets {(?>[^\[\]]+)*}) - (ref-link-regex (string {(\[(} nested-brackets {)\][ ]?(?:\n[ ]*)?\[(.*?)\])})) - (inline-regex {(\[(.*?)\]\([ ]*?[ ]*((['"])(.*?)\5[ \t]*)?\))}) - (link-text {}) - (url {}) - (title {})) - ; reference-style links: [link text] [id] - (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {} '$6 {}) ; i still don't think I should have to do this... - - ; what about this regex instead? - (set 'ref-link-regex {(\[(.*?)\][ ]?\[(.*?)\])}) - - (replace ref-link-regex txt (make-anchor $2 $3) 8) ; $2 is link text, $3 is id - ; inline links: [link text](url "optional title") - (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {} '$6 {}) - (replace - inline-regex - txt - (begin - (set 'link-text $2) - (set 'url $3) - (set 'title $6) - (if link-text (replace {"} link-text {"} 0)) - (if title - (begin - (replace {"} title {"} 0) - (replace {\*} title (HashTable {*}) 0) - (replace {_} title (HashTable {_}) 0)) - (set 'title {})) - (replace {\*} url (HashTable {*}) 0) - (replace {_} url (HashTable {_}) 0) - (replace {^<(.*)>$} url $1 0) - (string - {} link-text {} - )) - 8 - ) ; replace - ) txt) - -(define (auto-links txt) - (replace - [text]<((https?|ftp):[^'">\s]+)>[/text] - txt - (string {} $1 {}) - 0 - ) - ; to-do: email ... -) - -(define (amps-and-angles txt) -; Smart processing for ampersands and angle brackets - (replace - [text]&(?!\#?[xX]?(?:[0-9a-fA-F]+|\w+);)[/text] - txt - {&} - 10 - ) - (replace - [text]<(?![a-z/?\$!])[/text] - txt - {<} - 10)) - -(define (emphasis txt) - ; italics/bold: strong first - (replace - [text] (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 [/text] - txt - (string {} $2 {}) - 8 - ) - (replace - [text] (\*|_) (?=\S) (.+?) (?<=\S) \1 [/text] - txt - (string {} $2 {}) - 8 - )) - -(define (line-breaks txt) - ; handles line break markers - (replace " {2,}\n" txt "
    \n" 0)) - -(define (hex-str-to-unicode-char strng) - ; given a five character string, assume it's "U" + 4 hex chars and convert - ; return the character... - (char (int (string "0x" (1 strng)) 0 16))) - -(define (ustring s) - ; any four digit string preceded by U - (replace "U[0-9a-f]{4,}" s (hex-str-to-unicode-char $0) 0)) - -(define (cleanup txt) - ; cleanup the text by normalizing some possible variations - (replace "\r\n|\r" txt "\n" 0) ; standardize line ends - (push "\n\n" txt -1) ; end with two returns - (set 'txt (detab txt)) ; convert tabs to spaces - - ; convert inline Unicode: - (set 'txt (ustring txt)) - (replace "\n[ \t]+\n" txt "\n\n" 0) ; lines with only spaces and tabs - ) - -(define (protect txt) - ; protect or "hash html blocks" - (letn ((nested-block-regex [text](^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b(.*\n)*?[ \t]*(?=\n+|\Z))[/text]) - (liberal-tag-regex [text](^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b(.*\n)*?.*[ \t]*(?=\n+|\Z))[/text]) - (hr-regex [text](?:(?<=\n\n)|\A\n?)([ ]{0,3}<(hr)\b([^<>])*?/?>[ \t]*(?=\n{2,}|\Z))[/text]) - (html-comment-regex [text](?:(?<=\n\n)|\A\n?)([ ]{0,3}(?s:)[ \t]*(?=\n{2,}|\Z))[/text]) - (results '()) - (chunk-count (length (set 'chunks (parse txt "\n\n")))) - (chunk-size 500)) - - ; due to a limitation in PCRE, long sections have to be divided up otherwise we'll crash - ; so divide up long texts into chunks, then do the regex on each chunk - ; not an ideal solution, but it works ok :( - - (for (i 0 chunk-count chunk-size) - ; do a chunk - (set 'text-chunk (join (i (- (min chunk-count (- (+ i chunk-size) 1)) i) chunks) "\n\n")) - (dolist (rgx (list nested-block-regex liberal-tag-regex hr-regex html-comment-regex)) - (replace - rgx - text-chunk - (begin - (set 'key (Hash:hash $1)) - (push (list key $1 ) *hashed-html-blocks* -1) - (string "\n\n" key "\n\n")) - 2)) - ; save this partial result - (push text-chunk results -1) - ) ; for - ; return string result - (join results "\n\n"))) - -(define (unescape-special-chars t) - ; Swap back in all the special characters we've hidden. - (dolist (pair (HashTable)) - (replace (last pair) t (first pair) 10)) t) - -(define (strip-link-definitions txt) - ; strip link definitions from the text and store them - ; Link defs are in the form: ^[id]: url "optional title" - ; stored in link db list as (id (url title)) - (let ((link-db '()) - (url {}) - (id {}) - (title {})) - (replace - [text]^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(?<=\s)["(](.+?)[")][ \t]*)?(?:\n+|\Z)[/text] - txt - (begin - (set 'id (lower-case $1) 'url (amps-and-angles $2) 'title $3) - (if title (replace {"} title {"} 0)) - (push (list id (list url title)) link-db) - (set '$3 {}) ; necessary? - (string {}) ; remove from text - ) - 10) - (set '*link-database* link-db) - txt)) - -(define (horizontal-rules txt) - (replace - [text]^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$[/text] - txt - "\n
    " - 14) - (replace - [text]^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$[/text] - txt - "\n
    " - 14) - (replace - [text]^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$[/text] - txt - "\n
    " - 14)) - -(define (headers txt) - ; setext headers - (let ((level 1)) - (replace - [text]^(.+)[ \t]*\n=+[ \t]*\n+[/text] - txt - (string "

    " (span-transforms $1) "

    \n\n") - 2) - - (replace - [text]^(.+)[ \t]*\n-+[ \t]*\n+[/text] - txt - (string "

    " (span-transforms $1) "

    \n\n") - 2) - ; atx headers - (replace - [text]^(\#{1,6})\s*(.+?)[ ]*\#*(\n+)[/text] - txt - (begin - (set 'level (length $1)) - (string "" (span-transforms $2) "\n\n") - ) - 2))) - -(define (lists txt) - (letn ((marker-ul {[*+-]}) - (marker-ol {\d+[.]}) - (marker-any (string {(?:} marker-ul {|} marker-ol {)})) - (whole-list-regex (string [text](([ ]{0,3}([/text] marker-any [text])[ \t]+)(?s:.+?)(\z|\n{2,}(?=\S)(?![ \t]*[/text] marker-any [text][ \t]+)))[/text])) - (my-list {}) - (list-type {}) - (my-result {})) - (replace - (if (> *list-level* 0) - (string {^} whole-list-regex) - (string {(?:(?<=\n\n)|\A\n?)} whole-list-regex)) - txt - (begin - (set 'my-list $1) - (if (find $3 marker-ul) - (set 'list-type "ul" 'marker-type marker-ul) - (set 'list-type "ol" 'marker-type marker-ol)) - (replace [text]\n{2,}[/text] my-list "\n\n\n" 0) - (set 'my-result (process-list-items my-list marker-any)) - (replace {\s+$} my-result {} 0) - (string {<} list-type {>} "\n" my-result "\n" {} "\n")) - 10 ; must be multiline - ))) - -(define (process-list-items list-text marker-any) - (let ((list-regex (string [text](\n)?(^[ \t]*)([/text] marker-any [text])[ \t]+((?s:.+?)(\n{1,2}))(?=\n*(\z|\2([/text] marker-any [text])[ \t]+))[/text])) - (item {}) - (leading-line {}) - (leading-space {}) - (result {})) - (inc *list-level*) - (replace [text]\n{2,}\z[/text] list-text "\n" 0) - (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {}) - (replace - list-regex - list-text - (begin - (set 'item $4) - (set 'leading-line $1) - (set 'leading-space $2) - (if (or (not (empty? leading-line)) (ends-with item "\n{2,}" 0)) - (set 'item (block-transforms (outdent item))) - ; recurse for sub lists - (begin - (set 'item (lists (outdent item))) - (set 'item (span-transforms (trim item "\n"))) - )) - (string {
  • } item {
  • } "\n")) - 10) - (dec *list-level*) - list-text)) - -(define (code-blocks txt) - (let ((code-block {}) - (token-list '())) - (replace - [text](?:\n\n|\A)((?:(?:[ ]{4}|\t).*\n+)+)((?=^[ ]{0,3}\S)|\Z)[/text] - txt - (begin - (set 'code-block $1) - ; format if Nestor module is loaded and it's not marked as plain - (if (and (not (starts-with code-block " ;plain\n")) (context? Nestor)) - ; format newlisp - (begin - ; remove flag if present - (replace "[ ]{4};newlisp\n" code-block {} 0) - (set 'code-block (protect (Nestor:nlx-to-html (Nestor:my-read (trim (detab (outdent code-block)) "\n"))))) - code-block) - ; don't format - (begin - ; trim leading and trailing newlines - (replace "[ ]{4};plain\n" code-block {} 0) - (set 'code-block (trim (detab (encode-code (outdent code-block))) "\n")) - (set '$1 {}) - (set 'code-block (string "\n\n
    " code-block "\n
    \n\n"))))) - 10))) - -(define (block-quotes txt) - (let ((block-quote {})) - (replace - [text]((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)[/text] - txt - (begin - (set 'block-quote $1) - (replace {^[ ]*>[ ]?} block-quote {} 2) - (replace {^[ ]+$} block-quote {} 2) - (set 'block-quote (block-transforms block-quote)) ; recurse - ; remove leading spaces - (replace - {(\s*
    .+?
    )} - block-quote - (trim $1) - 2) - (string "
    \n" block-quote "\n
    \n\n")) - 2))) - -(define (outdent s) - (replace [text]^(\t|[ ]{1,4})[/text] s {} 2)) - -(define (detab s) - (replace [text](.*?)\t[/text] - s - (string $1 (dup { } (- 4 (% (length $1) 4)))) - 2)) - -(define (form-paragraphs txt) - (let ((grafs '()) - (original nil)) - (set 'txt (trim txt "\n")) ; strip blank lines before and after - (set 'grafs (parse txt "\n{2,}" 0)) ; split - (dolist (p grafs) - (if (set 'original (lookup p *hashed-html-blocks*)) - ; html blocks - (setf (grafs $idx) original) - ; wrap

    tags round everything else - (setf (grafs $idx) (string {

    } (replace {^[ ]*} (span-transforms p) {} (+ 4 8 16)) {

    })))) - (join grafs "\n\n"))) - -[text] -; three command line arguments: let's hope last one is a file -(when (= 3 (length (main-args))) - (println (markdown (read-file (main-args 2)))) - (exit)) - -; hack for command-line and module loading -(set 'level (sys-info 3)) - -; if level is 2, then we're probably invoking markdown.lsp directly -; if level is > 3, then we're probably loading it into another script... - -(when (= level 2) - ; running on command line, read STDIN and execute: - (while (read-line) - (push (current-line) *stdin* -1)) - (println (markdown (join *stdin* "\n"))) - (exit)) -[/text] - -;; version 2011-09-16 16:31:29 -;; Changed to different hash routine. Profiling shows that hashing takes 40% of the execution time. -;; Unfortunately this new version is only very slightly faster. -;; Command-line arguments hack in previous version doesn't work. -;; -;; version 2011-08-18 15:04:40 -;; various fixes, and added hack for running this from the command-line: -;; echo "hi there" | newlisp markdown.lsp -;; echo "hello world" | markdown.lsp -;; cat file.text | newlisp markdown.lsp -;; -;; version 2010-11-14 17:34:52 -;; some problems in ustring. Probably remove it one day, as it's non standard... -;; -;; version 2010-10-14 18:41:38 -;; added code to work round PCRE crash in (protect ... -;; -;; version date 2010-07-10 22:20:25 -;; modified call to 'read' since lutz has changed it -;; -;; version date 2009-11-16 22:10:10 -;; fixed bug in tokenize.html -;; -;; version date 2008-10-08 18:44:46 -;; changed nth-set to setf to be version-10 ready. -;; This means that now this script will NOT work with -;; earlier versions of newLISP!!!!!!!!!!! -;; requires Nestor if you want source code colouring... -;; -;; version date 2008-08-08 16:54:56 -;; changed (unless to (if (not ... :( -;; -;; version date 2008-07-20 14:!2:29 -;; added hex-str-to-unicode-char ustring -;; -;; version date 2008-03-07 15:36:09 -;; fixed load error -;; -;; version date 2007-11-17 16:20:57 -;; added syntax colouring module -;; -;; version date 2007-11-14 09:19:42 -;; removed reliance on dostring for compatibility with 9.1 - - -; eof \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/matlab_noreturn b/third_party/pygments/tests/examplefiles/matlab_noreturn deleted file mode 100644 index 780278276..000000000 --- a/third_party/pygments/tests/examplefiles/matlab_noreturn +++ /dev/null @@ -1,3 +0,0 @@ - function myfunc(s) - a = 1; - end diff --git a/third_party/pygments/tests/examplefiles/matlab_sample b/third_party/pygments/tests/examplefiles/matlab_sample deleted file mode 100644 index bb00b5173..000000000 --- a/third_party/pygments/tests/examplefiles/matlab_sample +++ /dev/null @@ -1,34 +0,0 @@ -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/third_party/pygments/tests/examplefiles/matlabsession_sample.txt b/third_party/pygments/tests/examplefiles/matlabsession_sample.txt deleted file mode 100644 index 1b33c9c4c..000000000 --- a/third_party/pygments/tests/examplefiles/matlabsession_sample.txt +++ /dev/null @@ -1,37 +0,0 @@ ->> ->> ->> a = 'okay' - -a = - -okay - ->> x = rand(3) % a matrix - -x = - - 0.8147 0.9134 0.2785 - 0.9058 0.6324 0.5469 - 0.1270 0.0975 0.9575 - ->> 1/0 - -ans = - - Inf - ->> foo -??? Undefined function or variable 'foo'. - ->> ->> ->> {cos(2*pi), 'testing'} - -ans = - - [1] 'testing' - ->> ->> ->> - diff --git a/third_party/pygments/tests/examplefiles/metagrammar.treetop b/third_party/pygments/tests/examplefiles/metagrammar.treetop deleted file mode 100644 index acd6af630..000000000 --- a/third_party/pygments/tests/examplefiles/metagrammar.treetop +++ /dev/null @@ -1,455 +0,0 @@ -module Treetop - module Compiler - grammar Metagrammar - rule treetop_file - requires:(space? require_statement)* prefix:space? module_or_grammar suffix:space? { - def compile - requires.text_value + prefix.text_value + module_or_grammar.compile + suffix.text_value - end - } - end - - rule require_statement - prefix:space? "require" [ \t]+ [^\n\r]+ [\n\r] - end - - rule module_or_grammar - module_declaration / grammar - end - - rule module_declaration - prefix:('module' space name:([A-Z] alphanumeric_char* ('::' [A-Z] alphanumeric_char*)*) space) module_contents:(module_declaration / grammar) suffix:(space 'end') { - def compile - prefix.text_value + module_contents.compile + suffix.text_value - end - - def parser_name - prefix.name.text_value+'::'+module_contents.parser_name - end - } - end - - rule grammar - 'grammar' space grammar_name space ('do' space)? declaration_sequence space? 'end' - end - - rule grammar_name - ([A-Z] alphanumeric_char*) - end - - rule declaration_sequence - head:declaration tail:(space declaration)* { - def declarations - [head] + tail - end - - def tail - super.elements.map { |elt| elt.declaration } - end - } - / - '' { - def compile(builder) - end - } - end - - rule declaration - parsing_rule / include_declaration - end - - rule include_declaration - 'include' space [A-Z] (alphanumeric_char / '::')* { - def compile(builder) - builder << text_value - end - } - end - - rule parsing_rule - 'rule' space nonterminal space ('do' space)? parsing_expression space 'end' - end - - rule parsing_expression - choice / sequence / primary - end - - rule choice - head:alternative tail:(space? '/' space? alternative)+ { - def alternatives - [head] + tail - end - - def tail - super.elements.map {|elt| elt.alternative} - end - - def inline_modules - (alternatives.map {|alt| alt.inline_modules }).flatten - end - } - end - - rule sequence - head:labeled_sequence_primary tail:(space labeled_sequence_primary)+ node_class_declarations { - def sequence_elements - [head] + tail - end - - def tail - super.elements.map {|elt| elt.labeled_sequence_primary } - end - - def inline_modules - (sequence_elements.map {|elt| elt.inline_modules}).flatten + - [sequence_element_accessor_module] + - node_class_declarations.inline_modules - end - - def inline_module_name - node_class_declarations.inline_module_name - end - } - end - - rule alternative - sequence / primary - end - - rule primary - prefix atomic { - def compile(address, builder, parent_expression=nil) - prefix.compile(address, builder, self) - end - - def prefixed_expression - atomic - end - - def inline_modules - atomic.inline_modules - end - - def inline_module_name - nil - end - } - / - prefix space? predicate_block { - def compile(address, builder, parent_expression=nil) - prefix.compile(address, builder, self) - end - def prefixed_expression - predicate_block - end - def inline_modules - [] - end - } - / - atomic suffix node_class_declarations { - def compile(address, builder, parent_expression=nil) - suffix.compile(address, builder, self) - end - - def optional_expression - atomic - end - - def node_class_name - node_class_declarations.node_class_name - end - - def inline_modules - atomic.inline_modules + node_class_declarations.inline_modules - end - - def inline_module_name - node_class_declarations.inline_module_name - end - } - / - atomic node_class_declarations { - def compile(address, builder, parent_expression=nil) - atomic.compile(address, builder, self) - end - - def node_class_name - node_class_declarations.node_class_name - end - - def inline_modules - atomic.inline_modules + node_class_declarations.inline_modules - end - - def inline_module_name - node_class_declarations.inline_module_name - end - } - end - - rule labeled_sequence_primary - label sequence_primary { - def compile(lexical_address, builder) - sequence_primary.compile(lexical_address, builder) - end - - def inline_modules - sequence_primary.inline_modules - end - - def label_name - if label.name - label.name - elsif sequence_primary.instance_of?(Nonterminal) - sequence_primary.text_value - else - nil - end - end - } - end - - rule label - (alpha_char alphanumeric_char*) ':' { - def name - elements[0].text_value - end - } - / - '' { - def name - nil - end - } - end - - rule sequence_primary - prefix atomic { - def compile(lexical_address, builder) - prefix.compile(lexical_address, builder, self) - end - - def prefixed_expression - elements[1] - end - - def inline_modules - atomic.inline_modules - end - - def inline_module_name - nil - end - } - / - prefix space? predicate_block { - def compile(address, builder, parent_expression=nil) - prefix.compile(address, builder, self) - end - def prefixed_expression - predicate_block - end - def inline_modules - [] - end - } - / - atomic suffix { - def compile(lexical_address, builder) - suffix.compile(lexical_address, builder, self) - end - - def node_class_name - nil - end - - def inline_modules - atomic.inline_modules - end - - def inline_module_name - nil - end - } - / - atomic - end - - rule suffix - repetition_suffix / optional_suffix - end - - rule optional_suffix - '?' - end - - rule node_class_declarations - node_class_expression trailing_inline_module { - def node_class_name - node_class_expression.node_class_name - end - - def inline_modules - trailing_inline_module.inline_modules - end - - def inline_module - trailing_inline_module.inline_module - end - - def inline_module_name - inline_module.module_name if inline_module - end - } - end - - rule repetition_suffix - '+' / '*' / occurrence_range - end - - rule occurrence_range - space? min:([0-9])* '..' max:([0-9])* - end - - rule prefix - '&' / '!' / '~' - end - - rule atomic - terminal - / - nonterminal - / - parenthesized_expression - end - - rule parenthesized_expression - '(' space? parsing_expression space? ')' { - def inline_modules - parsing_expression.inline_modules - end - } - end - - rule nonterminal - !keyword_inside_grammar (alpha_char alphanumeric_char*) - end - - rule terminal - quoted_string / character_class / anything_symbol - end - - rule quoted_string - (single_quoted_string / double_quoted_string) { - def string - super.text_value - end - } - end - - rule double_quoted_string - '"' string:(!'"' ("\\\\" / '\"' / .))* '"' - end - - rule single_quoted_string - "'" string:(!"'" ("\\\\" / "\\'" / .))* "'" - end - - rule character_class - '[' characters:(!']' ('\\' . / bracket_expression / !'\\' .))+ ']' { - def characters - super.text_value - end - } - end - - rule bracket_expression - '[:' '^'? ( - 'alnum' / 'alpha' / 'blank' / 'cntrl' / 'digit' / 'graph' / 'lower' / - 'print' / 'punct' / 'space' / 'upper' / 'xdigit' / 'word' - ) ':]' - end - - rule anything_symbol - '.' - end - - rule node_class_expression - space '<' (!'>' .)+ '>' { - def node_class_name - elements[2].text_value - end - } - / - '' { - def node_class_name - nil - end - } - end - - rule trailing_inline_module - space inline_module { - def inline_modules - [inline_module] - end - - def inline_module_name - inline_module.module_name - end - } - / - '' { - def inline_modules - [] - end - - def inline_module - nil - end - - def inline_module_name - nil - end - } - end - - rule predicate_block - '' inline_module - end - - rule inline_module - '{' (inline_module / ![{}] .)* '}' - end - - rule keyword_inside_grammar - ('rule' / 'end') !non_space_char - end - - rule non_space_char - !space . - end - - rule alpha_char - [A-Za-z_] - end - - rule alphanumeric_char - alpha_char / [0-9] - end - - rule space - (white / comment_to_eol)+ - end - - rule comment_to_eol - '#' (!"\n" .)* - end - - rule white - [ \t\n\r] - end - end - end -end diff --git a/third_party/pygments/tests/examplefiles/minehunt.qml b/third_party/pygments/tests/examplefiles/minehunt.qml deleted file mode 100644 index 548e7e89c..000000000 --- a/third_party/pygments/tests/examplefiles/minehunt.qml +++ /dev/null @@ -1,112 +0,0 @@ - /**************************************************************************** - ** - ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). - ** All rights reserved. - ** Contact: Nokia Corporation (qt-info@nokia.com) - ** - ** This file is part of the QtDeclarative module of the Qt Toolkit. - ** - ** $QT_BEGIN_LICENSE:LGPL$ - ** GNU Lesser General Public License Usage - ** This file may be used under the terms of the GNU Lesser General Public - ** License version 2.1 as published by the Free Software Foundation and - ** appearing in the file LICENSE.LGPL included in the packaging of this - ** file. Please review the following information to ensure the GNU Lesser - ** General Public License version 2.1 requirements will be met: - ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. - ** - ** In addition, as a special exception, Nokia gives you certain additional - ** rights. These rights are described in the Nokia Qt LGPL Exception - ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. - ** - ** GNU General Public License Usage - ** Alternatively, this file may be used under the terms of the GNU General - ** Public License version 3.0 as published by the Free Software Foundation - ** and appearing in the file LICENSE.GPL included in the packaging of this - ** file. Please review the following information to ensure the GNU General - ** Public License version 3.0 requirements will be met: - ** http://www.gnu.org/copyleft/gpl.html. - ** - ** Other Usage - ** Alternatively, this file may be used in accordance with the terms and - ** conditions contained in a signed written agreement between you and Nokia. - ** - ** - ** - ** - ** - ** $QT_END_LICENSE$ - ** - ****************************************************************************/ - - import QtQuick 1.0 - import "MinehuntCore" 1.0 - - Item { - id: field - property int clickx: 0 - property int clicky: 0 - - width: 450; height: 450 - - Image { source: "MinehuntCore/pics/background.png"; anchors.fill: parent; fillMode: Image.Tile } - - Grid { - anchors.horizontalCenter: parent.horizontalCenter - columns: 9; spacing: 1 - - Repeater { - id: repeater - model: tiles - delegate: Tile {} - } - } - - Row { - id: gamedata - x: 20; spacing: 20 - anchors.bottom: field.bottom; anchors.bottomMargin: 15 - - Image { - source: "MinehuntCore/pics/quit.png" - scale: quitMouse.pressed ? 0.8 : 1.0 - smooth: quitMouse.pressed - y: 10 - MouseArea { - id: quitMouse - anchors.fill: parent - anchors.margins: -20 - onClicked: Qt.quit() - } - } - Column { - spacing: 2 - Image { source: "MinehuntCore/pics/bomb-color.png" } - Text { anchors.horizontalCenter: parent.horizontalCenter; color: "white"; text: numMines } - } - - Column { - spacing: 2 - Image { source: "MinehuntCore/pics/flag-color.png" } - Text { anchors.horizontalCenter: parent.horizontalCenter; color: "white"; text: numFlags } - } - } - - Image { - anchors.bottom: field.bottom; anchors.bottomMargin: 15 - anchors.right: field.right; anchors.rightMargin: 20 - source: isPlaying ? 'MinehuntCore/pics/face-smile.png' : - hasWon ? 'MinehuntCore/pics/face-smile-big.png': 'MinehuntCore/pics/face-sad.png' - - MouseArea { anchors.fill: parent; onPressed: reset() } - } - Text { - anchors.centerIn: parent; width: parent.width - 20 - horizontalAlignment: Text.AlignHCenter - wrapMode: Text.WordWrap - text: "Minehunt demo has to be compiled to run.\n\nPlease see README." - color: "white"; font.bold: true; font.pixelSize: 14 - visible: tiles == undefined - } - - } diff --git a/third_party/pygments/tests/examplefiles/minimal.ns2 b/third_party/pygments/tests/examplefiles/minimal.ns2 deleted file mode 100644 index e8a92693a..000000000 --- a/third_party/pygments/tests/examplefiles/minimal.ns2 +++ /dev/null @@ -1,4 +0,0 @@ -class A = ( | a = self m. | ) ( - m = (^a isNil ifTrue: [0] ifFalse: [1]) -) -class B = C ( | b0 = 0. b1 = b0 + 1. | ) () diff --git a/third_party/pygments/tests/examplefiles/modula2_test_cases.def b/third_party/pygments/tests/examplefiles/modula2_test_cases.def deleted file mode 100644 index ce86a55b8..000000000 --- a/third_party/pygments/tests/examplefiles/modula2_test_cases.def +++ /dev/null @@ -1,354 +0,0 @@ -(* Test Cases for Modula-2 Lexer *) - -(* Notes: - (1) Without dialect option nor embedded dialect tag, the lexer operates in - fallback mode, recognising the *combined* literals, punctuation symbols - and operators of all supported dialects, and the *combined* reserved - words and builtins of PIM Modula-2, ISO Modula-2 and Modula-2 R10. - (1) If multiple embedded dialect tags are present, the lexer will use the - first valid tag and ignore any subsequent dialect tags in the file. - (2) An embedded dialect tag overrides any command line dialect option. *) - - -(* Testing command line dialect option *) - -(* for PIM Modula-2 : pygmentize -O full,dialect=m2pim ... - for ISO Modula-2 : pygmentize -O full,dialect=m2iso ... - for Modula-2 R10 : pygmentize -O full,dialect=m2r10 ... - for Objective Modula-2 : pygmentize -O full,dialect=objm2 ... *) - -(* for Aglet extensions : pygmentize -O full,dialect=m2iso+aglet ... - for GNU extensions : pygmentize -O full,dialect=m2pim+gm2 ... - for p1 extensions : pygmentize -O full,dialect=m2iso+p1 ... - for XDS extensions : pygmentize -O full,dialect=m2iso+xds ... - - -(* Testing embedded dialect tags *) - -(* !m2pim*) (* <-- remove whitespace before ! for PIM Modula-2 *) -(* !m2iso*) (* <-- remove whitespace before ! for ISO Modula-2 *) -(* !m2r10*) (* <-- remove whitespace before ! for Modula-2 R10 *) -(* !objm2*) (* <-- remove whitespace before ! for Objective Modula-2 *) - -(* !m2iso+aglet*) (* <-- remove whitespace before ! for Aglet extensions *) -(* !m2pim+gm2*) (* <-- remove whitespace before ! for GNU extensions *) -(* !m2iso+p1*) (* <-- remove whitespace before ! for p1 extensions *) -(* !m2iso+xds*) (* <-- remove whitespace before ! for XDS extensions *) - - -(* Dialect Indicating Names *) - -(* recognised names should be highlighted *) - -QUALIFIED (* PIM and ISO *) - -PACKEDSET (* ISO only *) - -ARGLIST (* M2 R10 and ObjM2 *) - -BYCOPY (* ObjM2 only *) - -BITSET8 (* Aglet, GNU and M2 R10 *) - -__FILE__ (* GNU only *) - -BCD (* p1 and M2 R10 *) - -SEQ (* XDS only *) - - -(* Literal Tests *) - -(* recognised literals should be rendered as one unit - unrecognised literals should be rendered as error *) - -ch := 'a'; ch := "a"; (* all dialects *) -ch := 0u20; unich := 0u2038 (* M2 R10 *) - -s := 'The cat said "meow!".'; -s := "It is eight O'clock."; - - -n := 123; n = 1000000; (* all dialects *) -n := 123; n = 1'000'000; (* M2 R10 *) - -n := 0b0110; n:= 0b0110'1100'0111; (* M2 R10 *) -n := 0xFF00; n:= 0xDEAD'BEEF'0F00; (* M2 R10 *) - -r := 1.23; r := 1000000.000001; (* all dialects *) -r := 1.23; r := 1'000'000.000'001; (* M2 R10 *) - -r := 1.234E6; r:= 1.234E-6; r := 1.234567E1000; (* PIM + ISO *) -r := 1.234e6; r:= 1.234e-6; r := 1.234'567e1'000; (* M2 R10 *) - -ch := 0377C; n := 0377B; n := 07FF0H; (* ISO + PIM *) - - -(* Non-Alphabetic Operator Tests *) - -(* supported operators should be rendered as one unit - unsupported operators should be rendered as errors *) - -a := b + c - d * e / f; (* all dialects *) - -SetDiff := A \ B; (* M2 R10 *) - -dotProduct := v1 *. v2; catArray := array1 +> array2; (* M2 R10 *) - -bool := a = b; bool := a > b; bool := a < b; -bool := a # b; bool := a >= b; bool := a <= b; - -bool := a <> b; (* PIM + ISO *) - -bool := a == b; (* M2 R10 *) - -(*&*) IF a & b THEN ... END; (* PIM + ISO *) - -(*~*) IF ~ b THEN ... END; (* PIM + ISO *) - -(*::*) int := real :: INTEGER; (* M2 R10 *) - -(*++*) FOR i++ IN range DO ... END; (* M2 R10 *) -(*--*) FOR i-- IN range DO ... END; (* M2 R10 *) - -(*^*) next := this^.next; (* all dialects *) -(*@*) next := this@.next; (* ISO *) - -(*`*) str := `NSString alloc init; (* ObjM2 *) - - -(* Punctuation Tests *) - -(* supported punctuation should be rendered as one unit - unsupported punctuation should be rendered as an error *) - -(*.*) Foo.Bar.Baz; (*..*) TYPE Sign = [-1..1] OF INTEGER; - -(*|:*) CASE foo OF | 1 : bar | 2 : bam | 3 : boo END; -(*!:*) CASE foo OF 1 : bar ! 2 : bam ! 3 : boo END; (* ISO *) - -(*[]()*) array[n] := foo(); - -(*{}*) CONST Bar = { 1, 2, 3 }; - -(*?*) TPROPERTIES = isCollection, isIndexed | isRigid?; (* M2 R10 *) - -(*~*) CONST ~ isFoobar = Foo AND Bar; (* M2 R10 *) -(*->*) isFoobar -> PROCEDURE [ABS]; (* M2 R10 *) - -(*<<>>*) GENLIB Foo FROM Template FOR Bar = <> END; (* M2 R10 *) - - -(* Single Line Comment Test *) - -(* should be rendered as comment if supported, as error if unsupported *) - -// This is a single line comment (M2 R10 + ObjM2) - - -(* Pragma Delimiter Tests *) - -(* PIM style pragma should be rendered as pragma in PIM dialects, - as multiline comment in all other dialects. *) - -(*$INLINE*) (* PIM *) - -(* ISO style pragma should be rendered as error in PIM dialects, - as pragma in all other dialects. *) - -<*INLINE*> (* all other dialects *) - - -(* Operator Substitution Test When in Algol mode *) - -IF foo # bar THEN ... END; (* # should be rendered as not equal symbol *) - -IF foo >= bar THEN ... END; (* >= should be rendered as not less symbol *) - -IF foo <= bar THEN ... END; (* <= should be rendered as not greater symbol *) - -IF foo == bar THEN ... END; (* == should be rendered as identity symbol *) - -dotProduct := v1 *. v2; (* *. should be rendered as dot product symbol *) - - -(* Reserved Words and Builtins Test *) - -(* supported reserved words and builtins should be highlighted *) - -(* reserved words common to all dialects *) - -AND ARRAY BEGIN BY CASE CONST DEFINITION DIV DO ELSE ELSIF END EXIT FOR FROM -IF IMPLEMENTATION IMPORT IN LOOP MOD MODULE NOT OF OR POINTER PROCEDURE -RECORD REPEAT RETURN SET THEN TO TYPE UNTIL VAR WHILE - -(* builtins common to all dialects *) - -ABS BOOLEAN CARDINAL CHAR CHR FALSE INTEGER LONGINT LONGREAL -MAX MIN NIL ODD ORD REAL TRUE - -(* pseudo builtins common to all dialects *) - -ADDRESS BYTE WORD ADR - - -(* additional reserved words for PIM *) - -EXPORT QUALIFIED WITH - -(* additional builtins for PIM *) - -BITSET CAP DEC DISPOSE EXCL FLOAT HALT HIGH INC INCL NEW NIL PROC SIZE TRUNC VAL - -(* additional pseudo-builtins for PIM *) - -SYSTEM PROCESS TSIZE NEWPROCESS TRANSFER - - -(* additional reserved words for ISO 10514-1 *) - -EXCEPT EXPORT FINALLY FORWARD PACKEDSET QUALIFIED REM RETRY WITH - -(* additional reserved words for ISO 10514-2 & ISO 10514-3 *) - -ABSTRACT AS CLASS GUARD INHERIT OVERRIDE READONLY REVEAL TRACED UNSAFEGUARDED - -(* additional builtins for ISO 10514-1 *) - -BITSET CAP CMPLX COMPLEX DEC DISPOSE EXCL FLOAT HALT HIGH IM INC INCL INT -INTERRUPTIBLE LENGTH LFLOAT LONGCOMPLEX NEW PROC PROTECTION RE SIZE TRUNC -UNINTERRUBTIBLE VAL - -(* additional builtins for ISO 10514-2 & ISO 10514-3 *) - -CREATE DESTROY EMPTY ISMEMBER SELF - - -(* additional pseudo-builtins for ISO *) - -(* SYSTEM *) -SYSTEM BITSPERLOC LOCSPERBYTE LOCSPERWORD LOC ADDADR SUBADR DIFADR MAKEADR -ADR ROTATE SHIFT CAST TSIZE - -(* COROUTINES *) -COROUTINES ATTACH COROUTINE CURRENT DETACH HANDLER INTERRUPTSOURCE IOTRANSFER -IsATTACHED LISTEN NEWCOROUTINE PROT TRANSFER - -(* EXCEPTIONS *) -EXCEPTIONS AllocateSource CurrentNumber ExceptionNumber ExceptionSource -GetMessage IsCurrentSource IsExceptionalExecution RAISE - -(* TERMINATION *) -TERMINATION IsTerminating HasHalted - -(* M2EXCEPTION *) -M2EXCEPTION M2Exceptions M2Exception IsM2Exception indexException rangeException -caseSelectException invalidLocation functionException wholeValueException -wholeDivException realValueException realDivException complexValueException -complexDivException protException sysException coException exException - - -(* additional reserved words for M2 R10 *) - -ALIAS ARGLIST BLUEPRINT COPY GENLIB INDETERMINATE NEW NONE OPAQUE REFERENTIAL -RELEASE RETAIN - -(* with symbolic assembler language extension *) -ASM REG - -(* additional builtins for M2 R10 *) - -CARDINAL COUNT EMPTY EXISTS INSERT LENGTH LONGCARD OCTET PTR PRED READ READNEW -REMOVE RETRIEVE SORT STORE SUBSET SUCC TLIMIT TMAX TMIN TRUE TSIZE UNICHAR -WRITE WRITEF - -(* additional pseudo-builtins for M2 R10 *) - -(* TPROPERTIES *) -TPROPERTIES PROPERTY LITERAL TPROPERTY TLITERAL TBUILTIN TDYN TREFC TNIL -TBASE TPRECISION TMAXEXP TMINEXP - -(* CONVERSION *) -CONVERSION TSXFSIZE SXF VAL - -(* UNSAFE *) -UNSAFE CAST INTRINSIC AVAIL ADD SUB ADDC SUBC FETCHADD FETCHSUB SHL SHR ASHR -ROTL ROTR ROTLC ROTRC BWNOT BWAND BWOR BWXOR BWNAND BWNOR SETBIT TESTBIT -LSBIT MSBIT CSBITS BAIL HALT TODO FFI ADDR VARGLIST VARGC - -(* ATOMIC *) -ATOMIC INTRINSIC AVAIL SWAP CAS INC DEC BWAND BWNAND BWOR BWXOR - -(* COMPILER *) -COMPILER DEBUG MODNAME PROCNAME LINENUM DEFAULT HASH - -(* ASSEMBLER *) -ASSEMBLER REGISTER SETREG GETREG CODE - - -(* standard library ADT identifiers for M2 R10 *) - -(* rendered as builtins when dialect is set to Modula-2 R10, - this can be turned off by option treat_stdlib_adts_as_builtins=off *) -BCD LONGBCD BITSET SHORTBITSET LONGBITSET LONGLONGBITSET COMPLEX LONGCOMPLEX -SHORTCARD LONGLONGCARD SHORTINT LONGLONGINT POSINT SHORTPOSINT LONGPOSINT -LONGLONGPOSINT BITSET8 BITSET16 BITSET32 BITSET64 BITSET128 BS8 BS16 BS32 -BS64 BS128 CARDINAL8 CARDINAL16 CARDINAL32 CARDINAL64 CARDINAL128 CARD8 -CARD16 CARD32 CARD64 CARD128 INTEGER8 INTEGER16 INTEGER32 INTEGER64 -INTEGER128 INT8 INT16 INT32 INT64 INT128 STRING UNISTRING - - -(* additional reserved words for ObjM2 *) - -(* Note: ObjM2 is a superset of M2 R10 *) - -BYCOPY BYREF CLASS CONTINUE CRITICAL INOUT METHOD ON OPTIONAL OUT PRIVATE -PROTECTED PROTOCOL PUBLIC SUPER TRY - -(* additional builtins for ObjM2 *) - -OBJECT NO YES - - -(* additional builtins for Aglet Extensions to ISO *) - -BITSET8 BITSET16 BITSET32 CARDINAL8 CARDINAL16 CARDINAL32 INTEGER8 INTEGER16 -INTEGER32 - - -(* additional reserved words for GNU Extensions to PIM *) - -ASM __ATTRIBUTE__ __BUILTIN__ __COLUMN__ __DATE__ __FILE__ __FUNCTION__ -__LINE__ __MODULE__ VOLATILE - -(* additional builtins for GNU Extensions to PIM *) - -BITSET8 BITSET16 BITSET32 CARDINAL8 CARDINAL16 CARDINAL32 CARDINAL64 COMPLEX32 -COMPLEX64 COMPLEX96 COMPLEX128 INTEGER8 INTEGER16 INTEGER32 INTEGER64 REAL8 -REAL16 REAL32 REAL96 REAL128 THROW - - -(* additional pseudo-builtins for p1 Extensions to ISO *) - -BCD - - -(* additional reserved words for XDS Extensions to ISO *) - -SEQ - -(* additional builtins for XDS Extensions to ISO *) - -ASH ASSERT DIFFADR_TYPE ENTIER INDEX LEN LONGCARD SHORTCARD SHORTINT - -(* additional pseudo-builtins for XDS Extensions to ISO *) - -(* SYSTEM *) -PROCESS NEWPROCESS BOOL8 BOOL16 BOOL32 CARD8 CARD16 CARD32 INT8 INT16 INT32 -REF MOVE FILL GET PUT CC int unsigned size_t void - -(* COMPILER *) -COMPILER OPTION EQUATION - - -(* end of file *) \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/moin_SyntaxReference.txt b/third_party/pygments/tests/examplefiles/moin_SyntaxReference.txt deleted file mode 100644 index a88fea4c2..000000000 --- a/third_party/pygments/tests/examplefiles/moin_SyntaxReference.txt +++ /dev/null @@ -1,340 +0,0 @@ -## Please edit system and help pages ONLY in the moinmaster wiki! For more -## information, please see MoinMaster:MoinPagesEditorGroup. -##master-page:Unknown-Page -##master-date:Unknown-Date -#acl MoinPagesEditorGroup:read,write,delete,revert All:read -#format wiki -#language en - -This page aims to introduce the most important elements of MoinMoin``'s syntax at a glance, showing first the markup verbatim and then how it is rendered by the wiki engine. Additionally, you'll find links to the relative help pages. Please note that some of the features depend on your configuration. - -= Table of Contents = -{{{ -'''Contents''' (up to the 2nd level) -[[TableOfContents(2)]] -}}} -'''Contents''' (up to the 2nd level) -[[TableOfContents(2)]] - -= Headings = -'''''see:''' HelpOnHeadlines'' -{{{ -= heading 1st level = -== heading 2nd level == -=== heading 3rd level === -==== heading 4th level ==== -===== heading 5th level ===== -}}} -= heading 1st level = -== heading 2nd level == -=== heading 3rd level === -==== heading 4th level ==== -===== heading 5th level ===== - -= Text Formatting = -'''''see:''' HelpOnFormatting'' -{{{ - * ''emphasized (italics)'' - * '''boldface''' - * '''''bold italics''''' - * `monospace` - * {{{source code}}} - * __underline__ - * ,,sub,,script - * ^super^script - * ~-smaller-~ - * ~+larger+~ - * --(strike through)-- -}}} - * ''emphasized (italics)'' - * '''boldface''' - * '''''bold italics''''' - * `monospace` - * {{{source code}}} - * __underline__ - * ,,sub,,script - * ^super^script - * ~-smaller-~ - * ~+larger+~ - * --(strike through)-- - -= Hyperlinks = -'''''see:''' HelpOnLinking'' -== Internal Links == -{{{ - * FrontPage - * ["FrontPage"] - * HelpOnEditing/SubPages - * /SubPage - * ../SiblingPage - * [:FrontPage:named link] - * [#anchorname] - * [#anchorname description] - * [wiki:Self:PageName#anchorname] - * [wiki:Self:PageName#anchorname description] - * attachment:filename.txt -}}} - * FrontPage - * ["FrontPage"] - * HelpOnEditing/SubPages - * /SubPage - * ../SiblingPage - * [:FrontPage:named link] - * [#anchorname] - * [#anchorname description] - * [wiki:Self:PageName#anchorname] - * [wiki:Self:PageName#anchorname description] - * attachment:filename.txt - -== External Links == -{{{ - * http://moinmoin.wikiwikiweb.de/ - * [http://moinmoin.wikiwikiweb.de/] - * [http://moinmoin.wikiwikiweb.de/ MoinMoin Wiki] - * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png] - * http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png - * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png moinmoin.png] - * MeatBall:InterWiki - * wiki:MeatBall/InterWiki - * [wiki:MeatBall/InterWiki] - * [wiki:MeatBall/InterWiki InterWiki page on MeatBall] - * [file://///servername/share/full/path/to/file/filename%20with%20spaces.txt link to file filename with spaces.txt] - * user@example.com -}}} - * http://moinmoin.wikiwikiweb.de/ - * [http://moinmoin.wikiwikiweb.de/] - * [http://moinmoin.wikiwikiweb.de/ MoinMoin Wiki] - * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png] - * http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png - * [http://moinmoin.wikiwikiweb.de/wiki/moinmoin.png moinmoin.png] - * MeatBall:InterWiki - * wiki:MeatBall/InterWiki - * [wiki:MeatBall/InterWiki] - * [wiki:MeatBall/InterWiki InterWiki page on MeatBall] - * [file://///servername/share/full/path/to/file/filename%20with%20spaces.txt link to file filename with spaces.txt] - * user@example.com - -== Avoid or Limit Automatical Linking == -{{{ - * Wiki''''''Name - * Wiki``Name - * !WikiName - * WikiName''''''s - * WikiName``s - * `http://www.example.com` -}}} - * Wiki''''''Name - * Wiki``Name - * !WikiName - * WikiName''''''s - * WikiName``s - * `http://www.example.com` - -= Blockquotes and Indentions = -{{{ - indented text - text indented to the 2nd level -}}} - indented text - text indented to the 2nd level - -= Lists = -'''''see:''' HelpOnLists'' -== Unordered Lists == -{{{ - * item 1 - - * item 2 (preceding white space) - * item 2.1 - * item 2.1.1 - * item 3 - . item 3.1 (bulletless) - . item 4 (bulletless) - * item 4.1 - . item 4.1.1 (bulletless) -}}} - * item 1 - - * item 2 (preceding white space) - * item 2.1 - * item 2.1.1 - * item 3 - . item 3.1 (bulletless) - . item 4 (bulletless) - * item 4.1 - . item 4.1.1 (bulletless) - -== Ordered Lists == -=== with Numbers === -{{{ - 1. item 1 - 1. item 1.1 - 1. item 1.2 - 1. item 2 -}}} - 1. item 1 - 1. item 1.1 - 1. item 1.2 - 1. item 2 - -=== with Roman Numbers === -{{{ - I. item 1 - i. item 1.1 - i. item 1.2 - I. item 2 -}}} - I. item 1 - i. item 1.1 - i. item 1.2 - I. item 2 - -=== with Letters === -{{{ - A. item A - a. item A. a) - a. item A. b) - A. item B -}}} - A. item A - a. item A. a) - a. item A. b) - A. item B - -== Definition Lists == -{{{ - term:: definition - object:: description 1 - :: description 2 - Action Items:: - :: First Item - :: Second Item -}}} - term:: definition - object:: description 1 - :: description 2 - Action Items:: - :: First Item - :: Second Item - -= Horizontal Rules = -'''''see:''' HelpOnRules'' -{{{ ----- ------ ------- -------- --------- ---------- ----------- -}}} ----- ------ ------- -------- --------- ---------- ----------- - -= Tables = -'''''see:''' HelpOnTables'' -== Tables == -{{{ -||'''A'''||'''B'''||'''C'''|| -||1 ||2 ||3 || -}}} -||'''A'''||'''B'''||'''C'''|| -||1 ||2 ||3 || - -== Cell Width == -{{{ -||minimal width ||<99%>maximal width || -}}} -||minimal width ||<99%>maximal width || - -== Spanning Rows and Columns == -{{{ -||<|2> cell spanning 2 rows ||cell in the 2nd column || -||cell in the 2nd column of the 2nd row || -||<-2> cell spanning 2 columns || -||||use empty cells as a shorthand || -}}} -||<|2> cell spanning 2 rows ||cell in the 2nd column || -||cell in the 2nd column of the 2nd row || -||<-2> cell spanning 2 columns || -||||use empty cells as a shorthand || - -== Alignment of Cell Contents == -{{{ -||<^|3> top (combined) ||<:99%> center (combined) || bottom (combined) || -||<)> right || -||<(> left || -}}} -||<^|3> top (combined) ||<:99%> center (combined) || bottom (combined) || -||<)> right || -||<(> left || - -== Coulored Table Cells == -{{{ -||<#0000FF> blue ||<#00FF00> green ||<#FF0000> red || -||<#00FFFF> cyan ||<#FF00FF> magenta ||<#FFFF00> yellow || -}}} -||<#0000FF> blue ||<#00FF00> green ||<#FF0000> red || -||<#00FFFF> cyan ||<#FF00FF> magenta ||<#FFFF00> yellow || - -== HTML-like Options for Tables == -{{{ -||A || like <|2> || -|| like <#00FF00> || -|| like <-2>|| -}}} -||A || like <|2> || -|| like <#00FF00> || -|| like <-2>|| - -= Macros and Variables = -== Macros == -'''''see:''' HelpOnMacros'' - * `[[Anchor(anchorname)]]` inserts a link anchor `anchorname` - * `[[BR]]` inserts a hard line break - * `[[FootNote(Note)]]` inserts a footnote saying `Note` - * `[[Include(HelpOnMacros/Include)]]` inserts the contents of the page `HelpOnMacros/Include` inline - * `[[MailTo(user AT example DOT com)]]` obfuscates the email address `user@example.com` to users not logged in - -== Variables == -'''''see:''' HelpOnVariables'' - * `@``SIG``@` inserts your login name and timestamp of modification - * `@``TIME``@` inserts date and time of modification - -= Smileys and Icons = -'''''see:''' HelpOnSmileys'' -[[ShowSmileys]] - -= Source code = -'''''see:''' HelpOnParsers'' -== Verbatim Display == -{{{ -{ { { -def hello(): - print "Hello World!" -} } } -}}} -/!\ Remove spaces between "`{ { {`" and "`} } }`". -{{{ -def hello(): - print "Hello World!" -}}} - -== Syntax Highlighting == -{{{ -{ { {#!python -def hello(): - print "Hello World!" -} } } -}}} -/!\ Remove spaces between "`{ { {`" and "`} } }`". -{{{#!python -def hello(): - print "Hello World!" -}}} - diff --git a/third_party/pygments/tests/examplefiles/multiline_regexes.rb b/third_party/pygments/tests/examplefiles/multiline_regexes.rb deleted file mode 100644 index 1b1e7612c..000000000 --- a/third_party/pygments/tests/examplefiles/multiline_regexes.rb +++ /dev/null @@ -1,38 +0,0 @@ -/ -this is a -multiline -regex -/ - -this /is a -multiline regex too/ - -foo = /is also -one/ - -also /4 -is one/ - -this(/ -too -/) - -# this not -2 /4 -asfsadf/ - -# this is also not one -0x4d /25 -foo/ - -42 and /this -is also a multiline -regex/ - - -# And here some special string cases -foo = % blah # comment here to ensure whitespace -foo(% blah ) -foo << % blah # stupid but has to work -foo = % blah + % blub # wicked -foo = %q wicked # works too diff --git a/third_party/pygments/tests/examplefiles/nanomsg.intr b/third_party/pygments/tests/examplefiles/nanomsg.intr deleted file mode 100644 index d21f62cc1..000000000 --- a/third_party/pygments/tests/examplefiles/nanomsg.intr +++ /dev/null @@ -1,95 +0,0 @@ -module: nanomsg -synopsis: generated bindings for the nanomsg library -author: Bruce Mitchener, Jr. -copyright: See LICENSE file in this distribution. - -define simple-C-mapped-subtype () - export-map , export-function: identity; -end; - -define interface - #include { - "sp/sp.h", - "sp/fanin.h", - "sp/inproc.h", - "sp/pair.h", - "sp/reqrep.h", - "sp/survey.h", - "sp/fanout.h", - "sp/ipc.h", - "sp/pubsub.h", - "sp/tcp.h" - }, - - exclude: { - "SP_HAUSNUMERO", - "SP_PAIR_ID", - "SP_PUBSUB_ID", - "SP_REQREP_ID", - "SP_FANIN_ID", - "SP_FANOUT_ID", - "SP_SURVEY_ID" - }, - - equate: {"char *" => }, - - rename: { - "sp_recv" => %sp-recv, - "sp_send" => %sp-send, - "sp_setsockopt" => %sp-setsockopt - }; - - function "sp_version", - output-argument: 1, - output-argument: 2, - output-argument: 3; - - function "sp_send", - map-argument: { 2 => }; - - function "sp_recv", - map-argument: { 2 => }; - -end interface; - -// Function for adding the base address of the repeated slots of a -// to an offset and returning the result as a . This is -// necessary for passing contents across the FFI. - -define function buffer-offset - (the-buffer :: , data-offset :: ) - => (result-offset :: ) - u%+(data-offset, - primitive-wrap-machine-word - (primitive-repeated-slot-as-raw - (the-buffer, primitive-repeated-slot-offset(the-buffer)))) -end function; - -define inline function sp-send (socket :: , data :: , flags :: ) => (res :: ) - %sp-send(socket, buffer-offset(data, 0), data.size, flags) -end; - -define inline function sp-recv (socket :: , data :: , flags :: ) => (res :: ) - %sp-recv(socket, buffer-offset(data, 0), data.size, flags); -end; - -define inline method sp-setsockopt (socket :: , level :: , option :: , value :: ) - with-stack-structure (int :: ) - pointer-value(int) := value; - let setsockopt-result = - %sp-setsockopt(socket, level, option, int, size-of()); - if (setsockopt-result < 0) - // Check error! - end; - setsockopt-result - end; -end; - -define inline method sp-setsockopt (socket :: , level :: , option :: , data :: ) - let setsockopt-result = - %sp-setsockopt(socket, level, option, as(, data), data.size); - if (setsockopt-result < 0) - // Check error! - end; - setsockopt-result -end; diff --git a/third_party/pygments/tests/examplefiles/nasm_aoutso.asm b/third_party/pygments/tests/examplefiles/nasm_aoutso.asm deleted file mode 100644 index 9fd9727ed..000000000 --- a/third_party/pygments/tests/examplefiles/nasm_aoutso.asm +++ /dev/null @@ -1,96 +0,0 @@ -; test source file for assembling to NetBSD/FreeBSD a.out shared library -; build with: -; nasm -f aoutb aoutso.asm -; ld -Bshareable -o aoutso.so aoutso.o -; test with: -; cc -o aoutso aouttest.c aoutso.so -; ./aoutso - -; This file should test the following: -; [1] Define and export a global text-section symbol -; [2] Define and export a global data-section symbol -; [3] Define and export a global BSS-section symbol -; [4] Define a non-global text-section symbol -; [5] Define a non-global data-section symbol -; [6] Define a non-global BSS-section symbol -; [7] Define a COMMON symbol -; [8] Define a NASM local label -; [9] Reference a NASM local label -; [10] Import an external symbol -; [11] Make a PC-relative call to an external symbol -; [12] Reference a text-section symbol in the text section -; [13] Reference a data-section symbol in the text section -; [14] Reference a BSS-section symbol in the text section -; [15] Reference a text-section symbol in the data section -; [16] Reference a data-section symbol in the data section -; [17] Reference a BSS-section symbol in the data section - - BITS 32 - EXTERN __GLOBAL_OFFSET_TABLE_ - GLOBAL _lrotate:function ; [1] - GLOBAL _greet:function ; [1] - GLOBAL _asmstr:data _asmstr.end-_asmstr ; [2] - GLOBAL _textptr:data 4 ; [2] - GLOBAL _selfptr:data 4 ; [2] - GLOBAL _integer:data 4 ; [3] - EXTERN _printf ; [10] - COMMON _commvar 4 ; [7] - - SECTION .text - -; prototype: long lrotate(long x, int num); -_lrotate: ; [1] - push ebp - mov ebp,esp - mov eax,[ebp+8] - mov ecx,[ebp+12] -.label rol eax,1 ; [4] [8] - loop .label ; [9] [12] - mov esp,ebp - pop ebp - ret - -; prototype: void greet(void); -_greet push ebx ; we'll use EBX for GOT, so save it - call .getgot -.getgot: pop ebx - add ebx,__GLOBAL_OFFSET_TABLE_ + $$ - .getgot wrt ..gotpc - mov eax,[ebx+_integer wrt ..got] ; [14] - mov eax,[eax] - inc eax - mov [ebx+localint wrt ..gotoff],eax ; [14] - mov eax,[ebx+_commvar wrt ..got] - push dword [eax] - mov eax,[ebx+localptr wrt ..gotoff] ; [13] - push dword [eax] - mov eax,[ebx+_integer wrt ..got] ; [1] [14] - push dword [eax] - lea eax,[ebx+_printfstr wrt ..gotoff] - push eax ; [13] - call _printf wrt ..plt ; [11] - add esp,16 - pop ebx - ret - - SECTION .data - -; a string -_asmstr db 'hello, world', 0 ; [2] -.end - -; a string for Printf -_printfstr db "integer==%d, localint==%d, commvar=%d" - db 10, 0 - -; some pointers -localptr dd localint ; [5] [17] -_textptr dd _greet wrt ..sym ; [15] -_selfptr dd _selfptr wrt ..sym ; [16] - - SECTION .bss - -; an integer -_integer resd 1 ; [3] - -; a local integer -localint resd 1 ; [6] diff --git a/third_party/pygments/tests/examplefiles/nasm_objexe.asm b/third_party/pygments/tests/examplefiles/nasm_objexe.asm deleted file mode 100644 index dcae5eed2..000000000 --- a/third_party/pygments/tests/examplefiles/nasm_objexe.asm +++ /dev/null @@ -1,30 +0,0 @@ -; Demonstration of how to write an entire .EXE format program as a .OBJ -; file to be linked. Tested with the VAL free linker. -; To build: -; nasm -fobj objexe.asm -; val objexe.obj,objexe.exe; -; To test: -; objexe -; (should print `hello, world') - - segment code - -..start: mov ax,data - mov ds,ax - mov ax,stack - mov ss,ax - mov sp,stacktop - - mov dx,hello - mov ah,9 - int 0x21 - - mov ax,0x4c00 - int 0x21 - - segment data -hello: db 'hello, world', 13, 10, '$' - - segment stack stack - resb 64 -stacktop: diff --git a/third_party/pygments/tests/examplefiles/nemerle_sample.n b/third_party/pygments/tests/examplefiles/nemerle_sample.n deleted file mode 100644 index 5236857df..000000000 --- a/third_party/pygments/tests/examplefiles/nemerle_sample.n +++ /dev/null @@ -1,87 +0,0 @@ -using System; - -namespace Demo.Ns -{ - /// sample class - public class ClassSample : Base - { - /* sample multiline comment */ -#region region sample - fieldSample : int; -#endregion - - public virtual someMethod(str : string) : list[double] - { - def x = "simple string"; - def x = $"simple $splice string $(spliceMethod() + 1)"; - def x = <# - recursive <# string #> sample - #>; - def x = $<# - recursive $splice <# string #> sample - ..$(lst; "; "; x => $"x * 2 = $(x * 2)") str - #>; - def x = @"somestring \"; - - def localFunc(arg) - { - arg + 1; - } - - match (localFunc(2)) - { - | 3 => "ok"; - | _ => "fail"; - } - - using (x = SomeObject()) - { - foreach (item in someCollection) - { - def i = try - { - int.Parse(item) - } - catch - { - | _ is FormatException => 0; - } - when (i > 0xff) - unless (i < 555L) - WriteLine(i); - - } - } - protected override overrideSample() : void - {} - - private privateSample() : void - {} - - public abstract abstractSample() : void - {} - } - - } - - module ModuleSample - { - } - - variant RgbColor { - | Red - | Yellow - | Green - | Different { - red : float; - green : float; - blue : float; - } - } - - macro sampleMacro(expr) - syntax ("write", expr) - { - <[ WriteLine($(expr : dyn)) ]> - } -} diff --git a/third_party/pygments/tests/examplefiles/nginx_nginx.conf b/third_party/pygments/tests/examplefiles/nginx_nginx.conf deleted file mode 100644 index 9dcdc8ab2..000000000 --- a/third_party/pygments/tests/examplefiles/nginx_nginx.conf +++ /dev/null @@ -1,118 +0,0 @@ - -#user nobody; -worker_processes 1; - -#error_log logs/error.log; -#error_log logs/error.log notice; -#error_log logs/error.log info; - -#pid logs/nginx.pid; - - -events { - worker_connections 1024; -} - - -http { - include mime.types; - default_type application/octet-stream; - - log_format main '$remote_addr - $remote_user [$time_local] $request ' - '"$status" $body_bytes_sent "$http_referer" ' - '"$http_user_agent" "$http_x_forwarded_for"'; - - #access_log logs/access.log main; - - sendfile on; - #tcp_nopush on; - - #keepalive_timeout 0; - keepalive_timeout 65; - - #gzip on; - - server { - listen 80; - server_name localhost; - - charset koi8-r; - - #access_log logs/host.access.log main; - - location / { - root html; - index index.html index.htm; - } - - #error_page 404 /404.html; - - # redirect server error pages to the static page /50x.html - # - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root html; - } - - # proxy the PHP scripts to Apache listening on 127.0.0.1:80 - # - location ~ \.php$ { - proxy_pass http://127.0.0.1; - } - - # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 - # - location ~ \.php$ { - root html; - fastcgi_pass 127.0.0.1:9000; - fastcgi_index index.php; - fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; - include fastcgi_params; - } - - # deny access to .htaccess files, if Apache's document root - # concurs with nginx's one - # - location ~ /\.ht { - deny all; - } - } - - - # another virtual host using mix of IP-, name-, and port-based configuration - # - server { - listen 8000; - listen somename:8080; - server_name somename alias another.alias; - - location / { - root html; - index index.html index.htm; - } - } - - - # HTTPS server - # - server { - listen 443; - server_name localhost; - - ssl on; - ssl_certificate cert.pem; - ssl_certificate_key cert.key; - - ssl_session_timeout 5m; - - ssl_protocols SSLv2 SSLv3 TLSv1; - ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; - ssl_prefer_server_ciphers on; - - location / { - root html; - index index.html index.htm; - } - } - -} diff --git a/third_party/pygments/tests/examplefiles/noexcept.cpp b/third_party/pygments/tests/examplefiles/noexcept.cpp deleted file mode 100644 index f83e50db4..000000000 --- a/third_party/pygments/tests/examplefiles/noexcept.cpp +++ /dev/null @@ -1,8 +0,0 @@ -void* operator new (std::size_t size); -void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept; -void* operator new (std::size_t size, const std::nothrow_t& nothrow_value)noexcept; -void* operator new (std::size_t size, const std::nothrow_t& nothrow_value); -void* operator new (std::size_t size); -void* operator new (std::size_t size) noexcept; -void* operator new (std::size_t size)noexcept; - diff --git a/third_party/pygments/tests/examplefiles/numbers.c b/third_party/pygments/tests/examplefiles/numbers.c deleted file mode 100644 index 80662eadd..000000000 --- a/third_party/pygments/tests/examplefiles/numbers.c +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Some Number Test - */ - -int i = 24241424; -float f1 = 342423423.24234; -float f2 = 25235235.; -float f3 = .234234; -float f4 = 234243e+34343; -float f5 = 24234e-234; -int o = 0234; -int h = 0x2342; diff --git a/third_party/pygments/tests/examplefiles/objc_example.m b/third_party/pygments/tests/examplefiles/objc_example.m deleted file mode 100644 index f3f85f650..000000000 --- a/third_party/pygments/tests/examplefiles/objc_example.m +++ /dev/null @@ -1,179 +0,0 @@ -// Test various types of includes -#import -# import -#import "stdio.h" -#\ - import \ - "stdlib.h" -# /*line1*/ \ -import /* line 2 */ \ -"stdlib.h" // line 3 - -// Commented out code with preprocessor -#if 0 -#define MY_NUMBER 3 -#endif - - #\ - if 1 -#define TEST_NUMBER 3 -#endif - -// Empty preprocessor -# - -// Class forward declaration -@class MyClass; - -// Empty classes -@interface EmptyClass -@end -@interface EmptyClass2 -{ -} -@end -@interface EmptyClass3 : EmptyClass2 -{ -} -@end - -// Custom class inheriting from built-in -@interface MyClass : NSObject -{ -@public - NSString *myString; - __weak NSString *_weakString; -@protected - NSTextField *_textField; -@private - NSDate *privateDate; -} - -// Various property aatributes -@property(copy, readwrite, nonatomic) NSString *myString; -@property(weak) NSString *weakString; -@property(retain, strong, atomic) IBOutlet NSTextField *textField; - -// Class methods -+ (void)classMethod1:(NSString *)arg; -+ (void)classMethod2:(NSString *) arg; // Test space before arg - -@end - -typedef id B; - -#pragma mark MyMarker - -// MyClass.m -// Class extension to declare private property -@interface MyClass () -@property(retain) NSDate *privateDate; -- (void)hiddenMethod; -@end - -// Special category -@interface MyClass (Special) -@property(retain) NSDate *specialDate; -@end - -@implementation MyClass -@synthesize myString; -@synthesize privateDate; - -- (id)a:(B)b { - /** - * C-style comment - */ - - // Selector keywords/types - SEL someMethod = @selector(hiddenMethod); - - // Boolean types - Boolean b1 = FALSE; - BOOL b2 = NO; - bool b3 = true; - - /** - * Number literals - */ - // Int Literal - NSNumber *n1 = @( 1 ); - // Method call - NSNumber *n2 = @( [b length] ); - // Define variable - NSNumber *n3 = @( TEST_NUMBER ); - // Arthimetic expression - NSNumber *n4 = @(1 + 2); - // From variable - int myInt = 5; - NSNumber *n5 = @(myInt); - // Nest expression - NSNumber *n6 = @(1 + (2 + 6.0)); - // Bool literal - NSNumber *n7 = @NO; - // Bool expression - NSNumber *n8 = @(YES); - // Character - NSNumber *n9 = @'a'; - // int - NSNumber *n10 = @123; - // unsigned - NSNumber *n11 = @1234U; - // long - NSNumber *n12 = @1234567890L; - // float - NSNumber *n13 = @3.14F; - // double - NSNumber *n14 = @3.14F; - - // Array literals - NSArray *arr = @[ @"1", @"2" ]; - arr = @[ @[ @"1", @"2" ], [arr lastObject] ]; - [arr lastObject]; - [@[ @"1", @"2" ] lastObject]; - - // Dictionary literals - NSDictionary *d = @{ @"key": @"value" }; - [[d allKeys] lastObject]; - [[@{ @"key": @"value" } allKeys] lastObject]; - d = @{ @"key": @{ @"key": @"value" } }; - - [self hiddenMethod]; - [b length]; - [privateDate class]; - - NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: - @"1", @"one", @"2", @"two", @"3", @"three", nil]; - - NSString *key; - for (key in dictionary) { - NSLog(@"Number: %@, Word: %@", key, [dictionary valueForKey:key]); - } - - // Blocks - int (^myBlock)(int arg1, int arg2); - NSString *(^myName)(NSString *) = ^(NSString *value) { - return value; - }; - - return nil; -} - -- (void)hiddenMethod { - // Synchronized block - @synchronized(self) { - [myString retain]; - [myString release]; - } -} - -+ (void)classMethod1:(NSString *)arg {} -+ (void)classMethod2:(NSString *) arg -{ - // Autorelease pool block - @autoreleasepool { - NSLog(@"Hello, World!"); - } -} - -@end diff --git a/third_party/pygments/tests/examplefiles/openedge_example b/third_party/pygments/tests/examplefiles/openedge_example deleted file mode 100644 index e8c17e339..000000000 --- a/third_party/pygments/tests/examplefiles/openedge_example +++ /dev/null @@ -1,34 +0,0 @@ -{include.i} -{nested.i {include.i}} - -&SCOPED-DEFINE MY_NAME "Abe" - -DEF VAR i AS INT NO-UNDO. -i = 0xABE + 1337 / (1 * 1.00) - -def var clowercasetest as char no-undo. -DEF VAR vardashtest AS DATETIME-TZ NO-UNDO. - -DEFINE TEMP-TABLE ttNames NO-UNDO - FIELD cName AS CHAR - INDEX IXPK_ttNames IS PRIMARY UNIQUE cName. - -/* One-line comment */ -/* Two-line - Comment */ -/* - Nested - /* - Multiline - /* - Comment - */ - */ -*/ - -CREATE ttNames. -ASSIGN ttNames.cName = {&MY_NAME}. - -FOR EACH ttNames: - MESSAGE "Hello, " + ttNames.cName + '!' VIEW-AS ALERT-BOX. -END. diff --git a/third_party/pygments/tests/examplefiles/pacman.conf b/third_party/pygments/tests/examplefiles/pacman.conf deleted file mode 100644 index 78dbf5e15..000000000 --- a/third_party/pygments/tests/examplefiles/pacman.conf +++ /dev/null @@ -1,49 +0,0 @@ -# -# /etc/pacman.conf -# -# This example file has no relation to `pacman.ijs` -# but is of configuration of Arch Linux's package manager `pacman`. -# - -# -# GENERAL OPTIONS -# -[options] -RootDir = /opt/local/site-private -#DBPath = /var/lib/pacman/ -#CacheDir = /var/cache/pacman/pkg/ -LogFile = /opt/local/site-private/var/log/pacman.log -#GPGDir = /etc/pacman.d/gnupg/ -HoldPkg = pacman -#XferCommand = /usr/bin/curl -C - -f %u > %o -XferCommand = /usr/local/bin/wget --passive-ftp -c -O %o %u -#CleanMethod = KeepInstalled -#UseDelta = 0.7 -Architecture = auto - -#IgnorePkg = -#IgnoreGroup = - -NoUpgrade = etc/passwd etc/group etc/shadow -NoUpgrade = etc/fstab -#NoExtract = - -#UseSyslog -Color -#TotalDownload -CheckSpace -#VerbosePkgLists - -#SigLevel = Never -SigLevel = Required DatabaseOptional -LocalFileSigLevel = Optional -RemoteFileSigLevel = Required - -Server = ftp://ftp9.yaphatchpotchgen.net/$repo/os/$arch - -[fubar32] -Include = /etc/pacman.d/mirrorlist.fubar32 # comment is allowed here - -#[custom] -#SigLevel = Optional TrustAll -#Server = file:///home/custompkgs diff --git a/third_party/pygments/tests/examplefiles/pacman.ijs b/third_party/pygments/tests/examplefiles/pacman.ijs deleted file mode 100644 index f067b6e28..000000000 --- a/third_party/pygments/tests/examplefiles/pacman.ijs +++ /dev/null @@ -1,1107 +0,0 @@ -cocurrent 'jpacman' -coinsert 'j' - -BASELIB=: 'base library' -DATAMASK=: 0 -HWNDP=: '' -ISGUI=: 0 -ONLINE=: 0 -PKGDATA=: 0 7$a: -SECTION=: ,<'All' -SYSNAME=: 'Package Manager' -TIMEOUT=: 60 -WWWREV=: REV=: _1 - -IgnoreIOS=: 0 : 0 -api/jni -data/dbman -data/ddmysql -data/odbc -demos/isigraph -demos/wd -demos/wdplot -games/minesweeper -games/nurikabe -games/pousse -games/solitaire -general/pcall -general/sfl -graphics/d3 -graphics/fvj3 -graphics/gl2 -graphics/gnuplot -graphics/graph -graphics/graphviz -graphics/jturtle -graphics/print -graphics/tgsj -graphics/treemap -graphics/viewmat -gui/monthview -gui/util -ide/qt -math/tabula -media/animate -media/gdiplus -media/image3 -media/ming -media/paint -media/wav -) - -Ignore=: 3 : 0'' -if. IFIOS do. - <;._2 IgnoreIOS -else. - <'ide/ios' -end. -) -3 : 0'' -nc=. '--no-cache' -if. IFUNIX do. - if. UNAME-:'Darwin' do. - HTTPCMD=: 'curl -o %O --stderr %L -f -s -S %U' - elseif. do. - if. 'Android'-:UNAME do. nc=. '' - else. try. nc=. nc #~ 1 e. nc E. shell 'wget --help' catch. nc=. '' end. end. - HTTPCMD=: 'wget ',nc,' -O %O -o %L -t %t %U' - end. -else. - if. fexist exe=. jpath '~tools/ftp/wget.exe' do. exe=. '"',exe,'"' else. exe=. 'wget.exe' end. - try. nc=. nc #~ 1 e. nc E. shell exe,' --help' catch. nc=. '' end. - HTTPCMD=: exe,' ',nc,' -O %O -o %L -t %t -T %T %U' - if. fexist UNZIP=: jpath '~tools/zip/unzip.exe' do. UNZIP=: '"',UNZIP,'" -o -C ' else. UNZIP=: 'unzip.exe -o -C ' end. -end. -) -setfiles=: 3 : 0 -ADDCFG=: jpath '~addons/config/' -makedir ADDCFG -ADDCFGIJS=: ADDCFG,'config.ijs' -JRELEASE=: ({.~i.&'/') 9!:14'' -JRELEASE=: 'j802' -LIBTREE=: readtree'' -if. IFIOS do. - WWW=: '/jal/',JRELEASE,'/' -else. - WWW=: 'http://www.jsoftware.com/jal/',JRELEASE,'/' -end. -LIBVER=: jpath '~system/config/version.txt' -) -destroy=: codestroy -CFGFILES=: <;._2 (0 : 0) -addons.txt -library.txt -release.txt -revision.txt -zips.txt -) -LIBDESC=: 0 : 0 -This is the base library of scripts and labs included in the J system. - -Reinstalling or upgrading this library will overwrite files in the system subdirectory. Restart J afterwards. - -Files outside the system subdirectory, such as profile.ijs, are not changed. -) -cutjal=: ([: (* 4 > +/\) ' ' = ]) <;._1 ] -cutjsp=: ([: (* 5 > +/\) ' ' = ]) <;._1 ] -dquote=: '"'&, @ (,&'"') -fname=: #~ ([: *./\. ~:&'/') -hostcmd=: [: 2!:0 '(' , ] , ' || true)'"_ -ischar=: 2 = 3!:0 -rnd=: [ * [: <. 0.5 + %~ -sep2under=: '/' & (I.@('_' = ])}) -termLF=: , (0 < #) # LF -. {: -todel=: ; @: (DEL&, @ (,&(DEL,' ')) each) -tolist=: }. @ ; @: (LF&,@,@":each) -isjpkgout=: ((4 = {:) *. 2 = #)@$ *. 1 = L. -getintro=: ('...' ,~ -&3@[ {. ])^:(<#) -info=: smoutput -getnames=: 3 : 0 -select. L.y -case. 0 do. - if. +/ BASELIB E. y do. - y=. ({:"1 y -y=. (45&getintro &.> idx{y) idx}y -) -deltree=: 3 : 0 -try. - res=. 0< ferase {."1 dirtree y - *./ res,0 #y do. i.0 5 return. end. -m=. _2 |. (LF,')',LF) E. y -r=. _2 }. each m <;._2 y -x=. r i.&> LF -d=. (x+1) }.each r -r=. x {.each r -r=. 3 {."1 cutjal &> ' ' ,each r -x=. d i.&> LF -c=. x {.each d -d=. (x+1) }.each d -r,.c,.d -) -fixjal2=: 3 : 0 -if. 2 > #y do. i.0 2 return. end. -cutjal &> ' ' ,each <;._2 y -) -fixjsp=: 3 : 0 -if. 2 > #y do. i.0 5 return. end. -m=. _2 |. (LF,')',LF) E. y -r=. _2 }. each m <;._2 y -x=. r i.&> LF -d=. (x+1) }.each r -r=. x {.each r -r=. ' ' ,each r -(cutjsp &> r),.d -) -fixlib=: 3 : 0 -msk=. ( #y do. - i.0 6 return. -end. -fls=. <;._2 y -ndx=. fls i.&> ' ' -siz=. <&> 0 ". (ndx+1) }.&> fls -fls=. ndx {.each fls -zps=. <;._2 &> fls ,each '_' -pfm=. 3 {"1 zps -uname=. tolower UNAME -msk=. (uname -: ({.~ i.&'.')) &> pfm -if. 1 ~: +/msk do. msk=. 1,~ }:0*.msk end. -msk # zps,.fls,.siz -) -fixrev=: 3 : 0 -{. _1 ". :: _1: y -. CRLF -) -fixupd=: 3 : 0 -_1 ". :: _1: y -. CRLF -) -fixver=: 3 : 0 -if. ischar y do. - y=. y -. CRLF - y=. 0 ". ' ' (I. y='.') } y -end. -3 {. y -) -fixvers=: 3 : 0 -s=. $y -y=. ,y -3 {."1 [ 0 ". s $ ' ' (I. y e. './') } y -) -fmtjal=: 3 : 0 -if. 0 = #y do. '' return. end. -r=. (4 {."1 y) ,each "1 ' ',LF2 -r=. <@; "1 r -; r ,each ({:"1 y) ,each <')',LF -) -fmtjal2=: 3 : 0 -if. 0 = #y do. '' return. end. -; (2 {."1 y) ,each "1 ' ',LF -) -fmtdep=: 3 : 0 -}. ; ',' ,each a: -.~ <;._2 y -) -fmtjsp=: 3 : 0 -if. 0 = #y do. '' return. end. -r=. (4 {."1 y) ,each "1 ' ',LF -r=. <@; "1 r -; r ,each ({:"1 y) ,each <')',LF -) -fmtlib=: 3 : 0 -, 'q<.>,q<.>r<0>3.0,r<0>3.0' 8!:2 y -) -fmtver=: 3 : 0 -if. 0=#y do. '' return. end. -if. ischar y do. y return. end. -}. ; '.' ,each ": each y -) -fmtverlib=: 3 : 0 -fmtver y -) -fixzips=: 3 : 0 -if. 2 > #y do. i.0 5 return. end. -fls=. <;._2 y -ndx=. fls i.&> ' ' -siz=. 0 ". (ndx+1) }.&> fls -fls=. ndx {.each fls -zps=. <;._2 &> fls ,each '_' -zps=. zps,.fls,.<&>siz -pfm=. 3 {"1 zps -and=. (1 e. 'android'&E.) &> pfm -lnx=. (1 e. 'linux'&E.) &> pfm -mac=. (1 e. 'darwin'&E.) &> pfm -win=. mac < (1 e. 'win'&E.) &> pfm - -select. UNAME -case. 'Win' do. - zps=. win # zps -case. 'Linux' do. - zps=. lnx # zps -case. 'Android' do. - zps=. and # zps -case. 'Darwin' do. - zps=. mac # zps - zps=. zps /: 3 {"1 zps - zps=. (~: 3 {."1 zps) # zps -end. - -bit=. IF64 pick '64';'32' -pfm=. 3 {"1 zps -exc=. (1 e. bit&E.) &> pfm -zps=. zps \: exc -zps=. (~: 3 {."1 zps) # zps -fnm=. 0 {"1 zps -lnm=. 1 {"1 zps -ver=. 2 {"1 zps -pfm=. 3 {"1 zps -fls=. 4 {"1 zps -siz=. 5 {"1 zps -nms=. fnm ,each '/' ,each lnm -pfm=. (pfm i.&> '.') {.each pfm -ndx=. \: # &> pfm -sort ndx { nms,.pfm,.ver,.fls,.siz -) -fwritenew=: 4 : 0 -if. x -: fread y do. - 0 -else. - x fwrite y -end. -) -platformparent=: 3 : 0 -((< _2 {. y) e. '32';'64') # _2 }. y -) -makedir=: 1!:5 :: 0: @ < -plural=: 4 : 0 -y,(1=x)#'s' -) -sizefmt=: 3 : 0 -select. +/ y >: 1e3 1e4 1e6 1e7 1e9 -case. 0 do. - (": y), ' byte',(y~:1)#'s' -case. 1 do. - (": 0.1 rnd y%1e3),' KB' -case. 2 do. - (": 1 rnd y%1e3),' KB' -case. 3 do. - (": 0.1 rnd y%1e6),' MB' -case. 4 do. - (": 1 rnd y%1e6),' MB' -case. do. - (": 0.1 rnd y%1e9),' GB' -end. -) -shellcmd=: 3 : 0 -if. IFUNIX do. - hostcmd y -else. - spawn_jtask_ y -end. -) -subdir=: 3 : 0 -if. 0=#y do. '' return. end. -a=. 1!:0 y,'*' -if. 0=#a do. '' return. end. -a=. a #~ '-d' -:"1 [ 1 4 {"1 > 4 {"1 a -( '/mnt/sdcard'-:2!:5'EXTERNAL_STORAGE' do. notarcmd=. 1 end. - end. - if. notarcmd do. - require 'tar' - 'file dir'=. y - if. (i.0 0) -: tar 'x';file;dir do. e=. '' end. - else. - e=. shellcmd 'tar ',((IFIOS+:UNAME-:'Android')#(('Darwin'-:UNAME){::'--no-same-owner --no-same-permissions';'-o -p')),' -xzf ',file,' -C ',dir - end. - if. (0~:FHS) *. ('root'-:2!:5'USER') +. (<2!:5'HOME') e. 0;'/var/root';'/root';'';,'/' do. - shellcmd ::0: 'find ',dir,' -type d -exec chmod a+rx {} \+' - shellcmd ::0: 'find ',dir,' -type f -exec chmod a+r {} \+' - end. -else. - dir=. (_2&}. , '/' -.~ _2&{.) dir - e=. shellcmd UNZIP,' ',file,' -d ',dir -end. -e -) -zipext=: 3 : 0 -y, IFUNIX pick '.zip';'.tar.gz' -) -CHECKADDONSDIR=: 0 : 0 -The addons directory does not exist and cannot be created. - -It is set to: XX. - -You can either create the directory manually, or set a new addons directory in your profile script. -) -CHECKASK=: 0 : 0 -Read catalog from the server using Internet connection now? - -Otherwise the local catalog is used offline. -) -CHECKONLINE=: 0 : 0 -An active Internet connection is needed to install packages. - -Continue only if you have an active Internet connection. - -OK to continue? -) -CHECKREADSVR=: 0 : 0 -An active Internet connection is needed to read the server repository catalog. - -Continue only if you have an active Internet connection. - -OK to continue? -) -CHECKSTARTUP=: 0 : 0 -Setup repository using Internet connection now? - -Select No if not connected, to complete setup later. After Setup is done, repository can be used offline with more options in Tools menu and Preferences dialog. -) -checkaccess=: 3 : 0 -if. testaccess'' do. 1 return. end. -msg=. 'Unable to run Package Manager, as you do not have access to the installation folder.' -if. IFWIN do. - msg=. msg,LF2,'To run as Administrator, right-click the J icon, select Run as... and ' - msg=. msg,'then select Adminstrator.' -end. -info msg -0 -) -checkaddonsdir=: 3 : 0 -d=. jpath '~addons' -if. # 1!:0 d do. 1 return. end. -if. 1!:5 :: 0: : 0 do. - ONLINE=: 0 - log 'Using local copy of catalog. See Preferences to change the setting.' - 1 return. - end. - if. 0 = getonline 'Read Catalog from Server';CHECKREADSVR do. 0 return. end. -case. 1 do. - ONLINE=: 1 -case. 2 do. - if. REV >: 0 do. - if. 0 = getonline 'Read Catalog from Server';CHECKASK do. - log 'Using local copy of catalog. See Preferences to change the setting.' - 1 return. - end. - else. - if. 0 = getonline 'Setup Repository';CHECKSTARTUP do. 0 return. end. - end. -end. -log 'Updating server catalog...' -if. 0 = getserver'' do. - ONLINE=: 0 - log 'Working offline using local copy of catalog.' -else. - log 'Done.' -end. -1 -) -checkstatus=: 3 : 0 -if. 0 e. #LIBS do. '' return. end. -msk=. masklib PKGDATA -ups=. pkgups'' -libupm=. 1 e. msk *. ups -msk=. -. msk -addnim=. +/msk *. pkgnew'' -addupm=. +/msk *. pkgups'' -tot=. +/addnim,addupm,libupm -if. 0 = tot do. - 'All available packages are installed and up to date.' return. -end. -select. 0 < addnim,addupm -case. 0 0 do. - msg=. 'Addons are up to date.' -case. 0 1 do. - msg=. 'All addons are installed, ',(":addupm), ' can be upgraded.' -case. 1 0 do. - if. addnim = <:#PKGDATA do. - msg=. 'No addons are installed.' - else. - j=. ' addon',('s'#~1: fsize p do. - if. _1-:msg=. freads q do. - if. 0=#msg=. e do. msg=. 'Unexpected error' end. end. - log 'Connection failed: ',msg - info 'Connection failed:',LF2,msg - r=. 1;msg - ferase p;q -else. - r=. 0;p - ferase q -end. -r -) -httpgetr=: 3 : 0 -res=. httpget y -if. 0 = 0 pick res do. - f=. 1 pick res - txt=. freads f - ferase f - 0;txt -end. -) -install=: 3 : 0 -dat=. getdepend y -'num siz'=. pmview_applycounts dat -many=. 1 < num -msg=. 'Installing ',(":num),' package',many#'s' -msg=. msg,' of ',(many#'total '),'size ',sizefmt siz -log msg -installdo 1 {"1 dat -log 'Done.' -readlocal'' -pacman_init 0 -) -install_console=: 3 : 0 - if. -. init_console 'server' do. '' return. end. - pkgs=. getnames y - if. pkgs -: ,<'all' do. pkgs=. 1 {"1 PKGDATA end. - pkgs=. pkgs (e. # [) ~. (<'base library'), ((pkgnew +. pkgups) # 1&{"1@]) PKGDATA - pkgs=. pkgs -. Ignore - pkgs=. getdepend_console pkgs - if. 0 = num=. #pkgs do. '' return. end. - many=. 1 < num - msg=. 'Installing ',(":num),' package',many#'s' - log msg - installdo pkgs - log 'Done.' - readlocal'' - pacman_init '' - checkstatus'' -) -upgrade_console=: 3 : 0 - if. -. init_console 'read' do. '' return. end. - pkgs=. getnames y - if. (0=#pkgs) +. pkgs -: ,<'all' do. pkgs=. 1{"1 PKGDATA end. - pkgs=. pkgs (e. # [) (pkgups # 1&{"1@])PKGDATA - install_console pkgs -) -installdo=: 3 : 0 -msk=. -. y e. :fsize jpath'~addons/',y,'/manifest.ijs' do. - log 'Extraction failed: ',msg - info 'Extraction failed:',LF2,msg - return. -end. -install_addins y -install_config y -) -install_addins=: 3 :0 -fl=. ADDCFG,'addins.txt' -ins=. fixjal2 freads fl -ins=. ins #~ ( txt -msk=. fexist &> ( msk # 1 {"1 PKGDATA) ,. res - res=. (2#LF) joinstring (70&foldtext)&.> res - end. - case. 'showinstalled' do. - dat=. (isjpkgout y) {:: (1 2 3 4 {"1 PKGDATA); (pkgs) ,&.> <'/',x,(x-:'history'){::'.ijs';'.txt' - res=. res #~ msk=. (<_1) ~: res=. fread@jpath &.> fn - if. #res do. - res=. ,((<'== '), &.> msk#pkgs) ,. res - res=. (2#LF) joinstring res - end. -) -remove_console=: 3 : 0 - if. -. init_console 'edit' do. '' return. end. - pkgs=. getnames y - if. pkgs -: ,<'all' do. pkgs=. 1 {"1 PKGDATA end. - pkgs=. pkgs (e. # [) (-.@pkgnew # 1&{"1@]) PKGDATA - pkgs=. pkgs -. . fixver freads LIBVER -) -readlocal=: 3 : 0 -readlin'' -ADDONS=: fixjal freads ADDCFG,'addons.txt' -ADDINS=: fixjal2 freads ADDCFG,'addins.txt' -REV=: fixrev freads ADDCFG,'revision.txt' -LASTUPD=: fixupd freads ADDCFG,'lastupdate.txt' -LIBS=: fixlibs freads ADDCFG,'library.txt' -LIB=: fixlib LIBS -ZIPS=: fixzips freads ADDCFG,'zips.txt' -EMPTY -) -readtree=: 3 : 0 -f=. ADDCFG,'tree.txt' -tree=. LF -.~ freads f -if. -. (d),'manifest.ijs' - if. mft -: _1 do. continue. end. - VERSION=: '' - 0!:100 mft - ver=. fmtver fixver VERSION - n=. }: (#p) }. >d - n=. '/' (I.n='\') } n - r=. r,n,' ',ver,LF - s=. s,d -end. -r fwritenew f -s=. (#p) }.each }: each s -install_labs each s -write_config'' -) -refreshjal=: 3 : 0 -'rc p'=. httpget WWW,zipext 'jal' -if. rc do. 0 return. end. -unzip p;ADDCFG -ferase p -if. *./ CFGFILES e. {."1 [ 1!:0 ADDCFG,'*' do. 1 return. end. -msg=. 'Could not install the local repository catalog.' -log msg -info msg -0 -) -updatejal=: 3 : 0 - log 'Updating server catalog...' - if. -. init_console 'server' do. '' return. end. - refreshaddins'' - readlocal'' - pacman_init'' - res=. checklastupdate'' - res,LF,checkstatus'' -) -RELIBMSG=: 0 : 0 -You are now using the XX base library, and can switch to the YY base library. - -This will download the YY version of the base library and overwrite existing files. Addons are not affected. - -OK to switch to the YY library? -) -prelib=: 3 : 0 -old=. LIBTREE -new=. (('stable';'current') i. (2-s) {"1 dat -srv=. fixvers > (3-s) {"1 dat -{."1 /:"2 srv ,:"1 loc -) -pkgnew=: 3 : 0 -dat=. (s=.isjpkgout y){:: PKGDATA; (2-s) {"1 dat -) -pkgups=: pkgnew < pkglater -pkgsearch=: 3 : 0 - +./"1 +./ y E."1&>"(0 _) 1{"1 PKGDATA -) -pkgshow=: 3 : 0 - y e.~ 1{"1 PKGDATA -) -setshowall=: 3 : 0 -PKGDATA=: ( '/') {.each nms -SECTION=: 'All';nms -DATAMASK=: (#PKGDATA) $ 1 -EMPTY -) -init_console=: 3 : 0 - if. 0=#y do. y=. 'read' end. - select. y - fcase. 'edit';'server' do. - if. -. checkaccess'' do. 0 return. end. - case. 'read' do. - if. -. checkaddonsdir'' do. 0 return. end. - setfiles'' - readlocal'' - pacman_init '' - res=. 1 - case. do. res=. 0 - end. - if. y -: 'server' do. res=. getserver'' end. - res -) -jpkg=: 4 : 0 - select. x - case. 'history';'manifest' do. - x showfiles_console y - case. 'install' do. - install_console y - case. 'reinstall' do. - remove_console y - install_console y - case. 'remove' do. - remove_console y - case. ;:'show search showinstalled shownotinstalled showupgrade status' do. - x show_console y - case. 'update' do. - updatejal '' - case. 'upgrade' do. - upgrade_console y - case. do. - msg=. 'Valid options are:',LF - msg=. msg,' history, install, manifest, remove, reinstall, show, search,',LF - msg=. msg,' showinstalled, shownotinstalled, showupgrade, status,',LF - msg,' update, upgrade' - end. -) -do_install=: 3 : 0 -if. -. checkaccess_jpacman_ '' do. return. end. -'update' jpkg '' -select. y -case. 'qtide';'angle' do. - 'install' jpkg 'base library ide/qt' - getqtbin (y-:'angle'){::0;'angle' - msg=. (+/ 2 1 * IFWIN,'Darwin'-:UNAME) pick 'jqt.sh';'the jqt icon';'jqt.cmd' - smoutput 'exit and restart J using ',msg -case. 'all' do. - 'install' jpkg 'all' - getqtbin 0 -end. -) -do_getqtbin=: 3 : 0 -smoutput 'Installing JQt binaries...' -if. 'Linux'-:UNAME do. - if. IFRASPI do. - z=. 'jqt-raspi-32.tar.gz' - else. - z=. 'jqt-',((y-:'slim') pick 'linux';'slim'),'-',(IF64 pick 'x86';'x64'),'.tar.gz' - end. - z1=. 'libjqt.so' -elseif. IFWIN do. - z=. 'jqt-win',((y-:'slim')#'slim'),'-',(IF64 pick 'x86';'x64'),'.zip' - z1=. 'jqt.dll' -elseif. do. - z=. 'jqt-mac',((y-:'slim')#'slim'),'-',(IF64 pick 'x86';'x64'),'.zip' - z1=. 'libjqt.dylib' -end. -'rc p'=. httpget_jpacman_ 'http://www.jsoftware.com/download/j802/qtide/',z -if. rc do. - smoutput 'unable to download: ',z return. -end. -d=. jpath '~bin' -if. IFWIN do. - unzip_jpacman_ p;d -else. - if. 'Linux'-:UNAME do. - if. (0~:FHS) do. - if. IFRASPI do. - d1=. '/usr/lib/arm-linux-gnueabihf/.' - elseif. IF64 do. - d1=. '/usr/lib/x86_64-linux-gnu/.' - elseif. do. - d1=. '/usr/lib/i386-linux-gnu/.' - end. - hostcmd_jpacman_ 'cd /usr/bin && tar --no-same-owner --no-same-permissions -xzf ',(dquote p), ' && chmod 755 jqt && chmod 644 libjqt.so && mv libjqt.so ',d1 - else. - hostcmd_jpacman_ 'cd ',(dquote d),' && tar xzf ',(dquote p) - end. - else. - hostcmd_jpacman_ 'unzip -o ',(dquote p),' -d ',dquote d - end. -end. -ferase p -if. #1!:0 ((0~:FHS)*.'Linux'-:UNAME){::(jpath '~bin/',z1);'/usr/bin/jqt' do. - m=. 'Finished install of JQt binaries.' -else. - m=. 'Unable to install JQt binaries.',LF - m=. m,'check that you have write permission for: ',LF,((0~:FHS)*.'Linux'-:UNAME){::(jpath '~bin');'/usr/bin' -end. -smoutput m -if. 'Linux'-:UNAME do. return. end. - -tgt=. jpath IFWIN{::'~install/Qt';'~bin/Qt5Core.dll' -y=. (*#y){::0;y -smoutput 'Installing Qt library...' -if. IFWIN do. - z=. 'qt53-',((y-:'angle') pick 'win';'angle'),'-',((y-:'slim')#'slim-'),(IF64 pick 'x86';'x64'),'.zip' -else. - z=. 'qt53-mac-',((y-:'slim')#'slim-'),(IF64 pick 'x86';'x64'),'.zip' -end. -'rc p'=. httpget_jpacman_ 'http://www.jsoftware.com/download/j802/qtlib/',z -if. rc do. - smoutput 'unable to download: ',z return. -end. -d=. jpath IFWIN{::'~install';'~bin' -if. IFWIN do. - unzip_jpacman_ p;d -else. - hostcmd_jpacman_ 'unzip -o ',(dquote p),' -d ',dquote d -end. -ferase p -if. #1!:0 tgt do. - m=. 'Finished install of Qt binaries.' -else. - m=. 'Unable to install Qt binaries.',LF - m=. m,'check that you have write permission for: ',LF,IFWIN{::tgt;jpath'~bin' -end. -smoutput m - -) -jpkg_z_=: 3 : 0 - 'help' jpkg y - : - a=. conew 'jpacman' - res=. x jpkg__a y - destroy__a'' - res -) -jpkgv_z_=: (<@:>"1@|:^:(0 ~: #))@jpkg \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/pawn_example b/third_party/pygments/tests/examplefiles/pawn_example deleted file mode 100644 index ee2ecca22..000000000 --- a/third_party/pygments/tests/examplefiles/pawn_example +++ /dev/null @@ -1,25 +0,0 @@ -{include.i} -{nested.i {include.i}} - -&SCOPED-DEFINE MY_NAME "Abe" - -DEF VAR i AS INT NO-UNDO. -i = 0xABE + 1337 / (1 * 1.00) - -def var clowercasetest as char no-undo. -DEF VAR vardashtest AS DATETIME-TZ NO-UNDO. - -DEFINE TEMP-TABLE ttNames NO-UNDO - FIELD cName AS CHAR - INDEX IXPK_ttNames IS PRIMARY UNIQUE cName. - -/* One-line comment */ -/* Two-line - Comment */ - -CREATE ttNames. -ASSIGN ttNames.cName = {&MY_NAME}. - -FOR EACH ttNames: - MESSAGE "Hello, " + ttNames.cName + '!' VIEW-AS ALERT-BOX. -END. diff --git a/third_party/pygments/tests/examplefiles/perl_misc b/third_party/pygments/tests/examplefiles/perl_misc deleted file mode 100644 index e6dbfb28d..000000000 --- a/third_party/pygments/tests/examplefiles/perl_misc +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/perl - -# from http://gist.github.com/485595 -use strict; -use warnings; -use Time::HiRes 'usleep'; - -for (1..5) { - open my $in, '<', '/proc/sys/kernel/random/entropy_avail' or die; - print <$in>; - close $in; - usleep 100_000; -} - -# other miscellaneous tests of numbers separated by _ -#usleep 100_000; -100_000_000; -my $nichts = 0.005_006; -print "$nichts\n"; -my $nichts2 = 0.005_006_007; -print 900_800_700.005_006_007, $/; - -# numbers from `man 1 perlnumber` -my $n; -$n = 1234; # decimal integer -$n = 0b1110011; # binary integer -$n = 01234; # octal integer -$n = 0x1234; # hexadecimal integer -$n = 12.34e-56; # exponential notation -$n = "-12.34e56"; # number specified as a string -$n = "1234"; # number specified as a string - -# other numbers -for ( - -9876, - +8765, - -9876.02, - -9876.02e+10, - +765_432e30, - 2002., - .2002, -) { - print $_, "\n"; -} - -# operators on numbers -for ( - $n + 300, - $n - 300, - $n / 300 + 10, - $n * 250 / 2.0, - $n == 100, - $n != 100, - $n > 100, - $n >= 100, - $n < 100, - $n <= 100, - $n % 2, - abs $n, -) { - print $_, "\n"; -} diff --git a/third_party/pygments/tests/examplefiles/perl_perl5db b/third_party/pygments/tests/examplefiles/perl_perl5db deleted file mode 100644 index ab9d5e304..000000000 --- a/third_party/pygments/tests/examplefiles/perl_perl5db +++ /dev/null @@ -1,998 +0,0 @@ - -=head1 NAME - -perl5db.pl - the perl debugger - -=head1 SYNOPSIS - - perl -d your_Perl_script - -=head1 DESCRIPTION - -After this routine is over, we don't have user code executing in the debugger's -context, so we can use C freely. - -=cut - -############################################## Begin lexical danger zone - -# 'my' variables used here could leak into (that is, be visible in) -# the context that the code being evaluated is executing in. This means that -# the code could modify the debugger's variables. -# -# Fiddling with the debugger's context could be Bad. We insulate things as -# much as we can. - -sub eval { - - # 'my' would make it visible from user code - # but so does local! --tchrist - # Remember: this localizes @DB::res, not @main::res. - local @res; - { - - # Try to keep the user code from messing with us. Save these so that - # even if the eval'ed code changes them, we can put them back again. - # Needed because the user could refer directly to the debugger's - # package globals (and any 'my' variables in this containing scope) - # inside the eval(), and we want to try to stay safe. - local $otrace = $trace; - local $osingle = $single; - local $od = $^D; - - # Untaint the incoming eval() argument. - { ($evalarg) = $evalarg =~ /(.*)/s; } - - # $usercontext built in DB::DB near the comment - # "set up the context for DB::eval ..." - # Evaluate and save any results. - @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug - - # Restore those old values. - $trace = $otrace; - $single = $osingle; - $^D = $od; - } - - # Save the current value of $@, and preserve it in the debugger's copy - # of the saved precious globals. - my $at = $@; - - # Since we're only saving $@, we only have to localize the array element - # that it will be stored in. - local $saved[0]; # Preserve the old value of $@ - eval { &DB::save }; - - # Now see whether we need to report an error back to the user. - if ($at) { - local $\ = ''; - print $OUT $at; - } - - # Display as required by the caller. $onetimeDump and $onetimedumpDepth - # are package globals. - elsif ($onetimeDump) { - if ( $onetimeDump eq 'dump' ) { - local $option{dumpDepth} = $onetimedumpDepth - if defined $onetimedumpDepth; - dumpit( $OUT, \@res ); - } - elsif ( $onetimeDump eq 'methods' ) { - methods( $res[0] ); - } - } ## end elsif ($onetimeDump) - @res; -} ## end sub eval - -############################################## End lexical danger zone - -# After this point it is safe to introduce lexicals. -# The code being debugged will be executing in its own context, and -# can't see the inside of the debugger. -# -# However, one should not overdo it: leave as much control from outside as -# possible. If you make something a lexical, it's not going to be addressable -# from outside the debugger even if you know its name. - -# This file is automatically included if you do perl -d. -# It's probably not useful to include this yourself. -# -# Before venturing further into these twisty passages, it is -# wise to read the perldebguts man page or risk the ire of dragons. -# -# (It should be noted that perldebguts will tell you a lot about -# the underlying mechanics of how the debugger interfaces into the -# Perl interpreter, but not a lot about the debugger itself. The new -# comments in this code try to address this problem.) - -# Note that no subroutine call is possible until &DB::sub is defined -# (for subroutines defined outside of the package DB). In fact the same is -# true if $deep is not defined. - -# Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich) - -# modified Perl debugger, to be run from Emacs in perldb-mode -# Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990 -# Johan Vromans -- upgrade to 4.0 pl 10 -# Ilya Zakharevich -- patches after 5.001 (and some before ;-) - -# (We have made efforts to clarify the comments in the change log -# in other places; some of them may seem somewhat obscure as they -# were originally written, and explaining them away from the code -# in question seems conterproductive.. -JM) - -=head1 DEBUGGER INITIALIZATION - -The debugger starts up in phases. - -=head2 BASIC SETUP - -First, it initializes the environment it wants to run in: turning off -warnings during its own compilation, defining variables which it will need -to avoid warnings later, setting itself up to not exit when the program -terminates, and defaulting to printing return values for the C command. - -=cut - -# Needed for the statement after exec(): -# -# This BEGIN block is simply used to switch off warnings during debugger -# compiliation. Probably it would be better practice to fix the warnings, -# but this is how it's done at the moment. - -BEGIN { - $ini_warn = $^W; - $^W = 0; -} # Switch compilation warnings off until another BEGIN. - -# test if assertions are supported and actived: -BEGIN { - $ini_assertion = eval "sub asserting_test : assertion {1}; 1"; - - # $ini_assertion = undef => assertions unsupported, - # " = 1 => assertions supported - # print "\$ini_assertion=$ini_assertion\n"; -} - -local ($^W) = 0; # Switch run-time warnings off during init. - -=head2 THREADS SUPPORT - -If we are running under a threaded Perl, we require threads and threads::shared -if the environment variable C is set, to enable proper -threaded debugger control. C<-dt> can also be used to set this. - -Each new thread will be announced and the debugger prompt will always inform -you of each new thread created. It will also indicate the thread id in which -we are currently running within the prompt like this: - - [tid] DB<$i> - -Where C<[tid]> is an integer thread id and C<$i> is the familiar debugger -command prompt. The prompt will show: C<[0]> when running under threads, but -not actually in a thread. C<[tid]> is consistent with C usage. - -While running under threads, when you set or delete a breakpoint (etc.), this -will apply to all threads, not just the currently running one. When you are -in a currently executing thread, you will stay there until it completes. With -the current implementation it is not currently possible to hop from one thread -to another. - -The C and C commands are currently fairly minimal - see C and C. - -Note that threading support was built into the debugger as of Perl version -C<5.8.6> and debugger version C<1.2.8>. - -=cut - -BEGIN { - # ensure we can share our non-threaded variables or no-op - if ($ENV{PERL5DB_THREADED}) { - require threads; - require threads::shared; - import threads::shared qw(share); - $DBGR; - share(\$DBGR); - lock($DBGR); - print "Threads support enabled\n"; - } else { - *lock = sub(*) {}; - *share = sub(*) {}; - } -} - -# This would probably be better done with "use vars", but that wasn't around -# when this code was originally written. (Neither was "use strict".) And on -# the principle of not fiddling with something that was working, this was -# left alone. -warn( # Do not ;-) - # These variables control the execution of 'dumpvar.pl'. - $dumpvar::hashDepth, - $dumpvar::arrayDepth, - $dumpvar::dumpDBFiles, - $dumpvar::dumpPackages, - $dumpvar::quoteHighBit, - $dumpvar::printUndef, - $dumpvar::globPrint, - $dumpvar::usageOnly, - - # used to save @ARGV and extract any debugger-related flags. - @ARGS, - - # used to control die() reporting in diesignal() - $Carp::CarpLevel, - - # used to prevent multiple entries to diesignal() - # (if for instance diesignal() itself dies) - $panic, - - # used to prevent the debugger from running nonstop - # after a restart - $second_time, - ) - if 0; - -foreach my $k (keys (%INC)) { - &share(\$main::{'_<'.$filename}); -}; - -# Command-line + PERLLIB: -# Save the contents of @INC before they are modified elsewhere. -@ini_INC = @INC; - -# This was an attempt to clear out the previous values of various -# trapped errors. Apparently it didn't help. XXX More info needed! -# $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?! - -# We set these variables to safe values. We don't want to blindly turn -# off warnings, because other packages may still want them. -$trace = $signal = $single = 0; # Uninitialized warning suppression - # (local $^W cannot help - other packages!). - -# Default to not exiting when program finishes; print the return -# value when the 'r' command is used to return from a subroutine. -$inhibit_exit = $option{PrintRet} = 1; - -=head1 OPTION PROCESSING - -The debugger's options are actually spread out over the debugger itself and -C; some of these are variables to be set, while others are -subs to be called with a value. To try to make this a little easier to -manage, the debugger uses a few data structures to define what options -are legal and how they are to be processed. - -First, the C<@options> array defines the I of all the options that -are to be accepted. - -=cut - -@options = qw( - CommandSet - hashDepth arrayDepth dumpDepth - DumpDBFiles DumpPackages DumpReused - compactDump veryCompact quote - HighBit undefPrint globPrint - PrintRet UsageOnly frame - AutoTrace TTY noTTY - ReadLine NonStop LineInfo - maxTraceLen recallCommand ShellBang - pager tkRunning ornaments - signalLevel warnLevel dieLevel - inhibit_exit ImmediateStop bareStringify - CreateTTY RemotePort windowSize - DollarCaretP OnlyAssertions WarnAssertions -); - -@RememberOnROptions = qw(DollarCaretP OnlyAssertions); - -=pod - -Second, C lists the variables that each option uses to save its -state. - -=cut - -%optionVars = ( - hashDepth => \$dumpvar::hashDepth, - arrayDepth => \$dumpvar::arrayDepth, - CommandSet => \$CommandSet, - DumpDBFiles => \$dumpvar::dumpDBFiles, - DumpPackages => \$dumpvar::dumpPackages, - DumpReused => \$dumpvar::dumpReused, - HighBit => \$dumpvar::quoteHighBit, - undefPrint => \$dumpvar::printUndef, - globPrint => \$dumpvar::globPrint, - UsageOnly => \$dumpvar::usageOnly, - CreateTTY => \$CreateTTY, - bareStringify => \$dumpvar::bareStringify, - frame => \$frame, - AutoTrace => \$trace, - inhibit_exit => \$inhibit_exit, - maxTraceLen => \$maxtrace, - ImmediateStop => \$ImmediateStop, - RemotePort => \$remoteport, - windowSize => \$window, - WarnAssertions => \$warnassertions, -); - -=pod - -Third, C<%optionAction> defines the subroutine to be called to process each -option. - -=cut - -%optionAction = ( - compactDump => \&dumpvar::compactDump, - veryCompact => \&dumpvar::veryCompact, - quote => \&dumpvar::quote, - TTY => \&TTY, - noTTY => \&noTTY, - ReadLine => \&ReadLine, - NonStop => \&NonStop, - LineInfo => \&LineInfo, - recallCommand => \&recallCommand, - ShellBang => \&shellBang, - pager => \&pager, - signalLevel => \&signalLevel, - warnLevel => \&warnLevel, - dieLevel => \&dieLevel, - tkRunning => \&tkRunning, - ornaments => \&ornaments, - RemotePort => \&RemotePort, - DollarCaretP => \&DollarCaretP, - OnlyAssertions=> \&OnlyAssertions, -); - -=pod - -Last, the C<%optionRequire> notes modules that must be Cd if an -option is used. - -=cut - -# Note that this list is not complete: several options not listed here -# actually require that dumpvar.pl be loaded for them to work, but are -# not in the table. A subsequent patch will correct this problem; for -# the moment, we're just recommenting, and we are NOT going to change -# function. -%optionRequire = ( - compactDump => 'dumpvar.pl', - veryCompact => 'dumpvar.pl', - quote => 'dumpvar.pl', -); - -=pod - -There are a number of initialization-related variables which can be set -by putting code to set them in a BEGIN block in the C environment -variable. These are: - -=over 4 - -=item C<$rl> - readline control XXX needs more explanation - -=item C<$warnLevel> - whether or not debugger takes over warning handling - -=item C<$dieLevel> - whether or not debugger takes over die handling - -=item C<$signalLevel> - whether or not debugger takes over signal handling - -=item C<$pre> - preprompt actions (array reference) - -=item C<$post> - postprompt actions (array reference) - -=item C<$pretype> - -=item C<$CreateTTY> - whether or not to create a new TTY for this debugger - -=item C<$CommandSet> - which command set to use (defaults to new, documented set) - -=back - -=cut - -# These guys may be defined in $ENV{PERL5DB} : -$rl = 1 unless defined $rl; -$warnLevel = 1 unless defined $warnLevel; -$dieLevel = 1 unless defined $dieLevel; -$signalLevel = 1 unless defined $signalLevel; -$pre = [] unless defined $pre; -$post = [] unless defined $post; -$pretype = [] unless defined $pretype; -$CreateTTY = 3 unless defined $CreateTTY; -$CommandSet = '580' unless defined $CommandSet; - -share($rl); -share($warnLevel); -share($dieLevel); -share($signalLevel); -share($pre); -share($post); -share($pretype); -share($rl); -share($CreateTTY); -share($CommandSet); - -=pod - -The default C, C, and C handlers are set up. - -=cut - -warnLevel($warnLevel); -dieLevel($dieLevel); -signalLevel($signalLevel); - -=pod - -The pager to be used is needed next. We try to get it from the -environment first. if it's not defined there, we try to find it in -the Perl C. If it's not there, we default to C. We -then call the C function to save the pager name. - -=cut - -# This routine makes sure $pager is set up so that '|' can use it. -pager( - - # If PAGER is defined in the environment, use it. - defined $ENV{PAGER} - ? $ENV{PAGER} - - # If not, see if Config.pm defines it. - : eval { require Config } - && defined $Config::Config{pager} - ? $Config::Config{pager} - - # If not, fall back to 'more'. - : 'more' - ) - unless defined $pager; - -=pod - -We set up the command to be used to access the man pages, the command -recall character (C unless otherwise defined) and the shell escape -character (C unless otherwise defined). Yes, these do conflict, and -neither works in the debugger at the moment. - -=cut - -setman(); - -# Set up defaults for command recall and shell escape (note: -# these currently don't work in linemode debugging). -&recallCommand("!") unless defined $prc; -&shellBang("!") unless defined $psh; - -=pod - -We then set up the gigantic string containing the debugger help. -We also set the limit on the number of arguments we'll display during a -trace. - -=cut - -sethelp(); - -# If we didn't get a default for the length of eval/stack trace args, -# set it here. -$maxtrace = 400 unless defined $maxtrace; - -=head2 SETTING UP THE DEBUGGER GREETING - -The debugger I helps to inform the user how many debuggers are -running, and whether the current debugger is the primary or a child. - -If we are the primary, we just hang onto our pid so we'll have it when -or if we start a child debugger. If we are a child, we'll set things up -so we'll have a unique greeting and so the parent will give us our own -TTY later. - -We save the current contents of the C environment variable -because we mess around with it. We'll also need to hang onto it because -we'll need it if we restart. - -Child debuggers make a label out of the current PID structure recorded in -PERLDB_PIDS plus the new PID. They also mark themselves as not having a TTY -yet so the parent will give them one later via C. - -=cut - -# Save the current contents of the environment; we're about to -# much with it. We'll need this if we have to restart. -$ini_pids = $ENV{PERLDB_PIDS}; - -if ( defined $ENV{PERLDB_PIDS} ) { - - # We're a child. Make us a label out of the current PID structure - # recorded in PERLDB_PIDS plus our (new) PID. Mark us as not having - # a term yet so the parent will give us one later via resetterm(). - $pids = "[$ENV{PERLDB_PIDS}]"; - $ENV{PERLDB_PIDS} .= "->$$"; - $term_pid = -1; -} ## end if (defined $ENV{PERLDB_PIDS... -else { - - # We're the parent PID. Initialize PERLDB_PID in case we end up with a - # child debugger, and mark us as the parent, so we'll know to set up - # more TTY's is we have to. - $ENV{PERLDB_PIDS} = "$$"; - $pids = "{pid=$$}"; - $term_pid = $$; -} - -$pidprompt = ''; - -# Sets up $emacs as a synonym for $slave_editor. -*emacs = $slave_editor if $slave_editor; # May be used in afterinit()... - -=head2 READING THE RC FILE - -The debugger will read a file of initialization options if supplied. If -running interactively, this is C<.perldb>; if not, it's C. - -=cut - -# As noted, this test really doesn't check accurately that the debugger -# is running at a terminal or not. - -if ( -e "/dev/tty" ) { # this is the wrong metric! - $rcfile = ".perldb"; -} -else { - $rcfile = "perldb.ini"; -} - -=pod - -The debugger does a safety test of the file to be read. It must be owned -either by the current user or root, and must only be writable by the owner. - -=cut - -# This wraps a safety test around "do" to read and evaluate the init file. -# -# This isn't really safe, because there's a race -# between checking and opening. The solution is to -# open and fstat the handle, but then you have to read and -# eval the contents. But then the silly thing gets -# your lexical scope, which is unfortunate at best. -sub safe_do { - my $file = shift; - - # Just exactly what part of the word "CORE::" don't you understand? - local $SIG{__WARN__}; - local $SIG{__DIE__}; - - unless ( is_safe_file($file) ) { - CORE::warn < command is invoked, it -tries to capture all of the state it can into environment variables, and -then sets C. When we start executing again, we check to see -if C is there; if so, we reload all the information that -the R command stuffed into the environment variables. - - PERLDB_RESTART - flag only, contains no restart data itself. - PERLDB_HIST - command history, if it's available - PERLDB_ON_LOAD - breakpoints set by the rc file - PERLDB_POSTPONE - subs that have been loaded/not executed, and have actions - PERLDB_VISITED - files that had breakpoints - PERLDB_FILE_... - breakpoints for a file - PERLDB_OPT - active options - PERLDB_INC - the original @INC - PERLDB_PRETYPE - preprompt debugger actions - PERLDB_PRE - preprompt Perl code - PERLDB_POST - post-prompt Perl code - PERLDB_TYPEAHEAD - typeahead captured by readline() - -We chug through all these variables and plug the values saved in them -back into the appropriate spots in the debugger. - -=cut - -if ( exists $ENV{PERLDB_RESTART} ) { - - # We're restarting, so we don't need the flag that says to restart anymore. - delete $ENV{PERLDB_RESTART}; - - # $restart = 1; - @hist = get_list('PERLDB_HIST'); - %break_on_load = get_list("PERLDB_ON_LOAD"); - %postponed = get_list("PERLDB_POSTPONE"); - - share(@hist); - share(@truehist); - share(%break_on_load); - share(%postponed); - - # restore breakpoints/actions - my @had_breakpoints = get_list("PERLDB_VISITED"); - for ( 0 .. $#had_breakpoints ) { - my %pf = get_list("PERLDB_FILE_$_"); - $postponed_file{ $had_breakpoints[$_] } = \%pf if %pf; - } - - # restore options - my %opt = get_list("PERLDB_OPT"); - my ( $opt, $val ); - while ( ( $opt, $val ) = each %opt ) { - $val =~ s/[\\\']/\\$1/g; - parse_options("$opt'$val'"); - } - - # restore original @INC - @INC = get_list("PERLDB_INC"); - @ini_INC = @INC; - - # return pre/postprompt actions and typeahead buffer - $pretype = [ get_list("PERLDB_PRETYPE") ]; - $pre = [ get_list("PERLDB_PRE") ]; - $post = [ get_list("PERLDB_POST") ]; - @typeahead = get_list( "PERLDB_TYPEAHEAD", @typeahead ); -} ## end if (exists $ENV{PERLDB_RESTART... - -=head2 SETTING UP THE TERMINAL - -Now, we'll decide how the debugger is going to interact with the user. -If there's no TTY, we set the debugger to run non-stop; there's not going -to be anyone there to enter commands. - -=cut - -if ($notty) { - $runnonstop = 1; - share($runnonstop); -} - -=pod - -If there is a TTY, we have to determine who it belongs to before we can -proceed. If this is a slave editor or graphical debugger (denoted by -the first command-line switch being '-emacs'), we shift this off and -set C<$rl> to 0 (XXX ostensibly to do straight reads). - -=cut - -else { - - # Is Perl being run from a slave editor or graphical debugger? - # If so, don't use readline, and set $slave_editor = 1. - $slave_editor = - ( ( defined $main::ARGV[0] ) and ( $main::ARGV[0] eq '-emacs' ) ); - $rl = 0, shift(@main::ARGV) if $slave_editor; - - #require Term::ReadLine; - -=pod - -We then determine what the console should be on various systems: - -=over 4 - -=item * Cygwin - We use C instead of a separate device. - -=cut - - if ( $^O eq 'cygwin' ) { - - # /dev/tty is binary. use stdin for textmode - undef $console; - } - -=item * Unix - use C. - -=cut - - elsif ( -e "/dev/tty" ) { - $console = "/dev/tty"; - } - -=item * Windows or MSDOS - use C. - -=cut - - elsif ( $^O eq 'dos' or -e "con" or $^O eq 'MSWin32' ) { - $console = "con"; - } - -=item * MacOS - use C if this is the MPW version; C if not. - -Note that Mac OS X returns C, not C. Also note that the debugger doesn't do anything special for C. Maybe it should. - -=cut - - elsif ( $^O eq 'MacOS' ) { - if ( $MacPerl::Version !~ /MPW/ ) { - $console = - "Dev:Console:Perl Debug"; # Separate window for application - } - else { - $console = "Dev:Console"; - } - } ## end elsif ($^O eq 'MacOS') - -=item * VMS - use C. - -=cut - - else { - - # everything else is ... - $console = "sys\$command"; - } - -=pod - -=back - -Several other systems don't use a specific console. We C -for those (Windows using a slave editor/graphical debugger, NetWare, OS/2 -with a slave editor, Epoc). - -=cut - - if ( ( $^O eq 'MSWin32' ) and ( $slave_editor or defined $ENV{EMACS} ) ) { - - # /dev/tty is binary. use stdin for textmode - $console = undef; - } - - if ( $^O eq 'NetWare' ) { - - # /dev/tty is binary. use stdin for textmode - $console = undef; - } - - # In OS/2, we need to use STDIN to get textmode too, even though - # it pretty much looks like Unix otherwise. - if ( defined $ENV{OS2_SHELL} and ( $slave_editor or $ENV{WINDOWID} ) ) - { # In OS/2 - $console = undef; - } - - # EPOC also falls into the 'got to use STDIN' camp. - if ( $^O eq 'epoc' ) { - $console = undef; - } - -=pod - -If there is a TTY hanging around from a parent, we use that as the console. - -=cut - - $console = $tty if defined $tty; - -=head2 SOCKET HANDLING - -The debugger is capable of opening a socket and carrying out a debugging -session over the socket. - -If C was defined in the options, the debugger assumes that it -should try to start a debugging session on that port. It builds the socket -and then tries to connect the input and output filehandles to it. - -=cut - - # Handle socket stuff. - - if ( defined $remoteport ) { - - # If RemotePort was defined in the options, connect input and output - # to the socket. - require IO::Socket; - $OUT = new IO::Socket::INET( - Timeout => '10', - PeerAddr => $remoteport, - Proto => 'tcp', - ); - if ( !$OUT ) { die "Unable to connect to remote host: $remoteport\n"; } - $IN = $OUT; - } ## end if (defined $remoteport) - -=pod - -If no C was defined, and we want to create a TTY on startup, -this is probably a situation where multiple debuggers are running (for example, -a backticked command that starts up another debugger). We create a new IN and -OUT filehandle, and do the necessary mojo to create a new TTY if we know how -and if we can. - -=cut - - # Non-socket. - else { - - # Two debuggers running (probably a system or a backtick that invokes - # the debugger itself under the running one). create a new IN and OUT - # filehandle, and do the necessary mojo to create a new tty if we - # know how, and we can. - create_IN_OUT(4) if $CreateTTY & 4; - if ($console) { - - # If we have a console, check to see if there are separate ins and - # outs to open. (They are assumed identiical if not.) - - my ( $i, $o ) = split /,/, $console; - $o = $i unless defined $o; - - # read/write on in, or just read, or read on STDIN. - open( IN, "+<$i" ) - || open( IN, "<$i" ) - || open( IN, "<&STDIN" ); - - # read/write/create/clobber out, or write/create/clobber out, - # or merge with STDERR, or merge with STDOUT. - open( OUT, "+>$o" ) - || open( OUT, ">$o" ) - || open( OUT, ">&STDERR" ) - || open( OUT, ">&STDOUT" ); # so we don't dongle stdout - - } ## end if ($console) - elsif ( not defined $console ) { - - # No console. Open STDIN. - open( IN, "<&STDIN" ); - - # merge with STDERR, or with STDOUT. - open( OUT, ">&STDERR" ) - || open( OUT, ">&STDOUT" ); # so we don't dongle stdout - $console = 'STDIN/OUT'; - } ## end elsif (not defined $console) - - # Keep copies of the filehandles so that when the pager runs, it - # can close standard input without clobbering ours. - $IN = \*IN, $OUT = \*OUT if $console or not defined $console; - } ## end elsif (from if(defined $remoteport)) - - # Unbuffer DB::OUT. We need to see responses right away. - my $previous = select($OUT); - $| = 1; # for DB::OUT - select($previous); - - # Line info goes to debugger output unless pointed elsewhere. - # Pointing elsewhere makes it possible for slave editors to - # keep track of file and position. We have both a filehandle - # and a I/O description to keep track of. - $LINEINFO = $OUT unless defined $LINEINFO; - $lineinfo = $console unless defined $lineinfo; - # share($LINEINFO); # <- unable to share globs - share($lineinfo); # - -=pod - -To finish initialization, we show the debugger greeting, -and then call the C subroutine if there is one. - -=cut - - # Show the debugger greeting. - $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/; - unless ($runnonstop) { - local $\ = ''; - local $, = ''; - if ( $term_pid eq '-1' ) { - print $OUT "\nDaughter DB session started...\n"; - } - else { - print $OUT "\nLoading DB routines from $header\n"; - print $OUT ( - "Editor support ", - $slave_editor ? "enabled" : "available", ".\n" - ); - print $OUT -"\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n"; - } ## end else [ if ($term_pid eq '-1') - } ## end unless ($runnonstop) -} ## end else [ if ($notty) - -# XXX This looks like a bug to me. -# Why copy to @ARGS and then futz with @args? -@ARGS = @ARGV; -for (@args) { - # Make sure backslashes before single quotes are stripped out, and - # keep args unless they are numeric (XXX why?) - # s/\'/\\\'/g; # removed while not justified understandably - # s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto -} - -# If there was an afterinit() sub defined, call it. It will get -# executed in our scope, so it can fiddle with debugger globals. -if ( defined &afterinit ) { # May be defined in $rcfile - &afterinit(); -} - -# Inform us about "Stack dump during die enabled ..." in dieLevel(). -$I_m_init = 1; - - diff --git a/third_party/pygments/tests/examplefiles/perl_regex-delims b/third_party/pygments/tests/examplefiles/perl_regex-delims deleted file mode 100644 index 6da5298dc..000000000 --- a/third_party/pygments/tests/examplefiles/perl_regex-delims +++ /dev/null @@ -1,120 +0,0 @@ -#! /usr/bin/env perl - -use strict; -use warnings; - -# common delimiters -print "a: "; -my $a = "foo"; -print $a, " - "; -$a =~ s/foo/bar/; -print $a, "\n"; - -print "b: "; -my $b = "foo"; -print $b, " - "; -$b =~ s!foo!bar!; -print $b, "\n"; - -print "c: "; -my $c = "foo"; -print $c, " - "; -$c =~ s@foo@bar@; -print $c, "\n"; - -print "d: "; -my $d = "foo"; -print $d, " - "; -$d =~ s\foo\bar\; -print $d, "\n"; - -print "\n"; - -# balanced delimiters -print "e: "; -my $e = "foo"; -print $e, " - "; -$e =~ s{foo}{bar}; -print $e, "\n"; - -print "f: "; -my $f = "foo"; -print $f, " - "; -$f =~ s(foo)(bar); -print $f, "\n"; - -print "g: "; -my $g = "foo"; -print $g, " - "; -$g =~ s; -print $g, "\n"; - -print "h: "; -my $h = "foo"; -print $h, " - "; -$h =~ s[foo][bar]; -print $h, "\n"; - -print "\n"; - -# balanced delimiters with whitespace -print "i: "; -my $i = "foo"; -print $i, " - "; -$i =~ s{foo} {bar}; -print $i, "\n"; - -print "j: "; -my $j = "foo"; -print $j, " - "; -$j =~ s ; -print $j, "\n"; - -print "k: "; -my $k = "foo"; -print $k, " - "; -$k =~ - s(foo) - - (bar); -print $k, "\n"; - -print "\n"; - -# mixed delimiters -print "l: "; -my $l = "foo"; -print $l, " - "; -$l =~ s{foo} ; -print $l, "\n"; - -print "m: "; -my $m = "foo"; -print $m, " - "; -$m =~ s(foo) !bar!; -print $m, "\n"; - -print "n: "; -my $n = "foo"; -print $n, " - "; -$n =~ s[foo] $bar$; -print $n, "\n"; - -print "\n"; - -# /x modifier -print "o: "; -my $o = "foo"; -print $o, " - "; -$o =~ s{ - foo - } {bar}x; -print $o, "\n"; - -print "p: "; -my $p = "foo"; -print $p, " - "; -$p =~ s% - foo - %bar%x; -print $p, "\n"; diff --git a/third_party/pygments/tests/examplefiles/perlfunc.1 b/third_party/pygments/tests/examplefiles/perlfunc.1 deleted file mode 100644 index 5f80f0d01..000000000 --- a/third_party/pygments/tests/examplefiles/perlfunc.1 +++ /dev/null @@ -1,856 +0,0 @@ -.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32 -.\" -.\" Standard preamble: -.\" ======================================================================== -.de Sh \" Subsection heading -.br -.if t .Sp -.ne 5 -.PP -\fB\\$1\fR -.PP -.. -.de Sp \" Vertical space (when we can't use .PP) -.if t .sp .5v -.if n .sp -.. -.de Vb \" Begin verbatim text -.ft CW -.nf -.ne \\$1 -.. -.de Ve \" End verbatim text -.ft R -.fi -.. -.\" Set up some character translations and predefined strings. \*(-- will -.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left -.\" double quote, and \*(R" will give a right double quote. | will give a -.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to -.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' -.\" expand to `' in nroff, nothing in troff, for use with C<>. -.tr \(*W-|\(bv\*(Tr -.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' -.ie n \{\ -. ds -- \(*W- -. ds PI pi -. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch -. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch -. ds L" "" -. ds R" "" -. ds C` "" -. ds C' "" -'br\} -.el\{\ -. ds -- \|\(em\| -. ds PI \(*p -. ds L" `` -. ds R" '' -'br\} -.\" -.\" If the F register is turned on, we'll generate index entries on stderr for -.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index -.\" entries marked with X<> in POD. Of course, you'll have to process the -.\" output yourself in some meaningful fashion. -.if \nF \{\ -. de IX -. tm Index:\\$1\t\\n%\t"\\$2" -.. -. nr % 0 -. rr F -.\} -.\" -.\" For nroff, turn off justification. Always turn off hyphenation; it makes -.\" way too many mistakes in technical documents. -.hy 0 -.if n .na -.\" -.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). -.\" Fear. Run. Save yourself. No user-serviceable parts. -. \" fudge factors for nroff and troff -.if n \{\ -. ds #H 0 -. ds #V .8m -. ds #F .3m -. ds #[ \f1 -. ds #] \fP -.\} -.if t \{\ -. ds #H ((1u-(\\\\n(.fu%2u))*.13m) -. ds #V .6m -. ds #F 0 -. ds #[ \& -. ds #] \& -.\} -. \" simple accents for nroff and troff -.if n \{\ -. ds ' \& -. ds ` \& -. ds ^ \& -. ds , \& -. ds ~ ~ -. ds / -.\} -.if t \{\ -. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" -. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' -. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' -. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' -. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' -. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' -.\} -. \" troff and (daisy-wheel) nroff accents -.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' -.ds 8 \h'\*(#H'\(*b\h'-\*(#H' -.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] -.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' -.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' -.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] -.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] -.ds ae a\h'-(\w'a'u*4/10)'e -.ds Ae A\h'-(\w'A'u*4/10)'E -. \" corrections for vroff -.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' -.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' -. \" for low resolution devices (crt and lpr) -.if \n(.H>23 .if \n(.V>19 \ -\{\ -. ds : e -. ds 8 ss -. ds o a -. ds d- d\h'-1'\(ga -. ds D- D\h'-1'\(hy -. ds th \o'bp' -. ds Th \o'LP' -. ds ae ae -. ds Ae AE -.\} -.rm #[ #] #H #V #F C -.\" ======================================================================== -.\" -.IX Title "PERLFUNC 1" -.TH PERLFUNC 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide" -.SH "NAME" -.IX Xref "function" -perlfunc \- Perl builtin functions -.SH "DESCRIPTION" -.IX Header "DESCRIPTION" -The functions in this section can serve as terms in an expression. -They fall into two major categories: list operators and named unary -operators. These differ in their precedence relationship with a -following comma. (See the precedence table in perlop.) List -operators take more than one argument, while unary operators can never -take more than one argument. Thus, a comma terminates the argument of -a unary operator, but merely separates the arguments of a list -operator. A unary operator generally provides a scalar context to its -argument, while a list operator may provide either scalar or list -contexts for its arguments. If it does both, the scalar arguments will -be first, and the list argument will follow. (Note that there can ever -be only one such list argument.) For instance, \fIsplice()\fR has three scalar -arguments followed by a list, whereas \fIgethostbyname()\fR has four scalar -arguments. -.PP -In the syntax descriptions that follow, list operators that expect a -list (and provide list context for the elements of the list) are shown -with \s-1LIST\s0 as an argument. Such a list may consist of any combination -of scalar arguments or list values; the list values will be included -in the list as if each individual element were interpolated at that -point in the list, forming a longer single-dimensional list value. -Commas should separate elements of the \s-1LIST\s0. -.PP -Any function in the list below may be used either with or without -parentheses around its arguments. (The syntax descriptions omit the -parentheses.) If you use the parentheses, the simple (but occasionally -surprising) rule is this: It \fIlooks\fR like a function, therefore it \fIis\fR a -function, and precedence doesn't matter. Otherwise it's a list -operator or unary operator, and precedence does matter. And whitespace -between the function and left parenthesis doesn't count\*(--so you need to -be careful sometimes: -.PP -.Vb 5 -\& print 1+2+4; # Prints 7. -\& print(1+2) + 4; # Prints 3. -\& print (1+2)+4; # Also prints 3! -\& print +(1+2)+4; # Prints 7. -\& print ((1+2)+4); # Prints 7. -.Ve -.PP -If you run Perl with the \fB\-w\fR switch it can warn you about this. For -example, the third line above produces: -.PP -.Vb 2 -\& print (...) interpreted as function at - line 1. -\& Useless use of integer addition in void context at - line 1. -.Ve -.PP -A few functions take no arguments at all, and therefore work as neither -unary nor list operators. These include such functions as \f(CW\*(C`time\*(C'\fR -and \f(CW\*(C`endpwent\*(C'\fR. For example, \f(CW\*(C`time+86_400\*(C'\fR always means -\&\f(CW\*(C`time() + 86_400\*(C'\fR. -.PP -For functions that can be used in either a scalar or list context, -nonabortive failure is generally indicated in a scalar context by -returning the undefined value, and in a list context by returning the -null list. -.PP -Remember the following important rule: There is \fBno rule\fR that relates -the behavior of an expression in list context to its behavior in scalar -context, or vice versa. It might do two totally different things. -Each operator and function decides which sort of value it would be most -appropriate to return in scalar context. Some operators return the -length of the list that would have been returned in list context. Some -operators return the first value in the list. Some operators return the -last value in the list. Some operators return a count of successful -operations. In general, they do what you want, unless you want -consistency. -.IX Xref "context" -.PP -A named array in scalar context is quite different from what would at -first glance appear to be a list in scalar context. You can't get a list -like \f(CW\*(C`(1,2,3)\*(C'\fR into being in scalar context, because the compiler knows -the context at compile time. It would generate the scalar comma operator -there, not the list construction version of the comma. That means it -was never a list to start with. -.PP -In general, functions in Perl that serve as wrappers for system calls -of the same name (like \fIchown\fR\|(2), \fIfork\fR\|(2), \fIclosedir\fR\|(2), etc.) all return -true when they succeed and \f(CW\*(C`undef\*(C'\fR otherwise, as is usually mentioned -in the descriptions below. This is different from the C interfaces, -which return \f(CW\*(C`\-1\*(C'\fR on failure. Exceptions to this rule are \f(CW\*(C`wait\*(C'\fR, -\&\f(CW\*(C`waitpid\*(C'\fR, and \f(CW\*(C`syscall\*(C'\fR. System calls also set the special \f(CW$!\fR -variable on failure. Other functions do not, except accidentally. -.Sh "Perl Functions by Category" -.IX Xref "function" -.IX Subsection "Perl Functions by Category" -Here are Perl's functions (including things that look like -functions, like some keywords and named operators) -arranged by category. Some functions appear in more -than one place. -.IP "Functions for SCALARs or strings" 4 -.IX Xref "scalar string character" -.IX Item "Functions for SCALARs or strings" -\&\f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chop\*(C'\fR, \f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`index\*(C'\fR, \f(CW\*(C`lc\*(C'\fR, \f(CW\*(C`lcfirst\*(C'\fR, -\&\f(CW\*(C`length\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`ord\*(C'\fR, \f(CW\*(C`pack\*(C'\fR, \f(CW\*(C`q/STRING/\*(C'\fR, \f(CW\*(C`qq/STRING/\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR, -\&\f(CW\*(C`rindex\*(C'\fR, \f(CW\*(C`sprintf\*(C'\fR, \f(CW\*(C`substr\*(C'\fR, \f(CW\*(C`tr///\*(C'\fR, \f(CW\*(C`uc\*(C'\fR, \f(CW\*(C`ucfirst\*(C'\fR, \f(CW\*(C`y///\*(C'\fR -.IP "Regular expressions and pattern matching" 4 -.IX Xref "regular expression regex regexp" -.IX Item "Regular expressions and pattern matching" -\&\f(CW\*(C`m//\*(C'\fR, \f(CW\*(C`pos\*(C'\fR, \f(CW\*(C`quotemeta\*(C'\fR, \f(CW\*(C`s///\*(C'\fR, \f(CW\*(C`split\*(C'\fR, \f(CW\*(C`study\*(C'\fR, \f(CW\*(C`qr//\*(C'\fR -.IP "Numeric functions" 4 -.IX Xref "numeric number trigonometric trigonometry" -.IX Item "Numeric functions" -\&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`atan2\*(C'\fR, \f(CW\*(C`cos\*(C'\fR, \f(CW\*(C`exp\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`int\*(C'\fR, \f(CW\*(C`log\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`rand\*(C'\fR, -\&\f(CW\*(C`sin\*(C'\fR, \f(CW\*(C`sqrt\*(C'\fR, \f(CW\*(C`srand\*(C'\fR -.ie n .IP "Functions for real @ARRAYs" 4 -.el .IP "Functions for real \f(CW@ARRAYs\fR" 4 -.IX Xref "array" -.IX Item "Functions for real @ARRAYs" -\&\f(CW\*(C`pop\*(C'\fR, \f(CW\*(C`push\*(C'\fR, \f(CW\*(C`shift\*(C'\fR, \f(CW\*(C`splice\*(C'\fR, \f(CW\*(C`unshift\*(C'\fR -.IP "Functions for list data" 4 -.IX Xref "list" -.IX Item "Functions for list data" -\&\f(CW\*(C`grep\*(C'\fR, \f(CW\*(C`join\*(C'\fR, \f(CW\*(C`map\*(C'\fR, \f(CW\*(C`qw/STRING/\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR, \f(CW\*(C`sort\*(C'\fR, \f(CW\*(C`unpack\*(C'\fR -.ie n .IP "Functions for real %HASHes" 4 -.el .IP "Functions for real \f(CW%HASHes\fR" 4 -.IX Xref "hash" -.IX Item "Functions for real %HASHes" -\&\f(CW\*(C`delete\*(C'\fR, \f(CW\*(C`each\*(C'\fR, \f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR -.IP "Input and output functions" 4 -.IX Xref "I O input output dbm" -.IX Item "Input and output functions" -\&\f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`close\*(C'\fR, \f(CW\*(C`closedir\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`eof\*(C'\fR, -\&\f(CW\*(C`fileno\*(C'\fR, \f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`format\*(C'\fR, \f(CW\*(C`getc\*(C'\fR, \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`printf\*(C'\fR, \f(CW\*(C`read\*(C'\fR, -\&\f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`rewinddir\*(C'\fR, \f(CW\*(C`seek\*(C'\fR, \f(CW\*(C`seekdir\*(C'\fR, \f(CW\*(C`select\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, -\&\f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`sysseek\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR, \f(CW\*(C`tell\*(C'\fR, \f(CW\*(C`telldir\*(C'\fR, \f(CW\*(C`truncate\*(C'\fR, -\&\f(CW\*(C`warn\*(C'\fR, \f(CW\*(C`write\*(C'\fR -.IP "Functions for fixed length data or records" 4 -.IX Item "Functions for fixed length data or records" -\&\f(CW\*(C`pack\*(C'\fR, \f(CW\*(C`read\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR, \f(CW\*(C`unpack\*(C'\fR, \f(CW\*(C`vec\*(C'\fR -.IP "Functions for filehandles, files, or directories" 4 -.IX Xref "file filehandle directory pipe link symlink" -.IX Item "Functions for filehandles, files, or directories" -\&\f(CW\*(C`\-\f(CIX\f(CW\*(C'\fR, \f(CW\*(C`chdir\*(C'\fR, \f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR, \f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, -\&\f(CW\*(C`ioctl\*(C'\fR, \f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`mkdir\*(C'\fR, \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`opendir\*(C'\fR, -\&\f(CW\*(C`readlink\*(C'\fR, \f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`rmdir\*(C'\fR, \f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, -\&\f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR, \f(CW\*(C`utime\*(C'\fR -.IP "Keywords related to the control flow of your Perl program" 4 -.IX Xref "control flow" -.IX Item "Keywords related to the control flow of your Perl program" -\&\f(CW\*(C`caller\*(C'\fR, \f(CW\*(C`continue\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR, \f(CW\*(C`exit\*(C'\fR, -\&\f(CW\*(C`goto\*(C'\fR, \f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`redo\*(C'\fR, \f(CW\*(C`return\*(C'\fR, \f(CW\*(C`sub\*(C'\fR, \f(CW\*(C`wantarray\*(C'\fR -.IP "Keywords related to scoping" 4 -.IX Item "Keywords related to scoping" -\&\f(CW\*(C`caller\*(C'\fR, \f(CW\*(C`import\*(C'\fR, \f(CW\*(C`local\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`use\*(C'\fR -.IP "Miscellaneous functions" 4 -.IX Item "Miscellaneous functions" -\&\f(CW\*(C`defined\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR, \f(CW\*(C`formline\*(C'\fR, \f(CW\*(C`local\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`reset\*(C'\fR, -\&\f(CW\*(C`scalar\*(C'\fR, \f(CW\*(C`undef\*(C'\fR, \f(CW\*(C`wantarray\*(C'\fR -.IP "Functions for processes and process groups" 4 -.IX Xref "process pid process id" -.IX Item "Functions for processes and process groups" -\&\f(CW\*(C`alarm\*(C'\fR, \f(CW\*(C`exec\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`kill\*(C'\fR, -\&\f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`qx/STRING/\*(C'\fR, \f(CW\*(C`setpgrp\*(C'\fR, \f(CW\*(C`setpriority\*(C'\fR, \f(CW\*(C`sleep\*(C'\fR, \f(CW\*(C`system\*(C'\fR, -\&\f(CW\*(C`times\*(C'\fR, \f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR -.IP "Keywords related to perl modules" 4 -.IX Xref "module" -.IX Item "Keywords related to perl modules" -\&\f(CW\*(C`do\*(C'\fR, \f(CW\*(C`import\*(C'\fR, \f(CW\*(C`no\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`require\*(C'\fR, \f(CW\*(C`use\*(C'\fR -.IP "Keywords related to classes and object-orientedness" 4 -.IX Xref "object class package" -.IX Item "Keywords related to classes and object-orientedness" -\&\f(CW\*(C`bless\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`ref\*(C'\fR, \f(CW\*(C`tie\*(C'\fR, \f(CW\*(C`tied\*(C'\fR, -\&\f(CW\*(C`untie\*(C'\fR, \f(CW\*(C`use\*(C'\fR -.IP "Low-level socket functions" 4 -.IX Xref "socket sock" -.IX Item "Low-level socket functions" -\&\f(CW\*(C`accept\*(C'\fR, \f(CW\*(C`bind\*(C'\fR, \f(CW\*(C`connect\*(C'\fR, \f(CW\*(C`getpeername\*(C'\fR, \f(CW\*(C`getsockname\*(C'\fR, -\&\f(CW\*(C`getsockopt\*(C'\fR, \f(CW\*(C`listen\*(C'\fR, \f(CW\*(C`recv\*(C'\fR, \f(CW\*(C`send\*(C'\fR, \f(CW\*(C`setsockopt\*(C'\fR, \f(CW\*(C`shutdown\*(C'\fR, -\&\f(CW\*(C`socket\*(C'\fR, \f(CW\*(C`socketpair\*(C'\fR -.IP "System V interprocess communication functions" 4 -.IX Xref "IPC System V semaphore shared memory memory message" -.IX Item "System V interprocess communication functions" -\&\f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR, \f(CW\*(C`msgrcv\*(C'\fR, \f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`semctl\*(C'\fR, \f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR, -\&\f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR, \f(CW\*(C`shmread\*(C'\fR, \f(CW\*(C`shmwrite\*(C'\fR -.IP "Fetching user and group info" 4 -.IX Xref "user group password uid gid passwd etc passwd" -.IX Item "Fetching user and group info" -\&\f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR, \f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR, \f(CW\*(C`getgrent\*(C'\fR, -\&\f(CW\*(C`getgrgid\*(C'\fR, \f(CW\*(C`getgrnam\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR, -\&\f(CW\*(C`getpwuid\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR -.IP "Fetching network info" 4 -.IX Xref "network protocol host hostname IP address service" -.IX Item "Fetching network info" -\&\f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`gethostbyaddr\*(C'\fR, \f(CW\*(C`gethostbyname\*(C'\fR, -\&\f(CW\*(C`gethostent\*(C'\fR, \f(CW\*(C`getnetbyaddr\*(C'\fR, \f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR, -\&\f(CW\*(C`getprotobyname\*(C'\fR, \f(CW\*(C`getprotobynumber\*(C'\fR, \f(CW\*(C`getprotoent\*(C'\fR, -\&\f(CW\*(C`getservbyname\*(C'\fR, \f(CW\*(C`getservbyport\*(C'\fR, \f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR, -\&\f(CW\*(C`setnetent\*(C'\fR, \f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setservent\*(C'\fR -.IP "Time-related functions" 4 -.IX Xref "time date" -.IX Item "Time-related functions" -\&\f(CW\*(C`gmtime\*(C'\fR, \f(CW\*(C`localtime\*(C'\fR, \f(CW\*(C`time\*(C'\fR, \f(CW\*(C`times\*(C'\fR -.IP "Functions new in perl5" 4 -.IX Xref "perl5" -.IX Item "Functions new in perl5" -\&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`bless\*(C'\fR, \f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`formline\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, -\&\f(CW\*(C`import\*(C'\fR, \f(CW\*(C`lc\*(C'\fR, \f(CW\*(C`lcfirst\*(C'\fR, \f(CW\*(C`map\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`no\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`prototype\*(C'\fR, -\&\f(CW\*(C`qx\*(C'\fR, \f(CW\*(C`qw\*(C'\fR, \f(CW\*(C`readline\*(C'\fR, \f(CW\*(C`readpipe\*(C'\fR, \f(CW\*(C`ref\*(C'\fR, \f(CW\*(C`sub*\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \f(CW\*(C`tie\*(C'\fR, -\&\f(CW\*(C`tied\*(C'\fR, \f(CW\*(C`uc\*(C'\fR, \f(CW\*(C`ucfirst\*(C'\fR, \f(CW\*(C`untie\*(C'\fR, \f(CW\*(C`use\*(C'\fR -.Sp -* \- \f(CW\*(C`sub\*(C'\fR was a keyword in perl4, but in perl5 it is an -operator, which can be used in expressions. -.IP "Functions obsoleted in perl5" 4 -.IX Item "Functions obsoleted in perl5" -\&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR -.Sh "Portability" -.IX Xref "portability Unix portable" -.IX Subsection "Portability" -Perl was born in Unix and can therefore access all common Unix -system calls. In non-Unix environments, the functionality of some -Unix system calls may not be available, or details of the available -functionality may differ slightly. The Perl functions affected -by this are: -.PP -\&\f(CW\*(C`\-X\*(C'\fR, \f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR, \f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR, -\&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR, -\&\f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`exec\*(C'\fR, -\&\f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, \f(CW\*(C`getgrent\*(C'\fR, \f(CW\*(C`getgrgid\*(C'\fR, \f(CW\*(C`gethostbyname\*(C'\fR, -\&\f(CW\*(C`gethostent\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR, \f(CW\*(C`getnetbyaddr\*(C'\fR, \f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR, -\&\f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`getprotobynumber\*(C'\fR, -\&\f(CW\*(C`getprotoent\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR, \f(CW\*(C`getpwuid\*(C'\fR, -\&\f(CW\*(C`getservbyport\*(C'\fR, \f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`getsockopt\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, \f(CW\*(C`ioctl\*(C'\fR, -\&\f(CW\*(C`kill\*(C'\fR, \f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR, \f(CW\*(C`msgrcv\*(C'\fR, -\&\f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`readlink\*(C'\fR, \f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`select\*(C'\fR, \f(CW\*(C`semctl\*(C'\fR, -\&\f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR, \f(CW\*(C`setnetent\*(C'\fR, -\&\f(CW\*(C`setpgrp\*(C'\fR, \f(CW\*(C`setpriority\*(C'\fR, \f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR, -\&\f(CW\*(C`setservent\*(C'\fR, \f(CW\*(C`setsockopt\*(C'\fR, \f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR, \f(CW\*(C`shmread\*(C'\fR, -\&\f(CW\*(C`shmwrite\*(C'\fR, \f(CW\*(C`socket\*(C'\fR, \f(CW\*(C`socketpair\*(C'\fR, -\&\f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \f(CW\*(C`system\*(C'\fR, -\&\f(CW\*(C`times\*(C'\fR, \f(CW\*(C`truncate\*(C'\fR, \f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR, -\&\f(CW\*(C`utime\*(C'\fR, \f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR -.PP -For more information about the portability of these functions, see -perlport and other available platform-specific documentation. -.Sh "Alphabetical Listing of Perl Functions" -.IX Subsection "Alphabetical Listing of Perl Functions" -.IP "\-X \s-1FILEHANDLE\s0" 8 -.IX Xref "-r -w -x -o -R -W -X -O -e -z -s -f -d -l -p -S -b -c -t -u -g -k -T -B -M -A -C" -.IX Item "-X FILEHANDLE" -.PD 0 -.IP "\-X \s-1EXPR\s0" 8 -.IX Item "-X EXPR" -.IP "\-X" 8 -.IX Item "-X" -.PD -A file test, where X is one of the letters listed below. This unary -operator takes one argument, either a filename or a filehandle, and -tests the associated file to see if something is true about it. If the -argument is omitted, tests \f(CW$_\fR, except for \f(CW\*(C`\-t\*(C'\fR, which tests \s-1STDIN\s0. -Unless otherwise documented, it returns \f(CW1\fR for true and \f(CW''\fR for false, or -the undefined value if the file doesn't exist. Despite the funny -names, precedence is the same as any other named unary operator, and -the argument may be parenthesized like any other unary operator. The -operator may be any of: -.Sp -.Vb 4 -\& -r File is readable by effective uid/gid. -\& -w File is writable by effective uid/gid. -\& -x File is executable by effective uid/gid. -\& -o File is owned by effective uid. -.Ve -.Sp -.Vb 4 -\& -R File is readable by real uid/gid. -\& -W File is writable by real uid/gid. -\& -X File is executable by real uid/gid. -\& -O File is owned by real uid. -.Ve -.Sp -.Vb 3 -\& -e File exists. -\& -z File has zero size (is empty). -\& -s File has nonzero size (returns size in bytes). -.Ve -.Sp -.Vb 8 -\& -f File is a plain file. -\& -d File is a directory. -\& -l File is a symbolic link. -\& -p File is a named pipe (FIFO), or Filehandle is a pipe. -\& -S File is a socket. -\& -b File is a block special file. -\& -c File is a character special file. -\& -t Filehandle is opened to a tty. -.Ve -.Sp -.Vb 3 -\& -u File has setuid bit set. -\& -g File has setgid bit set. -\& -k File has sticky bit set. -.Ve -.Sp -.Vb 2 -\& -T File is an ASCII text file (heuristic guess). -\& -B File is a "binary" file (opposite of -T). -.Ve -.Sp -.Vb 3 -\& -M Script start time minus file modification time, in days. -\& -A Same for access time. -\& -C Same for inode change time (Unix, may differ for other platforms) -.Ve -.Sp -Example: -.Sp -.Vb 5 -\& while (<>) { -\& chomp; -\& next unless -f $_; # ignore specials -\& #... -\& } -.Ve -.Sp -The interpretation of the file permission operators \f(CW\*(C`\-r\*(C'\fR, \f(CW\*(C`\-R\*(C'\fR, -\&\f(CW\*(C`\-w\*(C'\fR, \f(CW\*(C`\-W\*(C'\fR, \f(CW\*(C`\-x\*(C'\fR, and \f(CW\*(C`\-X\*(C'\fR is by default based solely on the mode -of the file and the uids and gids of the user. There may be other -reasons you can't actually read, write, or execute the file. Such -reasons may be for example network filesystem access controls, ACLs -(access control lists), read-only filesystems, and unrecognized -executable formats. -.Sp -Also note that, for the superuser on the local filesystems, the \f(CW\*(C`\-r\*(C'\fR, -\&\f(CW\*(C`\-R\*(C'\fR, \f(CW\*(C`\-w\*(C'\fR, and \f(CW\*(C`\-W\*(C'\fR tests always return 1, and \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR return 1 -if any execute bit is set in the mode. Scripts run by the superuser -may thus need to do a \fIstat()\fR to determine the actual mode of the file, -or temporarily set their effective uid to something else. -.Sp -If you are using ACLs, there is a pragma called \f(CW\*(C`filetest\*(C'\fR that may -produce more accurate results than the bare \fIstat()\fR mode bits. -When under the \f(CW\*(C`use filetest 'access'\*(C'\fR the above-mentioned filetests -will test whether the permission can (not) be granted using the -\&\fIaccess()\fR family of system calls. Also note that the \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR may -under this pragma return true even if there are no execute permission -bits set (nor any extra execute permission ACLs). This strangeness is -due to the underlying system calls' definitions. Read the -documentation for the \f(CW\*(C`filetest\*(C'\fR pragma for more information. -.Sp -Note that \f(CW\*(C`\-s/a/b/\*(C'\fR does not do a negated substitution. Saying -\&\f(CW\*(C`\-exp($foo)\*(C'\fR still works as expected, however\*(--only single letters -following a minus are interpreted as file tests. -.Sp -The \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR switches work as follows. The first block or so of the -file is examined for odd characters such as strange control codes or -characters with the high bit set. If too many strange characters (>30%) -are found, it's a \f(CW\*(C`\-B\*(C'\fR file; otherwise it's a \f(CW\*(C`\-T\*(C'\fR file. Also, any file -containing null in the first block is considered a binary file. If \f(CW\*(C`\-T\*(C'\fR -or \f(CW\*(C`\-B\*(C'\fR is used on a filehandle, the current \s-1IO\s0 buffer is examined -rather than the first block. Both \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR return true on a null -file, or a file at \s-1EOF\s0 when testing a filehandle. Because you have to -read a file to do the \f(CW\*(C`\-T\*(C'\fR test, on most occasions you want to use a \f(CW\*(C`\-f\*(C'\fR -against the file first, as in \f(CW\*(C`next unless \-f $file && \-T $file\*(C'\fR. -.Sp -If any of the file tests (or either the \f(CW\*(C`stat\*(C'\fR or \f(CW\*(C`lstat\*(C'\fR operators) are given -the special filehandle consisting of a solitary underline, then the stat -structure of the previous file test (or stat operator) is used, saving -a system call. (This doesn't work with \f(CW\*(C`\-t\*(C'\fR, and you need to remember -that \fIlstat()\fR and \f(CW\*(C`\-l\*(C'\fR will leave values in the stat structure for the -symbolic link, not the real file.) (Also, if the stat buffer was filled by -an \f(CW\*(C`lstat\*(C'\fR call, \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR will reset it with the results of \f(CW\*(C`stat _\*(C'\fR). -Example: -.Sp -.Vb 1 -\& print "Can do.\en" if -r $a || -w _ || -x _; -.Ve -.Sp -.Vb 9 -\& stat($filename); -\& print "Readable\en" if -r _; -\& print "Writable\en" if -w _; -\& print "Executable\en" if -x _; -\& print "Setuid\en" if -u _; -\& print "Setgid\en" if -g _; -\& print "Sticky\en" if -k _; -\& print "Text\en" if -T _; -\& print "Binary\en" if -B _; -.Ve -.IP "abs \s-1VALUE\s0" 8 -.IX Xref "abs absolute" -.IX Item "abs VALUE" -.PD 0 -.IP "abs" 8 -.IX Item "abs" -.PD -Returns the absolute value of its argument. -If \s-1VALUE\s0 is omitted, uses \f(CW$_\fR. -.IP "accept \s-1NEWSOCKET\s0,GENERICSOCKET" 8 -.IX Xref "accept" -.IX Item "accept NEWSOCKET,GENERICSOCKET" -Accepts an incoming socket connect, just as the \fIaccept\fR\|(2) system call -does. Returns the packed address if it succeeded, false otherwise. -See the example in \*(L"Sockets: Client/Server Communication\*(R" in perlipc. -.Sp -On systems that support a close-on-exec flag on files, the flag will -be set for the newly opened file descriptor, as determined by the -value of $^F. See \*(L"$^F\*(R" in perlvar. -.IP "alarm \s-1SECONDS\s0" 8 -.IX Xref "alarm SIGALRM timer" -.IX Item "alarm SECONDS" -.PD 0 -.IP "alarm" 8 -.IX Item "alarm" -.PD -Arranges to have a \s-1SIGALRM\s0 delivered to this process after the -specified number of wallclock seconds has elapsed. If \s-1SECONDS\s0 is not -specified, the value stored in \f(CW$_\fR is used. (On some machines, -unfortunately, the elapsed time may be up to one second less or more -than you specified because of how seconds are counted, and process -scheduling may delay the delivery of the signal even further.) -.Sp -Only one timer may be counting at once. Each call disables the -previous timer, and an argument of \f(CW0\fR may be supplied to cancel the -previous timer without starting a new one. The returned value is the -amount of time remaining on the previous timer. -.Sp -For delays of finer granularity than one second, you may use Perl's -four-argument version of \fIselect()\fR leaving the first three arguments -undefined, or you might be able to use the \f(CW\*(C`syscall\*(C'\fR interface to -access \fIsetitimer\fR\|(2) if your system supports it. The Time::HiRes -module (from \s-1CPAN\s0, and starting from Perl 5.8 part of the standard -distribution) may also prove useful. -.Sp -It is usually a mistake to intermix \f(CW\*(C`alarm\*(C'\fR and \f(CW\*(C`sleep\*(C'\fR calls. -(\f(CW\*(C`sleep\*(C'\fR may be internally implemented in your system with \f(CW\*(C`alarm\*(C'\fR) -.Sp -If you want to use \f(CW\*(C`alarm\*(C'\fR to time out a system call you need to use an -\&\f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR pair. You can't rely on the alarm causing the system call to -fail with \f(CW$!\fR set to \f(CW\*(C`EINTR\*(C'\fR because Perl sets up signal handlers to -restart system calls on some systems. Using \f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR always works, -modulo the caveats given in \*(L"Signals\*(R" in perlipc. -.Sp -.Vb 13 -\& eval { -\& local $SIG{ALRM} = sub { die "alarm\en" }; # NB: \en required -\& alarm $timeout; -\& $nread = sysread SOCKET, $buffer, $size; -\& alarm 0; -\& }; -\& if ($@) { -\& die unless $@ eq "alarm\en"; # propagate unexpected errors -\& # timed out -\& } -\& else { -\& # didn't -\& } -.Ve -.Sp -For more information see perlipc. -.IP "atan2 Y,X" 8 -.IX Xref "atan2 arctangent tan tangent" -.IX Item "atan2 Y,X" -Returns the arctangent of Y/X in the range \-PI to \s-1PI\s0. -.Sp -For the tangent operation, you may use the \f(CW\*(C`Math::Trig::tan\*(C'\fR -function, or use the familiar relation: -.Sp -.Vb 1 -\& sub tan { sin($_[0]) / cos($_[0]) } -.Ve -.Sp -Note that atan2(0, 0) is not well\-defined. -.IP "bind \s-1SOCKET\s0,NAME" 8 -.IX Xref "bind" -.IX Item "bind SOCKET,NAME" -Binds a network address to a socket, just as the bind system call -does. Returns true if it succeeded, false otherwise. \s-1NAME\s0 should be a -packed address of the appropriate type for the socket. See the examples in -\&\*(L"Sockets: Client/Server Communication\*(R" in perlipc. -.IP "binmode \s-1FILEHANDLE\s0, \s-1LAYER\s0" 8 -.IX Xref "binmode binary text DOS Windows" -.IX Item "binmode FILEHANDLE, LAYER" -.PD 0 -.IP "binmode \s-1FILEHANDLE\s0" 8 -.IX Item "binmode FILEHANDLE" -.PD -Arranges for \s-1FILEHANDLE\s0 to be read or written in \*(L"binary\*(R" or \*(L"text\*(R" -mode on systems where the run-time libraries distinguish between -binary and text files. If \s-1FILEHANDLE\s0 is an expression, the value is -taken as the name of the filehandle. Returns true on success, -otherwise it returns \f(CW\*(C`undef\*(C'\fR and sets \f(CW$!\fR (errno). -.Sp -On some systems (in general, \s-1DOS\s0 and Windows-based systems) \fIbinmode()\fR -is necessary when you're not working with a text file. For the sake -of portability it is a good idea to always use it when appropriate, -and to never use it when it isn't appropriate. Also, people can -set their I/O to be by default \s-1UTF\-8\s0 encoded Unicode, not bytes. -.Sp -In other words: regardless of platform, use \fIbinmode()\fR on binary data, -like for example images. -.Sp -If \s-1LAYER\s0 is present it is a single string, but may contain multiple -directives. The directives alter the behaviour of the file handle. -When \s-1LAYER\s0 is present using binmode on text file makes sense. -.Sp -If \s-1LAYER\s0 is omitted or specified as \f(CW\*(C`:raw\*(C'\fR the filehandle is made -suitable for passing binary data. This includes turning off possible \s-1CRLF\s0 -translation and marking it as bytes (as opposed to Unicode characters). -Note that, despite what may be implied in \fI\*(L"Programming Perl\*(R"\fR (the -Camel) or elsewhere, \f(CW\*(C`:raw\*(C'\fR is \fInot\fR the simply inverse of \f(CW\*(C`:crlf\*(C'\fR -\&\*(-- other layers which would affect binary nature of the stream are -\&\fIalso\fR disabled. See PerlIO, perlrun and the discussion about the -\&\s-1PERLIO\s0 environment variable. -.Sp -The \f(CW\*(C`:bytes\*(C'\fR, \f(CW\*(C`:crlf\*(C'\fR, and \f(CW\*(C`:utf8\*(C'\fR, and any other directives of the -form \f(CW\*(C`:...\*(C'\fR, are called I/O \fIlayers\fR. The \f(CW\*(C`open\*(C'\fR pragma can be used to -establish default I/O layers. See open. -.Sp -\&\fIThe \s-1LAYER\s0 parameter of the \fIbinmode()\fI function is described as \*(L"\s-1DISCIPLINE\s0\*(R" -in \*(L"Programming Perl, 3rd Edition\*(R". However, since the publishing of this -book, by many known as \*(L"Camel \s-1III\s0\*(R", the consensus of the naming of this -functionality has moved from \*(L"discipline\*(R" to \*(L"layer\*(R". All documentation -of this version of Perl therefore refers to \*(L"layers\*(R" rather than to -\&\*(L"disciplines\*(R". Now back to the regularly scheduled documentation...\fR -.Sp -To mark \s-1FILEHANDLE\s0 as \s-1UTF\-8\s0, use \f(CW\*(C`:utf8\*(C'\fR. -.Sp -In general, \fIbinmode()\fR should be called after \fIopen()\fR but before any I/O -is done on the filehandle. Calling \fIbinmode()\fR will normally flush any -pending buffered output data (and perhaps pending input data) on the -handle. An exception to this is the \f(CW\*(C`:encoding\*(C'\fR layer that -changes the default character encoding of the handle, see open. -The \f(CW\*(C`:encoding\*(C'\fR layer sometimes needs to be called in -mid\-stream, and it doesn't flush the stream. The \f(CW\*(C`:encoding\*(C'\fR -also implicitly pushes on top of itself the \f(CW\*(C`:utf8\*(C'\fR layer because -internally Perl will operate on \s-1UTF\-8\s0 encoded Unicode characters. -.Sp -The operating system, device drivers, C libraries, and Perl run-time -system all work together to let the programmer treat a single -character (\f(CW\*(C`\en\*(C'\fR) as the line terminator, irrespective of the external -representation. On many operating systems, the native text file -representation matches the internal representation, but on some -platforms the external representation of \f(CW\*(C`\en\*(C'\fR is made up of more than -one character. -.Sp -Mac \s-1OS\s0, all variants of Unix, and Stream_LF files on \s-1VMS\s0 use a single -character to end each line in the external representation of text (even -though that single character is \s-1CARRIAGE\s0 \s-1RETURN\s0 on Mac \s-1OS\s0 and \s-1LINE\s0 \s-1FEED\s0 -on Unix and most \s-1VMS\s0 files). In other systems like \s-1OS/2\s0, \s-1DOS\s0 and the -various flavors of MS-Windows your program sees a \f(CW\*(C`\en\*(C'\fR as a simple \f(CW\*(C`\ecJ\*(C'\fR, -but what's stored in text files are the two characters \f(CW\*(C`\ecM\ecJ\*(C'\fR. That -means that, if you don't use \fIbinmode()\fR on these systems, \f(CW\*(C`\ecM\ecJ\*(C'\fR -sequences on disk will be converted to \f(CW\*(C`\en\*(C'\fR on input, and any \f(CW\*(C`\en\*(C'\fR in -your program will be converted back to \f(CW\*(C`\ecM\ecJ\*(C'\fR on output. This is what -you want for text files, but it can be disastrous for binary files. -.Sp -Another consequence of using \fIbinmode()\fR (on some systems) is that -special end-of-file markers will be seen as part of the data stream. -For systems from the Microsoft family this means that if your binary -data contains \f(CW\*(C`\ecZ\*(C'\fR, the I/O subsystem will regard it as the end of -the file, unless you use \fIbinmode()\fR. -.Sp -\&\fIbinmode()\fR is not only important for \fIreadline()\fR and \fIprint()\fR operations, -but also when using \fIread()\fR, \fIseek()\fR, \fIsysread()\fR, \fIsyswrite()\fR and \fItell()\fR -(see perlport for more details). See the \f(CW$/\fR and \f(CW\*(C`$\e\*(C'\fR variables -in perlvar for how to manually set your input and output -line-termination sequences. -.IP "bless \s-1REF\s0,CLASSNAME" 8 -.IX Xref "bless" -.IX Item "bless REF,CLASSNAME" -.PD 0 -.IP "bless \s-1REF\s0" 8 -.IX Item "bless REF" -.PD -This function tells the thingy referenced by \s-1REF\s0 that it is now an object -in the \s-1CLASSNAME\s0 package. If \s-1CLASSNAME\s0 is omitted, the current package -is used. Because a \f(CW\*(C`bless\*(C'\fR is often the last thing in a constructor, -it returns the reference for convenience. Always use the two-argument -version if a derived class might inherit the function doing the blessing. -See perltoot and perlobj for more about the blessing (and blessings) -of objects. -.Sp -Consider always blessing objects in CLASSNAMEs that are mixed case. -Namespaces with all lowercase names are considered reserved for -Perl pragmata. Builtin types have all uppercase names. To prevent -confusion, you may wish to avoid such package names as well. Make sure -that \s-1CLASSNAME\s0 is a true value. -.Sp -See \*(L"Perl Modules\*(R" in perlmod. -.IP "caller \s-1EXPR\s0" 8 -.IX Xref "caller call stack stack stack trace" -.IX Item "caller EXPR" -.PD 0 -.IP "caller" 8 -.IX Item "caller" -.PD -Returns the context of the current subroutine call. In scalar context, -returns the caller's package name if there is a caller, that is, if -we're in a subroutine or \f(CW\*(C`eval\*(C'\fR or \f(CW\*(C`require\*(C'\fR, and the undefined value -otherwise. In list context, returns -.Sp -.Vb 1 -\& ($package, $filename, $line) = caller; -.Ve -.Sp -With \s-1EXPR\s0, it returns some extra information that the debugger uses to -print a stack trace. The value of \s-1EXPR\s0 indicates how many call frames -to go back before the current one. -.Sp -.Vb 2 -\& ($package, $filename, $line, $subroutine, $hasargs, -\& $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller($i); -.Ve -.Sp -Here \f(CW$subroutine\fR may be \f(CW\*(C`(eval)\*(C'\fR if the frame is not a subroutine -call, but an \f(CW\*(C`eval\*(C'\fR. In such a case additional elements \f(CW$evaltext\fR and -\&\f(CW$is_require\fR are set: \f(CW$is_require\fR is true if the frame is created by a -\&\f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR statement, \f(CW$evaltext\fR contains the text of the -\&\f(CW\*(C`eval EXPR\*(C'\fR statement. In particular, for an \f(CW\*(C`eval BLOCK\*(C'\fR statement, -\&\f(CW$filename\fR is \f(CW\*(C`(eval)\*(C'\fR, but \f(CW$evaltext\fR is undefined. (Note also that -each \f(CW\*(C`use\*(C'\fR statement creates a \f(CW\*(C`require\*(C'\fR frame inside an \f(CW\*(C`eval EXPR\*(C'\fR -frame.) \f(CW$subroutine\fR may also be \f(CW\*(C`(unknown)\*(C'\fR if this particular -subroutine happens to have been deleted from the symbol table. -\&\f(CW$hasargs\fR is true if a new instance of \f(CW@_\fR was set up for the frame. -\&\f(CW$hints\fR and \f(CW$bitmask\fR contain pragmatic hints that the caller was -compiled with. The \f(CW$hints\fR and \f(CW$bitmask\fR values are subject to change -between versions of Perl, and are not meant for external use. -.Sp -Furthermore, when called from within the \s-1DB\s0 package, caller returns more -detailed information: it sets the list variable \f(CW@DB::args\fR to be the -arguments with which the subroutine was invoked. -.Sp -Be aware that the optimizer might have optimized call frames away before -\&\f(CW\*(C`caller\*(C'\fR had a chance to get the information. That means that \f(CWcaller(N)\fR -might not return information about the call frame you expect it do, for -\&\f(CW\*(C`N > 1\*(C'\fR. In particular, \f(CW@DB::args\fR might have information from the -previous time \f(CW\*(C`caller\*(C'\fR was called. -.IP "chdir \s-1EXPR\s0" 8 -.IX Xref "chdir cd" -.IX Item "chdir EXPR" -.PD 0 -.IP "chdir \s-1FILEHANDLE\s0" 8 -.IX Item "chdir FILEHANDLE" -.IP "chdir \s-1DIRHANDLE\s0" 8 -.IX Item "chdir DIRHANDLE" -.IP "chdir" 8 -.IX Item "chdir" -.PD -Changes the working directory to \s-1EXPR\s0, if possible. If \s-1EXPR\s0 is omitted, -changes to the directory specified by \f(CW$ENV{HOME}\fR, if set; if not, -changes to the directory specified by \f(CW$ENV{LOGDIR}\fR. (Under \s-1VMS\s0, the -variable \f(CW$ENV{SYS$LOGIN}\fR is also checked, and used if it is set.) If -neither is set, \f(CW\*(C`chdir\*(C'\fR does nothing. It returns true upon success, -false otherwise. See the example under \f(CW\*(C`die\*(C'\fR. -.Sp -On systems that support fchdir, you might pass a file handle or -directory handle as argument. On systems that don't support fchdir, -passing handles produces a fatal error at run time. -.IP "chmod \s-1LIST\s0" 8 -.IX Xref "chmod permission mode" -.IX Item "chmod LIST" -Changes the permissions of a list of files. The first element of the -list must be the numerical mode, which should probably be an octal -number, and which definitely should \fInot\fR be a string of octal digits: -\&\f(CW0644\fR is okay, \f(CW'0644'\fR is not. Returns the number of files -successfully changed. See also \*(L"oct\*(R", if all you have is a string. -.Sp -.Vb 6 -\& $cnt = chmod 0755, 'foo', 'bar'; -\& chmod 0755, @executables; -\& $mode = '0644'; chmod $mode, 'foo'; # !!! sets mode to -\& # --w----r-T -\& $mode = '0644'; chmod oct($mode), 'foo'; # this is better -\& $mode = 0644; chmod $mode, 'foo'; # this is best -.Ve -.Sp -On systems that support fchmod, you might pass file handles among the -files. On systems that don't support fchmod, passing file handles -produces a fatal error at run time. -.Sp -.Vb 3 -\& open(my $fh, "<", "foo"); -\& my $perm = (stat $fh)[2] & 07777; -\& chmod($perm | 0600, $fh); -.Ve -.Sp -You can also import the symbolic \f(CW\*(C`S_I*\*(C'\fR constants from the Fcntl -module: -.Sp -.Vb 1 -\& use Fcntl ':mode'; -.Ve -.Sp -.Vb 2 -\& chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; -\& # This is identical to the chmod 0755 of the above example. -.Ve -.IP "chomp \s-1VARIABLE\s0" 8 -.IX Xref "chomp INPUT_RECORD_SEPARATOR $ newline eol" -.IX Item "chomp VARIABLE" -.PD 0 -.IP "chomp( \s-1LIST\s0 )" 8 -.IX Item "chomp( LIST )" -.IP "chomp" 8 -.IX Item "chomp" -.PD -This safer version of \*(L"chop\*(R" removes any trailing string -that corresponds to the current value of \f(CW$/\fR (also known as -\&\f(CW$INPUT_RECORD_SEPARATOR\fR in the \f(CW\*(C`English\*(C'\fR module). It returns the total -number of characters removed from all its arguments. It's often used to -remove the newline from the end of an input record when you're worried -that the final record may be missing its newline. When in paragraph -mode (\f(CW\*(C`$/ = ""\*(C'\fR), it removes all trailing newlines from the string. -When in slurp mode (\f(CW\*(C`$/ = undef\*(C'\fR) or fixed-length record mode (\f(CW$/\fR is -a reference to an integer or the like, see perlvar) \fIchomp()\fR won't -remove anything. -If \s-1VARIABLE\s0 is omitted, it chomps \f(CW$_\fR. Example: -.Sp -.Vb 5 -\& while (<>) { -\& chomp; # avoid \en on last field -\& @array = split(/:/); -\& # ... -\& } -.Ve -.Sp -If \s-1VARIABLE\s0 is a hash, it chomps the hash's values, but not its keys. -.Sp - diff --git a/third_party/pygments/tests/examplefiles/phpMyAdmin.spec b/third_party/pygments/tests/examplefiles/phpMyAdmin.spec deleted file mode 100644 index 120fbc923..000000000 --- a/third_party/pygments/tests/examplefiles/phpMyAdmin.spec +++ /dev/null @@ -1,163 +0,0 @@ -%define _myadminpath /var/www/myadmin -%define pkgrelease rc1 -%define microrelease 1 - -Name: phpMyAdmin -Version: 3.1.1 -Release: %{pkgrelease}.%{microrelease} -License: GPL -Group: Applications/Databases/Interfaces -Source0: http://prdownloads.sourceforge.net/phpmyadmin/%{name}-%{version}-%{pkgrelease}.tar.bz2 -Source1: phpMyAdmin-http.conf -URL: http://sourceforge.net/projects/phpmyadmin/ -Requires: mysql -Requires: php-mysql -Buildarch: noarch -#BuildRoot: %{_tmppath}/%{name}-root - -Summary: phpMyAdmin - web-based MySQL administration - -%description -phpMyAdmin can manage a whole MySQL-server (needs a super-user) but -also a single database. To accomplish the latter you'll need a -properly set up MySQL-user which can read/write only the desired -database. It's up to you to look up the appropiate part in the MySQL -manual. Currently phpMyAdmin can: - - create and drop databases - - create, copy, drop and alter tables - - delete, edit and add fields - - execute any SQL-statement, even batch-queries - - manage keys on fields - - load text files into tables - - create (*) and read dumps of tables - - export (*) and import data to CSV values - - administer multiple servers and single databases - - check referencial integrity - - create complex queries automatically connecting required tables - - create PDF graphics of your database layout - - communicate in more than 38 different languages - - -%prep -%setup -q -n %{name}-%{version}-%{pkgrelease} - - -%build - - -%install -[ "${RPM_BUILD_ROOT}" != "/" ] && [ -d "${RPM_BUILD_ROOT}" ] && \ - rm -rf "${RPM_BUILD_ROOT}" - -# Create directories. - -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/{css,js,lang,libraries,themes} -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/{auth,dbg,dbi,engines} -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/{export,tcpdf,import} -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/transformations -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/tcpdf/font -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/{darkblue_orange,original} -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/darkblue_orange/{css,img} -install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/original/{css,img} - -# Install files. - -install libraries/config.default.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}"/config.inc.php -install *.{php,ico} "${RPM_BUILD_ROOT}%{_myadminpath}"/ -install ChangeLog LICENSE README "${RPM_BUILD_ROOT}%{_myadminpath}"/ -install Documentation.html docs.css "${RPM_BUILD_ROOT}%{_myadminpath}"/ -install css/* "${RPM_BUILD_ROOT}%{_myadminpath}/css"/ -install js/* "${RPM_BUILD_ROOT}%{_myadminpath}/js"/ -install lang/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/lang"/ -install libraries/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries"/ -install libraries/auth/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/auth"/ -install libraries/dbg/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/dbg"/ -install libraries/dbi/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/dbi"/ -install libraries/engines/*.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/engines"/ -install libraries/export/*.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/export"/ -install libraries/tcpdf/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/tcpdf"/ -install libraries/tcpdf/font/*.{php,z} \ - "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/tcpdf/font"/ -install libraries/import/*.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/import"/ -install libraries/transformations/*.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/transformations"/ -install themes/darkblue_orange/*.{php,png} \ - "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange"/ -install themes/darkblue_orange/css/*.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange/css"/ -install themes/darkblue_orange/img/*.{png,ico} \ - "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange/img"/ -install themes/original/*.{php,png} \ - "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original"/ -install themes/original/css/*.php \ - "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original/css"/ -install themes/original/img/*.{png,ico} \ - "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original/img"/ - -# Create documentation directories. - -DOCROOT="${RPM_BUILD_ROOT}%{_docdir}/%{name}-%{version}" -install -d "${DOCROOT}" -install -d "${DOCROOT}"/{lang,scripts,transformations} - -# Install documentation files. - -install RELEASE-DATE-* "${DOCROOT}"/ -install CREDITS ChangeLog INSTALL LICENSE "${DOCROOT}"/ -install README TODO "${DOCROOT}"/ -install Documentation.* docs.css "${DOCROOT}"/ -install translators.html "${DOCROOT}"/ -install lang/*.sh "${DOCROOT}"/lang/ -install scripts/* "${DOCROOT}"/scripts/ -install libraries/tcpdf/README "${DOCROOT}"/README.tcpdf -install libraries/import/README "${DOCROOT}"/README.import -install libraries/transformations/README "${DOCROOT}"/transformations/ -install libraries/transformations/TEMPLATE* "${DOCROOT}"/transformations/ -install libraries/transformations/*.sh "${DOCROOT}"/transformations/ - -# Install configuration file for Apache. - -install -d "${RPM_BUILD_ROOT}%{_sysconfdir}/httpd/conf.d" -install "%{SOURCE1}" \ - "${RPM_BUILD_ROOT}%{_sysconfdir}/httpd/conf.d/phpMyAdmin.conf" - -# Generate non-configuration file list. - -(cd "${RPM_BUILD_ROOT}"; ls -d ."%{_myadminpath}"/*) | - sed -e '/\/config\.inc\.php$/d' -e 's/^.//' > files.list - - - -%clean -[ "${RPM_BUILD_ROOT}" != "/" ] && [ -d "${RPM_BUILD_ROOT}" ] && \ - rm -rf "${RPM_BUILD_ROOT}" - - -%files -f files.list -%defattr(644, root, root, 755) -%doc %{_docdir}/%{name}-%{version} -%dir %{_myadminpath} -%attr(640,root,apache) %config(noreplace) %verify(not size mtime md5) %{_myadminpath}/config.inc.php -%config(noreplace) %verify(not size mtime md5) %{_sysconfdir}/httpd/conf.d/* - - -%changelog -* Thu Feb 23 2006 Patrick Monnerat -- Version 2.8.0-rc1.1. - -* Thu Dec 22 2005 Patrick Monnerat -- Path "nullpw" to allow trying connection with null password after failure. -- Version 2.7.0-pl1.1. - -* Mon Aug 22 2005 Patrick Monnerat -- Version 2.6.3-pl1. - -* Wed Jul 21 2004 Patrick Monnerat -- Version 2.5.7-pl1. - -* Fri Nov 22 2002 Patrick Monnerat -- Version 2.3.0-rc1. diff --git a/third_party/pygments/tests/examplefiles/phpcomplete.vim b/third_party/pygments/tests/examplefiles/phpcomplete.vim deleted file mode 100644 index 17d74fd82..000000000 --- a/third_party/pygments/tests/examplefiles/phpcomplete.vim +++ /dev/null @@ -1,567 +0,0 @@ -" Vim completion script -" Language: PHP -" Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl ) -" Last Change: 2006 May 9 -" -" TODO: -" - Class aware completion: -" a) caching? -" - Switching to HTML (XML?) completion (SQL) inside of phpStrings -" - allow also for XML completion <- better do html_flavor for HTML -" completion -" - outside of getting parent tag may cause problems. Heh, even in -" perfect conditions GetLastOpenTag doesn't cooperate... Inside of -" phpStrings this can be even a bonus but outside of it is not the -" best situation - -function! phpcomplete#CompletePHP(findstart, base) - if a:findstart - unlet! b:php_menu - " Check if we are inside of PHP markup - let pos = getpos('.') - let phpbegin = searchpairpos('', 'bWn', - \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string\|comment"') - let phpend = searchpairpos('', 'Wn', - \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string\|comment"') - - if phpbegin == [0,0] && phpend == [0,0] - " We are outside of any PHP markup. Complete HTML - let htmlbegin = htmlcomplete#CompleteTags(1, '') - let cursor_col = pos[2] - let base = getline('.')[htmlbegin : cursor_col] - let b:php_menu = htmlcomplete#CompleteTags(0, base) - return htmlbegin - else - " locate the start of the word - let line = getline('.') - let start = col('.') - 1 - let curline = line('.') - let compl_begin = col('.') - 2 - while start >= 0 && line[start - 1] =~ '[a-zA-Z_0-9\x7f-\xff$]' - let start -= 1 - endwhile - let b:compl_context = getline('.')[0:compl_begin] - return start - - " We can be also inside of phpString with HTML tags. Deal with - " it later (time, not lines). - endif - - endif - " If exists b:php_menu it means completion was already constructed we - " don't need to do anything more - if exists("b:php_menu") - return b:php_menu - endif - " Initialize base return lists - let res = [] - let res2 = [] - " a:base is very short - we need context - if exists("b:compl_context") - let context = b:compl_context - unlet! b:compl_context - endif - - if !exists('g:php_builtin_functions') - call phpcomplete#LoadData() - endif - - let scontext = substitute(context, '\$\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*$', '', '') - - if scontext =~ '\(=\s*new\|extends\)\s\+$' - " Complete class name - " Internal solution for finding classes in current file. - let file = getline(1, '$') - call filter(file, - \ 'v:val =~ "class\\s\\+[a-zA-Z_\\x7f-\\xff][a-zA-Z_0-9\\x7f-\\xff]*\\s*("') - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - let jfile = join(file, ' ') - let int_values = split(jfile, 'class\s\+') - let int_classes = {} - for i in int_values - let c_name = matchstr(i, '^[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*') - if c_name != '' - let int_classes[c_name] = '' - endif - endfor - - " Prepare list of classes from tags file - let ext_classes = {} - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - if fnames != '' - exe 'silent! vimgrep /^'.a:base.'.*\tc\(\t\|$\)/j '.fnames - let qflist = getqflist() - if len(qflist) > 0 - for field in qflist - " [:space:] thing: we don't have to be so strict when - " dealing with tags files - entries there were already - " checked by ctags. - let item = matchstr(field['text'], '^[^[:space:]]\+') - let ext_classes[item] = '' - endfor - endif - endif - - " Prepare list of built in classes from g:php_builtin_functions - if !exists("g:php_omni_bi_classes") - let g:php_omni_bi_classes = {} - for i in keys(g:php_builtin_object_functions) - let g:php_omni_bi_classes[substitute(i, '::.*$', '', '')] = '' - endfor - endif - - let classes = sort(keys(int_classes)) - let classes += sort(keys(ext_classes)) - let classes += sort(keys(g:php_omni_bi_classes)) - - for m in classes - if m =~ '^'.a:base - call add(res, m) - endif - endfor - - let final_menu = [] - for i in res - let final_menu += [{'word':i, 'kind':'c'}] - endfor - - return final_menu - - elseif scontext =~ '\(->\|::\)$' - " Complete user functions and variables - " Internal solution for current file. - " That seems as unnecessary repeating of functions but there are - " few not so subtle differences as not appending of $ and addition - " of 'kind' tag (not necessary in regular completion) - - if scontext =~ '->$' && scontext !~ '\$this->$' - - " Get name of the class - let classname = phpcomplete#GetClassName(scontext) - - " Get location of class definition, we have to iterate through all - " tags files separately because we need relative path from current - " file to the exact file (tags file can be in different dir) - if classname != '' - let classlocation = phpcomplete#GetClassLocation(classname) - else - let classlocation = '' - endif - - if classlocation == 'VIMPHP_BUILTINOBJECT' - - for object in keys(g:php_builtin_object_functions) - if object =~ '^'.classname - let res += [{'word':substitute(object, '.*::', '', ''), - \ 'info': g:php_builtin_object_functions[object]}] - endif - endfor - - return res - - endif - - if filereadable(classlocation) - let classfile = readfile(classlocation) - let classcontent = '' - let classcontent .= "\n".phpcomplete#GetClassContents(classfile, classname) - let sccontent = split(classcontent, "\n") - - " YES, YES, YES! - we have whole content including extends! - " Now we need to get two elements: public functions and public - " vars - " NO, NO, NO! - third separate filtering looking for content - " :(, but all of them have differences. To squeeze them into - " one implementation would require many additional arguments - " and ifs. No good solution - " Functions declared with public keyword or without any - " keyword are public - let functions = filter(deepcopy(sccontent), - \ 'v:val =~ "^\\s*\\(static\\s\\+\\|public\\s\\+\\)*function"') - let jfuncs = join(functions, ' ') - let sfuncs = split(jfuncs, 'function\s\+') - let c_functions = {} - for i in sfuncs - let f_name = matchstr(i, - \ '^&\?\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') - let f_args = matchstr(i, - \ '^&\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*(\zs.\{-}\ze)\_s*{') - if f_name != '' - let c_functions[f_name.'('] = f_args - endif - endfor - " Variables declared with var or with public keyword are - " public - let variables = filter(deepcopy(sccontent), - \ 'v:val =~ "^\\s*\\(public\\|var\\)\\s\\+\\$"') - let jvars = join(variables, ' ') - let svars = split(jvars, '\$') - let c_variables = {} - for i in svars - let c_var = matchstr(i, - \ '^\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') - if c_var != '' - let c_variables[c_var] = '' - endif - endfor - - let all_values = {} - call extend(all_values, c_functions) - call extend(all_values, c_variables) - - for m in sort(keys(all_values)) - if m =~ '^'.a:base && m !~ '::' - call add(res, m) - elseif m =~ '::'.a:base - call add(res2, m) - endif - endfor - - let start_list = res + res2 - - let final_list = [] - for i in start_list - if has_key(c_variables, i) - let class = ' ' - if all_values[i] != '' - let class = i.' class ' - endif - let final_list += - \ [{'word':i, - \ 'info':class.all_values[i], - \ 'kind':'v'}] - else - let final_list += - \ [{'word':substitute(i, '.*::', '', ''), - \ 'info':i.all_values[i].')', - \ 'kind':'f'}] - endif - endfor - - return final_list - - endif - - endif - - if a:base =~ '^\$' - let adddollar = '$' - else - let adddollar = '' - endif - let file = getline(1, '$') - let jfile = join(file, ' ') - let sfile = split(jfile, '\$') - let int_vars = {} - for i in sfile - if i =~ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*=\s*new' - let val = matchstr(i, '^[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*').'->' - else - let val = matchstr(i, '^[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*') - endif - if val !~ '' - let int_vars[adddollar.val] = '' - endif - endfor - - " ctags has good support for PHP, use tags file for external - " variables - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - let ext_vars = {} - if fnames != '' - let sbase = substitute(a:base, '^\$', '', '') - exe 'silent! vimgrep /^'.sbase.'.*\tv\(\t\|$\)/j '.fnames - let qflist = getqflist() - if len(qflist) > 0 - for field in qflist - let item = matchstr(field['text'], '^[^[:space:]]\+') - " Add -> if it is possible object declaration - let classname = '' - if field['text'] =~ item.'\s*=\s*new\s\+' - let item = item.'->' - let classname = matchstr(field['text'], - \ '=\s*new\s\+\zs[a-zA-Z_0-9\x7f-\xff]\+\ze') - endif - let ext_vars[adddollar.item] = classname - endfor - endif - endif - - " Now we have all variables in int_vars dictionary - call extend(int_vars, ext_vars) - - " Internal solution for finding functions in current file. - let file = getline(1, '$') - call filter(file, - \ 'v:val =~ "function\\s\\+&\\?[a-zA-Z_\\x7f-\\xff][a-zA-Z_0-9\\x7f-\\xff]*\\s*("') - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - let jfile = join(file, ' ') - let int_values = split(jfile, 'function\s\+') - let int_functions = {} - for i in int_values - let f_name = matchstr(i, - \ '^&\?\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') - let f_args = matchstr(i, - \ '^&\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*(\zs.\{-}\ze)\_s*{') - let int_functions[f_name.'('] = f_args.')' - endfor - - " Prepare list of functions from tags file - let ext_functions = {} - if fnames != '' - exe 'silent! vimgrep /^'.a:base.'.*\tf\(\t\|$\)/j '.fnames - let qflist = getqflist() - if len(qflist) > 0 - for field in qflist - " File name - let item = matchstr(field['text'], '^[^[:space:]]\+') - let fname = matchstr(field['text'], '\t\zs\f\+\ze') - let prototype = matchstr(field['text'], - \ 'function\s\+&\?[^[:space:]]\+\s*(\s*\zs.\{-}\ze\s*)\s*{\?') - let ext_functions[item.'('] = prototype.') - '.fname - endfor - endif - endif - - let all_values = {} - call extend(all_values, int_functions) - call extend(all_values, ext_functions) - call extend(all_values, int_vars) " external variables are already in - call extend(all_values, g:php_builtin_object_functions) - - for m in sort(keys(all_values)) - if m =~ '\(^\|::\)'.a:base - call add(res, m) - endif - endfor - - let start_list = res - - let final_list = [] - for i in start_list - if has_key(int_vars, i) - let class = ' ' - if all_values[i] != '' - let class = i.' class ' - endif - let final_list += [{'word':i, 'info':class.all_values[i], 'kind':'v'}] - else - let final_list += - \ [{'word':substitute(i, '.*::', '', ''), - \ 'info':i.all_values[i], - \ 'kind':'f'}] - endif - endfor - - return final_list - endif - - if a:base =~ '^\$' - " Complete variables - " Built-in variables {{{ - let g:php_builtin_vars = {'$GLOBALS':'', - \ '$_SERVER':'', - \ '$_GET':'', - \ '$_POST':'', - \ '$_COOKIE':'', - \ '$_FILES':'', - \ '$_ENV':'', - \ '$_REQUEST':'', - \ '$_SESSION':'', - \ '$HTTP_SERVER_VARS':'', - \ '$HTTP_ENV_VARS':'', - \ '$HTTP_COOKIE_VARS':'', - \ '$HTTP_GET_VARS':'', - \ '$HTTP_POST_VARS':'', - \ '$HTTP_POST_FILES':'', - \ '$HTTP_SESSION_VARS':'', - \ '$php_errormsg':'', - \ '$this':'' - \ } - " }}} - - " Internal solution for current file. - let file = getline(1, '$') - let jfile = join(file, ' ') - let int_vals = split(jfile, '\ze\$') - let int_vars = {} - for i in int_vals - if i =~ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*=\s*new' - let val = matchstr(i, - \ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*').'->' - else - let val = matchstr(i, - \ '^\$[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*') - endif - if val != '' - let int_vars[val] = '' - endif - endfor - - call extend(int_vars,g:php_builtin_vars) - - " ctags has support for PHP, use tags file for external variables - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - let ext_vars = {} - if fnames != '' - let sbase = substitute(a:base, '^\$', '', '') - exe 'silent! vimgrep /^'.sbase.'.*\tv\(\t\|$\)/j '.fnames - let qflist = getqflist() - if len(qflist) > 0 - for field in qflist - let item = '$'.matchstr(field['text'], '^[^[:space:]]\+') - let m_menu = '' - " Add -> if it is possible object declaration - if field['text'] =~ item.'\s*=\s*new\s\+' - let item = item.'->' - let m_menu = matchstr(field['text'], - \ '=\s*new\s\+\zs[a-zA-Z_0-9\x7f-\xff]\+\ze') - endif - let ext_vars[item] = m_menu - endfor - endif - endif - - call extend(int_vars, ext_vars) - let g:a0 = keys(int_vars) - - for m in sort(keys(int_vars)) - if m =~ '^\'.a:base - call add(res, m) - endif - endfor - - let int_list = res - - let int_dict = [] - for i in int_list - if int_vars[i] != '' - let class = ' ' - if int_vars[i] != '' - let class = i.' class ' - endif - let int_dict += [{'word':i, 'info':class.int_vars[i], 'kind':'v'}] - else - let int_dict += [{'word':i, 'kind':'v'}] - endif - endfor - - return int_dict - - else - " Complete everything else - - " + functions, DONE - " + keywords of language DONE - " + defines (constant definitions), DONE - " + extend keywords for predefined constants, DONE - " + classes (after new), DONE - " + limit choice after -> and :: to funcs and vars DONE - - " Internal solution for finding functions in current file. - let file = getline(1, '$') - call filter(file, - \ 'v:val =~ "function\\s\\+&\\?[a-zA-Z_\\x7f-\\xff][a-zA-Z_0-9\\x7f-\\xff]*\\s*("') - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - let jfile = join(file, ' ') - let int_values = split(jfile, 'function\s\+') - let int_functions = {} - for i in int_values - let f_name = matchstr(i, - \ '^&\?\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze') - let f_args = matchstr(i, - \ '^&\?[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\s*(\s*\zs.\{-}\ze\s*)\_s*{') - let int_functions[f_name.'('] = f_args.')' - endfor - - " Prepare list of functions from tags file - let ext_functions = {} - if fnames != '' - exe 'silent! vimgrep /^'.a:base.'.*\tf\(\t\|$\)/j '.fnames - let qflist = getqflist() - if len(qflist) > 0 - for field in qflist - " File name - let item = matchstr(field['text'], '^[^[:space:]]\+') - let fname = matchstr(field['text'], '\t\zs\f\+\ze') - let prototype = matchstr(field['text'], - \ 'function\s\+&\?[^[:space:]]\+\s*(\s*\zs.\{-}\ze\s*)\s*{\?') - let ext_functions[item.'('] = prototype.') - '.fname - endfor - endif - endif - - " All functions - call extend(int_functions, ext_functions) - call extend(int_functions, g:php_builtin_functions) - - " Internal solution for finding constants in current file - let file = getline(1, '$') - call filter(file, 'v:val =~ "define\\s*("') - let jfile = join(file, ' ') - let int_values = split(jfile, 'define\s*(\s*') - let int_constants = {} - for i in int_values - let c_name = matchstr(i, '\(["'']\)\zs[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\ze\1') - " let c_value = matchstr(i, - " \ '\(["'']\)[a-zA-Z_\x7f-\xff][a-zA-Z_0-9\x7f-\xff]*\1\s*,\s*\zs.\{-}\ze\s*)') - if c_name != '' - let int_constants[c_name] = '' " c_value - endif - endfor - - " Prepare list of constants from tags file - let fnames = join(map(tagfiles(), 'escape(v:val, " \\#%")')) - let ext_constants = {} - if fnames != '' - exe 'silent! vimgrep /^'.a:base.'.*\td\(\t\|$\)/j '.fnames - let qflist = getqflist() - if len(qflist) > 0 - for field in qflist - let item = matchstr(field['text'], '^[^[:space:]]\+') - let ext_constants[item] = '' - endfor - endif - endif - - " All constants - call extend(int_constants, ext_constants) - " Treat keywords as constants - - let all_values = {} - - " One big dictionary of functions - call extend(all_values, int_functions) - - " Add constants - call extend(all_values, int_constants) - " Add keywords - call extend(all_values, g:php_keywords) - - for m in sort(keys(all_values)) - if m =~ '^'.a:base - call add(res, m) - endif - endfor - - let int_list = res - - let final_list = [] - for i in int_list - if has_key(int_functions, i) - let final_list += - \ [{'word':i, - \ 'info':i.int_functions[i], - \ 'kind':'f'}] - elseif has_key(int_constants, i) - let final_list += [{'word':i, 'kind':'d'}] - else - let final_list += [{'word':i}] - endif - endfor - - return final_list - - endif - -endfunction -" vim:set foldmethod=marker: diff --git a/third_party/pygments/tests/examplefiles/pkgconfig_example.pc b/third_party/pygments/tests/examplefiles/pkgconfig_example.pc deleted file mode 100644 index 2a59204ef..000000000 --- a/third_party/pygments/tests/examplefiles/pkgconfig_example.pc +++ /dev/null @@ -1,18 +0,0 @@ -# This is for a fictional package `yet another portable hatchpotch generator'. -prefix=/usr/local/opt/site/private # define variable `prefix` -exec_prefix=${prefix} # using variable reference -libdir=${exec_prefix}/lib -includedir=${prefix}/include -just_for_test=$${this is not a part of variable reference} # escape with `$$` - -Name: YAPHatchPotchGen -Description: Yet Another Portable HatchPotch GENerator. -Version: 352.9.3 -URL: http://www9.yaphatchpotchgen.net # Don't access. -Requires: piyohogelib-9.0 = 9.5.3 -Requires.private: nyorolib-3.0 = 3.0.9 -Conflicts: apiyohoge <= 8.3 -Libs: -L${libdir} -lyaphatchpotchgen-352.9 # using variable reference -Libs.private: -ll -ly -Cflags: -I${includedir}/piyohogelib-9.0 -I${libdir}/yaphatchpotchgen/include - diff --git a/third_party/pygments/tests/examplefiles/pleac.in.rb b/third_party/pygments/tests/examplefiles/pleac.in.rb deleted file mode 100644 index d1dea9f4f..000000000 --- a/third_party/pygments/tests/examplefiles/pleac.in.rb +++ /dev/null @@ -1,1223 +0,0 @@ -# -*- ruby -*- - -# Local variables: -# indent-tabs-mode: nil -# ruby-indent-level: 4 -# End: - -# @@PLEAC@@_NAME -# @@SKIP@@ Ruby - -# @@PLEAC@@_WEB -# @@SKIP@@ http://www.ruby-lang.org - - -# @@PLEAC@@_1.0 -string = '\n' # two characters, \ and an n -string = 'Jon \'Maddog\' Orwant' # literal single quotes - -string = "\n" # a "newline" character -string = "Jon \"Maddog\" Orwant" # literal double quotes - -string = %q/Jon 'Maddog' Orwant/ # literal single quotes - -string = %q[Jon 'Maddog' Orwant] # literal single quotes -string = %q{Jon 'Maddog' Orwant} # literal single quotes -string = %q(Jon 'Maddog' Orwant) # literal single quotes -string = %q # literal single quotes - -a = <<"EOF" -This is a multiline here document -terminated by EOF on a line by itself -EOF - - -# @@PLEAC@@_1.1 -value = string[offset,count] -value = string[offset..-1] - -string[offset,count] = newstring -string[offset..-1] = newtail - -# in Ruby we can also specify intervals by their two offsets -value = string[offset..offs2] -string[offset..offs2] = newstring - -leading, s1, s2, trailing = data.unpack("A5 x3 A8 A8 A*") - -fivers = string.unpack("A5" * (string.length/5)) - -chars = string.unpack("A1" * string.length) - -string = "This is what you have" -# +012345678901234567890 Indexing forwards (left to right) -# 109876543210987654321- Indexing backwards (right to left) -# note that 0 means 10 or 20, etc. above - -first = string[0, 1] # "T" -start = string[5, 2] # "is" -rest = string[13..-1] # "you have" -last = string[-1, 1] # "e" -end_ = string[-4..-1] # "have" -piece = string[-8, 3] # "you" - -string[5, 2] = "wasn't" # change "is" to "wasn't" -string[-12..-1] = "ondrous" # "This wasn't wondrous" -string[0, 1] = "" # delete first character -string[-10..-1] = "" # delete last 10 characters - -if string[-10..-1] =~ /pattern/ - puts "Pattern matches in last 10 characters" -end - -string[0, 5].gsub!(/is/, 'at') - -a = "make a hat" -a[0, 1], a[-1, 1] = a[-1, 1], a[0, 1] - -a = "To be or not to be" -b = a.unpack("x6 A6") - -b, c = a.unpack("x6 A2 X5 A2") -puts "#{b}\n#{c}\n" - -def cut2fmt(*args) - template = '' - lastpos = 1 - for place in args - template += "A" + (place - lastpos).to_s + " " - lastpos = place - end - template += "A*" - return template -end - -fmt = cut2fmt(8, 14, 20, 26, 30) - - -# @@PLEAC@@_1.2 -# careful! "b is true" doesn't mean "b != 0" (0 is true in Ruby) -# thus no problem of "defined" later since only nil is false -# the following sets to `c' if `b' is nil or false -a = b || c - -# if you need Perl's behaviour (setting to `c' if `b' is 0) the most -# effective way is to use Numeric#nonzero? (thanks to Dave Thomas!) -a = b.nonzero? || c - -# you will still want to use defined? in order to test -# for scope existence of a given object -a = defined?(b) ? b : c - -dir = ARGV.shift || "/tmp" - - -# @@PLEAC@@_1.3 -v1, v2 = v2, v1 - -alpha, beta, production = %w(January March August) -alpha, beta, production = beta, production, alpha - - -# @@PLEAC@@_1.4 -num = char[0] -char = num.chr - -# Ruby also supports having a char from character constant -num = ?r - -char = sprintf("%c", num) -printf("Number %d is character %c\n", num, num) - -ascii = string.unpack("C*") -string = ascii.pack("C*") - -hal = "HAL" -ascii = hal.unpack("C*") -# We can't use Array#each since we can't mutate a Fixnum -ascii.collect! { |i| - i + 1 # add one to each ASCII value -} -ibm = ascii.pack("C*") -puts ibm - - -# @@PLEAC@@_1.5 -array = string.split('') - -array = string.unpack("C*") - -string.scan(/./) { |b| - # do something with b -} - -string = "an apple a day" -print "unique chars are: ", string.split('').uniq.sort, "\n" - -sum = 0 -for ascval in string.unpack("C*") # or use Array#each for a pure OO style :) - sum += ascval -end -puts "sum is #{sum & 0xffffffff}" # since Ruby will go Bignum if necessary - -# @@INCLUDE@@ include/ruby/slowcat.rb - - -# @@PLEAC@@_1.6 -revbytes = string.reverse - -revwords = string.split(" ").reverse.join(" ") - -revwords = string.split(/(\s+)/).reverse.join - -# using the fact that IO is Enumerable, you can directly "select" it -long_palindromes = File.open("/usr/share/dict/words"). - select { |w| w.chomp!; w.reverse == w && w.length > 5 } - - -# @@PLEAC@@_1.7 -while string.sub!("\t+") { ' ' * ($&.length * 8 - $`.length % 8) } -end - - -# @@PLEAC@@_1.8 -'You owe #{debt} to me'.gsub(/\#{(\w+)}/) { eval($1) } - -rows, cols = 24, 80 -text = %q(I am #{rows} high and #{cols} long) -text.gsub!(/\#{(\w+)}/) { eval("#{$1}") } -puts text - -'I am 17 years old'.gsub(/\d+/) { 2 * $&.to_i } - - -# @@PLEAC@@_1.9 -e = "bo peep".upcase -e.downcase! -e.capitalize! - -"thIS is a loNG liNE".gsub!(/\w+/) { $&.capitalize } - - -# @@PLEAC@@_1.10 -"I have #{n+1} guanacos." -print "I have ", n+1, " guanacos." - - -# @@PLEAC@@_1.11 -var = <<'EOF'.gsub(/^\s+/, '') - your text - goes here -EOF - - -# @@PLEAC@@_1.12 -string = "Folding and splicing is the work of an editor,\n"+ - "not a mere collection of silicon\n"+ - "and\n"+ - "mobile electrons!" - -def wrap(str, max_size) - all = [] - line = '' - for l in str.split - if (line+l).length >= max_size - all.push(line) - line = '' - end - line += line == '' ? l : ' ' + l - end - all.push(line).join("\n") -end - -print wrap(string, 20) -#=> Folding and -#=> splicing is the -#=> work of an editor, -#=> not a mere -#=> collection of -#=> silicon and mobile -#=> electrons! - - -# @@PLEAC@@_1.13 -string = %q(Mom said, "Don't do that.") -string.gsub(/['"]/) { '\\'+$& } -string.gsub(/['"]/, '\&\&') -string.gsub(/[^A-Z]/) { '\\'+$& } -"is a test!".gsub(/\W/) { '\\'+$& } # no function like quotemeta? - - -# @@PLEAC@@_1.14 -string.strip! - - -# @@PLEAC@@_1.15 -def parse_csv(text) - new = text.scan(/"([^\"\\]*(?:\\.[^\"\\]*)*)",?|([^,]+),?|,/) - new << nil if text[-1] == ?, - new.flatten.compact -end - -line = %q -fields = parse_csv(line) -fields.each_with_index { |v,i| - print "#{i} : #{v}\n"; -} - - -# @@PLEAC@@_1.16 -# Use the soundex.rb Library from Michael Neumann. -# http://www.s-direktnet.de/homepages/neumann/rb_prgs/Soundex.rb -require 'Soundex' - -code = Text::Soundex.soundex(string) -codes = Text::Soundex.soundex(array) - -# substitution function for getpwent(): -# returns an array of user entries, -# each entry contains the username and the full name -def login_names - result = [] - File.open("/etc/passwd") { |file| - file.each_line { |line| - next if line.match(/^#/) - cols = line.split(":") - result.push([cols[0], cols[4]]) - } - } - result -end - -puts "Lookup user: " -user = STDIN.gets -user.chomp! -exit unless user -name_code = Text::Soundex.soundex(user) - -splitter = Regexp.new('(\w+)[^,]*\b(\w+)') -for username, fullname in login_names do - firstname, lastname = splitter.match(fullname)[1,2] - if name_code == Text::Soundex.soundex(username) - || name_code == Text::Soundex.soundex(firstname) - || name_code == Text::Soundex.soundex(lastname) - then - puts "#{username}: #{firstname} #{lastname}" - end -end - - -# @@PLEAC@@_1.17 -# @@INCLUDE@@ include/ruby/fixstyle.rb - - -# @@PLEAC@@_1.18 -# @@INCLUDE@@ include/ruby/psgrep.rb - - -# @@PLEAC@@_2.1 -# Matz tells that you can use Integer() for strict checked conversion. -Integer("abc") -#=> `Integer': invalid value for Integer: "abc" (ArgumentError) -Integer("567") -#=> 567 - -# You may use Float() for floating point stuff -Integer("56.7") -#=> `Integer': invalid value for Integer: "56.7" (ArgumentError) -Float("56.7") -#=> 56.7 - -# You may also use a regexp for that -if string =~ /^[+-]?\d+$/ - p 'is an integer' -else - p 'is not' -end - -if string =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ - p 'is a decimal number' -else - p 'is not' -end - - -# @@PLEAC@@_2.2 -# equal(num1, num2, accuracy) : returns true if num1 and num2 are -# equal to accuracy number of decimal places -def equal(i, j, a) - sprintf("%.#{a}g", i) == sprintf("%.#{a}g", j) -end - -wage = 536 # $5.36/hour -week = 40 * wage # $214.40 -printf("One week's wage is: \$%.2f\n", week/100.0) - - -# @@PLEAC@@_2.3 -num.round # rounds to integer - -a = 0.255 -b = sprintf("%.2f", a) -print "Unrounded: #{a}\nRounded: #{b}\n" -printf "Unrounded: #{a}\nRounded: %.2f\n", a - -print "number\tint\tfloor\tceil\n" -a = [ 3.3 , 3.5 , 3.7, -3.3 ] -for n in a - printf("% .1f\t% .1f\t% .1f\t% .1f\n", # at least I don't fake my output :) - n, n.to_i, n.floor, n.ceil) -end - - -# @@PLEAC@@_2.4 -def dec2bin(n) - [n].pack("N").unpack("B32")[0].sub(/^0+(?=\d)/, '') -end - -def bin2dec(n) - [("0"*32+n.to_s)[-32..-1]].pack("B32").unpack("N")[0] -end - - -# @@PLEAC@@_2.5 -for i in x .. y - # i is set to every integer from x to y, inclusive -end - -x.step(y,7) { |i| - # i is set to every integer from x to y, stepsize = 7 -} - -print "Infancy is: " -(0..2).each { |i| - print i, " " -} -print "\n" - - -# @@PLEAC@@_2.6 -# We can add conversion methods to the Integer class, -# this makes a roman number just a representation for normal numbers. -class Integer - - @@romanlist = [["M", 1000], - ["CM", 900], - ["D", 500], - ["CD", 400], - ["C", 100], - ["XC", 90], - ["L", 50], - ["XL", 40], - ["X", 10], - ["IX", 9], - ["V", 5], - ["IV", 4], - ["I", 1]] - - def to_roman - remains = self - roman = "" - for sym, num in @@romanlist - while remains >= num - remains -= num - roman << sym - end - end - roman - end - - def Integer.from_roman(roman) - ustr = roman.upcase - sum = 0 - for entry in @@romanlist - sym, num = entry[0], entry[1] - while sym == ustr[0, sym.length] - sum += num - ustr.slice!(0, sym.length) - end - end - sum - end - -end - - -roman_fifteen = 15.to_roman -puts "Roman for fifteen is #{roman_fifteen}" -i = Integer.from_roman(roman_fifteen) -puts "Converted back, #{roman_fifteen} is #{i}" - -# check -for i in (1..3900) - r = i.to_roman - j = Integer.from_roman(r) - if i != j - puts "error: #{i} : #{r} - #{j}" - end -end - - -# @@PLEAC@@_2.7 -random = rand(y-x+1)+x - -chars = ["A".."Z","a".."z","0".."9"].collect { |r| r.to_a }.join + %q(!@$%^&*) -password = (1..8).collect { chars[rand(chars.size)] }.pack("C*") - - -# @@PLEAC@@_2.8 -srand # uses a combination of the time, the process id, and a sequence number -srand(val) # for repeatable behaviour - - -# @@PLEAC@@_2.9 -# from the randomr lib: -# http://raa.ruby-lang.org/project/randomr/ -----> http://raa.ruby-lang.org/project/randomr/ - -require 'random/mersenne_twister' -mers = Random::MersenneTwister.new 123456789 -puts mers.rand(0) # 0.550321932544541 -puts mers.rand(10) # 2 - -# using online sources of random data via the realrand package: -# http://raa.ruby-lang.org/project/realrand/ -# **Note** -# The following online services are used in this package: -# http://www.random.org - source: atmospheric noise -# http://www.fourmilab.ch/hotbits - source: radioactive decay timings -# http://random.hd.org - source: entropy from local and network noise -# Please visit the sites and respect the rules of each service. - -require 'random/online' - -generator1 = Random::RandomOrg.new -puts generator1.randbyte(5).join(",") -puts generator1.randnum(10, 1, 6).join(",") # Roll dice 10 times. - -generator2 = Random::FourmiLab.new -puts generator2.randbyte(5).join(",") -# randnum is not supported. - -generator3 = Random::EntropyPool.new -puts generator3.randbyte(5).join(",") -# randnum is not supported. - - -# @@PLEAC@@_2.10 -def gaussian_rand - begin - u1 = 2 * rand() - 1 - u2 = 2 * rand() - 1 - w = u1*u1 + u2*u2 - end while (w >= 1) - w = Math.sqrt((-2*Math.log(w))/w) - [ u2*w, u1*w ] -end - -mean = 25 -sdev = 2 -salary = gaussian_rand[0] * sdev + mean -printf("You have been hired at \$%.2f\n", salary) - - -# @@PLEAC@@_2.11 -def deg2rad(d) - (d/180.0)*Math::PI -end - -def rad2deg(r) - (r/Math::PI)*180 -end - - -# @@PLEAC@@_2.12 -sin_val = Math.sin(angle) -cos_val = Math.cos(angle) -tan_val = Math.tan(angle) - -# AFAIK Ruby's Math module doesn't provide acos/asin -# While we're at it, let's also define missing hyperbolic functions -module Math - def Math.asin(x) - atan2(x, sqrt(1 - x**2)) - end - def Math.acos(x) - atan2(sqrt(1 - x**2), x) - end - def Math.atan(x) - atan2(x, 1) - end - def Math.sinh(x) - (exp(x) - exp(-x)) / 2 - end - def Math.cosh(x) - (exp(x) + exp(-x)) / 2 - end - def Math.tanh(x) - sinh(x) / cosh(x) - end -end - -# The support for Complex numbers is not built-in -y = Math.acos(3.7) -#=> in `sqrt': square root for negative number (ArgumentError) - -# There is an implementation of Complex numbers in 'complex.rb' in current -# Ruby distro, but it doesn't support atan2 with complex args, so it doesn't -# solve this problem. - - -# @@PLEAC@@_2.13 -log_e = Math.log(val) -log_10 = Math.log10(val) - -def log_base(base, val) - Math.log(val)/Math.log(base) -end - -answer = log_base(10, 10_000) -puts "log10(10,000) = #{answer}" - - -# @@PLEAC@@_2.14 -require 'matrix.rb' - -a = Matrix[[3, 2, 3], [5, 9, 8]] -b = Matrix[[4, 7], [9, 3], [8, 1]] -c = a * b - -a.row_size -a.column_size - -c.det -a.transpose - - -# @@PLEAC@@_2.15 -require 'complex.rb' -require 'rational.rb' - -a = Complex(3, 5) # 3 + 5i -b = Complex(2, -2) # 2 - 2i -puts "c = #{a*b}" - -c = a * b -d = 3 + 4*Complex::I - -printf "sqrt(#{d}) = %s\n", Math.sqrt(d) - - -# @@PLEAC@@_2.16 -number = hexadecimal.hex -number = octal.oct - -print "Gimme a number in decimal, octal, or hex: " -num = gets.chomp -exit unless defined?(num) -num = num.oct if num =~ /^0/ # does both oct and hex -printf "%d %x %o\n", num, num, num - -print "Enter file permission in octal: " -permissions = gets.chomp -raise "Exiting ...\n" unless defined?(permissions) -puts "The decimal value is #{permissions.oct}" - - -# @@PLEAC@@_2.17 -def commify(n) - n.to_s =~ /([^\.]*)(\..*)?/ - int, dec = $1.reverse, $2 ? $2 : "" - while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3') - end - int.reverse + dec -end - - -# @@PLEAC@@_2.18 -printf "It took %d hour%s\n", time, time == 1 ? "" : "s" - -# dunno if an equivalent to Lingua::EN::Inflect exists... - - -# @@PLEAC@@_2.19 -#----------------------------- -#!/usr/bin/ruby -# bigfact - calculating prime factors -def factorize(orig) - factors = {} - factors.default = 0 # return 0 instead nil if key not found in hash - n = orig - i = 2 - sqi = 4 # square of i - while sqi <= n do - while n.modulo(i) == 0 do - n /= i - factors[i] += 1 - # puts "Found factor #{i}" - end - # we take advantage of the fact that (i +1)**2 = i**2 + 2*i +1 - sqi += 2 * i + 1 - i += 1 - end - - if (n != 1) && (n != orig) - factors[n] += 1 - end - factors -end - -def printfactorhash(orig, factorcount) - print format("%-10d ", orig) - if factorcount.length == 0 - print "PRIME" - else - # sorts after number, because the hash keys are numbers - factorcount.sort.each { |factor,exponent| - print factor - if exponent > 1 - print "**", exponent - end - print " " - } - end - puts -end - -for arg in ARGV - n = arg.to_i - mfactors = factorize(n) - printfactorhash(n, mfactors) -end -#----------------------------- - - -# @@PLEAC@@_3.0 -puts Time.now - -print "Today is day ", Time.now.yday, " of the current year.\n" -print "Today is day ", Time.now.day, " of the current month.\n" - - -# @@PLEAC@@_3.1 -day, month, year = Time.now.day, Time.now.month, Time.now.year -# or -day, month, year = Time.now.to_a[3..5] - -tl = Time.now.localtime -printf("The current date is %04d %02d %02d\n", tl.year, tl.month, tl.day) - -Time.now.localtime.strftime("%Y-%m-%d") - - -# @@PLEAC@@_3.2 -Time.local(year, month, day, hour, minute, second).tv_sec -Time.gm(year, month, day, hour, minute, second).tv_sec - - -# @@PLEAC@@_3.3 -sec, min, hour, day, month, year, wday, yday, isdst, zone = Time.at(epoch_secs).to_a - - -# @@PLEAC@@_3.4 -when_ = now + difference # now -> Time ; difference -> Numeric (delta in seconds) -then_ = now - difference - - -# @@PLEAC@@_3.5 -bree = 361535725 -nat = 96201950 - -difference = bree - nat -puts "There were #{difference} seconds between Nat and Bree" - -seconds = difference % 60 -difference = (difference - seconds) / 60 -minutes = difference % 60 -difference = (difference - minutes) / 60 -hours = difference % 24 -difference = (difference - hours) / 24 -days = difference % 7 -weeks = (difference - days) / 7 - -puts "(#{weeks} weeks, #{days} days, #{hours}:#{minutes}:#{seconds})" - - -# @@PLEAC@@_3.6 -monthday, weekday, yearday = date.mday, date.wday, date.yday - -# AFAIK the week number is not just a division since week boundaries are on sundays -weeknum = d.strftime("%U").to_i + 1 - -year = 1981 -month = "jun" # or `6' if you want to emulate a broken language -day = 16 -t = Time.mktime(year, month, day) -print "#{month}/#{day}/#{year} was a ", t.strftime("%A"), "\n" - - -# @@PLEAC@@_3.7 -yyyy, mm, dd = $1, $2, $3 if "1998-06-25" =~ /(\d+)-(\d+)-(\d+)/ - -epoch_seconds = Time.mktime(yyyy, mm, dd).tv_sec - -# dunno an equivalent to Date::Manip#ParseDate - - -# @@PLEAC@@_3.8 -string = Time.at(epoch_secs) -Time.at(1234567890).gmtime # gives: Fri Feb 13 23:31:30 UTC 2009 - -time = Time.mktime(1973, "jan", 18, 3, 45, 50) -print "In localtime it gives: ", time.localtime, "\n" - - -# @@PLEAC@@_3.9 -# Ruby provides micro-seconds in Time object -Time.now.usec - -# Ruby gives the seconds in floating format when substracting two Time objects -before = Time.now -line = gets -elapsed = Time.now - before -puts "You took #{elapsed} seconds." - -# On my Celeron-400 with Linux-2.2.19-14mdk, average for three execs are: -# This Ruby version: average 0.00321 sec -# Cookbook's Perl version: average 0.00981 sec -size = 500 -number_of_times = 100 -total_time = 0 -number_of_times.times { - # populate array - array = [] - size.times { array << rand } - # sort it - begin_ = Time.now - array.sort! - time = Time.now - begin_ - total_time += time -} -printf "On average, sorting %d random numbers takes %.5f seconds\n", - size, (total_time/Float(number_of_times)) - - -# @@PLEAC@@_3.10 -sleep(0.005) # Ruby is definitely not as broken as Perl :) -# (may be interrupted by sending the process a SIGALRM) - - -# @@PLEAC@@_3.11 -#!/usr/bin/ruby -w -# hopdelta - feed mail header, produce lines -# showing delay at each hop. -require 'time' -class MailHopDelta - - def initialize(mail) - @head = mail.gsub(/\n\s+/,' ') - @topline = %w-Sender Recipient Time Delta- - @start_from = mail.match(/^From.*\@([^\s>]*)/)[1] - @date = Time.parse(mail.match(/^Date:\s+(.*)/)[1]) - end - - def out(line) - "%-20.20s %-20.20s %-20.20s %s" % line - end - - def hop_date(day) - day.strftime("%I:%M:%S %Y/%m/%d") - end - - def puts_hops - puts out(@topline) - puts out(['Start', @start_from, hop_date(@date),'']) - @head.split(/\n/).reverse.grep(/^Received:/).each do |hop| - hop.gsub!(/\bon (.*?) (id.*)/,'; \1') - whence = hop.match(/;\s+(.*)$/)[1] - unless whence - warn "Bad received line: #{hop}" - next - end - from = $+ if hop =~ /from\s+(\S+)|\((.*?)\)/ - by = $1 if hop =~ /by\s+(\S+\.\S+)/ - next unless now = Time.parse(whence).localtime - delta = now - @date - puts out([from, by, hop_date(now), hop_time(delta)]) - @date = now - end - end - - def hop_time(secs) - sign = secs < 0 ? -1 : 1 - days, secs = secs.abs.divmod(60 * 60 * 24) - hours,secs = secs.abs.divmod(60 * 60) - mins, secs = secs.abs.divmod(60) - rtn = "%3ds" % [secs * sign] - rtn << "%3dm" % [mins * sign] if mins != 0 - rtn << "%3dh" % [hours * sign] if hours != 0 - rtn << "%3dd" % [days * sign] if days != 0 - rtn - end -end - -$/ = "" -mail = MailHopDelta.new(ARGF.gets).puts_hops - - -# @@PLEAC@@_4.0 -single_level = [ "this", "that", "the", "other" ] - -# Ruby directly supports nested arrays -double_level = [ "this", "that", [ "the", "other" ] ] -still_single_level = [ "this", "that", [ "the", "other" ] ].flatten - - -# @@PLEAC@@_4.1 -a = [ "quick", "brown", "fox" ] -a = %w(Why are you teasing me?) - -lines = <<"END_OF_HERE_DOC".gsub(/^\s*(.+)/, '\1') - The boy stood on the burning deck, - It was as hot as glass. -END_OF_HERE_DOC - -bigarray = IO.readlines("mydatafile").collect { |l| l.chomp } - -name = "Gandalf" -banner = %Q(Speak, #{name}, and welcome!) - -host_info = `host #{his_host}` - -%x(ps #{$$}) - -banner = 'Costs only $4.95'.split(' ') - -rax = %w! ( ) < > { } [ ] ! - - -# @@PLEAC@@_4.2 -def commify_series(arr) - return '' if not arr - case arr.size - when 0 then '' - when 1 then arr[0] - when 2 then arr.join(' and ') - else arr[0..-2].join(', ') + ', and ' + arr[-1] - end -end - -array = [ "red", "yellow", "green" ] - -print "I have ", array, " marbles\n" -# -> I have redyellowgreen marbles - -# But unlike Perl: -print "I have #{array} marbles\n" -# -> I have redyellowgreen marbles -# So, needs: -print "I have #{array.join(' ')} marbles\n" -# -> I have red yellow green marbles - -#!/usr/bin/ruby -# communify_series - show proper comma insertion in list output - -def commify_series(arr) - return '' if not arr - sepchar = arr.find { |p| p =~ /,/ } ? '; ' : ', ' - case arr.size - when 0 then '' - when 1 then arr[0] - when 2 then arr.join(' and ') - else arr[0..-2].join(sepchar) + sepchar + 'and ' + arr[-1] - end -end - -lists = [ - [ 'just one thing' ], - %w(Mutt Jeff), - %w(Peter Paul Mary), - [ 'To our parents', 'Mother Theresa', 'God' ], - [ 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ], - [ 'recycle tired, old phrases', 'ponder big, happy thoughts' ], - [ 'recycle tired, old phrases', - 'ponder big, happy thoughts', - 'sleep and dream peacefully' ], -] - -for list in lists do - puts "The list is: #{commify_series(list)}." -end - - -# @@PLEAC@@_4.3 -# (note: AFAIK Ruby doesn't allow gory change of Array length) -# grow the array by assigning nil to past the end of array -ary[new_size-1] = nil -# shrink the array by slicing it down -ary.slice!(new_size..-1) -# init the array with given size -Array.new(number_of_elems) -# assign to an element past the original end enlarges the array -ary[index_new_last_elem] = value - -def what_about_that_array(a) - print "The array now has ", a.size, " elements.\n" - # Index of last element is not really interesting in Ruby - print "Element #3 is `#{a[3]}'.\n" -end -people = %w(Crosby Stills Nash Young) -what_about_that_array(people) - - -# @@PLEAC@@_4.4 -# OO style -bad_users.each { |user| - complain(user) -} -# or, functional style -for user in bad_users - complain(user) -end - -for var in ENV.keys.sort - puts "#{var}=#{ENV[var]}" -end - -for user in all_users - disk_space = get_usage(user) - if (disk_space > MAX_QUOTA) - complain(user) - end -end - -for l in IO.popen("who").readlines - print l if l =~ /^gc/ -end - -# we can mimic the obfuscated Perl way -while fh.gets # $_ is set to the line just read - chomp # $_ has a trailing \n removed, if it had one - split.each { |w| # $_ is split on whitespace - # but $_ is not set to each chunk as in Perl - print w.reverse - } -end -# ...or use a cleaner way -for l in fh.readlines - l.chomp.split.each { |w| print w.reverse } -end - -# same drawback as in problem 1.4, we can't mutate a Numeric... -array.collect! { |v| v - 1 } - -a = [ .5, 3 ]; b = [ 0, 1 ] -for ary in [ a, b ] - ary.collect! { |v| v * 7 } -end -puts "#{a.join(' ')} #{b.join(' ')}" - -# we can mutate Strings, cool; we need a trick for the scalar -for ary in [ [ scalar ], array, hash.values ] - ary.each { |v| v.strip! } # String#strip rules :) -end - - -# @@PLEAC@@_4.5 -# not relevant in Ruby since we have always references -for item in array - # do somethingh with item -end - - -# @@PLEAC@@_4.6 -unique = list.uniq - -# generate a list of users logged in, removing duplicates -users = `who`.collect { |l| l =~ /(\w+)/; $1 }.sort.uniq -puts("users logged in: #{commify_series(users)}") # see 4.2 for commify_series - - -# @@PLEAC@@_4.7 -a - b -# [ 1, 1, 2, 2, 3, 3, 3, 4, 5 ] - [ 1, 2, 4 ] -> [3, 5] - - -# @@PLEAC@@_4.8 -union = a | b -intersection = a & b -difference = a - b - - -# @@PLEAC@@_4.9 -array1.concat(array2) -# if you will assign to another object, better use: -new_ary = array1 + array2 - -members = [ "Time", "Flies" ] -initiates = [ "An", "Arrow" ] -members += initiates - -members = [ "Time", "Flies" ] -initiates = [ "An", "Arrow" ] -members[2,0] = [ "Like", initiates ].flatten - -members[0] = "Fruit" -members[3,2] = "A", "Banana" - - -# @@PLEAC@@_4.10 -reversed = ary.reverse - -ary.reverse_each { |e| - # do something with e -} - -descending = ary.sort.reverse -descending = ary.sort { |a,b| b <=> a } - - -# @@PLEAC@@_4.11 -# remove n elements from front of ary (shift n) -front = ary.slice!(0, n) - -# remove n elements from the end of ary (pop n) -end_ = ary.slice!(-n .. -1) - -# let's extend the Array class, to make that useful -class Array - def shift2() - slice!(0 .. 1) # more symetric with pop2... - end - def pop2() - slice!(-2 .. -1) - end -end - -friends = %w(Peter Paul Mary Jim Tim) -this, that = friends.shift2 - -beverages = %w(Dew Jolt Cola Sprite Fresca) -pair = beverages.pop2 - - -# @@PLEAC@@_4.12 -# use Enumerable#detect (or the synonym Enumerable#find) -highest_eng = employees.detect { |emp| emp.category == 'engineer' } - - -# @@PLEAC@@_4.13 -# use Enumerable#select (or the synonym Enumerable#find_all) -bigs = nums.select { |i| i > 1_000_000 } -pigs = users.keys.select { |k| users[k] > 1e7 } - -matching = `who`.select { |u| u =~ /^gnat / } - -engineers = employees.select { |e| e.position == 'Engineer' } - -secondary_assistance = applicants.select { |a| - a.income >= 26_000 && a.income < 30_000 -} - - -# @@PLEAC@@_4.14 -# normally you would have an array of Numeric (Float or -# Fixnum or Bignum), so you would use: -sorted = unsorted.sort -# if you have strings representing Integers or Floats -# you may specify another sort method: -sorted = unsorted.sort { |a,b| a.to_f <=> b.to_f } - -# let's use the list of my own PID's -`ps ux`.split("\n")[1..-1]. - select { |i| i =~ /^#{ENV['USER']}/ }. - collect { |i| i.split[1] }. - sort { |a,b| a.to_i <=> b.to_i }.each { |i| puts i } -puts "Select a process ID to kill:" -pid = gets.chomp -raise "Exiting ... \n" unless pid && pid =~ /^\d+$/ -Process.kill('TERM', pid.to_i) -sleep 2 -Process.kill('KILL', pid.to_i) - -descending = unsorted.sort { |a,b| b.to_f <=> a.to_f } - - -# @@PLEAC@@_4.15 -ordered = unordered.sort { |a,b| compare(a,b) } - -precomputed = unordered.collect { |e| [compute, e] } -ordered_precomputed = precomputed.sort { |a,b| a[0] <=> b[0] } -ordered = ordered_precomputed.collect { |e| e[1] } - -ordered = unordered.collect { |e| [compute, e] }. - sort { |a,b| a[0] <=> b[0] }. - collect { |e| e[1] } - -for employee in employees.sort { |a,b| a.name <=> b.name } - print employee.name, " earns \$ ", employee.salary, "\n" -end - -# Beware! `0' is true in Ruby. -# For chaining comparisons, you may use Numeric#nonzero?, which -# returns num if num is not zero, nil otherwise -sorted = employees.sort { |a,b| (a.name <=> b.name).nonzero? || b.age <=> a.age } - -users = [] -# getpwent is not wrapped in Ruby... let's fallback -IO.readlines('/etc/passwd').each { |u| users << u.split(':') } -users.sort! { |a,b| a[0] <=> b[0] } -for user in users - puts user[0] -end - -sorted = names.sort { |a,b| a[1, 1] <=> b[1, 1] } -sorted = strings.sort { |a,b| a.length <=> b.length } - -# let's show only the compact version -ordered = strings.collect { |e| [e.length, e] }. - sort { |a,b| a[0] <=> b[0] }. - collect { |e| e[1] } - -ordered = strings.collect { |e| [/\d+/.match(e)[0].to_i, e] }. - sort { |a,b| a[0] <=> b[0] }. - collect { |e| e[1] } - -print `cat /etc/passwd`.collect { |e| [e, e.split(':').indexes(3,2,0)].flatten }. - sort { |a,b| (a[1] <=> b[1]).nonzero? || (a[2] <=> b[2]).nonzero? || a[3] <=> b[3] }. - collect { |e| e[0] } - - -# @@PLEAC@@_4.16 -circular.unshift(circular.pop) # the last shall be first -circular.push(circular.shift) # and vice versa - -def grab_and_rotate(l) - l.push(ret = l.shift) - ret -end - -processes = [1, 2, 3, 4, 5] -while (1) - process = grab_and_rotate(processes) - puts "Handling process #{process}" - sleep 1 -end - - -# @@PLEAC@@_4.17 -def fisher_yates_shuffle(a) - (a.size-1).downto(1) { |i| - j = rand(i+1) - a[i], a[j] = a[j], a[i] if i != j - } -end - -def naive_shuffle(a) - for i in 0...a.size - j = rand(a.size) - a[i], a[j] = a[j], a[i] - end -end - - diff --git a/third_party/pygments/tests/examplefiles/postgresql_test.txt b/third_party/pygments/tests/examplefiles/postgresql_test.txt deleted file mode 100644 index 190d184f5..000000000 --- a/third_party/pygments/tests/examplefiles/postgresql_test.txt +++ /dev/null @@ -1,47 +0,0 @@ -CREATE OR REPLACE FUNCTION something() RETURNS int4 AS -$x$ -BEGIN - RETURN 42; -END -$x$ -LANGUAGE 'plpgsql'; - -CREATE FUNCTION pymax (a integer, b integer) - RETURNS integer -AS $$ - if a > b: - return a - return b -$$ language plpythonu; - -CREATE FUNCTION nested_lexers (a integer, b integer) -$function$ -BEGIN - SELECT ($1 ~ $q$[\t\r\n\v\\]$q$); -END; -$function$ -LANGUAGE sql; - -CREATE OR REPLACE FUNCTION measurement_insert_trigger() -RETURNS TRIGGER AS $$ -BEGIN - <> - INSERT INTO measurement_y2008m01 VALUES (NEW.*); - RETURN NULL; -END; -$$ -LANGUAGE plpgsql; - --- As returned by pg_dump -CREATE FUNCTION test_function() RETURNS integer - LANGUAGE plpgsql STABLE STRICT - AS $$ -begin - return 42; -end -$$; - --- Unicode names and strings -SELECT U&'\0441\043B\043E\043D' -FROM U&"\0441\043B\043E\043D"; - diff --git a/third_party/pygments/tests/examplefiles/pppoe.applescript b/third_party/pygments/tests/examplefiles/pppoe.applescript deleted file mode 100644 index 4cb380e54..000000000 --- a/third_party/pygments/tests/examplefiles/pppoe.applescript +++ /dev/null @@ -1,10 +0,0 @@ -tell application "System Events" - tell network preferences - tell current location - set aPPPoEService to a reference to (first service whose kind is 10) - if exists aPPPoEService then - connect aPPPoEService - end if - end tell - end tell -end tell diff --git a/third_party/pygments/tests/examplefiles/psql_session.txt b/third_party/pygments/tests/examplefiles/psql_session.txt deleted file mode 100644 index 7096072b1..000000000 --- a/third_party/pygments/tests/examplefiles/psql_session.txt +++ /dev/null @@ -1,122 +0,0 @@ -regression=# select foo; -ERROR: column "foo" does not exist -CONTEXT: PL/pgSQL function "test1" while casting return value to function's return type -LINE 1: select foo; - ^ -regression=# \q - -peter@localhost testdb=> \a \t \x -Output format is aligned. -Tuples only is off. -Expanded display is on. - -regression=# select '\x'; -WARNING: nonstandard use of escape in a string literal -LINE 1: select '\x'; - ^ -HINT: Use the escape string syntax for escapes, e.g., E'\r\n'. - ?column? ----------- - x -(1 row) - -regression=# select E'\x'; - -piro=> \set foo 30; -piro=> select * from test where foo <= :foo; - foo | bar ------+----- - 10 | - 20 | -(2 rows) - -testdb=> \set foo 'my_table' -testdb=> SELECT * FROM :"foo"; - -testdb=> \set content `cat my_file.txt` -testdb=> INSERT INTO my_table VALUES (:'content'); - -regression=# select ( -regression(# 1); - ?column? ----------- - 1 -(1 row) - -piro=> select ( -piro(> ' -piro'> ' || $$ -piro$> $$) -piro-> from " -piro"> foo"; -ERROR: relation " -foo" does not exist -LINE 5: from " - ^ - -testdb=> CREATE TABLE my_table ( -first integer not null default 0, -second text) ; -- end of command -CREATE TABLE - --- Table output -=# SELECT '0x10'::mpz AS "hex", '10'::mpz AS "dec", --# '010'::mpz AS oct, '0b10'::mpz AS bin; - hex | dec | oct | bin ------+-----+-----+----- - 16 | 10 | 8 | 2 -(1 row) - --- One field output -regression=# select schemaname from pg_tables limit 3; - schemaname ------------- - pg_catalog - pg_catalog - pg_catalog -(3 rows) - --- TODO: prompt in multiline comments still not handled correctly -test=> select 1 /* multiline -test*> and 2 /* and 3 */ -test*> end comment */, 2; - ?column? | ?column? -----------+---------- - 1 | 2 - -=# select 10.0, 1e-6, 1E+6; - ?column? | ?column? | ?column? -----------+----------+---------- - 10.0 | 0.000001 | 1000000 -(1 row) - -regression=# begin; -BEGIN -regression=# create table asdf (foo serial primary key); -NOTICE: CREATE TABLE will create implicit sequence "asdf_foo_seq" for serial column "asdf.foo" -NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "asdf_pkey" for table "asdf" -CREATE TABLE -regression=# insert into asdf values (10) returning foo; - foo ------ - 10 -(1 row) - -INSERT 0 1 -regression=# ROLLBACK ; -ROLLBACK - -=> EXPLAIN SELECT * FROM tenk1 --> WHERE unique1 < 100; -- Don't take -> in the plan as a prompt - - QUERY PLAN ------------------------------------------------------------------------------- - Bitmap Heap Scan on tenk1 (cost=2.37..232.35 rows=106 width=244) - Recheck Cond: (unique1 < 100) - -> Bitmap Index Scan on tenk1_unique1 (cost=0.00..2.37 rows=106 width=0) - Index Cond: (unique1 < 100) - - --- don't swallow the end of a malformed line -test=> select 1, -'this line must be emitted' diff --git a/third_party/pygments/tests/examplefiles/py3_test.txt b/third_party/pygments/tests/examplefiles/py3_test.txt deleted file mode 100644 index 21fea754a..000000000 --- a/third_party/pygments/tests/examplefiles/py3_test.txt +++ /dev/null @@ -1,2 +0,0 @@ -class Käse: - pass diff --git a/third_party/pygments/tests/examplefiles/py3tb_test.py3tb b/third_party/pygments/tests/examplefiles/py3tb_test.py3tb deleted file mode 100644 index 706a540fa..000000000 --- a/third_party/pygments/tests/examplefiles/py3tb_test.py3tb +++ /dev/null @@ -1,4 +0,0 @@ - File "", line 1 - 1+ - ^ -SyntaxError: invalid syntax diff --git a/third_party/pygments/tests/examplefiles/pycon_ctrlc_traceback b/third_party/pygments/tests/examplefiles/pycon_ctrlc_traceback deleted file mode 100644 index 4998fd9c8..000000000 --- a/third_party/pygments/tests/examplefiles/pycon_ctrlc_traceback +++ /dev/null @@ -1,118 +0,0 @@ -x = r""" ->>> import os ->>> print os - ->>> for x in range(10): -... y = x + 2 -... print(x) -... if x > 5: -... raise Exception -... -0 -1 -2 -3 -4 -5 -6 -Traceback (most recent call last): - File "", line 5, in -Exception ->>> ->>> while True: -... pass -... -^CTraceback (most recent call last): - File "", line 1, in -KeyboardInterrupt - ->>> class A(Exception):pass -... ->>> class B(Exception):pass -... ->>> try: -... try: -... raise A('first') -... finally: -... raise B('second') -... except A as c: -... print(c) -... -Traceback (most recent call last): - File "", line 3, in -__main__.A: first - -During handling of the above exception, another exception occurred: - -Traceback (most recent call last): - File "", line 5, in -__main__.B: second - ->>> x = - File "", line 1 - x = - ^ -SyntaxError: invalid syntax ->>> - ->>> x = 3 ->>> with 5 as y: -... print(x + y) -... -8 - -# TODO -#>>> raise ValueError('multi\n line\ndetail') -#Traceback (most recent call last): -#........ -#ValueError: multi -# line -#detail - ->>> raise ValueError('multi\n line\ndetail') -Traceback (most recent call last): - .123 -ValueError: multi - line -detail - ->>> raise ValueError('multi\n line\ndetail') -Traceback (most recent call last): - ... -ValueError: multi - line -detail - ->>> raise ValueError('multi\n line\ndetail') -Traceback (most recent call last): - .... -ValueError: multi - line -detail - ->>> raise ValueError('multi\n line\ndetail') -Traceback (most recent call last): - .... -ValueError: multi - line -detail - ->>> raise ValueError('multi\n line\ndetail') -Traceback (most recent call last): - ... -ValueError: multi - line -detail - ->>> raise Exception -Traceback (most recent call last): - File "", line 1, in -Exception ->>> import somemodule ->>> somemodule.blah() -Traceback (most recent call last): - File "", line 1, in - File "/path/to/stuff/somemodule/blah.py", line 658, in blah - raise Exception('Hi.') -Exception: Hi. - diff --git a/third_party/pygments/tests/examplefiles/pycon_test.pycon b/third_party/pygments/tests/examplefiles/pycon_test.pycon deleted file mode 100644 index 9c4fc3d32..000000000 --- a/third_party/pygments/tests/examplefiles/pycon_test.pycon +++ /dev/null @@ -1,17 +0,0 @@ ->>> : - File "", line 1 - : - ^ -SyntaxError: invalid syntax ->>> -KeyboardInterrupt ->>> - ->>> 1/0 -Traceback (most recent call last): - ... -ZeroDivisionError - ->>> 1/0 # this used to swallow the traceback -Traceback (most recent call last): - ... diff --git a/third_party/pygments/tests/examplefiles/pytb_test2.pytb b/third_party/pygments/tests/examplefiles/pytb_test2.pytb deleted file mode 100644 index c4d20339b..000000000 --- a/third_party/pygments/tests/examplefiles/pytb_test2.pytb +++ /dev/null @@ -1,2 +0,0 @@ - File "temp.py", line 1 -SyntaxError: Non-ASCII character '\xc3' in file temp.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details diff --git a/third_party/pygments/tests/examplefiles/pytb_test3.pytb b/third_party/pygments/tests/examplefiles/pytb_test3.pytb deleted file mode 100644 index 6947c1ef1..000000000 --- a/third_party/pygments/tests/examplefiles/pytb_test3.pytb +++ /dev/null @@ -1,4 +0,0 @@ ->>> 3/"3" -Traceback (most recent call last): - File "", line 1, in -TypeError: unsupported operand type(s) for /: 'int' and 'str' diff --git a/third_party/pygments/tests/examplefiles/python25-bsd.mak b/third_party/pygments/tests/examplefiles/python25-bsd.mak deleted file mode 100644 index 51c25967c..000000000 --- a/third_party/pygments/tests/examplefiles/python25-bsd.mak +++ /dev/null @@ -1,234 +0,0 @@ -# New ports collection makefile for: python25 -# Date created: 3 July 2003 -# Whom: Hye-Shik Chang -# -# $FreeBSD: ports/lang/python25/Makefile,v 1.145 2007/10/03 23:22:04 edwin Exp $ - -PORTNAME= python25 -PORTVERSION= 2.5.1 -CATEGORIES= lang python ipv6 -MASTER_SITES= ${PYTHON_MASTER_SITES} -MASTER_SITE_SUBDIR= ${PYTHON_MASTER_SITE_SUBDIR} -DISTFILES= ${PYTHON_DISTFILE} - -MAINTAINER= python@FreeBSD.org -COMMENT?= An interpreted object-oriented programming language - -DIST_SUBDIR= python -WRKSRC= ${PYTHON_WRKSRC}/portbld.static -PATCH_WRKSRC= ${PYTHON_WRKSRC} -GNU_CONFIGURE= yes -CONFIGURE_TARGET= --build=${MACHINE_ARCH}-portbld-freebsd${OSREL} -CONFIGURE_SCRIPT= ../configure # must be relative -CONFIGURE_ENV= OPT="${CFLAGS}" SVNVERSION="echo freebsd" -MAKE_ENV= VPATH="${PYTHON_WRKSRC}" -INSTALLS_SHLIB= yes -INSTALL_TARGET= altinstall -MAN1= ${PYTHON_VERSION}.1 - -USE_PYTHON= yes -PYTHON_VERSION= python2.5 -PYTHON_NO_DEPENDS= yes - -SHARED_WRKSRC= ${PYTHON_WRKSRC}/portbld.shared -PLIST= ${WRKDIR}/PLIST -PLIST_TEMPLATE?=${PKGDIR}/pkg-plist -PLIST_SUB= PYVER=${PYTHON_VERSION:S/python//} \ - PYVER_WITHPAT=${PORTVERSION:S/.c/c/} -DEMODIR= ${PREFIX}/share/examples/${PYTHON_VERSION} -TOOLSDIR= ${PREFIX}/share/${PYTHON_VERSION} - -BIN_SCRIPTS= idle pydoc python python-shared smtpd.py python-config \ - python-shared-config -BINLINKS_SUB= -e 's,smtpd,smtpd${PYTHON_VER},' \ - -e 's,(idle|pydoc|python-shared|python),\1${PYTHON_VER},' - -OPTIONS= THREADS "Enable thread support" on \ - HUGE_STACK_SIZE "Use a larger thread stack" off \ - UCS4 "Use UCS4 for unicode support" on \ - PYMALLOC "Use python's internal malloc" on \ - IPV6 "Enable IPv6 support" on \ - FPECTL "Enable floating point exception handling" off - -.include - -.if ${PYTHON_VERSION} == ${PYTHON_DEFAULT_VERSION} -MLINKS= ${PYTHON_VERSION}.1 python.1 -PLIST_SUB+= IF_DEFAULT="" -.else -PLIST_SUB+= IF_DEFAULT="@comment " -.endif - -# workaround for a bug in base curses.h. -CFLAGS+= -D__wchar_t=wchar_t - -.if !defined(WITHOUT_THREADS) -CONFIGURE_ARGS+= --with-threads -CFLAGS+= ${PTHREAD_CFLAGS} -.if defined(WITHOUT_HUGE_STACK_SIZE) -CFLAGS+= -DTHREAD_STACK_SIZE=0x20000 -.else -CFLAGS+= -DTHREAD_STACK_SIZE=0x100000 -.endif # defined(WITHOUT_HUGE_STACK_SIZE) -CONFIGURE_ENV+= LDFLAGS="${PTHREAD_LIBS} ${LDFLAGS}" -.else -CONFIGURE_ARGS+= --without-threads -.if defined(LDFLAGS) -CONFIGURE_ENV+= LDFLAGS="${LDFLAGS}" -.endif # defined(LDFLAGS) -.endif # !defined(WITHOUT_THREADS) - -.if !defined(WITHOUT_UCS4) && !defined(WITH_UCS2) -CONFIGURE_ARGS+= --enable-unicode=ucs4 -.endif - -.if defined(WITHOUT_PYMALLOC) -CONFIGURE_ARGS+= --without-pymalloc -.endif - -.if ${ARCH} == i386 -PLIST_SUB+= X86_ONLY="" -.else -PLIST_SUB+= X86_ONLY="@comment " -.endif -.if ${ARCH} == amd64 || ${ARCH} == ia64 || ${ARCH} == sparc64 || ${ARCH} == alpha -PLIST_SUB+= 32BIT_ONLY="@comment " -.else -PLIST_SUB+= 32BIT_ONLY="" -.endif -.if ${ARCH} == sparc64 -CFLAGS+= -DPYTHON_DEFAULT_RECURSION_LIMIT=900 -.endif - -.if !exists(/usr/bin/ypcat) # the world with NO_NIS -PLIST_SUB+= NO_NIS="@comment " -.else -PLIST_SUB+= NO_NIS="" -.endif - -.if !defined(WITHOUT_IPV6) -CONFIGURE_ARGS+= --enable-ipv6 -.else -CONFIGURE_ARGS+= --disable-ipv6 -.endif - -.if defined(WITH_FPECTL) -CONFIGURE_ARGS+= --with-fpectl -.endif - -.if ${OSVERSION} >= 700000 -PLATFORMS=plat-freebsd4 plat-freebsd5 plat-freebsd6 -.elif ${OSVERSION} >= 600000 -PLATFORMS=plat-freebsd4 plat-freebsd5 plat-freebsd7 -.else -PLATFORMS=plat-freebsd4 plat-freebsd6 plat-freebsd7 -.endif - -pre-patch: - ${MKDIR} ${WRKSRC} ${SHARED_WRKSRC}/Modules - ${SED} -e '1s,^.*$$,#!${PREFIX}/bin/${PYTHON_VERSION},' \ - ${PATCH_WRKSRC}/Tools/scripts/pydoc > ${WRKDIR}/pydoc2.5 - ${SED} -e '1s,^.*$$,#!${PREFIX}/bin/${PYTHON_VERSION},' \ - ${PATCH_WRKSRC}/Tools/scripts/idle > ${WRKDIR}/idle2.5 - ${SED} -e '1s,^.*$$,#!${PREFIX}/bin/${PYTHON_VERSION},' \ - ${PATCH_WRKSRC}/Lib/smtpd.py > ${WRKDIR}/smtpd2.5.py - ${REINPLACE_CMD} -e \ - 's,/usr/doc/python-docs-,${PREFIX}/share/doc/python,g' \ - ${PATCH_WRKSRC}/Lib/pydoc.py - ${REINPLACE_CMD} -e \ - 's|^\( *prefixes = .*\)\]$$|\1, "${X11BASE}"]|g' \ - ${PATCH_WRKSRC}/Lib/site.py - ${REINPLACE_CMD} -e \ - 's|^ \(..ASDLGEN.*\)$$| ${TRUE}|g' \ - ${PATCH_WRKSRC}/Makefile.pre.in - - ${REINPLACE_CMD} -e \ - 's|*\(..INSTALL_SCRIPT.*\)python-config$$|#port \1|' \ - ${PATCH_WRKSRC}/Makefile.pre.in - - ${SED} -e 's|^#!.*|#!${PREFIX}/bin/${PYTHON_VERSION}|' \ - ${PATCH_WRKSRC}/Misc/python-config.in > ${WRKDIR}/${PYTHON_VERSION}-config - ${SED} -e 's|^#!.*|#!${PREFIX}/bin/${PYTHON_VERSION:S/thon/thon-shared/}|' \ - ${PATCH_WRKSRC}/Misc/python-config.in > ${WRKDIR}/${PYTHON_VERSION:S/thon/thon-shared/}-config - -.if defined(WITH_FPECTL) && ${ARCH} == i386 - ${MKDIR} ${WRKSRC}/Modules - ${ECHO} "fpectl fpectlmodule.c" >> ${WRKSRC}/Modules/Setup.dist -.endif - -post-configure: - ${TAR} -C ${WRKSRC} -cf - . | ${TAR} -C ${SHARED_WRKSRC} -xf - - ${LN} -sf ${PYTHON_WRKSRC}/Lib ${WRKSRC}/Lib - ${SED} -e 's,^\(LDLIBRARY=\).*$$,\1libpython$$(VERSION).so,' \ - -e 's,^\(BLDLIBRARY=\).*$$,\1-L. -lpython$$(VERSION),' \ - -e 's,^\(CFLAGSFORSHARED=\).*$$,\1$$(CCSHARED),' \ - -e 's,^\(Makefile Modules/config.c:.*\)Makefile.pre,\1,' \ - -e 's,^\(.(BUILDPYTHON)\: .*\).(LIBRARY),\1,' \ - -e 's,^\(.(BUILDPYTHON):.*\).(LIBRARY),\1,' \ - ${WRKSRC}/Makefile > ${SHARED_WRKSRC}/Makefile - -pre-build: - cd ${SHARED_WRKSRC}; \ - ${SETENV} ${MAKE_ENV} ${MAKE} lib${PYTHON_VERSION}.so python; \ - ${LN} -f lib${PYTHON_VERSION}.so lib${PYTHON_VERSION}.so.1; \ - ${LN} -f python ${PYTHON_VERSION:S/thon/thon-shared/} - -pre-su-install: -.for platform in ${PLATFORMS} - ${MKDIR} ${PYTHONPREFIX_LIBDIR}/${platform} -.for file in IN.py regen - ${INSTALL_DATA} ${WRKSRC}/Lib/${platform}/${file} \ - ${PYTHONPREFIX_LIBDIR}/${platform}/ -.endfor -.endfor - -pre-install: - ${CAT} ${PLIST_TEMPLATE} | ${AWK} '{ print $$0; } \ - /LIBDIR.*\.py$$/ && !/\/bad/ { print $$0 "o"; print $$0 "c"; }' > ${PLIST} - - @# if openssl 0.9.8 is detected, _sha{256,512} module won't be installed - ([ -f ${WRKSRC}/.without_own_sha ] && \ - ${GREP} -v 'lib-dynload/_sha' ${PLIST} > ${PLIST}.tmp && \ - ${CAT} ${PLIST}.tmp > ${PLIST}) || ${TRUE} - -post-install: - @# install config providers - ${INSTALL_SCRIPT} ${WRKDIR}/${PYTHON_VERSION}-config ${PREFIX}/bin - ${INSTALL_SCRIPT} ${WRKDIR}/${PYTHON_VERSION:S/thon/thon-shared/}-config ${PREFIX}/bin - - @# shared version of executable and library - ${INSTALL_PROGRAM} ${SHARED_WRKSRC}/lib${PYTHON_VERSION}.so.1 \ - ${PREFIX}/lib - cd ${PREFIX}/lib; ${LN} -sf lib${PYTHON_VERSION}.so.1 \ - lib${PYTHON_VERSION}.so - ${LN} -sf ${PREFIX}/lib/lib${PYTHON_VERSION}.so ${PYTHONPREFIX_LIBDIR}/config - ${INSTALL_PROGRAM} \ - ${SHARED_WRKSRC}/${PYTHON_VERSION:S/thon/thon-shared/} \ - ${PREFIX}/bin - - @# additional files installing by ports - ${INSTALL_SCRIPT} ${WRKDIR}/pydoc2.5 ${WRKDIR}/idle2.5 \ - ${WRKDIR}/smtpd2.5.py ${PREFIX}/bin - @${MKDIR} ${MANPREFIX}/man/man1 - ${INSTALL_MAN} ${PYTHON_WRKSRC}/Misc/python.man \ - ${MANPREFIX}/man/man1/${PYTHON_VERSION}.1 - -.if ${PYTHON_VERSION} == ${PYTHON_DEFAULT_VERSION} - for f in ${BIN_SCRIPTS}; do \ - TARGET=`${ECHO_CMD} $$f | ${SED} -E ${BINLINKS_SUB}`; \ - cd ${PREFIX}/bin && ${LN} -f $$TARGET $$f; \ - done -.endif - -.if !defined(NOPORTDOCS) - @${MKDIR} ${TOOLSDIR} - @cd ${PYTHON_WRKSRC}; ${TAR} -cf - Tools | \ - (cd ${TOOLSDIR}; ${TAR} -xf -) - @${MKDIR} ${DEMODIR} - @cd ${PYTHON_WRKSRC}/Demo; ${TAR} -cf - * | \ - (cd ${DEMODIR}; ${TAR} -xf -) -.endif - - @${CAT} ${PKGMESSAGE} - -.include diff --git a/third_party/pygments/tests/examplefiles/qbasic_example b/third_party/pygments/tests/examplefiles/qbasic_example deleted file mode 100644 index 27041af61..000000000 --- a/third_party/pygments/tests/examplefiles/qbasic_example +++ /dev/null @@ -1,2 +0,0 @@ -10 print RIGHT$("hi there", 5) -20 goto 10 diff --git a/third_party/pygments/tests/examplefiles/qsort.prolog b/third_party/pygments/tests/examplefiles/qsort.prolog deleted file mode 100644 index d78de6f1b..000000000 --- a/third_party/pygments/tests/examplefiles/qsort.prolog +++ /dev/null @@ -1,13 +0,0 @@ -partition([], _, [], []). -partition([X|Xs], Pivot, Smalls, Bigs) :- - ( X @< Pivot -> - Smalls = [X|Rest], - partition(Xs, Pivot, Rest, Bigs) - ; Bigs = [X|Rest], - partition(Xs, Pivot, Smalls, Rest) - ). - -quicksort([]) --> []. -quicksort([X|Xs]) --> - { partition(Xs, X, Smaller, Bigger) }, - quicksort(Smaller), [X], quicksort(Bigger). diff --git a/third_party/pygments/tests/examplefiles/r-console-transcript.Rout b/third_party/pygments/tests/examplefiles/r-console-transcript.Rout deleted file mode 100644 index d0cf34b97..000000000 --- a/third_party/pygments/tests/examplefiles/r-console-transcript.Rout +++ /dev/null @@ -1,38 +0,0 @@ - -R version 2.9.2 (2009-08-24) -Copyright (C) 2009 The R Foundation for Statistical Computing -ISBN 3-900051-07-0 - -R is free software and comes with ABSOLUTELY NO WARRANTY. -You are welcome to redistribute it under certain conditions. -Type 'license()' or 'licence()' for distribution details. - - Natural language support but running in an English locale - -R is a collaborative project with many contributors. -Type 'contributors()' for more information and -'citation()' on how to cite R or R packages in publications. - -Type 'demo()' for some demos, 'help()' for on-line help, or -'help.start()' for an HTML browser interface to help. -Type 'q()' to quit R. - -[R.app GUI 1.29 (5464) i386-apple-darwin8.11.1] - -> x <- function {} -Error: syntax error -> x <- function() {} -> x <- function() { -+ cat("hello") -+ cat("world") -+ } -> x -function() { -cat("hello") -cat("world") -} -> x() -helloworld -> 2 + 2 -[1] 4 -> \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/r6rs-comments.scm b/third_party/pygments/tests/examplefiles/r6rs-comments.scm deleted file mode 100644 index cd5c36361..000000000 --- a/third_party/pygments/tests/examplefiles/r6rs-comments.scm +++ /dev/null @@ -1,23 +0,0 @@ -#!r6rs - -#| - - The FACT procedure computes the factorial - - of a non-negative integer. - -|# - -(define fact - - (lambda (n) - - ;; base case - - (if (= n 0) - - #;(= n 1) - - 1 ; identity of * - - (* n (fact (- n 1)))))) diff --git a/third_party/pygments/tests/examplefiles/ragel-cpp_rlscan b/third_party/pygments/tests/examplefiles/ragel-cpp_rlscan deleted file mode 100644 index 4b1463291..000000000 --- a/third_party/pygments/tests/examplefiles/ragel-cpp_rlscan +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Lexes Ragel input files. - * - * @LANG: c++ - * - * Test works with split code gen. - */ - -#include -#include -#include -#include - -using namespace std; - -void escapeXML( const char *data ) -{ - while ( *data != 0 ) { - switch ( *data ) { - case '<': cout << "<"; break; - case '>': cout << ">"; break; - case '&': cout << "&"; break; - default: cout << *data; break; - } - data += 1; - } -} - -void escapeXML( char c ) -{ - switch ( c ) { - case '<': cout << "<"; break; - case '>': cout << ">"; break; - case '&': cout << "&"; break; - default: cout << c; break; - } -} - -void escapeXML( const char *data, int len ) -{ - for ( const char *end = data + len; data != end; data++ ) { - switch ( *data ) { - case '<': cout << "<"; break; - case '>': cout << ">"; break; - case '&': cout << "&"; break; - default: cout << *data; break; - } - } -} - -inline void write( const char *data ) -{ - cout << data; -} - -inline void write( char c ) -{ - cout << c; -} - -inline void write( const char *data, int len ) -{ - cout.write( data, len ); -} - - -%%{ - machine RagelScan; - - word = [a-zA-Z_][a-zA-Z_0-9]*; - integer = [0-9]+; - hex = '0x' [0-9a-fA-F] [0-9a-fA-F]*; - - default = ^0; - EOF = 0; - - # Handles comments in outside code and inline blocks. - c_comment := - ( default* :>> '*/' ) - ${ escapeXML( fc ); } - @{ fret; }; - - action emit { - escapeXML( ts, te-ts ); - } - - # - # Inline action code - # - - ilscan := |* - - "'" ( [^'\\] | /\\./ )* "'" => emit; - '"' ( [^"\\] | /\\./ )* '"' => emit; - '/*' { - write( "/*" ); - fcall c_comment; - }; - '//' [^\n]* '\n' => emit; - - '{' { - write( '{' ); - inline_depth += 1; - }; - - '}' { - write( '}' ); - /* If dropping down to the last } then return - * to ragel code. */ - if ( --inline_depth == 0 ) { - write( "\n" ); - fgoto rlscan; - } - }; - - default => { escapeXML( *ts ); }; - *|; - - # - # Ragel Tokens - # - - rlscan := |* - '}%%' { - if ( !single_line ) { - write( "\n" ); - fgoto main; - } - }; - - '\n' { - if ( single_line ) { - write( "\n" ); - fgoto main; - } - }; - - # Word - word { - write( "" ); - write( ts, te-ts ); - write( "\n" ); - }; - - # Decimal integer. - integer { - write( "" ); - write( ts, te-ts ); - write( "\n" ); - }; - - # Hexidecimal integer. - hex { - write( "" ); - write( ts, te-ts ); - write( "\n" ); - }; - - # Consume comments. - '#' [^\n]* '\n'; - - # Single literal string. - "'" ( [^'\\] | /\\./ )* "'" { - write( "" ); - escapeXML( ts, te-ts ); - write( "\n" ); - }; - - # Double literal string. - '"' ( [^"\\] | /\\./ )* '"' { - write( "" ); - escapeXML( ts, te-ts ); - write( "\n" ); - }; - - # Or literal. - '[' ( [^\]\\] | /\\./ )* ']' { - write( "" ); - escapeXML( ts, te-ts ); - write( "\n" ); - }; - - # Regex Literal. - '/' ( [^/\\] | /\\./ ) * '/' { - write( "" ); - escapeXML( ts, te-ts ); - write( "\n" ); - }; - - # Open an inline block - '{' { - inline_depth = 1; - write( "{" ); - fgoto ilscan; - }; - - punct { - write( "" ); - escapeXML( fc ); - write( "\n" ); - }; - - default; - *|; - - # - # Outside code. - # - - main := |* - - "'" ( [^'\\] | /\\./ )* "'" => emit; - '"' ( [^"\\] | /\\./ )* '"' => emit; - - '/*' { - escapeXML( ts, te-ts ); - fcall c_comment; - }; - - '//' [^\n]* '\n' => emit; - - '%%{' { - write( "
    \n" ); - single_line = false; - fgoto rlscan; - }; - - '%%' { - write( "
    \n" ); - single_line = true; - fgoto rlscan; - }; - - default { - escapeXML( *ts ); - }; - - # EOF. - EOF; - *|; -}%% - -%% write data nofinal; - -void test( const char *data ) -{ - std::ios::sync_with_stdio(false); - - int cs, act; - const char *ts, *te; - int stack[1], top; - - bool single_line = false; - int inline_depth = 0; - - %% write init; - - /* Read in a block. */ - const char *p = data; - const char *pe = data + strlen( data ); - const char *eof = pe; - %% write exec; - - if ( cs == RagelScan_error ) { - /* Machine failed before finding a token. */ - cerr << "PARSE ERROR" << endl; - exit(1); - } -} - -#define BUFSIZE 2048 - -int main() -{ - std::ios::sync_with_stdio(false); - - test("hi %%{ /'}%%'/ { /*{*/ {} } + '\\'' }%%there\n"); - - return 0; -} diff --git a/third_party/pygments/tests/examplefiles/ragel-cpp_snippet b/third_party/pygments/tests/examplefiles/ragel-cpp_snippet deleted file mode 100644 index 203ae28b3..000000000 --- a/third_party/pygments/tests/examplefiles/ragel-cpp_snippet +++ /dev/null @@ -1,2 +0,0 @@ - %% write init; - /* Read in a block. */ diff --git a/third_party/pygments/tests/examplefiles/regex.js b/third_party/pygments/tests/examplefiles/regex.js deleted file mode 100644 index 7790cb001..000000000 --- a/third_party/pygments/tests/examplefiles/regex.js +++ /dev/null @@ -1,22 +0,0 @@ -// regex - -blah(/abc/); -x = /abc/; -x = /abc/.match; - -// math - -blah(1/2); //comment -x = 1 / 2 / 3; -x = 1/1/.1; - -// broken - -x=/1/; -x=1/a/g; -x=a/a/g; - -// real-world - -var x = 1/(1+Math.sqrt(sum)); // convert to number between 1-0 -return Math.round((num / den) * 100)/100; diff --git a/third_party/pygments/tests/examplefiles/resourcebundle_demo b/third_party/pygments/tests/examplefiles/resourcebundle_demo deleted file mode 100644 index e1daa56aa..000000000 --- a/third_party/pygments/tests/examplefiles/resourcebundle_demo +++ /dev/null @@ -1,9 +0,0 @@ -root:table { - usage:string { "Usage: genrb [Options] files" } - version:int { 122 } - errorcodes:array { - :string { "Invalid argument" } - :string { "File not found" } - :string { "\x00 \r \t \n \u1234" } - } -} diff --git a/third_party/pygments/tests/examplefiles/reversi.lsp b/third_party/pygments/tests/examplefiles/reversi.lsp deleted file mode 100644 index fa9a333c1..000000000 --- a/third_party/pygments/tests/examplefiles/reversi.lsp +++ /dev/null @@ -1,427 +0,0 @@ -#!/usr/bin/env newlisp -;; @module reversi.lsp -;; @description a simple version of Reversi: you as white against newLISP as black -;; @version 0.1 alpha August 2007 -;; @author cormullion -;; -;; 2008-10-08 21:46:54 -;; updated for newLISP version 10. (changed nth-set to setf) -;; this now does not work with newLISP version 9! -;; -;; This is my first attempt at writing a simple application using newLISP-GS. -;; The game algorithms are basically by -;; Peter Norvig http://norvig.com/paip/othello.lisp -;; and all I've done is translate to newLISP and add the interface... -;; -;; To-Do: work out how to handle the end of the game properly... -;; To-Do: complete newlispdoc for the functions - -(constant 'empty 0) -(constant 'black 1) -(constant 'white 2) -(constant 'outer 3) ; squares outside the 8x8 board - -(set '*board* '()) ; the master board is a 100 element list -(set '*moves* '()) ; list of moves made - -; these are the 8 different directions from a square on the board - -(set 'all-directions '(-11 -10 -9 -1 1 9 10 11)) - -; return a list of all the playable squares (the 8 by 8 grid inside the 10by10 - -(define (all-squares) - (local (result) - (for (square 11 88) - (if (<= 1 (mod square 10) 8) - (push square result -1))) -result)) - -; make a board - -(define (make-board) - (set '*board* (dup outer 100)) - (dolist (s (all-squares)) - (setf (*board* s) empty))) - -; for testing and working at a terminal - -(define (print-board) - (print { }) - (for (c 1 8) - (print c)) - (set 'c 0) - (for (i 0 99) - (cond - ((= (*board* i) 0) (print {.})) - ((= (*board* i) 1) (print {b})) - ((= (*board* i) 2) (print {w}))) - (if (and (<= i 88) (= (mod (+ i 1) 10) 0)) ; newline - (print "\n" (inc c)))) - (println "\n")) - -; the initial starting pattern - -(define (initial-board) - (make-board) - (setf (*board* 44) white) - (setf (*board* 55) white) - (setf (*board* 45) black) - (setf (*board* 54) black)) - -(define (opponent player) - (if (= player black) white black)) - -(define (player-name player) - (if (= player white) "white" "black")) - -(define (valid-move? move) - (and - (integer? move) - (<= 11 move 88) - (<= 1 (mod move 10) 8))) - -(define (empty-square? square) - (and - (valid-move? square) - (= (*board* square) empty))) - -; test whether a move is legal. The square must be empty -; and it must flip at least one of the opponent's piece - -(define (legal-move? move player) - (and - (empty-square? move) - (exists (fn (dir) (would-flip? move player dir)) all-directions))) - -; would this move by player result in any flips in the given direction? -; if so, return the number of the 'opposite' (bracketing) piece's square - -(define (would-flip? move player dir) - (let - ((c (+ move dir))) - (and - (= (*board* c) (opponent player)) - (find-bracketing-piece (+ c dir) player dir)))) - -(define (find-bracketing-piece square player dir) - ; return the square of the bracketing piece, if any - (cond - ((= (*board* square) player) square) - ((= (*board* square) (opponent player)) - (find-bracketing-piece (+ square dir) player dir)) - (true nil))) - -(define (make-flips move player dir) - (let - ((bracketer (would-flip? move player dir)) - (c (+ move dir))) - (if bracketer - (do-until (= c bracketer) - (setf (*board* c) player) - (push c *flips* -1) - (inc c dir))))) - -; make the move on the master game board, not yet visually - -(define (make-move move player) - (setf (*board* move) player) - (push move *moves* -1) - (set '*flips* '()) ; we're going to keep a record of the flips made - (dolist (dir all-directions) - (make-flips move player dir))) - -(define (next-to-play previous-player) - (let ((opp (opponent previous-player))) - (cond - ((any-legal-move? opp) opp) - ((any-legal-move? previous-player) - (println (player-name opp) " has no moves") - previous-player) - (true nil)))) - -; are there any legal moves (returns first) for this player? -(define (any-legal-move? player) - (exists (fn (move) (legal-move? move player)) - (all-squares))) - -; a list of all legal moves might be useful -(define (legal-moves player) - (let ((result '())) - (dolist (move (all-squares)) - (if (legal-move? move player) - (push move result))) - (unique result))) - -; define any number of strategies that can be called on to calculate -; the next computer move. This is the only one I've done... - make -; any legal move at random! - -(define (random-strategy player) - (seed (date-value)) - (apply amb (legal-moves player))) - -; get the next move using a particular strategy - -(define (get-move strategy player) - (let ((move (apply strategy (list player)))) - (cond - ((and - (valid-move? move) - (legal-move? move player)) - (make-move move player)) - (true - (println "no valid or legal move for " (player-name player) ) - nil)) - move)) - -; that's about all the game algorithms for now -; now for the interface - -(if (= ostype "Win32") - (load (string (env "PROGRAMFILES") "/newlisp/guiserver.lsp")) - (load "/usr/share/newlisp/guiserver.lsp") -) - -(gs:init) -(map set '(screen-width screen-height) (gs:get-screen)) -(set 'board-width 540) -; center on screen -(gs:frame 'Reversi (- (/ screen-width 2) (/ board-width 2)) 60 board-width 660 "Reversi") -(gs:set-border-layout 'Reversi) - -(gs:canvas 'MyCanvas 'Reversi) - (gs:set-background 'MyCanvas '(.8 .9 .7 .8)) - (gs:mouse-released 'MyCanvas 'mouse-released-action true) - -(gs:panel 'Controls) - (gs:button 'Start 'start-game "Start") - -(gs:panel 'Lower) - (gs:label 'WhiteScore "") - (gs:label 'BlackScore "") - -(gs:add-to 'Controls 'Start ) -(gs:add-to 'Lower 'WhiteScore 'BlackScore) -(gs:add-to 'Reversi 'MyCanvas "center" 'Controls "north" 'Lower "south") - -(gs:set-anti-aliasing true) -(gs:set-visible 'Reversi true) - -; size of board square, and radius/width of counter -(set 'size 60 'width 30) - -; initialize the master board - -(define (initial-board) - (make-board) - (setf (*board* 44) white) - (setf (*board* 55) white) - (setf (*board* 45) black) - (setf (*board* 54) black) -) - -; draw a graphical repesentation of the board - -(define (draw-board) - (local (x y) - (dolist (i (all-squares)) - (map set '(x y) (square-to-xy i)) - (gs:draw-rect - (string x y) - (- (* y size) width ) ; !!!!!! - (- (* x size) width ) - (* width 2) - (* width 2) - gs:white)))) - -(define (draw-first-four-pieces) - (draw-piece 44 "white") - (draw-piece 55 "white") - (draw-piece 45 "black") - (draw-piece 54 "black")) - -; this next function can mark the legal moves available to a player - -(define (show-legal-moves player) - (local (legal-move-list x y) - (set 'legal-move-list (legal-moves player)) - (dolist (m (all-squares)) - (map set '(x y) (square-to-xy m)) - (gs:draw-rect - (string x y) - (- (* y size) width ) ; !!!!!! - (- (* x size) width ) - (* width 2) - (* width 2) - (if (find m legal-move-list) gs:blue gs:white) - ) - ) - ) -) - -; convert the number of a square on the master board to coordinates - -(define (square-to-xy square) - (list (/ square 10) (mod square 10))) - -; draw one of the pieces - -(define (draw-piece square colour) - (local (x y) - (map set '(x y) (square-to-xy square)) - (cond - ((= colour "white") - (gs:fill-circle - (string x y) - (* y size) ; !!!!!!! y first, cos y is x ;-) - (* x size) - width - gs:white)) - - ((= colour "black") - (gs:fill-circle - (string x y) - (* y size) - (* x size) - width - gs:black)) - - ((= colour "empty") - (gs:draw-rect - (string x y) - (- (* y size) width ) - (- (* x size) width ) - (* width 2) - (* width 2) - gs:white)) - ))) - -; animate the pieces flipping - -(define (flip-piece square player) -; flip by drawing thinner and fatter ellipses -; go from full disk in opposite colour to invisible -; then from invisible to full disk in true colour - (local (x y colour) - (map set '(x y) (square-to-xy square)) - ; delete original piece - (gs:delete-tag (string x y)) - (set 'colour (if (= player 2) gs:black gs:white )) - (for (i width 1 -3) - (gs:fill-ellipse - (string x y {flip} i) - (* y size) ; y first :-) !!! - (* x size) - i - width - colour) - (sleep 20) ; this might need adjusting... - (gs:delete-tag (string x y {flip} i)) - ) - (set 'colour (if (= player 2) gs:white gs:black)) - (for (i 1 width 3) - (gs:fill-ellipse - (string x y {flip} i) - (* y size) ; :-) !!! - (* x size) - i - width - colour) - (sleep 20) - (gs:delete-tag (string x y {flip} i)) - ) - ; draw the piece again - (gs:fill-circle - (string x y) - (* y size) - (* x size) - width - colour) - ) -) - -(define (do-move move player) - (cond - ; check if the move is good ... - ((and (!= player nil) - (valid-move? move) - (legal-move? move player)) - - ; ... play it - ; make move on board - (make-move move player) - ; and on screen - (draw-piece move (player-name player)) - (gs:update) - ; do flipping stuff - - ; wait for a while - (sleep 1000) - - ; then do flipping - (dolist (f *flips*) - (flip-piece f player)) - - (inc *move-number*) - (draw-piece move (player-name player)) - (gs:update) - - ; update scores - (gs:set-text 'WhiteScore - (string "White: " (first (count (list white) *board*)))) - (gs:set-text 'BlackScore - (string "Black: " (first (count (list black) *board*)))) - ) - ; or return nil - (true - nil))) - -; the game is driven by the mouse clicks of the user -; in reply, the computer plays a black piece -; premature clicking is possible and possibly a bad thing... - -(define (mouse-released-action x y button modifiers tags) - ; extract the tag of the clicked square - (set 'move (int (string (first tags)) 0 10)) - (if (do-move move player) - (begin - (set 'player (next-to-play player)) - ; there is a training mode - legal squares are highlighted - ; you can uncomment the next line... - ; (show-legal-moves player) - (gs:update) - - ; wait for black's reply - (gs:set-cursor 'Reversi "wait") - (gs:set-text 'Start "black's move - thinking...") - ; give the illusion of Deep Thought... - (sleep 2000) - ; black's reply - ; currently only the random strategy has been defined... - (set 'strategy random-strategy) - (set 'move (apply strategy (list player))) - (do-move move player) - (set 'player (next-to-play player)) - ; (show-legal-moves player) ; to see black's moves - (gs:set-text 'Start "your move") - (gs:set-cursor 'Reversi "default") - (gs:update)))) - -(define (start-game) - (gs:set-text 'Start "Click a square to place a piece!") - (gs:disable 'Start) - (set 'player white)) - -(define (start) - (gs:set-text 'Start "Start") - (gs:enable 'Start) - (set '*move-number* 1 - '*flips* '()) - (initial-board) - (draw-board) - (draw-first-four-pieces)) - -(start) - -(gs:listen) \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/roboconf.graph b/third_party/pygments/tests/examplefiles/roboconf.graph deleted file mode 100644 index e5fdedff6..000000000 --- a/third_party/pygments/tests/examplefiles/roboconf.graph +++ /dev/null @@ -1,40 +0,0 @@ -################## -# A sample graph -################## - -import some-definition.graph; -import another-definition.graph; - -VM { - installer : target; - children: deployable; -} - -facet deployable { - # nothing -} - -# Sample deployables -mysql { - insTaller: puppet; - facets: deployable; - exports: ip, port = 3306; -} - -tomcat { - installer: bash; - facets: deployable; - exports: ip; - children: web-application; -} - -facet web-application { - exports: full-path = undefined; -} - -my-war-1 { - facets: web-application; - installer: file; - exports: full-path = apps/my-war-1; # the relative path - imports: mysql.*; -} diff --git a/third_party/pygments/tests/examplefiles/roboconf.instances b/third_party/pygments/tests/examplefiles/roboconf.instances deleted file mode 100644 index c69a2ab08..000000000 --- a/third_party/pygments/tests/examplefiles/roboconf.instances +++ /dev/null @@ -1,24 +0,0 @@ - -# Deal with imports -import others.instances; - -instance of VM { - name: VM-mysql; - instance of mysql { - name: MySQL; - } -} - -instance of VM { - name: VM ; - count: 5; - - INSTANCE of tomcat { - name: Tomcat; - - instance of my-war-1 { - name: my-war-1; - full-path: apps/my-war; - } - } -} diff --git a/third_party/pygments/tests/examplefiles/robotframework_test.txt b/third_party/pygments/tests/examplefiles/robotframework_test.txt deleted file mode 100644 index 0d8179c09..000000000 --- a/third_party/pygments/tests/examplefiles/robotframework_test.txt +++ /dev/null @@ -1,40 +0,0 @@ -*** Settings *** -Documentation Simple example demonstrating syntax highlighting. -Library ExampleLibrary -Test Setup Keyword argument argument with ${VARIABLE} - -*** Variables *** -${VARIABLE} Variable value -@{LIST} List variable here -&{DICT} Key1=Value1 Key2=Value2 - -*** Test Cases *** -Keyword-driven example - Initialize System - Do Something - Result Should Be 42 - [Teardown] Cleanup System - -Data-driven example - [Template] Keyword - argument1 argument2 - argument ${VARIABLE} - @{LIST} - -Gherkin - Given system is initialized - When something is done - Then result should be "42" - -| Pipes | -| | [Documentation] | Also pipe separated format is supported. | -| | Log | As this example demonstrates. | - -*** Keywords *** -Result Should Be - [Arguments] ${expected} - ${actual} = Get Value - Should be Equal ${actual} ${expected} - -Then result should be "${expected}" - Result Should Be ${expected} diff --git a/third_party/pygments/tests/examplefiles/rql-queries.rql b/third_party/pygments/tests/examplefiles/rql-queries.rql deleted file mode 100644 index 1d86df3c2..000000000 --- a/third_party/pygments/tests/examplefiles/rql-queries.rql +++ /dev/null @@ -1,34 +0,0 @@ -Any N, N2 where N is Note, N2 is Note, N a_faire_par P1, P1 nom 'john', N2 a_faire_par P2, P2 nom 'jane' ; -DISTINCT Any N, D, C, T, A ORDERBY D DESC LIMIT 40 where N is Note, N diem D, W is Workcase, W concerned_by N, N cost C, N text T, N author A, N diem <= today -Bookmark B WHERE B owned_by G, G eid 5; -Any X WHERE E eid 22762, NOT E is_in X, X modification_date D ORDERBY D DESC LIMIT 41; -Any A, R, SUB ORDERBY R WHERE A is "Workcase", S is Division, S concerned_by A, A subject SUB, S eid 85, A ref R; -Any D, T, L WHERE D is Document, A concerned_by D,A eid 14533, D title T, D location L; -Any N,A,B,C,D ORDERBY A DESC WHERE N is Note, W concerned_by N, W eid 14533, N diem A,N author B,N text C,N cost D; -Any X ORDERBY D DESC LIMIT 41 WHERE E eid 18134, NOT E concerned_by X, X modification_date D -DISTINCT Any N, D, C, T, A ORDERBY D ASC LIMIT 40 WHERE N is Note, N diem D, P is Person, N to_be_contacted_by G, N cost C, N text T, N author A, G login "john"; -INSERT Person X: X surname "Doe", X firstname "John"; -Workcase W where W ref "ABCD12"; -Workcase W where W ref LIKE "AB%"; -Any X WHERE X X eid 53 -Any X WHERE X Document X occurence_of F, F class C, C name 'Comics' X owned_by U, U login 'syt' X available true -Person P WHERE P work_for P, S name 'Acme', P interested_by T, T name 'training' -Note N WHERE N written_on D, D day> (today -10), N written_by P, P name 'joe' or P name 'jack' -Person P WHERE (P interested_by T, T name 'training') or (P city 'Paris') -Any N, P WHERE X is Person, X name N, X first_name P -String N, P WHERE X is Person, X name N, X first_name P -INSERT Person X: X name 'widget' -INSERT Person X, Person Y: X name 'foo', Y name 'nice', X friend Y -INSERT Person X: X name 'foo', X friend Y WHERE name 'nice' -SET X name 'bar', X first_name 'original' where X is Person X name 'foo' -SET X know Y WHERE X friend Y -DELETE Person X WHERE X name 'foo' -DELETE X friend Y WHERE X is Person, X name 'foo' -Any X WHERE X name LIKE '%lt' -Any X WHERE X name IN ( 'joe', 'jack', 'william', 'averell') -Any X, V WHERE X concerns P, P eid 42, X corrected_in V? -Any C, P WHERE C is Card, P? documented_by C -Point P where P abs X, P ord Y, P value X+Y -Document X where X class C, C name 'Cartoon', X owned_by U, U login 'joe', X available true -(Any X WHERE X is Document) UNION (Any X WHERE X is File) -Any A,B WHERE A creation_date B WITH A BEING (Any X WHERE X is Document) UNION (Any X WHERE X is File) diff --git a/third_party/pygments/tests/examplefiles/ruby_func_def.rb b/third_party/pygments/tests/examplefiles/ruby_func_def.rb deleted file mode 100644 index a820c68fa..000000000 --- a/third_party/pygments/tests/examplefiles/ruby_func_def.rb +++ /dev/null @@ -1,11 +0,0 @@ -class (get_foo("blub"))::Foo - def (foo("bar") + bar("baz")).something argh, aaahaa - 42 - end -end - -class get_the_fuck("out")::Of::My - def parser_definition - ruby! - end -end diff --git a/third_party/pygments/tests/examplefiles/sample.qvto b/third_party/pygments/tests/examplefiles/sample.qvto deleted file mode 100644 index 6241ee231..000000000 --- a/third_party/pygments/tests/examplefiles/sample.qvto +++ /dev/null @@ -1,4 +0,0 @@ -transformation Foo(uml: SimpleUML, - rdbms : SimpleRDBMS) { -} -/* comment */ diff --git a/third_party/pygments/tests/examplefiles/scilab.sci b/third_party/pygments/tests/examplefiles/scilab.sci deleted file mode 100644 index 8dea7b9cb..000000000 --- a/third_party/pygments/tests/examplefiles/scilab.sci +++ /dev/null @@ -1,30 +0,0 @@ -// Scilab ( http://www.scilab.org/ ) -// Copyright (C) INRIA - Serge STEER -// - -function I=sub2ind(dims,varargin) -//sub2ind is used to determine the equivalent single index -//corresponding to a given set of subscript values. - -//I = sub2ind(dims,i1,i2,..) returns the linear index equivalent to the -//row, column, ... subscripts in the arrays i1,i2,.. for an matrix of -//size dims. - -//I = sub2ind(dims,Mi) returns the linear index -//equivalent to the n subscripts in the columns of the matrix Mi for a matrix -//of size dims. - - d=[1;cumprod(matrix(dims(1:$-1),-1,1))] - for i=1:size(varargin) - if varargin(i)==[] then I=[],return,end - end - - if size(varargin)==1 then //subindices are the columns of the argument - I=(varargin(1)-1)*d+1 - else //subindices are given as separated arguments - I=1 - for i=1:size(varargin) - I=I+(varargin(i)-1)*d(i) - end - end -endfunction diff --git a/third_party/pygments/tests/examplefiles/scope.cirru b/third_party/pygments/tests/examplefiles/scope.cirru deleted file mode 100644 index c3d1a2c6c..000000000 --- a/third_party/pygments/tests/examplefiles/scope.cirru +++ /dev/null @@ -1,237 +0,0 @@ - --- demo - -define a (read cd) $ if (> a cd) - print demo - print "not demo" - -say $ print a $ save $ b $ x $ c 8 - -print fun - --- test on folding - -a $ - -b $ c - -d $ e $ f - -g $ h $ i j $ k $ - --- test on comma - -print (, a) - a - , b - , c (, d) - --- test on HTML - -doctype - -html - head - title $ = Cirru - script (:defer) $ :src build/build.js - link (:rel stylesheet) $ :href css/page.css - link (:rel icon) - :href http://logo.cirru.org/cirru-32x32.png?v=3 - body - textarea.demo.source $ :placeholder "Source Code" - textarea.demo.target $ :placeholder "Compiled Data" - @insert ../html/ga.html - --- test on indentation - -a $ b $ c - -e f - (g) - h - --- test on parentheses - -3 4 (1) 4 - -((((1)))) - -x - --- test on quotes - -a b c d - -"a b c d" - -"a b \" c d" - -"a b" "c d" - --- test on unfolding - -set - add 1 $ - , x y - add 5 $ - add 2 - --- test on HTML attributes - -div - div - :class a - div - :class a b c d - - div - :class a (@ b) (@ c) d - - div - :class a - @if (@ b) - div b - div c - div - :class a - @if (@ b) b c - --- test on helpers - -@if (@call a b) (div) (span) - -@each members - div (@ name) - -@each a - div (@ b) - @each c - div (@ d) - --- test on HTML structure - -@rich more - #demo-more-box - #demo-more - :data-lang-text demo-more - #demo-more-list - @each room - .demo-more-room - span.demo-name - @ topic - span.demo-join - :data-lang-text demo-join - :data-id (@ id) - --- text on bool - -print #true -print #false -print #yes -print #no -print #t -print #f - --- test on Cirru js - -set a 1 -set a (= "This is a string") -set b #t - --- this is comment - -number 1.4 -string x -regex ^\s$ -regex "^\\s-\"$" -sentence this is a string - -array 1 2 3 (= nothing) #t (= #t) - -set c (array 1 (= nothing)) - -set d $ object (a (= google)) - b (= reader) - c 1 - d $ array 1 2 (= string) - -1 c --1 c - -:b d -.log console a 2 -.log console - -set demo $ object - call $ \ x (.log console x) (. this call) -. demo (.call 1) (.call 4) - -=.x d 3 - -set d null - -new Array 1 2 3 - -set x (:length c) -set str (= str) -set c (.toUpperCase str) - -\ x (+ x 1) -\ (x y) (+ x y) -\ x (set aa 1) (+ aa x) - -set f (\ x (+ x 1)) - -+ a 1 2 -+= a 1 - -> 1 2 3 - -if (> 2 1) (+ a 1) -else 2 - -if (> a 2) - .log console (= "large") -elseif (> a 1) - .log console (= "still good") -else - .log console (= "so so") - -set a $ if (> 2 1) #t #f - -switch a - 1 (.log console 1) - 2 (.log console 2) - else (.log console (= "something else")) - -set a $ array 2 +3 -4 -for (a x i) (.log console x i) - -set a 0 -while (< a 10) (+= a 1) (.log console a) - --- WebAssembly variable names - --- ":(c) 2015 Andreas Rossberg" - -module - export :even $even - export "odd" $odd - - func $even (param $n i32) (result i32) - if (i32.eq (get_local $n) (i32.const 0)) - i32.const 1 - call $odd (i32.sub (get_local $n) (i32.const 1)) - - func $odd (param $n i32) (result i32) - store_global $scratch (get_local $n) - if (i32.eq (get_local $n) (i32.const 0) - i32.const 0 - call $even (i32.sub (get_local $n) (i32.const 1)) - - global $scratch i32 - -assert_eq (invoke :even (i32.const 13)) (i32.const 0) -assert_eq (invoke :even (i32.const 20)) (i32.const 1) -assert_eq (invoke :odd (i32.const 13)) (i32.const 1) -assert_eq (invoke :odd (i32.const 20)) (i32.const 0) diff --git a/third_party/pygments/tests/examplefiles/session.dylan-console b/third_party/pygments/tests/examplefiles/session.dylan-console deleted file mode 100644 index 6f289c8e8..000000000 --- a/third_party/pygments/tests/examplefiles/session.dylan-console +++ /dev/null @@ -1,9 +0,0 @@ -? 7 * 52; -=> 364 -? define variable *your-variable* = $foo; -? begin - let yours = "apple"; - let mine = yours; - mine == yours; - end; -=> #t diff --git a/third_party/pygments/tests/examplefiles/sibling.prolog b/third_party/pygments/tests/examplefiles/sibling.prolog deleted file mode 100644 index bc591502b..000000000 --- a/third_party/pygments/tests/examplefiles/sibling.prolog +++ /dev/null @@ -1,19 +0,0 @@ -/* Comments /* can nest */ -still a comment -*/ - -:- module(maplist, maplist/3) - -assert(world:done). % asserts - -sibling(X, Y) :- parent_child(Z, X), parent_child(Z, Y). - -parent_child(X, Y) :- father_child(X, Y). -parent_child(X, Y) :- mother_child(X, Y). - -mother_child(trude, sally). - -father_child(tom, sally). -father_child(tom, erica). -father_child(mike, tom). - diff --git a/third_party/pygments/tests/examplefiles/simple.camkes b/third_party/pygments/tests/examplefiles/simple.camkes deleted file mode 100644 index 43e117322..000000000 --- a/third_party/pygments/tests/examplefiles/simple.camkes +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Example input for CAmkES lexer. - */ - -import ; - -// A single-line comment. - -import "components/Client/Client.camkes"; -import "components/Echo/Echo.camkes"; - -component Foo { - include "proc_defn.h"; - control; - dataport Buf my_port; -} - -#ifdef BAR_AVAILABLE - component Bar { - provides CharAccess ca; - } -#endif - - #define HASH_DEF_WITH_LEADING_SPACE - -assembly { /* Another multiline comment. */ - composition { - component Echo echo; - component Client client; - - connection seL4RPC simple(from client.s, to echo.s); - } - - configuration { - echo.dma_pool = 4096; - } -} - diff --git a/third_party/pygments/tests/examplefiles/simple.croc b/third_party/pygments/tests/examplefiles/simple.croc deleted file mode 100644 index 8f12771a9..000000000 --- a/third_party/pygments/tests/examplefiles/simple.croc +++ /dev/null @@ -1,747 +0,0 @@ -module simple; - -// Importing stuff. -{ - function loadMod(name, ns) - { - assert(name == "mod"); - - ns.x = "I'm x"; - - ns.foo = function foo() - { - writefln("foo"); - }; - - ns.bar = function bar(x) - { - return x[0]; - }; - - ns.baz = function baz() - { - writefln(x); - }; - - foreach(k, v; ns) - if(isFunction(v)) - v.environment(ns); - } - - setModuleLoader("mod", loadMod); - - import mod : foo, bar; - foo(); - writefln(bar([5])); - mod.baz(); - - writefln(); -} - -// Super calls. -{ - class Base - { - function fork() - { - writefln("Base fork."); - } - } - - class Derived : Base - { - function fork() - { - writefln("Derived fork!"); - super.fork(); - } - } - - local d = Derived(); - d.fork(); - - writefln(); -} - -// Coroutines and coroutine iteration. -{ - local countDown = coroutine function countDown(x) - { - yield(); - - while(x > 0) - { - yield(x); - x--; - } - }; - - foreach(v; countDown, 5) - writefln(v); - - writefln(); - - local forEach = coroutine function forEach(t) - { - yield(); - - foreach(k, v; t) - yield(k, v); - }; - - foreach(_, k, v; forEach, {hi = 1, bye = 2}) - writefln("key: ", k, ", value: ", v); - - writefln(); -} - -// Testing tailcalls. -{ - function recurse(x) - { - writefln("recurse: ", x); - - if(x == 0) - return toString(x); - else - return recurse(x - 1); - } - - writefln(recurse(5)); - writefln(); - - class A - { - function f(x) - { - writefln("A.f: ", x); - - if(x == 0) - return toString(x); - else - return this.f(x - 1); // call it as this.f to force a 'method' instruction to be generated - } - } - - local a = A(); - writefln(a.f(5)); - writefln(); -} - -{ - // A function which lets us define properties for a class. - // The varargs should be a bunch of tables, each with a 'name' field, and 'getter' and/or 'setter' fields. - function mixinProperties(classType, vararg) - { - classType.mProps = { }; - - classType.opIndex = function opIndex(key) - { - local prop = mProps[key]; - - if(prop is null) - throw format(classType, ".opIndex() - Property '%s' does not exist", key); - - local getter = prop.getter; - - if(getter is null) - throw format(classType, ".opIndex() - Property '%s' has no getter", key); - - return getter(with this); - }; - - classType.opIndexAssign = function opIndexAssign(key, value) - { - local prop = mProps[key]; - - if(prop is null) - throw format(classType, ".opIndexAssign() - Property '%s' does not exist", key); - - local setter = prop.setter; - - if(setter is null) - throw format(classType, ".opIndexAssign() - Property '%s' has no setter", key); - - setter(with this, value); - }; - - foreach(i, prop; [vararg]) - { - if(!isTable(prop)) - throw format("mixinProperties() - property ", i, " is not a table"); - - if(prop.name is null) - throw format("mixinProperties() - property ", i, " has no name"); - - if(prop.setter is null && prop.getter is null) - throw format("mixinProperties() - property '%s' has no getter or setter", prop.name); - - classType.mProps[prop.name] = prop; - } - } - - // Create a class to test out. - class PropTest - { - mX = 0; - mY = 0; - mName = ""; - - function constructor(name) - { - mName = name; - } - - function toString() - { - return format("name = '", mName, "' x = ", mX, " y = ", mY); - } - } - - // Mix in the properties. - mixinProperties - ( - PropTest, - - { - name = "x", - - function setter(value) - { - mX = value; - } - - function getter() - { - return mX; - } - }, - - { - name = "y", - - function setter(value) - { - mY = value; - } - - function getter() - { - return mY; - } - }, - - { - name = "name", - - function getter() - { - return mName; - } - } - ); - - // Create an instance and try it out. - local p = PropTest("hello"); - - writefln(p); - p.x = 46; - p.y = 123; - p.x = p.x + p.y; - writefln(p); - - // Try to access a nonexistent property. - try - p.name = "crap"; - catch(e) - { - writefln("caught: ", e); - writefln(getTraceback()); - } - - writefln(); -} - -// Some container classes. -{ - class PQ - { - mData; - mLength = 0; - - function constructor() - { - mData = array.new(15); - } - - function insert(data) - { - resizeArray(); - mData[mLength] = data; - - local index = mLength; - local parentIndex = (index - 1) / 2; - - while(index > 0 && mData[parentIndex] > mData[index]) - { - local temp = mData[parentIndex]; - mData[parentIndex] = mData[index]; - mData[index] = temp; - - index = parentIndex; - parentIndex = (index - 1) / 2; - } - - mLength += 1; - } - - function remove() - { - if(mLength == 0) - throw "PQ.remove() - No items to remove"; - - local data = mData[0]; - mLength -= 1; - mData[0] = mData[mLength]; - - local index = 0; - local left = 1; - local right = 2; - - while(index < mLength) - { - local smaller; - - if(left >= mLength) - { - if(right >= mLength) - break; - else - smaller = right; - } - else - { - if(right >= mLength) - smaller = left; - else - { - if(mData[left] < mData[right]) - smaller = left; - else - smaller = right; - } - } - - if(mData[index] > mData[smaller]) - { - local temp = mData[index]; - mData[index] = mData[smaller]; - mData[smaller] = temp; - - index = smaller; - left = (index * 2) + 1; - right = left + 1; - } - else - break; - } - - return data; - } - - function resizeArray() - { - if(mLength >= #mData) - mData.length((#mData + 1) * 2 - 1); - } - - function hasData() - { - return mLength != 0; - } - } - - class Stack - { - mHead = null; - - function push(data) - { - local t = { data = data, next = mHead }; - mHead = t; - } - - function pop() - { - if(mHead is null) - throw "Stack.pop() - No items to pop"; - - local item = mHead; - mHead = mHead.next; - - return item.data; - } - - function hasData() - { - return mHead !is null; - } - } - - class Queue - { - mHead = null; - mTail = null; - - function push(data) - { - local t = { data = data, next = null }; - - if(mTail is null) - { - mHead = t; - mTail = t; - } - else - { - mTail.next = t; - mTail = t; - } - } - - function pop() - { - if(mTail is null) - throw "Queue.pop() - No items to pop"; - - local item = mHead; - mHead = mHead.next; - - if(mHead is null) - mTail = null; - - return item.data; - } - - function hasData() - { - return mHead !is null; - } - } - - writefln("Priority queue (heap)"); - - local prioQ = PQ(); - - for(i : 0 .. 10) - prioQ.insert(math.rand(0, 20)); - - while(prioQ.hasData()) - writefln(prioQ.remove()); - - writefln(); - writefln("Stack"); - - local stack = Stack(); - - for(i : 0 .. 5) - stack.push(i + 1); - - while(stack.hasData()) - writefln(stack.pop()); - - writefln(); - writefln("Queue"); - - local queue = Queue(); - - for(i : 0 .. 5) - queue.push(i + 1); - - while(queue.hasData()) - writefln(queue.pop()); - - writefln(); -} - -// opApply tests. -{ - class Test - { - mData = [4, 5, 6]; - - function opApply(extra) - { - if(isString(extra) && extra == "reverse") - { - local function iterator_reverse(index) - { - index--; - - if(index < 0) - return; - - return index, mData[index]; - } - - return iterator_reverse, this, #mData; - } - else - { - local function iterator(index) - { - index++; - - if(index >= #mData) - return; - - return index, mData[index]; - } - - return iterator, this, -1; - } - } - } - - local test = Test(); - - foreach(k, v; test) - writefln("test[", k, "] = ", v); - - writefln(); - - foreach(k, v; test, "reverse") - writefln("test[", k, "] = ", v); - - writefln(); - - test = - { - fork = 5, - knife = 10, - spoon = "hi" - }; - - foreach(k, v; test) - writefln("test[", k, "] = ", v); - - test = [5, 10, "hi"]; - - writefln(); - - foreach(k, v; test) - writefln("test[", k, "] = ", v); - - writefln(); - - foreach(k, v; test, "reverse") - writefln("test[", k, "] = ", v); - - writefln(); - - foreach(k, v; "hello") - writefln("str[", k, "] = ", v); - - writefln(); - - foreach(k, v; "hello", "reverse") - writefln("str[", k, "] = ", v); - - writefln(); -} - -// Testing upvalues in for loops. -{ - local arr = array.new(10); - - for(i : 0 .. 10) - arr[i] = function() { return i; }; - - writefln("This should be the values 0 through 9:"); - - foreach(func; arr) - writefln(func()); - - writefln(); -} - -// Testing nested functions. -{ - function outer() - { - local x = 3; - - function inner() - { - x++; - writefln("inner x: ", x); - } - - writefln("outer x: ", x); - inner(); - writefln("outer x: ", x); - - return inner; - } - - local func = outer(); - func(); - - writefln(); -} - -// Testing Exceptions. -{ - function thrower(x) - { - if(x >= 3) - throw "Sorry, x is too big for me!"; - } - - function tryCatch(iterations) - { - try - { - for(i : 0 .. iterations) - { - writefln("tryCatch: ", i); - thrower(i); - } - } - catch(e) - { - writefln("tryCatch caught: ", e); - throw e; - } - finally - writefln("tryCatch finally"); - } - - try - { - tryCatch(2); - tryCatch(5); - } - catch(e) - writefln("caught: ", e); - - writefln(); -} - -// Testing arrays. -{ - local array = [7, 9, 2, 3, 6]; - - array.sort(); - - foreach(i, v; array) - writefln("arr[", i, "] = ", v); - - array ~= ["foo", "far"]; - - writefln(); - - foreach(i, v; array) - writefln("arr[", i, "] = ", v); - - writefln(); -} - -// Testing vararg functions. -{ - function vargs(vararg) - { - local args = [vararg]; - - writefln("num varargs: ", #args); - - foreach(i, v; args) - writefln("args[", i, "] = ", v); - } - - vargs(); - - writefln(); - - vargs(2, 3, 5, "foo", "bar"); - - writefln(); -} - -// Testing switches. -{ - foreach(v; ["hi", "bye", "foo"]) - { - switch(v) - { - case "hi": - writefln("switched to hi"); - break; - - case "bye": - writefln("switched to bye"); - break; - - default: - writefln("switched to something else"); - break; - } - } - - writefln(); - - foreach(v; [null, false, 1, 2.3, 'x', "hi"]) - { - switch(v) - { - case null: writefln("null"); break; - case false: writefln("false"); break; - case 1: writefln("1"); break; - case 2.3: writefln("2.3"); break; - case 'x': writefln("x"); break; - case "hi": writefln("hi"); break; - } - } - - writefln(); - - class A - { - mValue; - - this(value) - { - mValue = value; - } - - function opCmp(other) - { - assert(other as A); - return mValue <=> other.mValue; - } - } - - local a1 = A(1); - local a2 = A(2); - local a3 = A(3); - - for(s : 1 .. 4) - { - local ss = A(s); - - switch(ss) - { - case a1: - writefln(1); - break; - - case a2: - writefln(2); - break; - - case a3: - writefln(3); - break; - } - } -} \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/smarty_example.html b/third_party/pygments/tests/examplefiles/smarty_example.html deleted file mode 100644 index cf4ffdc35..000000000 --- a/third_party/pygments/tests/examplefiles/smarty_example.html +++ /dev/null @@ -1,209 +0,0 @@ -{php} - include "some/php/file.php"; - - foreach ($rows as $row) { - echo $row; - } -{/php} - -{* smarty comment *} - - {serendipity_hookPlugin hook="entries_header" addData="$entry_id"} - - {foreach from=$entries item="dategroup"} - - {foreachelse} - {if not $plugin_clean_page} - {$CONST.NO_ENTRIES_TO_PRINT} - {/if} - {/foreach} - -{if $footer_info} - {/if} - {serendipity_hookPlugin hook="entries_footer"} - diff --git a/third_party/pygments/tests/examplefiles/source.lgt b/third_party/pygments/tests/examplefiles/source.lgt deleted file mode 100644 index ce5abced0..000000000 --- a/third_party/pygments/tests/examplefiles/source.lgt +++ /dev/null @@ -1,343 +0,0 @@ - -% this is a single-line comment - -/* -this is -a block -comment -*/ - - -:- encoding(some_encoding). -:- op(Precedence, Associativity, Operator). - - -:- object(prototype, - implements(protocol), - imports(category), - extends(parent)). - - :- info([ - version is 1.0, - author is 'Paulo Moura', - date is 2008/5/1, - comment is 'Sample prototype for testing syntax coloring.']). - :- threaded. - :- synchronized. - :- dynamic. - :- initialization(some_goal(X, Y)). - :- calls(some_other_protocol). - :- uses(another_object). - - :- alias(set, member/2, set_member/2). - :- alias(words, singular//0, peculiar//0). - - :- uses(list, [append/3, member/2]). - :- uses(queues, [new/1::new_queue/1]). - - :- public(aaa/2). - :- meta_predicate(aaa(::, *)). - :- discontiguous(aaa/2). - :- mode(aaa(+callable, ?integer), zero_or_one). - :- info(position/2, [ - comment is 'Predicate brief description.', - arguments is ['Arg1'-'Arg1 description', 'Arg2'-'Arg2 description']]). - - :- protected(bbb/2). - :- synchronized(bbb/2). - :- mode(bbb(+integer, -float), one). - :- info(bbb/2, [ - comment is 'Predicate brief description.', - argnames is ['Arg1', 'Arg2']]). - - :- private(ccc/2). - :- dynamic(ccc/2). - :- mode(ccc(@atom, ?atom), one_or_more). - :- info(ccc/2, [ - comment is 'Predicate brief description.', - argnames is ['Arg1', 'Arg2']]). - - enumerating_entities(Object, Protocol, Category) :- - current_category(Category), - current_object(Object), - current_protocol(Protocol). - - enumerating_properties :- - category_property(Category, Property), - object_property(Object, Property), - protocol_property(Protocol, Property). - - creating_entities(Object, Protocol, Category) :- - create_category(Category, Relations, Directives, Clauses), - create_object(Object, Relations, Directives, Clauses), - create_protocol(Protocol, Relations, Directives). - - abolishing_entities(Object, Protocol, Category) :- - abolish_category(Category), - abolish_object(Object), - abolish_protocol(Protocol). - - entity_relations :- - extends_object(Prototype, Parent, Scope), - extends_protocol(Protocol1, Protocol2, Scope), - extends_category(Category1, Category2, Scope), - implements_protocol(Object, Protocol, Scope), - imports_category(Object, Category, Scope), - instantiates_class(Instance, Class, Scope), - specializes_class(Class, Superclass, Scope), - complements_object(Category, Object). - - event_handling :- - abolish_events(Event, Object, Message, Sender, Monitor), - current_event(Event, Object, Message, Sender, Monitor), - define_events(Event, Object, Message, Sender, Monitor). - - multi_threading :- - threaded(Goals), - threaded_call(Goal), - threaded_once(Goal), - threaded_ignore(Goal), - threaded_exit(Goal), - threaded_peek(Goal), - threaded_wait(Goal), - threaded_notify(Notification). - - compiling_and_loading :- - logtalk_compile(File, Options), - logtalk_load(File, Options), - logtalk_library_path(Library, Path). - - flags :- - current_logtalk_flag(Flag, Value), - set_logtalk_flag(Flag, Value). - - execution_context_methods :- - parameter(N, Parameter), - self(Self), - sender(Sender), - this(This). - - reflection_methods :- - current_predicate(Predicate), - predicate_property(Predicate, Property). - - database_methods :- - abolish(Functor/Arity), - asserta(Clause), - assertz(Clause), - clause(Head, Body), - retract(Clause), - retractall(Head). - - meta_call_methods :- - call(Goal). - - all_solutions_methods :- - bagof(Term, Goal, List), - findall(Term, Goal, List), - forall(Generate, Test), - setof(Term, Goal, List). - - event_handler_methods :- - before(Object, Message, Sender), - after(Object, Message, Sender). - - dcg_rules_parsing_methods :- - phrase(NonTerminal, Input, Rest). - - term_expansion_methods :- - expand_term(Term, Expanded), - term_expansion(Term, Expanded), - goal_expansion(Goal, Expanded). - - message_sending :- - Object::Message, - ::Message, - ^^Message. - - calling_external_code :- - {goal1, goal2, goal3}. - - context_switching_calls :- - Object< - Then - ; Else - ). - - numbers :- - X is 13, - Y is 13.13, - Z is 13.13e-23, - C1 is 0'A, C2 is 0'', C3 is 0'", - B is 0b1011101, - O is 0o1234560, - H is 0x1234567890abcDEF. - - functions :- - A is atan(3.14) + sin(0.77) - cos(123.23), - B is sign(-12) * abs(35/78), - C is truncate(3.14) + round(-7.8) - ceiling(111.88), - D is exp(3.8) - log(123.98) / sqrt(33) * 23 ** 4, - E is rem(3, 2) + mod(5, 3) * 2 rem 2 // 5 mod 3, - F is float_fractional_part(3.14) + float_integer_part(3.14), - G is float(33) + floor(99.99). - - bitwise :- - A is 16 >> 2, - B is 16 << 2, - C is 10 /\ 12, - D is 10 \/ 12, - E is \ 10. - - term_unification :- - Term1 = Term2, - Term1 \= Term2, - unify_with_occurs_check(Term1, Term2). - - term_testing :- - atom(Atom), - atomic(Atomic), - integer(Integer), - float(Float), - compound(Term), - nonvar(Term), - var(Term), - number(Number). - - term_comparison :- - Term1 == Term2, - Term1 \== Term2, - Term1 @< Term2, - Term1 @=< Term2, - Term1 @>= Term2, - Term1 @> Term2. - - term_creation_and_decomposition :- - functor(Term, Functor, Arity), - arg(N, Term, Arg), - Term =.. [Functor| Args], - copy_term(Term, Copy). - - arithemtic_evaluation :- - X is Expression. - - arithemtic_comparison :- - Exp1 =:= Exp2, - Exp1 =\= Exp2, - Exp1 < Exp2, - Exp1 =< Exp2, - Exp1 > Exp2, - Exp1 >= Exp2. - - stream_selection_and_control :- - current_input(Stream), - current_output(Stream), - set_input(Stream), - set_output(Stream), - open(Source, Mode, Stream, Options), - close(Stream), - flush_output(Stream), - stream_property(Stream, Property), - at_end_of_stream(Stream), - set_stream_position(Stream, Position), - flush_output, - at_end_of_stream. - - character_input_output :- - get_char(Char), - get_code(Code), - peek_char(Char), - peek_code(Code), - put_char(Char), - put_code(Code), - nl(Stream), - nl. - - byte_input_output :- - get_byte(Byte), - peek_byte(Byte), - put_byte(Byte). - - term_input_output :- - read(Term), - read_term(Term), - write(Term), - write(Term), - write_canonical(Term), - write_term(Stream, Term, Options), - current_op(Precedence, Associativity, Operator), - op(Precedence, Associativity, Operator), - current_char_conversion(InChar, OutChar), - char_conversion(InChar, OutChar). - - logic_and_control :- - \+ Goal, - once(Goal), - repeat, - !. - - atomic_term_processing :- - atom_length(Atom, Length), - atom_chars(Atom, Chars), - atom_codes(Atom, Codes), - atom_concat(Atom1, Atom2, Atom), - sub_atom(Atom, Before, Length, After, SubAtom), - char_code(Char, Code), - number_chars(Number, Chars), - number_codes(Number, Codes). - - implementation_defined_hooks :- - current_prolog_flag(Flag, Value), - set_prolog_flag(Flag, Value), - halt(ExitCode), - halt. - - number(C) --> "+", number(C). - number(C) --> "-", number(X), {C is -X}. - number(X) --> [C], {0'0 =< C, C =< 0'9, X is C - 0'0}. - -:- end_object. - - - -:- object(class, - implements(protocol), - imports(category), - instantiates(metaclass), - specializes(superclass)). - - -:- end_object. - - - -:- object(parametric(_Par1, _Par2), - implements(protocol), - imports(category), - extends(parent(_Par))). - - -:- end_object. - - - -:- category(category, - implements(protocol), - extends(other_category)). - - -:- end_category. - - - -:- protocol(extended, - extends(minimal)). - - -:- end_protocol. diff --git a/third_party/pygments/tests/examplefiles/sources.list b/third_party/pygments/tests/examplefiles/sources.list deleted file mode 100644 index 3f363352d..000000000 --- a/third_party/pygments/tests/examplefiles/sources.list +++ /dev/null @@ -1,62 +0,0 @@ -## CD ROM -deb cdrom:[Xubuntu 6.06.1 _Dapper Drake_ - Release i386 (20060807)]/ dapper main restricted - -deb http://archive.ubuntu.com/ubuntu/ dapper main restricted -deb-src http://archive.ubuntu.com/ubuntu/ dapper main restricted - -deb http://foo.com/$(ARCH)/ main foo - -## Major bug fix updates produced after the final release of the -## distribution. -deb http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted -deb-src http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted - -## Uncomment the following two lines to add software from the 'universe' -## repository. -## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu -## team, and may not be under a free licence. Please satisfy yourself as to -## your rights to use the software. Also, please note that software in -## universe WILL NOT receive any review or updates from the Ubuntu security -## team. -deb http://archive.ubuntu.com/ubuntu/ dapper universe multiverse -deb-src http://archive.ubuntu.com/ubuntu/ dapper universe multiverse - -## Uncomment the following two lines to add software from the 'backports' -## repository. -## N.B. software from this repository may not have been tested as -## extensively as that contained in the main release, although it includes -## newer versions of some applications which may provide useful features. -## Also, please note that software in backports WILL NOT receive any review -## or updates from the Ubuntu security team. -deb http://archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse -deb-src http://archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse - -deb http://security.ubuntu.com/ubuntu dapper-security main restricted -deb-src http://security.ubuntu.com/ubuntu dapper-security main restricted -deb http://security.ubuntu.com/ubuntu dapper-security universe multiverse -deb-src http://security.ubuntu.com/ubuntu dapper-security universe multiverse - -## dapper-commercial by canonical -## currently has realplay (realplayer 10) and opera (opera 9) -deb http://archive.canonical.com/ubuntu dapper-commercial main - -## Bleeding edge wine repository for Dapper -## only uncomment it if you need it -## deb http://wine.budgetdedicated.com/apt dapper main -## deb-src http://wine.budgetdedicated.com/apt dapper main - -## skype -## only uncomment it if you need it -## deb http://download.skype.com/linux/repos/debian/ stable non-free - -deb http://de.archive.ubuntu.com/ubuntu/ edgy main restricted multiverse universe - -deb http://de.archive.ubuntu.com/ubuntu/ edgy-updates main restricted multiverse universe - -deb http://de.archive.ubuntu.com/ubuntu/ edgy-backports main restricted universe multiverse - -deb http://security.ubuntu.com/ubuntu edgy-security main restricted universe multiverse - -deb http://wine.budgetdedicated.com/apt edgy main - -deb http://archive.czessi.net/ubuntu edgy main restricted universe multiverse i18n-de diff --git a/third_party/pygments/tests/examplefiles/sparql.rq b/third_party/pygments/tests/examplefiles/sparql.rq deleted file mode 100644 index d979d2033..000000000 --- a/third_party/pygments/tests/examplefiles/sparql.rq +++ /dev/null @@ -1,48 +0,0 @@ -# This is a test SPARQL query - -BASE - -PREFIX foaf: -PREFIX ex: -PREFIX xsd: -PREFIX dcterms: - -SELECT ?person (COUNT(?nick) AS ?nickCount) { - <#jonny> foaf:knows ?person . - ?person a foaf:Person . - ?person foaf:firstName "Freddy" . - ?person foaf:lastName "Smith" . - # predicate-object list - ?person foaf:nick ?nick ; - foaf:age "21"^^xsd:int ; # typed literal - ex:title 'Mr' ; # single-quoted string - ex:width 2 ; # integer - ex:height 1.80 ; # float - ex:distanceToSun 1.4e8 ; # float with exponent - ex:ownsACat true ; - ex:catName "Kitty", "Kitty_" ; # object list - # some other float values - ex:float1 .125 ; - ex:float2 +2.5e10 ; - ex:float3 2.5e+10 ; - ex:float4 -1.e-10 ; - ex:float5 .0e1 ; - ex:float6 5e11 ; - ex:float7 1. ; - ex:aUnicodeÀExample "somestring" ; - ex:catName "Kitty", "Kitty_" ; # object list - ex:escape "\n\u00c0\U00010000"; - ex:catAge ?catage ; - dcterms:description "Someone with a cat called \"cat\"."@en . # language tag - ?person foaf:knows _:b0 . - _:b0 foaf:knows [ _:b1 a foaf:Person; foaf:name "Jonny" . ] . - OPTIONAL { ?person foaf:isPrimaryTopicOf ?page } - OPTIONAL { ?person foaf:name ?name - { ?person foaf:depiction ?img } - UNION - { ?person foaf:firstName ?firstN } } - FILTER ( bound(?page) || bound(?img) || bound(?firstN) ) - FILTER ( ?catage < 101 && ?catage > 9 && ?catage >= 10 && ?catage <= 100 && ?catage != 20 ) -} -GROUP BY ?person -ORDER BY ?img ASC(?firstN) DESC(?page) diff --git a/third_party/pygments/tests/examplefiles/sphere.pov b/third_party/pygments/tests/examplefiles/sphere.pov deleted file mode 100644 index 847ed4513..000000000 --- a/third_party/pygments/tests/examplefiles/sphere.pov +++ /dev/null @@ -1,18 +0,0 @@ -#include "colors.inc" - -background { color Cyan } - -camera { - location <0, 2, -3> - look_at <0, 1, 2> -} - -sphere { - <0, 1, 2>, 2 - texture { - pigment { color Yellow } - } -} - -light_source { <2, 4, -3> color White} - diff --git a/third_party/pygments/tests/examplefiles/sqlite3.sqlite3-console b/third_party/pygments/tests/examplefiles/sqlite3.sqlite3-console deleted file mode 100644 index 3ec271359..000000000 --- a/third_party/pygments/tests/examplefiles/sqlite3.sqlite3-console +++ /dev/null @@ -1,27 +0,0 @@ -SQLite version 3.4.2 -Enter ".help" for instructions -sqlite> .schema -CREATE TABLE paste (paste_id integer, code text, parsed_code text, pub_date -varchar(24), language varchar(64), parent_id integer, url varchar(128)); -CREATE TABLE vars (key varchar(24), value varchar(128)); -sqlite> a ' - ...> ' - ...> ; -SQL error: near "a": syntax error -sqlite> %; -SQL error: near "%": syntax error -sqlite> select count(language), language from paste group by language order - ...> by count(language) desc; -144|python -76|text -22|pycon -9|ruby -7|c -7|js -6|html+django -4|html -4|tex -2|html+php -1|cpp -1|scheme -sqlite> diff --git a/third_party/pygments/tests/examplefiles/squid.conf b/third_party/pygments/tests/examplefiles/squid.conf deleted file mode 100644 index 833d4fca1..000000000 --- a/third_party/pygments/tests/examplefiles/squid.conf +++ /dev/null @@ -1,30 +0,0 @@ -# Some multiline comments - -acl manager proto cache_object -acl localhost src 127.0.0.1/32 ::1 -acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access allow manager localhost -http_access deny manager -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost -http_access deny all -http_port 3128 -hierarchy_stoplist cgi-bin ? -coredump_dir /var/spool/squid3 -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern . 0 20% 4320 diff --git a/third_party/pygments/tests/examplefiles/string.jl b/third_party/pygments/tests/examplefiles/string.jl deleted file mode 100644 index 67bf6c706..000000000 --- a/third_party/pygments/tests/examplefiles/string.jl +++ /dev/null @@ -1,1031 +0,0 @@ -## core string functions ## - -length(s::String) = error("you must implement length(",typeof(s),")") -next(s::String, i::Int) = error("you must implement next(",typeof(s),",Int)") -next(s::DirectIndexString, i::Int) = (s[i],i+1) -next(s::String, i::Integer) = next(s,int(i)) - -## generic supplied functions ## - -start(s::String) = 1 -done(s::String,i) = (i > length(s)) -isempty(s::String) = done(s,start(s)) -ref(s::String, i::Int) = next(s,i)[1] -ref(s::String, i::Integer) = s[int(i)] -ref(s::String, x::Real) = s[iround(x)] -ref{T<:Integer}(s::String, r::Range1{T}) = s[int(first(r)):int(last(r))] - -symbol(s::String) = symbol(cstring(s)) -string(s::String) = s - -print(s::String) = for c=s; print(c); end -print(x...) = for i=x; print(i); end -println(args...) = print(args..., '\n') - -show(s::String) = print_quoted(s) - -(*)(s::String...) = strcat(s...) -(^)(s::String, r::Integer) = repeat(s,r) - -size(s::String) = (length(s),) -size(s::String, d::Integer) = d==1 ? length(s) : - error("in size: dimension ",d," out of range") - -strlen(s::DirectIndexString) = length(s) -function strlen(s::String) - i = start(s) - if done(s,i) - return 0 - end - n = 1 - while true - c, j = next(s,i) - if done(s,j) - return n - end - n += 1 - i = j - end -end - -isvalid(s::DirectIndexString, i::Integer) = (start(s) <= i <= length(s)) -function isvalid(s::String, i::Integer) - try - next(s,i) - true - catch - false - end -end - -prevind(s::DirectIndexString, i::Integer) = i-1 -thisind(s::DirectIndexString, i::Integer) = i -nextind(s::DirectIndexString, i::Integer) = i+1 - -prevind(s::String, i::Integer) = thisind(s,thisind(s,i)-1) - -function thisind(s::String, i::Integer) - for j = i:-1:1 - if isvalid(s,j) - return j - end - end - return 0 # out of range -end - -function nextind(s::String, i::Integer) - for j = i+1:length(s) - if isvalid(s,j) - return j - end - end - length(s)+1 # out of range -end - -ind2chr(s::DirectIndexString, i::Integer) = i -chr2ind(s::DirectIndexString, i::Integer) = i - -function ind2chr(s::String, i::Integer) - s[i] # throws error if invalid - j = 1 - k = start(s) - while true - c, l = next(s,k) - if i <= k - return j - end - j += 1 - k = l - end -end - -function chr2ind(s::String, i::Integer) - if i < 1 - return i - end - j = 1 - k = start(s) - while true - c, l = next(s,k) - if i == j - return k - end - j += 1 - k = l - end -end - -function strchr(s::String, c::Char, i::Integer) - i = nextind(s,i) - while !done(s,i) - d, j = next(s,i) - if c == d - return i - end - i = j - end - return 0 -end -strchr(s::String, c::Char) = strchr(s, c, start(s)) -contains(s::String, c::Char) = (strchr(s,c)!=0) - -function chars(s::String) - cx = Array(Char,strlen(s)) - i = 0 - for c in s - cx[i += 1] = c - end - return cx -end - -function cmp(a::String, b::String) - i = start(a) - j = start(b) - while !done(a,i) && !done(b,i) - c, i = next(a,i) - d, j = next(b,j) - if c != d - return c < d ? -1 : +1 - end - end - done(a,i) && !done(b,j) ? -1 : - !done(a,i) && done(b,j) ? +1 : 0 -end - -isequal(a::String, b::String) = cmp(a,b) == 0 -isless(a::String, b::String) = cmp(a,b) < 0 - -# faster comparisons for byte strings - -cmp(a::ByteString, b::ByteString) = lexcmp(a.data, b.data) -isequal(a::ByteString, b::ByteString) = length(a)==length(b) && cmp(a,b)==0 - -## character column width function ## - -charwidth(c::Char) = max(0,int(ccall(:wcwidth, Int32, (Char,), c))) -strwidth(s::String) = (w=0; for c in s; w += charwidth(c); end; w) -strwidth(s::ByteString) = ccall(:u8_strwidth, Int, (Ptr{Uint8},), s.data) -# TODO: implement and use u8_strnwidth that takes a length argument - -## generic string uses only length and next ## - -type GenericString <: String - string::String -end - -length(s::GenericString) = length(s.string) -next(s::GenericString, i::Int) = next(s.string, i) - -## plain old character arrays ## - -type CharString <: String - chars::Array{Char,1} - - CharString(a::Array{Char,1}) = new(a) - CharString(c::Char...) = new([ c[i] | i=1:length(c) ]) -end -CharString(x...) = CharString(map(char,x)...) - -next(s::CharString, i::Int) = (s.chars[i], i+1) -length(s::CharString) = length(s.chars) -strlen(s::CharString) = length(s) - -string(c::Char) = CharString(c) -string(c::Char, x::Char...) = CharString(c, x...) - -## substrings reference original strings ## - -type SubString <: String - string::String - offset::Int - length::Int - - SubString(s::String, i::Int, j::Int) = new(s, i-1, j-i+1) - SubString(s::SubString, i::Int, j::Int) = - new(s.string, i-1+s.offset, j-i+1) -end -SubString(s::String, i::Integer, j::Integer) = SubString(s, int(i), int(j)) - -function next(s::SubString, i::Int) - if i < 1 || i > s.length - error("string index out of bounds") - end - c, i = next(s.string, i+s.offset) - c, i-s.offset -end - -length(s::SubString) = s.length -# TODO: strlen(s::SubString) = ?? -# default implementation will work but it's slow -# can this be delegated efficiently somehow? -# that may require additional string interfaces - -function ref(s::String, r::Range1{Int}) - if first(r) < 1 || length(s) < last(r) - error("in substring slice: index out of range") - end - SubString(s, first(r), last(r)) -end - -## efficient representation of repeated strings ## - -type RepString <: String - string::String - repeat::Integer -end - -length(s::RepString) = length(s.string)*s.repeat -strlen(s::RepString) = strlen(s.string)*s.repeat - -function next(s::RepString, i::Int) - if i < 1 || i > length(s) - error("string index out of bounds") - end - j = mod1(i,length(s.string)) - c, k = next(s.string, j) - c, k-j+i -end - -function repeat(s::String, r::Integer) - r < 0 ? error("can't repeat a string ",r," times") : - r == 0 ? "" : - r == 1 ? s : - RepString(s,r) -end - -## reversed strings without data movement ## - -type RevString <: String - string::String -end - -length(s::RevString) = length(s.string) -strlen(s::RevString) = strlen(s.string) - -start(s::RevString) = (n=length(s); n-thisind(s.string,n)+1) -function next(s::RevString, i::Int) - n = length(s); j = n-i+1 - (s.string[j], n-thisind(s.string,j-1)+1) -end - -reverse(s::String) = RevString(s) -reverse(s::RevString) = s.string - -## ropes for efficient concatenation, etc. ## - -# Idea: instead of this standard binary tree structure, -# how about we keep an array of substrings, with an -# offset array. We can do binary search on the offset -# array so we get O(log(n)) indexing time still, but we -# can compute the offsets lazily and avoid all the -# futzing around while the string is being constructed. - -type RopeString <: String - head::String - tail::String - depth::Int32 - length::Int - - RopeString(h::RopeString, t::RopeString) = - depth(h.tail) + depth(t) < depth(h.head) ? - RopeString(h.head, RopeString(h.tail, t)) : - new(h, t, max(h.depth,t.depth)+1, length(h)+length(t)) - - RopeString(h::RopeString, t::String) = - depth(h.tail) < depth(h.head) ? - RopeString(h.head, RopeString(h.tail, t)) : - new(h, t, h.depth+1, length(h)+length(t)) - - RopeString(h::String, t::RopeString) = - depth(t.head) < depth(t.tail) ? - RopeString(RopeString(h, t.head), t.tail) : - new(h, t, t.depth+1, length(h)+length(t)) - - RopeString(h::String, t::String) = - new(h, t, 1, length(h)+length(t)) -end - -depth(s::String) = 0 -depth(s::RopeString) = s.depth - -function next(s::RopeString, i::Int) - if i <= length(s.head) - return next(s.head, i) - else - c, j = next(s.tail, i-length(s.head)) - return c, j+length(s.head) - end -end - -length(s::RopeString) = s.length -strlen(s::RopeString) = strlen(s.head) + strlen(s.tail) - -strcat() = "" -strcat(s::String) = s -strcat(x...) = strcat(map(string,x)...) -strcat(s::String, t::String...) = - (t = strcat(t...); isempty(s) ? t : isempty(t) ? s : RopeString(s, t)) - -print(s::RopeString) = print(s.head, s.tail) - -## transformed strings ## - -type TransformedString <: String - transform::Function - string::String -end - -length(s::TransformedString) = length(s.string) -strlen(s::TransformedString) = strlen(s.string) - -function next(s::TransformedString, i::Int) - c, j = next(s.string,i) - c = s.transform(c, i) - return c, j -end - -## uppercase and lowercase transformations ## - -uppercase(c::Char) = ccall(:towupper, Char, (Char,), c) -lowercase(c::Char) = ccall(:towlower, Char, (Char,), c) - -uppercase(s::String) = TransformedString((c,i)->uppercase(c), s) -lowercase(s::String) = TransformedString((c,i)->lowercase(c), s) - -ucfirst(s::String) = TransformedString((c,i)->i==1 ? uppercase(c) : c, s) -lcfirst(s::String) = TransformedString((c,i)->i==1 ? lowercase(c) : c, s) - -const uc = uppercase -const lc = lowercase - -## string map ## - -function map(f::Function, s::String) - out = memio(length(s)) - for c in s - write(out, f(c)::Char) - end - takebuf_string(out) -end - -## conversion of general objects to strings ## - -string(x) = print_to_string(show, x) -cstring(x...) = print_to_string(print, x...) - -function cstring(p::Ptr{Uint8}) - p == C_NULL ? error("cannot convert NULL to string") : - ccall(:jl_cstr_to_string, Any, (Ptr{Uint8},), p)::ByteString -end - -## string promotion rules ## - -promote_rule(::Type{UTF8String} , ::Type{ASCIIString}) = UTF8String -promote_rule(::Type{UTF8String} , ::Type{CharString} ) = UTF8String -promote_rule(::Type{ASCIIString}, ::Type{CharString} ) = UTF8String - -## printing literal quoted string data ## - -# TODO: this is really the inverse of print_unbackslashed - -function print_quoted_literal(s::String) - print('"') - for c = s; c == '"' ? print("\\\"") : print(c); end - print('"') -end - -## string escaping & unescaping ## - -escape_nul(s::String, i::Int) = - !done(s,i) && '0' <= next(s,i)[1] <= '7' ? L"\x00" : L"\0" - -is_hex_digit(c::Char) = '0'<=c<='9' || 'a'<=c<='f' || 'A'<=c<='F' -need_full_hex(s::String, i::Int) = !done(s,i) && is_hex_digit(next(s,i)[1]) - -function print_escaped(s::String, esc::String) - i = start(s) - while !done(s,i) - c, j = next(s,i) - c == '\0' ? print(escape_nul(s,j)) : - c == '\e' ? print(L"\e") : - c == '\\' ? print("\\\\") : - contains(esc,c) ? print('\\', c) : - iswprint(c) ? print(c) : - 7 <= c <= 13 ? print('\\', "abtnvfr"[c-6]) : - c <= '\x7f' ? print(L"\x", hex(c, 2)) : - c <= '\uffff' ? print(L"\u", hex(c, need_full_hex(s,j) ? 4 : 2)) : - print(L"\U", hex(c, need_full_hex(s,j) ? 8 : 4)) - i = j - end -end - -escape_string(s::String) = print_to_string(length(s), print_escaped, s, "\"") -print_quoted(s::String) = (print('"'); print_escaped(s, "\"\$"); print('"')) -#" # work around syntax highlighting problem -quote_string(s::String) = print_to_string(length(s)+2, print_quoted, s) - -# bare minimum unescaping function unescapes only given characters - -function print_unescaped_chars(s::String, esc::String) - if !contains(esc,'\\') - esc = strcat("\\", esc) - end - i = start(s) - while !done(s,i) - c, i = next(s,i) - if c == '\\' && !done(s,i) && contains(esc,s[i]) - c, i = next(s,i) - end - print(c) - end -end - -unescape_chars(s::String, esc::String) = - print_to_string(length(s), print_unescaped_chars, s, esc) - -# general unescaping of traditional C and Unicode escape sequences - -function print_unescaped(s::String) - i = start(s) - while !done(s,i) - c, i = next(s,i) - if !done(s,i) && c == '\\' - c, i = next(s,i) - if c == 'x' || c == 'u' || c == 'U' - n = k = 0 - m = c == 'x' ? 2 : - c == 'u' ? 4 : 8 - while (k+=1) <= m && !done(s,i) - c, j = next(s,i) - n = '0' <= c <= '9' ? n<<4 + c-'0' : - 'a' <= c <= 'f' ? n<<4 + c-'a'+10 : - 'A' <= c <= 'F' ? n<<4 + c-'A'+10 : break - i = j - end - if k == 1 - error("\\x used with no following hex digits") - end - if m == 2 # \x escape sequence - write(uint8(n)) - else - print(char(n)) - end - elseif '0' <= c <= '7' - k = 1 - n = c-'0' - while (k+=1) <= 3 && !done(s,i) - c, j = next(s,i) - n = '0' <= c <= '7' ? n<<3 + c-'0' : break - i = j - end - if n > 255 - error("octal escape sequence out of range") - end - write(uint8(n)) - else - print(c == 'a' ? '\a' : - c == 'b' ? '\b' : - c == 't' ? '\t' : - c == 'n' ? '\n' : - c == 'v' ? '\v' : - c == 'f' ? '\f' : - c == 'r' ? '\r' : - c == 'e' ? '\e' : c) - end - else - print(c) - end - end -end - -unescape_string(s::String) = print_to_string(length(s), print_unescaped, s) - -## checking UTF-8 & ACSII validity ## - -byte_string_classify(s::ByteString) = - ccall(:u8_isvalid, Int32, (Ptr{Uint8}, Int), s.data, length(s)) - # 0: neither valid ASCII nor UTF-8 - # 1: valid ASCII - # 2: valid UTF-8 - -is_valid_ascii(s::ByteString) = byte_string_classify(s) == 1 -is_valid_utf8 (s::ByteString) = byte_string_classify(s) != 0 - -check_ascii(s::ByteString) = is_valid_ascii(s) ? s : error("invalid ASCII sequence") -check_utf8 (s::ByteString) = is_valid_utf8(s) ? s : error("invalid UTF-8 sequence") - -## string interpolation parsing ## - -function _jl_interp_parse(s::String, unescape::Function, printer::Function) - sx = {} - i = j = start(s) - while !done(s,j) - c, k = next(s,j) - if c == '$' - if !isempty(s[i:j-1]) - push(sx, unescape(s[i:j-1])) - end - ex, j = parseatom(s,k) - push(sx, ex) - i = j - elseif c == '\\' && !done(s,k) - if s[k] == '$' - if !isempty(s[i:j-1]) - push(sx, unescape(s[i:j-1])) - end - i = k - end - c, j = next(s,k) - else - j = k - end - end - if !isempty(s[i:]) - push(sx, unescape(s[i:j-1])) - end - length(sx) == 1 && isa(sx[1],ByteString) ? sx[1] : - expr(:call, :print_to_string, printer, sx...) -end - -_jl_interp_parse(s::String, u::Function) = _jl_interp_parse(s, u, print) -_jl_interp_parse(s::String) = _jl_interp_parse(s, x->check_utf8(unescape_string(x))) - -function _jl_interp_parse_bytes(s::String) - writer(x...) = for w=x; write(w); end - _jl_interp_parse(s, unescape_string, writer) -end - -## core string macros ## - -macro str(s); _jl_interp_parse(s); end -macro S_str(s); _jl_interp_parse(s); end -macro I_str(s); _jl_interp_parse(s, x->unescape_chars(x,"\"")); end -macro E_str(s); check_utf8(unescape_string(s)); end -macro B_str(s); _jl_interp_parse_bytes(s); end -macro b_str(s); ex = _jl_interp_parse_bytes(s); :(($ex).data); end - -## shell-like command parsing ## - -function _jl_shell_parse(s::String, interp::Bool) - - in_single_quotes = false - in_double_quotes = false - - args = {} - arg = {} - i = start(s) - j = i - - function update_arg(x) - if !isa(x,String) || !isempty(x) - push(arg, x) - end - end - function append_arg() - if isempty(arg); arg = {"",}; end - push(args, arg) - arg = {} - end - - while !done(s,j) - c, k = next(s,j) - if !in_single_quotes && !in_double_quotes && iswspace(c) - update_arg(s[i:j-1]) - append_arg() - j = k - while !done(s,j) - c, k = next(s,j) - if !iswspace(c) - i = j - break - end - j = k - end - elseif interp && !in_single_quotes && c == '$' - update_arg(s[i:j-1]); i = k; j = k - if done(s,k) - error("\$ right before end of command") - end - if iswspace(s[k]) - error("space not allowed right after \$") - end - ex, j = parseatom(s,j) - update_arg(ex); i = j - else - if !in_double_quotes && c == '\'' - in_single_quotes = !in_single_quotes - update_arg(s[i:j-1]); i = k - elseif !in_single_quotes && c == '"' - in_double_quotes = !in_double_quotes - update_arg(s[i:j-1]); i = k - elseif c == '\\' - if in_double_quotes - if done(s,k) - error("unterminated double quote") - end - if s[k] == '"' || s[k] == '$' - update_arg(s[i:j-1]); i = k - c, k = next(s,k) - end - elseif !in_single_quotes - if done(s,k) - error("dangling backslash") - end - update_arg(s[i:j-1]); i = k - c, k = next(s,k) - end - end - j = k - end - end - - if in_single_quotes; error("unterminated single quote"); end - if in_double_quotes; error("unterminated double quote"); end - - update_arg(s[i:]) - append_arg() - - if !interp - return args - end - - # construct an expression - exprs = {} - for arg in args - push(exprs, expr(:tuple, arg)) - end - expr(:tuple,exprs) -end -_jl_shell_parse(s::String) = _jl_shell_parse(s,true) - -function shell_split(s::String) - parsed = _jl_shell_parse(s,false) - args = String[] - for arg in parsed - push(args, strcat(arg...)) - end - args -end - -function print_shell_word(word::String) - if isempty(word) - print("''") - end - has_single = false - has_special = false - for c in word - if iswspace(c) || c=='\\' || c=='\'' || c=='"' || c=='$' - has_special = true - if c == '\'' - has_single = true - end - end - end - if !has_special - print(word) - elseif !has_single - print('\'', word, '\'') - else - print('"') - for c in word - if c == '"' || c == '$' - print('\\') - end - print(c) - end - print('"') - end -end - -function print_shell_escaped(cmd::String, args::String...) - print_shell_word(cmd) - for arg in args - print(' ') - print_shell_word(arg) - end -end - -shell_escape(cmd::String, args::String...) = - print_to_string(print_shell_escaped, cmd, args...) - -## interface to parser ## - -function parse(s::String, pos, greedy) - # returns (expr, end_pos). expr is () in case of parse error. - ex, pos = ccall(:jl_parse_string, Any, - (Ptr{Uint8}, Int32, Int32), - cstring(s), pos-1, greedy ? 1:0) - if isa(ex,Expr) && is(ex.head,:error) - throw(ParseError(ex.args[1])) - end - if ex == (); throw(ParseError("end of input")); end - ex, pos+1 # C is zero-based, Julia is 1-based -end - -parse(s::String) = parse(s, 1, true) -parse(s::String, pos) = parse(s, pos, true) -parseatom(s::String) = parse(s, 1, false) -parseatom(s::String, pos) = parse(s, pos, false) - -## miscellaneous string functions ## - -function lpad(s::String, n::Integer, p::String) - m = n - strlen(s) - if m <= 0; return s; end - l = strlen(p) - if l==1 - return p^m * s - end - q = div(m,l) - r = m - q*l - cstring(p^q*p[1:chr2ind(p,r)]*s) -end - -function rpad(s::String, n::Integer, p::String) - m = n - strlen(s) - if m <= 0; return s; end - l = strlen(p) - if l==1 - return s * p^m - end - q = div(m,l) - r = m - q*l - cstring(s*p^q*p[1:chr2ind(p,r)]) -end - -lpad(s, n::Integer, p) = lpad(string(s), n, string(p)) -rpad(s, n::Integer, p) = rpad(string(s), n, string(p)) - -lpad(s, n::Integer) = lpad(string(s), n, " ") -rpad(s, n::Integer) = rpad(string(s), n, " ") - -function split(s::String, delims, include_empty::Bool) - i = 1 - strs = String[] - len = length(s) - while true - tokstart = tokend = i - while !done(s,i) - (c,i) = next(s,i) - if contains(delims, c) - break - end - tokend = i - end - tok = s[tokstart:(tokend-1)] - if include_empty || !isempty(tok) - push(strs, tok) - end - if !((i <= len) || (i==len+1 && tokend!=i)) - break - end - end - strs -end - -split(s::String) = split(s, (' ','\t','\n','\v','\f','\r'), false) -split(s::String, x) = split(s, x, true) -split(s::String, x::Char, incl::Bool) = split(s, (x,), incl) - -function print_joined(strings, delim, last) - i = start(strings) - if done(strings,i) - return - end - str, i = next(strings,i) - print(str) - while !done(strings,i) - str, i = next(strings,i) - print(done(strings,i) ? last : delim) - print(str) - end -end - -function print_joined(strings, delim) - i = start(strings) - while !done(strings,i) - str, i = next(strings,i) - print(str) - if !done(strings,i) - print(delim) - end - end -end -print_joined(strings) = print_joined(strings, "") - -join(args...) = print_to_string(print_joined, args...) - -chop(s::String) = s[1:thisind(s,length(s))-1] -chomp(s::String) = (i=thisind(s,length(s)); s[i]=='\n' ? s[1:i-1] : s) -chomp(s::ByteString) = s.data[end]==0x0a ? s[1:end-1] : s - -function lstrip(s::String) - i = start(s) - while !done(s,i) - c, j = next(s,i) - if !iswspace(c) - return s[i:end] - end - i = j - end - "" -end - -function rstrip(s::String) - r = reverse(s) - i = start(r) - while !done(r,i) - c, j = next(r,i) - if !iswspace(c) - return s[1:end-i+1] - end - i = j - end - "" -end - -strip(s::String) = lstrip(rstrip(s)) - -## string to integer functions ## - -function parse_int{T<:Integer}(::Type{T}, s::String, base::Integer) - if !(2 <= base <= 36); error("invalid base: ",base); end - i = start(s) - if done(s,i) - error("premature end of integer (in ",show_to_string(s),")") - end - c,i = next(s,i) - sgn = one(T) - if T <: Signed && c == '-' - sgn = -sgn - if done(s,i) - error("premature end of integer (in ",show_to_string(s),")") - end - c,i = next(s,i) - end - base = convert(T,base) - n::T = 0 - while true - d = '0' <= c <= '9' ? c-'0' : - 'A' <= c <= 'Z' ? c-'A'+10 : - 'a' <= c <= 'z' ? c-'a'+10 : typemax(Int) - if d >= base - error(show_to_string(c)," is not a valid digit (in ",show_to_string(s),")") - end - # TODO: overflow detection? - n = n*base + d - if done(s,i) - break - end - c,i = next(s,i) - end - return flipsign(n,sgn) -end - -parse_int(s::String, base::Integer) = parse_int(Int,s,base) -parse_int(T::Type, s::String) = parse_int(T,s,10) -parse_int(s::String) = parse_int(Int,s,10) - -parse_bin(T::Type, s::String) = parse_int(T,s,2) -parse_oct(T::Type, s::String) = parse_int(T,s,8) -parse_hex(T::Type, s::String) = parse_int(T,s,16) - -parse_bin(s::String) = parse_int(Int,s,2) -parse_oct(s::String) = parse_int(Int,s,8) -parse_hex(s::String) = parse_int(Int,s,16) - -integer (s::String) = int(s) -unsigned(s::String) = uint(s) -int (s::String) = parse_int(Int,s) -uint (s::String) = parse_int(Uint,s) -int8 (s::String) = parse_int(Int8,s) -uint8 (s::String) = parse_int(Uint8,s) -int16 (s::String) = parse_int(Int16,s) -uint16 (s::String) = parse_int(Uint16,s) -int32 (s::String) = parse_int(Int32,s) -uint32 (s::String) = parse_int(Uint32,s) -int64 (s::String) = parse_int(Int64,s) -uint64 (s::String) = parse_int(Uint64,s) - -## integer to string functions ## - -const _jl_dig_syms = "0123456789abcdefghijklmnopqrstuvwxyz".data - -function int2str(n::Union(Int64,Uint64), b::Integer, l::Int) - if b < 2 || b > 36; error("int2str: invalid base ", b); end - neg = n < 0 - n = unsigned(abs(n)) - b = convert(typeof(n), b) - ndig = ndigits(n, b) - sz = max(convert(Int, ndig), l) + neg - data = Array(Uint8, sz) - i = sz - if ispow2(b) - digmask = b-1 - shift = trailing_zeros(b) - while i > neg - ch = n & digmask - data[i] = _jl_dig_syms[int(ch)+1] - n >>= shift - i -= 1 - end - else - while i > neg - ch = n % b - data[i] = _jl_dig_syms[int(ch)+1] - n = div(n,b) - i -= 1 - end - end - if neg - data[1] = '-' - end - ASCIIString(data) -end -int2str(n::Integer, b::Integer) = int2str(n, b, 0) -int2str(n::Integer, b::Integer, l::Int) = int2str(int64(n), b, l) - -string(x::Signed) = dec(int64(x)) -cstring(x::Signed) = dec(int64(x)) - -## string to float functions ## - -function float64_isvalid(s::String, out::Array{Float64,1}) - s = cstring(s) - return (ccall(:jl_strtod, Int32, (Ptr{Uint8},Ptr{Float64}), s, out)==0) -end - -function float32_isvalid(s::String, out::Array{Float32,1}) - s = cstring(s) - return (ccall(:jl_strtof, Int32, (Ptr{Uint8},Ptr{Float32}), s, out)==0) -end - -begin - local tmp::Array{Float64,1} = Array(Float64,1) - local tmpf::Array{Float32,1} = Array(Float32,1) - global float64, float32 - function float64(s::String) - if !float64_isvalid(s, tmp) - throw(ArgumentError("float64(String): invalid number format")) - end - return tmp[1] - end - - function float32(s::String) - if !float32_isvalid(s, tmpf) - throw(ArgumentError("float32(String): invalid number format")) - end - return tmpf[1] - end -end - -float(x::String) = float64(x) -parse_float(x::String) = float64(x) -parse_float(::Type{Float64}, x::String) = float64(x) -parse_float(::Type{Float32}, x::String) = float32(x) - -# copying a byte string (generally not needed due to "immutability") - -strcpy{T<:ByteString}(s::T) = T(copy(s.data)) - -# lexicographically compare byte arrays (used by Latin-1 and UTF-8) - -function lexcmp(a::Array{Uint8,1}, b::Array{Uint8,1}) - c = ccall(:memcmp, Int32, (Ptr{Uint8}, Ptr{Uint8}, Uint), - a, b, min(length(a),length(b))) - c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b)) -end - -# find the index of the first occurrence of a byte value in a byte array - -function memchr(a::Array{Uint8,1}, b::Integer) - p = pointer(a) - q = ccall(:memchr, Ptr{Uint8}, (Ptr{Uint8}, Int32, Uint), p, b, length(a)) - q == C_NULL ? 0 : q - p + 1 -end - -# concatenate byte arrays into a single array - -memcat() = Array(Uint8,0) -memcat(a::Array{Uint8,1}) = copy(a) - -function memcat(arrays::Array{Uint8,1}...) - n = 0 - for a in arrays - n += length(a) - end - arr = Array(Uint8, n) - ptr = pointer(arr) - offset = 0 - for a in arrays - ccall(:memcpy, Ptr{Uint8}, (Ptr{Uint8}, Ptr{Uint8}, Uint), - ptr+offset, a, length(a)) - offset += length(a) - end - return arr -end - -# concatenate the data fields of byte strings - -memcat(s::ByteString) = memcat(s.data) -memcat(sx::ByteString...) = memcat(map(s->s.data, sx)...) diff --git a/third_party/pygments/tests/examplefiles/string_delimiters.d b/third_party/pygments/tests/examplefiles/string_delimiters.d deleted file mode 100644 index 288aacc20..000000000 --- a/third_party/pygments/tests/examplefiles/string_delimiters.d +++ /dev/null @@ -1,21 +0,0 @@ -import std.stdio; - -void main() { - // Nesting delimited strings - auto a = q"{foo " {bar} baz}"; - auto b = q"[foo [bar] " baz]"; - auto c = q"(foo " (bar) baz)"; - auto d = q" " baz>"; - // Non-nesting delimited strings - auto e = q"/foo " bar/"; - auto f = q"-Another " string-"; - // "heredoc" strings - auto g = q"FOO - This is a string! -FOO"; - // Token strings (only the q{} should be highlighted as a string) - auto h = q{ - int i; - void foo() { writefln("Hello, world!"); } - }; -} diff --git a/third_party/pygments/tests/examplefiles/stripheredoc.sh b/third_party/pygments/tests/examplefiles/stripheredoc.sh deleted file mode 100644 index 33e7ff334..000000000 --- a/third_party/pygments/tests/examplefiles/stripheredoc.sh +++ /dev/null @@ -1,3 +0,0 @@ -cat <<-EOF - Hello world $PATH - EOF diff --git a/third_party/pygments/tests/examplefiles/subr.el b/third_party/pygments/tests/examplefiles/subr.el deleted file mode 100644 index deadca6ef..000000000 --- a/third_party/pygments/tests/examplefiles/subr.el +++ /dev/null @@ -1,4868 +0,0 @@ -;;; subr.el --- basic lisp subroutines for Emacs -*- coding: utf-8; lexical-binding:t -*- - -;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2015 Free Software -;; Foundation, Inc. - -;; Maintainer: emacs-devel@gnu.org -;; Keywords: internal -;; Package: emacs - -;; This file is part of GNU Emacs. - -;; GNU Emacs 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. - -;; GNU Emacs 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 GNU Emacs. If not, see . - -;;; Commentary: - -;;; Code: - -;; Beware: while this file has tag `utf-8', before it's compiled, it gets -;; loaded as "raw-text", so non-ASCII chars won't work right during bootstrap. - -(defmacro declare-function (_fn _file &optional _arglist _fileonly) - "Tell the byte-compiler that function FN is defined, in FILE. -Optional ARGLIST is the argument list used by the function. -The FILE argument is not used by the byte-compiler, but by the -`check-declare' package, which checks that FILE contains a -definition for FN. ARGLIST is used by both the byte-compiler -and `check-declare' to check for consistency. - -FILE can be either a Lisp file (in which case the \".el\" -extension is optional), or a C file. C files are expanded -relative to the Emacs \"src/\" directory. Lisp files are -searched for using `locate-library', and if that fails they are -expanded relative to the location of the file containing the -declaration. A FILE with an \"ext:\" prefix is an external file. -`check-declare' will check such files if they are found, and skip -them without error if they are not. - -FILEONLY non-nil means that `check-declare' will only check that -FILE exists, not that it defines FN. This is intended for -function-definitions that `check-declare' does not recognize, e.g. -`defstruct'. - -To specify a value for FILEONLY without passing an argument list, -set ARGLIST to t. This is necessary because nil means an -empty argument list, rather than an unspecified one. - -Note that for the purposes of `check-declare', this statement -must be the first non-whitespace on a line. - -For more information, see Info node `(elisp)Declaring Functions'." - ;; Does nothing - byte-compile-declare-function does the work. - nil) - - -;;;; Basic Lisp macros. - -(defalias 'not 'null) - -(defmacro noreturn (form) - "Evaluate FORM, expecting it not to return. -If FORM does return, signal an error." - (declare (debug t)) - `(prog1 ,form - (error "Form marked with `noreturn' did return"))) - -(defmacro 1value (form) - "Evaluate FORM, expecting a constant return value. -This is the global do-nothing version. There is also `testcover-1value' -that complains if FORM ever does return differing values." - (declare (debug t)) - form) - -(defmacro def-edebug-spec (symbol spec) - "Set the `edebug-form-spec' property of SYMBOL according to SPEC. -Both SYMBOL and SPEC are unevaluated. The SPEC can be: -0 (instrument no arguments); t (instrument all arguments); -a symbol (naming a function with an Edebug specification); or a list. -The elements of the list describe the argument types; see -Info node `(elisp)Specification List' for details." - `(put (quote ,symbol) 'edebug-form-spec (quote ,spec))) - -(defmacro lambda (&rest cdr) - "Return a lambda expression. -A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is -self-quoting; the result of evaluating the lambda expression is the -expression itself. The lambda expression may then be treated as a -function, i.e., stored as the function value of a symbol, passed to -`funcall' or `mapcar', etc. - -ARGS should take the same form as an argument list for a `defun'. -DOCSTRING is an optional documentation string. - If present, it should describe how to call the function. - But documentation strings are usually not useful in nameless functions. -INTERACTIVE should be a call to the function `interactive', which see. -It may also be omitted. -BODY should be a list of Lisp expressions. - -\(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)" - (declare (doc-string 2) (indent defun) - (debug (&define lambda-list - [&optional stringp] - [&optional ("interactive" interactive)] - def-body))) - ;; Note that this definition should not use backquotes; subr.el should not - ;; depend on backquote.el. - (list 'function (cons 'lambda cdr))) - -(defmacro setq-local (var val) - "Set variable VAR to value VAL in current buffer." - ;; Can't use backquote here, it's too early in the bootstrap. - (list 'set (list 'make-local-variable (list 'quote var)) val)) - -(defmacro defvar-local (var val &optional docstring) - "Define VAR as a buffer-local variable with default value VAL. -Like `defvar' but additionally marks the variable as being automatically -buffer-local wherever it is set." - (declare (debug defvar) (doc-string 3)) - ;; Can't use backquote here, it's too early in the bootstrap. - (list 'progn (list 'defvar var val docstring) - (list 'make-variable-buffer-local (list 'quote var)))) - -(defun apply-partially (fun &rest args) - "Return a function that is a partial application of FUN to ARGS. -ARGS is a list of the first N arguments to pass to FUN. -The result is a new function which does the same as FUN, except that -the first N arguments are fixed at the values with which this function -was called." - (lambda (&rest args2) - (apply fun (append args args2)))) - -(defmacro push (newelt place) - "Add NEWELT to the list stored in the generalized variable PLACE. -This is morally equivalent to (setf PLACE (cons NEWELT PLACE)), -except that PLACE is only evaluated once (after NEWELT)." - (declare (debug (form gv-place))) - (if (symbolp place) - ;; Important special case, to avoid triggering GV too early in - ;; the bootstrap. - (list 'setq place - (list 'cons newelt place)) - (require 'macroexp) - (macroexp-let2 macroexp-copyable-p v newelt - (gv-letplace (getter setter) place - (funcall setter `(cons ,v ,getter)))))) - -(defmacro pop (place) - "Return the first element of PLACE's value, and remove it from the list. -PLACE must be a generalized variable whose value is a list. -If the value is nil, `pop' returns nil but does not actually -change the list." - (declare (debug (gv-place))) - ;; We use `car-safe' here instead of `car' because the behavior is the same - ;; (if it's not a cons cell, the `cdr' would have signaled an error already), - ;; but `car-safe' is total, so the byte-compiler can safely remove it if the - ;; result is not used. - `(car-safe - ,(if (symbolp place) - ;; So we can use `pop' in the bootstrap before `gv' can be used. - (list 'prog1 place (list 'setq place (list 'cdr place))) - (gv-letplace (getter setter) place - (macroexp-let2 macroexp-copyable-p x getter - `(prog1 ,x ,(funcall setter `(cdr ,x)))))))) - -(defmacro when (cond &rest body) - "If COND yields non-nil, do BODY, else return nil. -When COND yields non-nil, eval BODY forms sequentially and return -value of last one, or nil if there are none. - -\(fn COND BODY...)" - (declare (indent 1) (debug t)) - (list 'if cond (cons 'progn body))) - -(defmacro unless (cond &rest body) - "If COND yields nil, do BODY, else return nil. -When COND yields nil, eval BODY forms sequentially and return -value of last one, or nil if there are none. - -\(fn COND BODY...)" - (declare (indent 1) (debug t)) - (cons 'if (cons cond (cons nil body)))) - -(defmacro dolist (spec &rest body) - "Loop over a list. -Evaluate BODY with VAR bound to each car from LIST, in turn. -Then evaluate RESULT to get return value, default nil. - -\(fn (VAR LIST [RESULT]) BODY...)" - (declare (indent 1) (debug ((symbolp form &optional form) body))) - ;; It would be cleaner to create an uninterned symbol, - ;; but that uses a lot more space when many functions in many files - ;; use dolist. - ;; FIXME: This cost disappears in byte-compiled lexical-binding files. - (let ((temp '--dolist-tail--)) - ;; This is not a reliable test, but it does not matter because both - ;; semantics are acceptable, tho one is slightly faster with dynamic - ;; scoping and the other is slightly faster (and has cleaner semantics) - ;; with lexical scoping. - (if lexical-binding - `(let ((,temp ,(nth 1 spec))) - (while ,temp - (let ((,(car spec) (car ,temp))) - ,@body - (setq ,temp (cdr ,temp)))) - ,@(cdr (cdr spec))) - `(let ((,temp ,(nth 1 spec)) - ,(car spec)) - (while ,temp - (setq ,(car spec) (car ,temp)) - ,@body - (setq ,temp (cdr ,temp))) - ,@(if (cdr (cdr spec)) - `((setq ,(car spec) nil) ,@(cdr (cdr spec)))))))) - -(defmacro dotimes (spec &rest body) - "Loop a certain number of times. -Evaluate BODY with VAR bound to successive integers running from 0, -inclusive, to COUNT, exclusive. Then evaluate RESULT to get -the return value (nil if RESULT is omitted). - -\(fn (VAR COUNT [RESULT]) BODY...)" - (declare (indent 1) (debug dolist)) - ;; It would be cleaner to create an uninterned symbol, - ;; but that uses a lot more space when many functions in many files - ;; use dotimes. - ;; FIXME: This cost disappears in byte-compiled lexical-binding files. - (let ((temp '--dotimes-limit--) - (start 0) - (end (nth 1 spec))) - ;; This is not a reliable test, but it does not matter because both - ;; semantics are acceptable, tho one is slightly faster with dynamic - ;; scoping and the other has cleaner semantics. - (if lexical-binding - (let ((counter '--dotimes-counter--)) - `(let ((,temp ,end) - (,counter ,start)) - (while (< ,counter ,temp) - (let ((,(car spec) ,counter)) - ,@body) - (setq ,counter (1+ ,counter))) - ,@(if (cddr spec) - ;; FIXME: This let often leads to "unused var" warnings. - `((let ((,(car spec) ,counter)) ,@(cddr spec)))))) - `(let ((,temp ,end) - (,(car spec) ,start)) - (while (< ,(car spec) ,temp) - ,@body - (setq ,(car spec) (1+ ,(car spec)))) - ,@(cdr (cdr spec)))))) - -(defmacro declare (&rest _specs) - "Do not evaluate any arguments, and return nil. -If a `declare' form appears as the first form in the body of a -`defun' or `defmacro' form, SPECS specifies various additional -information about the function or macro; these go into effect -during the evaluation of the `defun' or `defmacro' form. - -The possible values of SPECS are specified by -`defun-declarations-alist' and `macro-declarations-alist'. - -For more information, see info node `(elisp)Declare Form'." - ;; FIXME: edebug spec should pay attention to defun-declarations-alist. - nil) - -(defmacro ignore-errors (&rest body) - "Execute BODY; if an error occurs, return nil. -Otherwise, return result of last form in BODY. -See also `with-demoted-errors' that does something similar -without silencing all errors." - (declare (debug t) (indent 0)) - `(condition-case nil (progn ,@body) (error nil))) - -;;;; Basic Lisp functions. - -(defun ignore (&rest _ignore) - "Do nothing and return nil. -This function accepts any number of arguments, but ignores them." - (interactive) - nil) - -;; Signal a compile-error if the first arg is missing. -(defun error (&rest args) - "Signal an error, making error message by passing all args to `format'. -In Emacs, the convention is that error messages start with a capital -letter but *do not* end with a period. Please follow this convention -for the sake of consistency." - (declare (advertised-calling-convention (string &rest args) "23.1")) - (signal 'error (list (apply 'format args)))) - -(defun user-error (format &rest args) - "Signal a pilot error, making error message by passing all args to `format'. -In Emacs, the convention is that error messages start with a capital -letter but *do not* end with a period. Please follow this convention -for the sake of consistency. -This is just like `error' except that `user-error's are expected to be the -result of an incorrect manipulation on the part of the user, rather than the -result of an actual problem." - (signal 'user-error (list (apply #'format format args)))) - -(defun define-error (name message &optional parent) - "Define NAME as a new error signal. -MESSAGE is a string that will be output to the echo area if such an error -is signaled without being caught by a `condition-case'. -PARENT is either a signal or a list of signals from which it inherits. -Defaults to `error'." - (unless parent (setq parent 'error)) - (let ((conditions - (if (consp parent) - (apply #'append - (mapcar (lambda (parent) - (cons parent - (or (get parent 'error-conditions) - (error "Unknown signal `%s'" parent)))) - parent)) - (cons parent (get parent 'error-conditions))))) - (put name 'error-conditions - (delete-dups (copy-sequence (cons name conditions)))) - (when message (put name 'error-message message)))) - -;; We put this here instead of in frame.el so that it's defined even on -;; systems where frame.el isn't loaded. -(defun frame-configuration-p (object) - "Return non-nil if OBJECT seems to be a frame configuration. -Any list whose car is `frame-configuration' is assumed to be a frame -configuration." - (and (consp object) - (eq (car object) 'frame-configuration))) - - -;;;; List functions. - -(defsubst caar (x) - "Return the car of the car of X." - (car (car x))) - -(defsubst cadr (x) - "Return the car of the cdr of X." - (car (cdr x))) - -(defsubst cdar (x) - "Return the cdr of the car of X." - (cdr (car x))) - -(defsubst cddr (x) - "Return the cdr of the cdr of X." - (cdr (cdr x))) - -(defun last (list &optional n) - "Return the last link of LIST. Its car is the last element. -If LIST is nil, return nil. -If N is non-nil, return the Nth-to-last link of LIST. -If N is bigger than the length of LIST, return LIST." - (if n - (and (>= n 0) - (let ((m (safe-length list))) - (if (< n m) (nthcdr (- m n) list) list))) - (and list - (nthcdr (1- (safe-length list)) list)))) - -(defun butlast (list &optional n) - "Return a copy of LIST with the last N elements removed. -If N is omitted or nil, the last element is removed from the -copy." - (if (and n (<= n 0)) list - (nbutlast (copy-sequence list) n))) - -(defun nbutlast (list &optional n) - "Modifies LIST to remove the last N elements. -If N is omitted or nil, remove the last element." - (let ((m (length list))) - (or n (setq n 1)) - (and (< n m) - (progn - (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil)) - list)))) - -(defun zerop (number) - "Return t if NUMBER is zero." - ;; Used to be in C, but it's pointless since (= 0 n) is faster anyway because - ;; = has a byte-code. - (declare (compiler-macro (lambda (_) `(= 0 ,number)))) - (= 0 number)) - -(defun delete-dups (list) - "Destructively remove `equal' duplicates from LIST. -Store the result in LIST and return it. LIST must be a proper list. -Of several `equal' occurrences of an element in LIST, the first -one is kept." - (let ((tail list)) - (while tail - (setcdr tail (delete (car tail) (cdr tail))) - (setq tail (cdr tail)))) - list) - -;; See http://lists.gnu.org/archive/html/emacs-devel/2013-05/msg00204.html -(defun delete-consecutive-dups (list &optional circular) - "Destructively remove `equal' consecutive duplicates from LIST. -First and last elements are considered consecutive if CIRCULAR is -non-nil." - (let ((tail list) last) - (while (consp tail) - (if (equal (car tail) (cadr tail)) - (setcdr tail (cddr tail)) - (setq last (car tail) - tail (cdr tail)))) - (if (and circular - (cdr list) - (equal last (car list))) - (nbutlast list) - list))) - -(defun number-sequence (from &optional to inc) - "Return a sequence of numbers from FROM to TO (both inclusive) as a list. -INC is the increment used between numbers in the sequence and defaults to 1. -So, the Nth element of the list is (+ FROM (* N INC)) where N counts from -zero. TO is only included if there is an N for which TO = FROM + N * INC. -If TO is nil or numerically equal to FROM, return (FROM). -If INC is positive and TO is less than FROM, or INC is negative -and TO is larger than FROM, return nil. -If INC is zero and TO is neither nil nor numerically equal to -FROM, signal an error. - -This function is primarily designed for integer arguments. -Nevertheless, FROM, TO and INC can be integer or float. However, -floating point arithmetic is inexact. For instance, depending on -the machine, it may quite well happen that -\(number-sequence 0.4 0.6 0.2) returns the one element list (0.4), -whereas (number-sequence 0.4 0.8 0.2) returns a list with three -elements. Thus, if some of the arguments are floats and one wants -to make sure that TO is included, one may have to explicitly write -TO as (+ FROM (* N INC)) or use a variable whose value was -computed with this exact expression. Alternatively, you can, -of course, also replace TO with a slightly larger value -\(or a slightly more negative value if INC is negative)." - (if (or (not to) (= from to)) - (list from) - (or inc (setq inc 1)) - (when (zerop inc) (error "The increment can not be zero")) - (let (seq (n 0) (next from)) - (if (> inc 0) - (while (<= next to) - (setq seq (cons next seq) - n (1+ n) - next (+ from (* n inc)))) - (while (>= next to) - (setq seq (cons next seq) - n (1+ n) - next (+ from (* n inc))))) - (nreverse seq)))) - -(defun copy-tree (tree &optional vecp) - "Make a copy of TREE. -If TREE is a cons cell, this recursively copies both its car and its cdr. -Contrast to `copy-sequence', which copies only along the cdrs. With second -argument VECP, this copies vectors as well as conses." - (if (consp tree) - (let (result) - (while (consp tree) - (let ((newcar (car tree))) - (if (or (consp (car tree)) (and vecp (vectorp (car tree)))) - (setq newcar (copy-tree (car tree) vecp))) - (push newcar result)) - (setq tree (cdr tree))) - (nconc (nreverse result) tree)) - (if (and vecp (vectorp tree)) - (let ((i (length (setq tree (copy-sequence tree))))) - (while (>= (setq i (1- i)) 0) - (aset tree i (copy-tree (aref tree i) vecp))) - tree) - tree))) - -;;;; Various list-search functions. - -(defun assoc-default (key alist &optional test default) - "Find object KEY in a pseudo-alist ALIST. -ALIST is a list of conses or objects. Each element - (or the element's car, if it is a cons) is compared with KEY by - calling TEST, with two arguments: (i) the element or its car, - and (ii) KEY. -If that is non-nil, the element matches; then `assoc-default' - returns the element's cdr, if it is a cons, or DEFAULT if the - element is not a cons. - -If no element matches, the value is nil. -If TEST is omitted or nil, `equal' is used." - (let (found (tail alist) value) - (while (and tail (not found)) - (let ((elt (car tail))) - (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key) - (setq found t value (if (consp elt) (cdr elt) default)))) - (setq tail (cdr tail))) - value)) - -(defun assoc-ignore-case (key alist) - "Like `assoc', but ignores differences in case and text representation. -KEY must be a string. Upper-case and lower-case letters are treated as equal. -Unibyte strings are converted to multibyte for comparison." - (declare (obsolete assoc-string "22.1")) - (assoc-string key alist t)) - -(defun assoc-ignore-representation (key alist) - "Like `assoc', but ignores differences in text representation. -KEY must be a string. -Unibyte strings are converted to multibyte for comparison." - (declare (obsolete assoc-string "22.1")) - (assoc-string key alist nil)) - -(defun member-ignore-case (elt list) - "Like `member', but ignore differences in case and text representation. -ELT must be a string. Upper-case and lower-case letters are treated as equal. -Unibyte strings are converted to multibyte for comparison. -Non-strings in LIST are ignored." - (while (and list - (not (and (stringp (car list)) - (eq t (compare-strings elt 0 nil (car list) 0 nil t))))) - (setq list (cdr list))) - list) - -(defun assq-delete-all (key alist) - "Delete from ALIST all elements whose car is `eq' to KEY. -Return the modified alist. -Elements of ALIST that are not conses are ignored." - (while (and (consp (car alist)) - (eq (car (car alist)) key)) - (setq alist (cdr alist))) - (let ((tail alist) tail-cdr) - (while (setq tail-cdr (cdr tail)) - (if (and (consp (car tail-cdr)) - (eq (car (car tail-cdr)) key)) - (setcdr tail (cdr tail-cdr)) - (setq tail tail-cdr)))) - alist) - -(defun rassq-delete-all (value alist) - "Delete from ALIST all elements whose cdr is `eq' to VALUE. -Return the modified alist. -Elements of ALIST that are not conses are ignored." - (while (and (consp (car alist)) - (eq (cdr (car alist)) value)) - (setq alist (cdr alist))) - (let ((tail alist) tail-cdr) - (while (setq tail-cdr (cdr tail)) - (if (and (consp (car tail-cdr)) - (eq (cdr (car tail-cdr)) value)) - (setcdr tail (cdr tail-cdr)) - (setq tail tail-cdr)))) - alist) - -(defun alist-get (key alist &optional default remove) - "Get the value associated to KEY in ALIST. -DEFAULT is the value to return if KEY is not found in ALIST. -REMOVE, if non-nil, means that when setting this element, we should -remove the entry if the new value is `eql' to DEFAULT." - (ignore remove) ;;Silence byte-compiler. - (let ((x (assq key alist))) - (if x (cdr x) default))) - -(defun remove (elt seq) - "Return a copy of SEQ with all occurrences of ELT removed. -SEQ must be a list, vector, or string. The comparison is done with `equal'." - (if (nlistp seq) - ;; If SEQ isn't a list, there's no need to copy SEQ because - ;; `delete' will return a new object. - (delete elt seq) - (delete elt (copy-sequence seq)))) - -(defun remq (elt list) - "Return LIST with all occurrences of ELT removed. -The comparison is done with `eq'. Contrary to `delq', this does not use -side-effects, and the argument LIST is not modified." - (while (and (eq elt (car list)) (setq list (cdr list)))) - (if (memq elt list) - (delq elt (copy-sequence list)) - list)) - -;;;; Keymap support. - -(defun kbd (keys) - "Convert KEYS to the internal Emacs key representation. -KEYS should be a string constant in the format used for -saving keyboard macros (see `edmacro-mode')." - ;; Don't use a defalias, since the `pure' property is only true for - ;; the calling convention of `kbd'. - (read-kbd-macro keys)) -(put 'kbd 'pure t) - -(defun undefined () - "Beep to tell the user this binding is undefined." - (interactive) - (ding) - (message "%s is undefined" (key-description (this-single-command-keys))) - (setq defining-kbd-macro nil) - (force-mode-line-update) - ;; If this is a down-mouse event, don't reset prefix-arg; - ;; pass it to the command run by the up event. - (setq prefix-arg - (when (memq 'down (event-modifiers last-command-event)) - current-prefix-arg))) - -;; Prevent the \{...} documentation construct -;; from mentioning keys that run this command. -(put 'undefined 'suppress-keymap t) - -(defun suppress-keymap (map &optional nodigits) - "Make MAP override all normally self-inserting keys to be undefined. -Normally, as an exception, digits and minus-sign are set to make prefix args, -but optional second arg NODIGITS non-nil treats them like other chars." - (define-key map [remap self-insert-command] 'undefined) - (or nodigits - (let (loop) - (define-key map "-" 'negative-argument) - ;; Make plain numbers do numeric args. - (setq loop ?0) - (while (<= loop ?9) - (define-key map (char-to-string loop) 'digit-argument) - (setq loop (1+ loop)))))) - -(defun make-composed-keymap (maps &optional parent) - "Construct a new keymap composed of MAPS and inheriting from PARENT. -When looking up a key in the returned map, the key is looked in each -keymap of MAPS in turn until a binding is found. -If no binding is found in MAPS, the lookup continues in PARENT, if non-nil. -As always with keymap inheritance, a nil binding in MAPS overrides -any corresponding binding in PARENT, but it does not override corresponding -bindings in other keymaps of MAPS. -MAPS can be a list of keymaps or a single keymap. -PARENT if non-nil should be a keymap." - `(keymap - ,@(if (keymapp maps) (list maps) maps) - ,@parent)) - -(defun define-key-after (keymap key definition &optional after) - "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding. -This is like `define-key' except that the binding for KEY is placed -just after the binding for the event AFTER, instead of at the beginning -of the map. Note that AFTER must be an event type (like KEY), NOT a command -\(like DEFINITION). - -If AFTER is t or omitted, the new binding goes at the end of the keymap. -AFTER should be a single event type--a symbol or a character, not a sequence. - -Bindings are always added before any inherited map. - -The order of bindings in a keymap only matters when it is used as -a menu, so this function is not useful for non-menu keymaps." - (unless after (setq after t)) - (or (keymapp keymap) - (signal 'wrong-type-argument (list 'keymapp keymap))) - (setq key - (if (<= (length key) 1) (aref key 0) - (setq keymap (lookup-key keymap - (apply 'vector - (butlast (mapcar 'identity key))))) - (aref key (1- (length key))))) - (let ((tail keymap) done inserted) - (while (and (not done) tail) - ;; Delete any earlier bindings for the same key. - (if (eq (car-safe (car (cdr tail))) key) - (setcdr tail (cdr (cdr tail)))) - ;; If we hit an included map, go down that one. - (if (keymapp (car tail)) (setq tail (car tail))) - ;; When we reach AFTER's binding, insert the new binding after. - ;; If we reach an inherited keymap, insert just before that. - ;; If we reach the end of this keymap, insert at the end. - (if (or (and (eq (car-safe (car tail)) after) - (not (eq after t))) - (eq (car (cdr tail)) 'keymap) - (null (cdr tail))) - (progn - ;; Stop the scan only if we find a parent keymap. - ;; Keep going past the inserted element - ;; so we can delete any duplications that come later. - (if (eq (car (cdr tail)) 'keymap) - (setq done t)) - ;; Don't insert more than once. - (or inserted - (setcdr tail (cons (cons key definition) (cdr tail)))) - (setq inserted t))) - (setq tail (cdr tail))))) - -(defun map-keymap-sorted (function keymap) - "Implement `map-keymap' with sorting. -Don't call this function; it is for internal use only." - (let (list) - (map-keymap (lambda (a b) (push (cons a b) list)) - keymap) - (setq list (sort list - (lambda (a b) - (setq a (car a) b (car b)) - (if (integerp a) - (if (integerp b) (< a b) - t) - (if (integerp b) t - ;; string< also accepts symbols. - (string< a b)))))) - (dolist (p list) - (funcall function (car p) (cdr p))))) - -(defun keymap--menu-item-binding (val) - "Return the binding part of a menu-item." - (cond - ((not (consp val)) val) ;Not a menu-item. - ((eq 'menu-item (car val)) - (let* ((binding (nth 2 val)) - (plist (nthcdr 3 val)) - (filter (plist-get plist :filter))) - (if filter (funcall filter binding) - binding))) - ((and (consp (cdr val)) (stringp (cadr val))) - (cddr val)) - ((stringp (car val)) - (cdr val)) - (t val))) ;Not a menu-item either. - -(defun keymap--menu-item-with-binding (item binding) - "Build a menu-item like ITEM but with its binding changed to BINDING." - (cond - ((not (consp item)) binding) ;Not a menu-item. - ((eq 'menu-item (car item)) - (setq item (copy-sequence item)) - (let ((tail (nthcdr 2 item))) - (setcar tail binding) - ;; Remove any potential filter. - (if (plist-get (cdr tail) :filter) - (setcdr tail (plist-put (cdr tail) :filter nil)))) - item) - ((and (consp (cdr item)) (stringp (cadr item))) - (cons (car item) (cons (cadr item) binding))) - (t (cons (car item) binding)))) - -(defun keymap--merge-bindings (val1 val2) - "Merge bindings VAL1 and VAL2." - (let ((map1 (keymap--menu-item-binding val1)) - (map2 (keymap--menu-item-binding val2))) - (if (not (and (keymapp map1) (keymapp map2))) - ;; There's nothing to merge: val1 takes precedence. - val1 - (let ((map (list 'keymap map1 map2)) - (item (if (keymapp val1) (if (keymapp val2) nil val2) val1))) - (keymap--menu-item-with-binding item map))))) - -(defun keymap-canonicalize (map) - "Return a simpler equivalent keymap. -This resolves inheritance and redefinitions. The returned keymap -should behave identically to a copy of KEYMAP w.r.t `lookup-key' -and use in active keymaps and menus. -Subkeymaps may be modified but are not canonicalized." - ;; FIXME: Problem with the difference between a nil binding - ;; that hides a binding in an inherited map and a nil binding that's ignored - ;; to let some further binding visible. Currently a nil binding hides all. - ;; FIXME: we may want to carefully (re)order elements in case they're - ;; menu-entries. - (let ((bindings ()) - (ranges ()) - (prompt (keymap-prompt map))) - (while (keymapp map) - (setq map (map-keymap ;; -internal - (lambda (key item) - (if (consp key) - ;; Treat char-ranges specially. - (push (cons key item) ranges) - (push (cons key item) bindings))) - map))) - ;; Create the new map. - (setq map (funcall (if ranges 'make-keymap 'make-sparse-keymap) prompt)) - (dolist (binding ranges) - ;; Treat char-ranges specially. FIXME: need to merge as well. - (define-key map (vector (car binding)) (cdr binding))) - ;; Process the bindings starting from the end. - (dolist (binding (prog1 bindings (setq bindings ()))) - (let* ((key (car binding)) - (oldbind (assq key bindings))) - (push (if (not oldbind) - ;; The normal case: no duplicate bindings. - binding - ;; This is the second binding for this key. - (setq bindings (delq oldbind bindings)) - (cons key (keymap--merge-bindings (cdr binding) - (cdr oldbind)))) - bindings))) - (nconc map bindings))) - -(put 'keyboard-translate-table 'char-table-extra-slots 0) - -(defun keyboard-translate (from to) - "Translate character FROM to TO on the current terminal. -This function creates a `keyboard-translate-table' if necessary -and then modifies one entry in it." - (or (char-table-p keyboard-translate-table) - (setq keyboard-translate-table - (make-char-table 'keyboard-translate-table nil))) - (aset keyboard-translate-table from to)) - -;;;; Key binding commands. - -(defun global-set-key (key command) - "Give KEY a global binding as COMMAND. -COMMAND is the command definition to use; usually it is -a symbol naming an interactively-callable function. -KEY is a key sequence; noninteractively, it is a string or vector -of characters or event types, and non-ASCII characters with codes -above 127 (such as ISO Latin-1) can be included if you use a vector. - -Note that if KEY has a local binding in the current buffer, -that local binding will continue to shadow any global binding -that you make with this function." - (interactive "KSet key globally: \nCSet key %s to command: ") - (or (vectorp key) (stringp key) - (signal 'wrong-type-argument (list 'arrayp key))) - (define-key (current-global-map) key command)) - -(defun local-set-key (key command) - "Give KEY a local binding as COMMAND. -COMMAND is the command definition to use; usually it is -a symbol naming an interactively-callable function. -KEY is a key sequence; noninteractively, it is a string or vector -of characters or event types, and non-ASCII characters with codes -above 127 (such as ISO Latin-1) can be included if you use a vector. - -The binding goes in the current buffer's local map, which in most -cases is shared with all other buffers in the same major mode." - (interactive "KSet key locally: \nCSet key %s locally to command: ") - (let ((map (current-local-map))) - (or map - (use-local-map (setq map (make-sparse-keymap)))) - (or (vectorp key) (stringp key) - (signal 'wrong-type-argument (list 'arrayp key))) - (define-key map key command))) - -(defun global-unset-key (key) - "Remove global binding of KEY. -KEY is a string or vector representing a sequence of keystrokes." - (interactive "kUnset key globally: ") - (global-set-key key nil)) - -(defun local-unset-key (key) - "Remove local binding of KEY. -KEY is a string or vector representing a sequence of keystrokes." - (interactive "kUnset key locally: ") - (if (current-local-map) - (local-set-key key nil)) - nil) - -;;;; substitute-key-definition and its subroutines. - -(defvar key-substitution-in-progress nil - "Used internally by `substitute-key-definition'.") - -(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix) - "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF. -In other words, OLDDEF is replaced with NEWDEF where ever it appears. -Alternatively, if optional fourth argument OLDMAP is specified, we redefine -in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP. - -If you don't specify OLDMAP, you can usually get the same results -in a cleaner way with command remapping, like this: - (define-key KEYMAP [remap OLDDEF] NEWDEF) -\n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)" - ;; Don't document PREFIX in the doc string because we don't want to - ;; advertise it. It's meant for recursive calls only. Here's its - ;; meaning - - ;; If optional argument PREFIX is specified, it should be a key - ;; prefix, a string. Redefined bindings will then be bound to the - ;; original key, with PREFIX added at the front. - (or prefix (setq prefix "")) - (let* ((scan (or oldmap keymap)) - (prefix1 (vconcat prefix [nil])) - (key-substitution-in-progress - (cons scan key-substitution-in-progress))) - ;; Scan OLDMAP, finding each char or event-symbol that - ;; has any definition, and act on it with hack-key. - (map-keymap - (lambda (char defn) - (aset prefix1 (length prefix) char) - (substitute-key-definition-key defn olddef newdef prefix1 keymap)) - scan))) - -(defun substitute-key-definition-key (defn olddef newdef prefix keymap) - (let (inner-def skipped menu-item) - ;; Find the actual command name within the binding. - (if (eq (car-safe defn) 'menu-item) - (setq menu-item defn defn (nth 2 defn)) - ;; Skip past menu-prompt. - (while (stringp (car-safe defn)) - (push (pop defn) skipped)) - ;; Skip past cached key-equivalence data for menu items. - (if (consp (car-safe defn)) - (setq defn (cdr defn)))) - (if (or (eq defn olddef) - ;; Compare with equal if definition is a key sequence. - ;; That is useful for operating on function-key-map. - (and (or (stringp defn) (vectorp defn)) - (equal defn olddef))) - (define-key keymap prefix - (if menu-item - (let ((copy (copy-sequence menu-item))) - (setcar (nthcdr 2 copy) newdef) - copy) - (nconc (nreverse skipped) newdef))) - ;; Look past a symbol that names a keymap. - (setq inner-def - (or (indirect-function defn t) defn)) - ;; For nested keymaps, we use `inner-def' rather than `defn' so as to - ;; avoid autoloading a keymap. This is mostly done to preserve the - ;; original non-autoloading behavior of pre-map-keymap times. - (if (and (keymapp inner-def) - ;; Avoid recursively scanning - ;; where KEYMAP does not have a submap. - (let ((elt (lookup-key keymap prefix))) - (or (null elt) (natnump elt) (keymapp elt))) - ;; Avoid recursively rescanning keymap being scanned. - (not (memq inner-def key-substitution-in-progress))) - ;; If this one isn't being scanned already, scan it now. - (substitute-key-definition olddef newdef keymap inner-def prefix))))) - - -;;;; The global keymap tree. - -;; global-map, esc-map, and ctl-x-map have their values set up in -;; keymap.c; we just give them docstrings here. - -(defvar global-map nil - "Default global keymap mapping Emacs keyboard input into commands. -The value is a keymap which is usually (but not necessarily) Emacs's -global map.") - -(defvar esc-map nil - "Default keymap for ESC (meta) commands. -The normal global definition of the character ESC indirects to this keymap.") - -(defvar ctl-x-map nil - "Default keymap for C-x commands. -The normal global definition of the character C-x indirects to this keymap.") - -(defvar ctl-x-4-map (make-sparse-keymap) - "Keymap for subcommands of C-x 4.") -(defalias 'ctl-x-4-prefix ctl-x-4-map) -(define-key ctl-x-map "4" 'ctl-x-4-prefix) - -(defvar ctl-x-5-map (make-sparse-keymap) - "Keymap for frame commands.") -(defalias 'ctl-x-5-prefix ctl-x-5-map) -(define-key ctl-x-map "5" 'ctl-x-5-prefix) - - -;;;; Event manipulation functions. - -(defconst listify-key-sequence-1 (logior 128 ?\M-\C-@)) - -(defun listify-key-sequence (key) - "Convert a key sequence to a list of events." - (if (vectorp key) - (append key nil) - (mapcar (function (lambda (c) - (if (> c 127) - (logxor c listify-key-sequence-1) - c))) - key))) - -(defun eventp (obj) - "True if the argument is an event object." - (when obj - (or (integerp obj) - (and (symbolp obj) obj (not (keywordp obj))) - (and (consp obj) (symbolp (car obj)))))) - -(defun event-modifiers (event) - "Return a list of symbols representing the modifier keys in event EVENT. -The elements of the list may include `meta', `control', -`shift', `hyper', `super', `alt', `click', `double', `triple', `drag', -and `down'. -EVENT may be an event or an event type. If EVENT is a symbol -that has never been used in an event that has been read as input -in the current Emacs session, then this function may fail to include -the `click' modifier." - (let ((type event)) - (if (listp type) - (setq type (car type))) - (if (symbolp type) - ;; Don't read event-symbol-elements directly since we're not - ;; sure the symbol has already been parsed. - (cdr (internal-event-symbol-parse-modifiers type)) - (let ((list nil) - (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@ - ?\H-\^@ ?\s-\^@ ?\A-\^@))))) - (if (not (zerop (logand type ?\M-\^@))) - (push 'meta list)) - (if (or (not (zerop (logand type ?\C-\^@))) - (< char 32)) - (push 'control list)) - (if (or (not (zerop (logand type ?\S-\^@))) - (/= char (downcase char))) - (push 'shift list)) - (or (zerop (logand type ?\H-\^@)) - (push 'hyper list)) - (or (zerop (logand type ?\s-\^@)) - (push 'super list)) - (or (zerop (logand type ?\A-\^@)) - (push 'alt list)) - list)))) - -(defun event-basic-type (event) - "Return the basic type of the given event (all modifiers removed). -The value is a printing character (not upper case) or a symbol. -EVENT may be an event or an event type. If EVENT is a symbol -that has never been used in an event that has been read as input -in the current Emacs session, then this function may return nil." - (if (consp event) - (setq event (car event))) - (if (symbolp event) - (car (get event 'event-symbol-elements)) - (let* ((base (logand event (1- ?\A-\^@))) - (uncontrolled (if (< base 32) (logior base 64) base))) - ;; There are some numbers that are invalid characters and - ;; cause `downcase' to get an error. - (condition-case () - (downcase uncontrolled) - (error uncontrolled))))) - -(defsubst mouse-movement-p (object) - "Return non-nil if OBJECT is a mouse movement event." - (eq (car-safe object) 'mouse-movement)) - -(defun mouse-event-p (object) - "Return non-nil if OBJECT is a mouse click event." - ;; is this really correct? maybe remove mouse-movement? - (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))) - -(defun event-start (event) - "Return the starting position of EVENT. -EVENT should be a mouse click, drag, or key press event. If -EVENT is nil, the value of `posn-at-point' is used instead. - -The following accessor functions are used to access the elements -of the position: - -`posn-window': The window the event is in. -`posn-area': A symbol identifying the area the event occurred in, -or nil if the event occurred in the text area. -`posn-point': The buffer position of the event. -`posn-x-y': The pixel-based coordinates of the event. -`posn-col-row': The estimated column and row corresponding to the -position of the event. -`posn-actual-col-row': The actual column and row corresponding to the -position of the event. -`posn-string': The string object of the event, which is either -nil or (STRING . POSITION)'. -`posn-image': The image object of the event, if any. -`posn-object': The image or string object of the event, if any. -`posn-timestamp': The time the event occurred, in milliseconds. - -For more information, see Info node `(elisp)Click Events'." - (if (consp event) (nth 1 event) - (or (posn-at-point) - (list (selected-window) (point) '(0 . 0) 0)))) - -(defun event-end (event) - "Return the ending position of EVENT. -EVENT should be a click, drag, or key press event. - -See `event-start' for a description of the value returned." - (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event) - (or (posn-at-point) - (list (selected-window) (point) '(0 . 0) 0)))) - -(defsubst event-click-count (event) - "Return the multi-click count of EVENT, a click or drag event. -The return value is a positive integer." - (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1)) - -;;;; Extracting fields of the positions in an event. - -(defun posnp (obj) - "Return non-nil if OBJ appears to be a valid `posn' object specifying a window. -If OBJ is a valid `posn' object, but specifies a frame rather -than a window, return nil." - ;; FIXME: Correct the behavior of this function so that all valid - ;; `posn' objects are recognized, after updating other code that - ;; depends on its present behavior. - (and (windowp (car-safe obj)) - (atom (car-safe (setq obj (cdr obj)))) ;AREA-OR-POS. - (integerp (car-safe (car-safe (setq obj (cdr obj))))) ;XOFFSET. - (integerp (car-safe (cdr obj))))) ;TIMESTAMP. - -(defsubst posn-window (position) - "Return the window in POSITION. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (nth 0 position)) - -(defsubst posn-area (position) - "Return the window area recorded in POSITION, or nil for the text area. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (let ((area (if (consp (nth 1 position)) - (car (nth 1 position)) - (nth 1 position)))) - (and (symbolp area) area))) - -(defun posn-point (position) - "Return the buffer location in POSITION. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions. -Returns nil if POSITION does not correspond to any buffer location (e.g. -a click on a scroll bar)." - (or (nth 5 position) - (let ((pt (nth 1 position))) - (or (car-safe pt) - ;; Apparently this can also be `vertical-scroll-bar' (bug#13979). - (if (integerp pt) pt))))) - -(defun posn-set-point (position) - "Move point to POSITION. -Select the corresponding window as well." - (if (not (windowp (posn-window position))) - (error "Position not in text area of window")) - (select-window (posn-window position)) - (if (numberp (posn-point position)) - (goto-char (posn-point position)))) - -(defsubst posn-x-y (position) - "Return the x and y coordinates in POSITION. -The return value has the form (X . Y), where X and Y are given in -pixels. POSITION should be a list of the form returned by -`event-start' and `event-end'." - (nth 2 position)) - -(declare-function scroll-bar-scale "scroll-bar" (num-denom whole)) - -(defun posn-col-row (position) - "Return the nominal column and row in POSITION, measured in characters. -The column and row values are approximations calculated from the x -and y coordinates in POSITION and the frame's default character width -and default line height, including spacing. -For a scroll-bar event, the result column is 0, and the row -corresponds to the vertical position of the click in the scroll bar. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (let* ((pair (posn-x-y position)) - (frame-or-window (posn-window position)) - (frame (if (framep frame-or-window) - frame-or-window - (window-frame frame-or-window))) - (window (when (windowp frame-or-window) frame-or-window)) - (area (posn-area position))) - (cond - ((null frame-or-window) - '(0 . 0)) - ((eq area 'vertical-scroll-bar) - (cons 0 (scroll-bar-scale pair (1- (window-height window))))) - ((eq area 'horizontal-scroll-bar) - (cons (scroll-bar-scale pair (window-width window)) 0)) - (t - ;; FIXME: This should take line-spacing properties on - ;; newlines into account. - (let* ((spacing (when (display-graphic-p frame) - (or (with-current-buffer - (window-buffer (frame-selected-window frame)) - line-spacing) - (frame-parameter frame 'line-spacing))))) - (cond ((floatp spacing) - (setq spacing (truncate (* spacing - (frame-char-height frame))))) - ((null spacing) - (setq spacing 0))) - (cons (/ (car pair) (frame-char-width frame)) - (/ (cdr pair) (+ (frame-char-height frame) spacing)))))))) - -(defun posn-actual-col-row (position) - "Return the window row number in POSITION and character number in that row. - -Return nil if POSITION does not contain the actual position; in that case -\`posn-col-row' can be used to get approximate values. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions. - -This function does not account for the width on display, like the -number of visual columns taken by a TAB or image. If you need -the coordinates of POSITION in character units, you should use -\`posn-col-row', not this function." - (nth 6 position)) - -(defsubst posn-timestamp (position) - "Return the timestamp of POSITION. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (nth 3 position)) - -(defun posn-string (position) - "Return the string object of POSITION. -Value is a cons (STRING . STRING-POS), or nil if not a string. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (let ((x (nth 4 position))) - ;; Apparently this can also be `handle' or `below-handle' (bug#13979). - (when (consp x) x))) - -(defsubst posn-image (position) - "Return the image object of POSITION. -Value is a list (image ...), or nil if not an image. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (nth 7 position)) - -(defsubst posn-object (position) - "Return the object (image or string) of POSITION. -Value is a list (image ...) for an image object, a cons cell -\(STRING . STRING-POS) for a string object, and nil for a buffer position. -POSITION should be a list of the form returned by the `event-start' -and `event-end' functions." - (or (posn-image position) (posn-string position))) - -(defsubst posn-object-x-y (position) - "Return the x and y coordinates relative to the object of POSITION. -The return value has the form (DX . DY), where DX and DY are -given in pixels. POSITION should be a list of the form returned -by `event-start' and `event-end'." - (nth 8 position)) - -(defsubst posn-object-width-height (position) - "Return the pixel width and height of the object of POSITION. -The return value has the form (WIDTH . HEIGHT). POSITION should -be a list of the form returned by `event-start' and `event-end'." - (nth 9 position)) - - -;;;; Obsolescent names for functions. - -(define-obsolete-function-alias 'window-dot 'window-point "22.1") -(define-obsolete-function-alias 'set-window-dot 'set-window-point "22.1") -(define-obsolete-function-alias 'read-input 'read-string "22.1") -(define-obsolete-function-alias 'show-buffer 'set-window-buffer "22.1") -(define-obsolete-function-alias 'eval-current-buffer 'eval-buffer "22.1") -(define-obsolete-function-alias 'string-to-int 'string-to-number "22.1") - -(make-obsolete 'forward-point "use (+ (point) N) instead." "23.1") -(make-obsolete 'buffer-has-markers-at nil "24.3") - -(defun insert-string (&rest args) - "Mocklisp-compatibility insert function. -Like the function `insert' except that any argument that is a number -is converted into a string by expressing it in decimal." - (declare (obsolete insert "22.1")) - (dolist (el args) - (insert (if (integerp el) (number-to-string el) el)))) - -(defun makehash (&optional test) - (declare (obsolete make-hash-table "22.1")) - (make-hash-table :test (or test 'eql))) - -(defun log10 (x) - "Return (log X 10), the log base 10 of X." - (declare (obsolete log "24.4")) - (log x 10)) - -;; These are used by VM and some old programs -(defalias 'focus-frame 'ignore "") -(make-obsolete 'focus-frame "it does nothing." "22.1") -(defalias 'unfocus-frame 'ignore "") -(make-obsolete 'unfocus-frame "it does nothing." "22.1") -(make-obsolete 'make-variable-frame-local - "explicitly check for a frame-parameter instead." "22.2") -(set-advertised-calling-convention - 'all-completions '(string collection &optional predicate) "23.1") -(set-advertised-calling-convention 'unintern '(name obarray) "23.3") -(set-advertised-calling-convention 'indirect-function '(object) "25.1") -(set-advertised-calling-convention 'redirect-frame-focus '(frame focus-frame) "24.3") -(set-advertised-calling-convention 'decode-char '(ch charset) "21.4") -(set-advertised-calling-convention 'encode-char '(ch charset) "21.4") - -;;;; Obsolescence declarations for variables, and aliases. - -;; Special "default-FOO" variables which contain the default value of -;; the "FOO" variable are nasty. Their implementation is brittle, and -;; slows down several unrelated variable operations; furthermore, they -;; can lead to really odd behavior if you decide to make them -;; buffer-local. - -;; Not used at all in Emacs, last time I checked: -(make-obsolete-variable 'default-mode-line-format 'mode-line-format "23.2") -(make-obsolete-variable 'default-header-line-format 'header-line-format "23.2") -(make-obsolete-variable 'default-line-spacing 'line-spacing "23.2") -(make-obsolete-variable 'default-abbrev-mode 'abbrev-mode "23.2") -(make-obsolete-variable 'default-ctl-arrow 'ctl-arrow "23.2") -(make-obsolete-variable 'default-truncate-lines 'truncate-lines "23.2") -(make-obsolete-variable 'default-left-margin 'left-margin "23.2") -(make-obsolete-variable 'default-tab-width 'tab-width "23.2") -(make-obsolete-variable 'default-case-fold-search 'case-fold-search "23.2") -(make-obsolete-variable 'default-left-margin-width 'left-margin-width "23.2") -(make-obsolete-variable 'default-right-margin-width 'right-margin-width "23.2") -(make-obsolete-variable 'default-left-fringe-width 'left-fringe-width "23.2") -(make-obsolete-variable 'default-right-fringe-width 'right-fringe-width "23.2") -(make-obsolete-variable 'default-fringes-outside-margins 'fringes-outside-margins "23.2") -(make-obsolete-variable 'default-scroll-bar-width 'scroll-bar-width "23.2") -(make-obsolete-variable 'default-vertical-scroll-bar 'vertical-scroll-bar "23.2") -(make-obsolete-variable 'default-indicate-empty-lines 'indicate-empty-lines "23.2") -(make-obsolete-variable 'default-indicate-buffer-boundaries 'indicate-buffer-boundaries "23.2") -(make-obsolete-variable 'default-fringe-indicator-alist 'fringe-indicator-alist "23.2") -(make-obsolete-variable 'default-fringe-cursor-alist 'fringe-cursor-alist "23.2") -(make-obsolete-variable 'default-scroll-up-aggressively 'scroll-up-aggressively "23.2") -(make-obsolete-variable 'default-scroll-down-aggressively 'scroll-down-aggressively "23.2") -(make-obsolete-variable 'default-fill-column 'fill-column "23.2") -(make-obsolete-variable 'default-cursor-type 'cursor-type "23.2") -(make-obsolete-variable 'default-cursor-in-non-selected-windows 'cursor-in-non-selected-windows "23.2") -(make-obsolete-variable 'default-buffer-file-coding-system 'buffer-file-coding-system "23.2") -(make-obsolete-variable 'default-major-mode 'major-mode "23.2") -(make-obsolete-variable 'default-enable-multibyte-characters - "use enable-multibyte-characters or set-buffer-multibyte instead" "23.2") - -(make-obsolete-variable 'define-key-rebound-commands nil "23.2") -(make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1") -(make-obsolete-variable 'deferred-action-list 'post-command-hook "24.1") -(make-obsolete-variable 'deferred-action-function 'post-command-hook "24.1") -(make-obsolete-variable 'redisplay-dont-pause nil "24.5") -(make-obsolete 'window-redisplay-end-trigger nil "23.1") -(make-obsolete 'set-window-redisplay-end-trigger nil "23.1") - -(make-obsolete 'process-filter-multibyte-p nil "23.1") -(make-obsolete 'set-process-filter-multibyte nil "23.1") - -;; Lisp manual only updated in 22.1. -(define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro - "before 19.34") - -(define-obsolete-variable-alias 'x-lost-selection-hooks - 'x-lost-selection-functions "22.1") -(define-obsolete-variable-alias 'x-sent-selection-hooks - 'x-sent-selection-functions "22.1") - -;; This was introduced in 21.4 for pre-unicode unification. That -;; usage was rendered obsolete in 23.1 which uses Unicode internally. -;; Other uses are possible, so this variable is not _really_ obsolete, -;; but Stefan insists to mark it so. -(make-obsolete-variable 'translation-table-for-input nil "23.1") - -(defvaralias 'messages-buffer-max-lines 'message-log-max) - -;;;; Alternate names for functions - these are not being phased out. - -(defalias 'send-string 'process-send-string) -(defalias 'send-region 'process-send-region) -(defalias 'string= 'string-equal) -(defalias 'string< 'string-lessp) -(defalias 'move-marker 'set-marker) -(defalias 'rplaca 'setcar) -(defalias 'rplacd 'setcdr) -(defalias 'beep 'ding) ;preserve lingual purity -(defalias 'indent-to-column 'indent-to) -(defalias 'backward-delete-char 'delete-backward-char) -(defalias 'search-forward-regexp (symbol-function 're-search-forward)) -(defalias 'search-backward-regexp (symbol-function 're-search-backward)) -(defalias 'int-to-string 'number-to-string) -(defalias 'store-match-data 'set-match-data) -(defalias 'chmod 'set-file-modes) -(defalias 'mkdir 'make-directory) -;; These are the XEmacs names: -(defalias 'point-at-eol 'line-end-position) -(defalias 'point-at-bol 'line-beginning-position) - -(defalias 'user-original-login-name 'user-login-name) - - -;;;; Hook manipulation functions. - -(defun add-hook (hook function &optional append local) - "Add to the value of HOOK the function FUNCTION. -FUNCTION is not added if already present. -FUNCTION is added (if necessary) at the beginning of the hook list -unless the optional argument APPEND is non-nil, in which case -FUNCTION is added at the end. - -The optional fourth argument, LOCAL, if non-nil, says to modify -the hook's buffer-local value rather than its global value. -This makes the hook buffer-local, and it makes t a member of the -buffer-local value. That acts as a flag to run the hook -functions of the global value as well as in the local value. - -HOOK should be a symbol, and FUNCTION may be any valid function. If -HOOK is void, it is first set to nil. If HOOK's value is a single -function, it is changed to a list of functions." - (or (boundp hook) (set hook nil)) - (or (default-boundp hook) (set-default hook nil)) - (if local (unless (local-variable-if-set-p hook) - (set (make-local-variable hook) (list t))) - ;; Detect the case where make-local-variable was used on a hook - ;; and do what we used to do. - (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook))) - (setq local t))) - (let ((hook-value (if local (symbol-value hook) (default-value hook)))) - ;; If the hook value is a single function, turn it into a list. - (when (or (not (listp hook-value)) (functionp hook-value)) - (setq hook-value (list hook-value))) - ;; Do the actual addition if necessary - (unless (member function hook-value) - (when (stringp function) - (setq function (purecopy function))) - (setq hook-value - (if append - (append hook-value (list function)) - (cons function hook-value)))) - ;; Set the actual variable - (if local - (progn - ;; If HOOK isn't a permanent local, - ;; but FUNCTION wants to survive a change of modes, - ;; mark HOOK as partially permanent. - (and (symbolp function) - (get function 'permanent-local-hook) - (not (get hook 'permanent-local)) - (put hook 'permanent-local 'permanent-local-hook)) - (set hook hook-value)) - (set-default hook hook-value)))) - -(defun remove-hook (hook function &optional local) - "Remove from the value of HOOK the function FUNCTION. -HOOK should be a symbol, and FUNCTION may be any valid function. If -FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the -list of hooks to run in HOOK, then nothing is done. See `add-hook'. - -The optional third argument, LOCAL, if non-nil, says to modify -the hook's buffer-local value rather than its default value." - (or (boundp hook) (set hook nil)) - (or (default-boundp hook) (set-default hook nil)) - ;; Do nothing if LOCAL is t but this hook has no local binding. - (unless (and local (not (local-variable-p hook))) - ;; Detect the case where make-local-variable was used on a hook - ;; and do what we used to do. - (when (and (local-variable-p hook) - (not (and (consp (symbol-value hook)) - (memq t (symbol-value hook))))) - (setq local t)) - (let ((hook-value (if local (symbol-value hook) (default-value hook)))) - ;; Remove the function, for both the list and the non-list cases. - (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda)) - (if (equal hook-value function) (setq hook-value nil)) - (setq hook-value (delete function (copy-sequence hook-value)))) - ;; If the function is on the global hook, we need to shadow it locally - ;;(when (and local (member function (default-value hook)) - ;; (not (member (cons 'not function) hook-value))) - ;; (push (cons 'not function) hook-value)) - ;; Set the actual variable - (if (not local) - (set-default hook hook-value) - (if (equal hook-value '(t)) - (kill-local-variable hook) - (set hook hook-value)))))) - -(defmacro letrec (binders &rest body) - "Bind variables according to BINDERS then eval BODY. -The value of the last form in BODY is returned. -Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds -SYMBOL to the value of VALUEFORM. -All symbols are bound before the VALUEFORMs are evalled." - ;; Only useful in lexical-binding mode. - ;; As a special-form, we could implement it more efficiently (and cleanly, - ;; making the vars actually unbound during evaluation of the binders). - (declare (debug let) (indent 1)) - `(let ,(mapcar #'car binders) - ,@(mapcar (lambda (binder) `(setq ,@binder)) binders) - ,@body)) - -(defmacro with-wrapper-hook (hook args &rest body) - "Run BODY, using wrapper functions from HOOK with additional ARGS. -HOOK is an abnormal hook. Each hook function in HOOK \"wraps\" -around the preceding ones, like a set of nested `around' advices. - -Each hook function should accept an argument list consisting of a -function FUN, followed by the additional arguments in ARGS. - -The first hook function in HOOK is passed a FUN that, if it is called -with arguments ARGS, performs BODY (i.e., the default operation). -The FUN passed to each successive hook function is defined based -on the preceding hook functions; if called with arguments ARGS, -it does what the `with-wrapper-hook' call would do if the -preceding hook functions were the only ones present in HOOK. - -Each hook function may call its FUN argument as many times as it wishes, -including never. In that case, such a hook function acts to replace -the default definition altogether, and any preceding hook functions. -Of course, a subsequent hook function may do the same thing. - -Each hook function definition is used to construct the FUN passed -to the next hook function, if any. The last (or \"outermost\") -FUN is then called once." - (declare (indent 2) (debug (form sexp body)) - (obsolete "use a -function variable modified by `add-function'." - "24.4")) - ;; We need those two gensyms because CL's lexical scoping is not available - ;; for function arguments :-( - (let ((funs (make-symbol "funs")) - (global (make-symbol "global")) - (argssym (make-symbol "args")) - (runrestofhook (make-symbol "runrestofhook"))) - ;; Since the hook is a wrapper, the loop has to be done via - ;; recursion: a given hook function will call its parameter in order to - ;; continue looping. - `(letrec ((,runrestofhook - (lambda (,funs ,global ,argssym) - ;; `funs' holds the functions left on the hook and `global' - ;; holds the functions left on the global part of the hook - ;; (in case the hook is local). - (if (consp ,funs) - (if (eq t (car ,funs)) - (funcall ,runrestofhook - (append ,global (cdr ,funs)) nil ,argssym) - (apply (car ,funs) - (apply-partially - (lambda (,funs ,global &rest ,argssym) - (funcall ,runrestofhook ,funs ,global ,argssym)) - (cdr ,funs) ,global) - ,argssym)) - ;; Once there are no more functions on the hook, run - ;; the original body. - (apply (lambda ,args ,@body) ,argssym))))) - (funcall ,runrestofhook ,hook - ;; The global part of the hook, if any. - ,(if (symbolp hook) - `(if (local-variable-p ',hook) - (default-value ',hook))) - (list ,@args))))) - -(defun add-to-list (list-var element &optional append compare-fn) - "Add ELEMENT to the value of LIST-VAR if it isn't there yet. -The test for presence of ELEMENT is done with `equal', or with -COMPARE-FN if that's non-nil. -If ELEMENT is added, it is added at the beginning of the list, -unless the optional argument APPEND is non-nil, in which case -ELEMENT is added at the end. - -The return value is the new value of LIST-VAR. - -This is handy to add some elements to configuration variables, -but please do not abuse it in Elisp code, where you are usually -better off using `push' or `cl-pushnew'. - -If you want to use `add-to-list' on a variable that is not -defined until a certain package is loaded, you should put the -call to `add-to-list' into a hook function that will be run only -after loading the package. `eval-after-load' provides one way to -do this. In some cases other hooks, such as major mode hooks, -can do the job." - (declare - (compiler-macro - (lambda (exp) - ;; FIXME: Something like this could be used for `set' as well. - (if (or (not (eq 'quote (car-safe list-var))) - (special-variable-p (cadr list-var)) - (not (macroexp-const-p append))) - exp - (let* ((sym (cadr list-var)) - (append (eval append)) - (msg (format "`add-to-list' can't use lexical var `%s'; use `push' or `cl-pushnew'" - sym)) - ;; Big ugly hack so we only output a warning during - ;; byte-compilation, and so we can use - ;; byte-compile-not-lexical-var-p to silence the warning - ;; when a defvar has been seen but not yet executed. - (warnfun (lambda () - ;; FIXME: We should also emit a warning for let-bound - ;; variables with dynamic binding. - (when (assq sym byte-compile--lexical-environment) - (byte-compile-log-warning msg t :error)))) - (code - (macroexp-let2 macroexp-copyable-p x element - `(if ,(if compare-fn - (progn - (require 'cl-lib) - `(cl-member ,x ,sym :test ,compare-fn)) - ;; For bootstrapping reasons, don't rely on - ;; cl--compiler-macro-member for the base case. - `(member ,x ,sym)) - ,sym - ,(if append - `(setq ,sym (append ,sym (list ,x))) - `(push ,x ,sym)))))) - (if (not (macroexp--compiling-p)) - code - `(progn - (macroexp--funcall-if-compiled ',warnfun) - ,code))))))) - (if (cond - ((null compare-fn) - (member element (symbol-value list-var))) - ((eq compare-fn 'eq) - (memq element (symbol-value list-var))) - ((eq compare-fn 'eql) - (memql element (symbol-value list-var))) - (t - (let ((lst (symbol-value list-var))) - (while (and lst - (not (funcall compare-fn element (car lst)))) - (setq lst (cdr lst))) - lst))) - (symbol-value list-var) - (set list-var - (if append - (append (symbol-value list-var) (list element)) - (cons element (symbol-value list-var)))))) - - -(defun add-to-ordered-list (list-var element &optional order) - "Add ELEMENT to the value of LIST-VAR if it isn't there yet. -The test for presence of ELEMENT is done with `eq'. - -The resulting list is reordered so that the elements are in the -order given by each element's numeric list order. Elements -without a numeric list order are placed at the end of the list. - -If the third optional argument ORDER is a number (integer or -float), set the element's list order to the given value. If -ORDER is nil or omitted, do not change the numeric order of -ELEMENT. If ORDER has any other value, remove the numeric order -of ELEMENT if it has one. - -The list order for each element is stored in LIST-VAR's -`list-order' property. - -The return value is the new value of LIST-VAR." - (let ((ordering (get list-var 'list-order))) - (unless ordering - (put list-var 'list-order - (setq ordering (make-hash-table :weakness 'key :test 'eq)))) - (when order - (puthash element (and (numberp order) order) ordering)) - (unless (memq element (symbol-value list-var)) - (set list-var (cons element (symbol-value list-var)))) - (set list-var (sort (symbol-value list-var) - (lambda (a b) - (let ((oa (gethash a ordering)) - (ob (gethash b ordering))) - (if (and oa ob) - (< oa ob) - oa))))))) - -(defun add-to-history (history-var newelt &optional maxelt keep-all) - "Add NEWELT to the history list stored in the variable HISTORY-VAR. -Return the new history list. -If MAXELT is non-nil, it specifies the maximum length of the history. -Otherwise, the maximum history length is the value of the `history-length' -property on symbol HISTORY-VAR, if set, or the value of the `history-length' -variable. -Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil. -If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even -if it is empty or a duplicate." - (unless maxelt - (setq maxelt (or (get history-var 'history-length) - history-length))) - (let ((history (symbol-value history-var)) - tail) - (when (and (listp history) - (or keep-all - (not (stringp newelt)) - (> (length newelt) 0)) - (or keep-all - (not (equal (car history) newelt)))) - (if history-delete-duplicates - (setq history (delete newelt history))) - (setq history (cons newelt history)) - (when (integerp maxelt) - (if (= 0 maxelt) - (setq history nil) - (setq tail (nthcdr (1- maxelt) history)) - (when (consp tail) - (setcdr tail nil))))) - (set history-var history))) - - -;;;; Mode hooks. - -(defvar delay-mode-hooks nil - "If non-nil, `run-mode-hooks' should delay running the hooks.") -(defvar delayed-mode-hooks nil - "List of delayed mode hooks waiting to be run.") -(make-variable-buffer-local 'delayed-mode-hooks) -(put 'delay-mode-hooks 'permanent-local t) - -(defvar change-major-mode-after-body-hook nil - "Normal hook run in major mode functions, before the mode hooks.") - -(defvar after-change-major-mode-hook nil - "Normal hook run at the very end of major mode functions.") - -(defun run-mode-hooks (&rest hooks) - "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS. -If the variable `delay-mode-hooks' is non-nil, does not run any hooks, -just adds the HOOKS to the list `delayed-mode-hooks'. -Otherwise, runs hooks in the sequence: `change-major-mode-after-body-hook', -`delayed-mode-hooks' (in reverse order), HOOKS, and finally -`after-change-major-mode-hook'. Major mode functions should use -this instead of `run-hooks' when running their FOO-mode-hook." - (if delay-mode-hooks - ;; Delaying case. - (dolist (hook hooks) - (push hook delayed-mode-hooks)) - ;; Normal case, just run the hook as before plus any delayed hooks. - (setq hooks (nconc (nreverse delayed-mode-hooks) hooks)) - (setq delayed-mode-hooks nil) - (apply 'run-hooks (cons 'change-major-mode-after-body-hook hooks)) - (run-hooks 'after-change-major-mode-hook))) - -(defmacro delay-mode-hooks (&rest body) - "Execute BODY, but delay any `run-mode-hooks'. -These hooks will be executed by the first following call to -`run-mode-hooks' that occurs outside any `delayed-mode-hooks' form. -Only affects hooks run in the current buffer." - (declare (debug t) (indent 0)) - `(progn - (make-local-variable 'delay-mode-hooks) - (let ((delay-mode-hooks t)) - ,@body))) - -;; PUBLIC: find if the current mode derives from another. - -(defun derived-mode-p (&rest modes) - "Non-nil if the current major mode is derived from one of MODES. -Uses the `derived-mode-parent' property of the symbol to trace backwards." - (let ((parent major-mode)) - (while (and (not (memq parent modes)) - (setq parent (get parent 'derived-mode-parent)))) - parent)) - -;;;; Minor modes. - -;; If a minor mode is not defined with define-minor-mode, -;; add it here explicitly. -;; isearch-mode is deliberately excluded, since you should -;; not call it yourself. -(defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode - overwrite-mode view-mode - hs-minor-mode) - "List of all minor mode functions.") - -(defun add-minor-mode (toggle name &optional keymap after toggle-fun) - "Register a new minor mode. - -This is an XEmacs-compatibility function. Use `define-minor-mode' instead. - -TOGGLE is a symbol which is the name of a buffer-local variable that -is toggled on or off to say whether the minor mode is active or not. - -NAME specifies what will appear in the mode line when the minor mode -is active. NAME should be either a string starting with a space, or a -symbol whose value is such a string. - -Optional KEYMAP is the keymap for the minor mode that will be added -to `minor-mode-map-alist'. - -Optional AFTER specifies that TOGGLE should be added after AFTER -in `minor-mode-alist'. - -Optional TOGGLE-FUN is an interactive function to toggle the mode. -It defaults to (and should by convention be) TOGGLE. - -If TOGGLE has a non-nil `:included' property, an entry for the mode is -included in the mode-line minor mode menu. -If TOGGLE has a `:menu-tag', that is used for the menu item's label." - (unless (memq toggle minor-mode-list) - (push toggle minor-mode-list)) - - (unless toggle-fun (setq toggle-fun toggle)) - (unless (eq toggle-fun toggle) - (put toggle :minor-mode-function toggle-fun)) - ;; Add the name to the minor-mode-alist. - (when name - (let ((existing (assq toggle minor-mode-alist))) - (if existing - (setcdr existing (list name)) - (let ((tail minor-mode-alist) found) - (while (and tail (not found)) - (if (eq after (caar tail)) - (setq found tail) - (setq tail (cdr tail)))) - (if found - (let ((rest (cdr found))) - (setcdr found nil) - (nconc found (list (list toggle name)) rest)) - (push (list toggle name) minor-mode-alist)))))) - ;; Add the toggle to the minor-modes menu if requested. - (when (get toggle :included) - (define-key mode-line-mode-menu - (vector toggle) - (list 'menu-item - (concat - (or (get toggle :menu-tag) - (if (stringp name) name (symbol-name toggle))) - (let ((mode-name (if (symbolp name) (symbol-value name)))) - (if (and (stringp mode-name) (string-match "[^ ]+" mode-name)) - (concat " (" (match-string 0 mode-name) ")")))) - toggle-fun - :button (cons :toggle toggle)))) - - ;; Add the map to the minor-mode-map-alist. - (when keymap - (let ((existing (assq toggle minor-mode-map-alist))) - (if existing - (setcdr existing keymap) - (let ((tail minor-mode-map-alist) found) - (while (and tail (not found)) - (if (eq after (caar tail)) - (setq found tail) - (setq tail (cdr tail)))) - (if found - (let ((rest (cdr found))) - (setcdr found nil) - (nconc found (list (cons toggle keymap)) rest)) - (push (cons toggle keymap) minor-mode-map-alist))))))) - -;;;; Load history - -(defsubst autoloadp (object) - "Non-nil if OBJECT is an autoload." - (eq 'autoload (car-safe object))) - -;; (defun autoload-type (object) -;; "Returns the type of OBJECT or `function' or `command' if the type is nil. -;; OBJECT should be an autoload object." -;; (when (autoloadp object) -;; (let ((type (nth 3 object))) -;; (cond ((null type) (if (nth 2 object) 'command 'function)) -;; ((eq 'keymap t) 'macro) -;; (type))))) - -;; (defalias 'autoload-file #'cadr -;; "Return the name of the file from which AUTOLOAD will be loaded. -;; \n\(fn AUTOLOAD)") - -(defun symbol-file (symbol &optional type) - "Return the name of the file that defined SYMBOL. -The value is normally an absolute file name. It can also be nil, -if the definition is not associated with any file. If SYMBOL -specifies an autoloaded function, the value can be a relative -file name without extension. - -If TYPE is nil, then any kind of definition is acceptable. If -TYPE is `defun', `defvar', or `defface', that specifies function -definition, variable definition, or face definition only." - (if (and (or (null type) (eq type 'defun)) - (symbolp symbol) - (autoloadp (symbol-function symbol))) - (nth 1 (symbol-function symbol)) - (let ((files load-history) - file) - (while files - (if (if type - (if (eq type 'defvar) - ;; Variables are present just as their names. - (member symbol (cdr (car files))) - ;; Other types are represented as (TYPE . NAME). - (member (cons type symbol) (cdr (car files)))) - ;; We accept all types, so look for variable def - ;; and then for any other kind. - (or (member symbol (cdr (car files))) - (rassq symbol (cdr (car files))))) - (setq file (car (car files)) files nil)) - (setq files (cdr files))) - file))) - -(defun locate-library (library &optional nosuffix path interactive-call) - "Show the precise file name of Emacs library LIBRARY. -LIBRARY should be a relative file name of the library, a string. -It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is -nil (which is the default, see below). -This command searches the directories in `load-path' like `\\[load-library]' -to find the file that `\\[load-library] RET LIBRARY RET' would load. -Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes' -to the specified name LIBRARY. - -If the optional third arg PATH is specified, that list of directories -is used instead of `load-path'. - -When called from a program, the file name is normally returned as a -string. When run interactively, the argument INTERACTIVE-CALL is t, -and the file name is displayed in the echo area." - (interactive (list (completing-read "Locate library: " - (apply-partially - 'locate-file-completion-table - load-path (get-load-suffixes))) - nil nil - t)) - (let ((file (locate-file library - (or path load-path) - (append (unless nosuffix (get-load-suffixes)) - load-file-rep-suffixes)))) - (if interactive-call - (if file - (message "Library is file %s" (abbreviate-file-name file)) - (message "No library %s in search path" library))) - file)) - - -;;;; Process stuff. - -(defun process-lines (program &rest args) - "Execute PROGRAM with ARGS, returning its output as a list of lines. -Signal an error if the program returns with a non-zero exit status." - (with-temp-buffer - (let ((status (apply 'call-process program nil (current-buffer) nil args))) - (unless (eq status 0) - (error "%s exited with status %s" program status)) - (goto-char (point-min)) - (let (lines) - (while (not (eobp)) - (setq lines (cons (buffer-substring-no-properties - (line-beginning-position) - (line-end-position)) - lines)) - (forward-line 1)) - (nreverse lines))))) - -(defun process-live-p (process) - "Returns non-nil if PROCESS is alive. -A process is considered alive if its status is `run', `open', -`listen', `connect' or `stop'. Value is nil if PROCESS is not a -process." - (and (processp process) - (memq (process-status process) - '(run open listen connect stop)))) - -;; compatibility - -(make-obsolete - 'process-kill-without-query - "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'." - "22.1") -(defun process-kill-without-query (process &optional _flag) - "Say no query needed if PROCESS is running when Emacs is exited. -Optional second argument if non-nil says to require a query. -Value is t if a query was formerly required." - (let ((old (process-query-on-exit-flag process))) - (set-process-query-on-exit-flag process nil) - old)) - -(defun process-kill-buffer-query-function () - "Ask before killing a buffer that has a running process." - (let ((process (get-buffer-process (current-buffer)))) - (or (not process) - (not (memq (process-status process) '(run stop open listen))) - (not (process-query-on-exit-flag process)) - (yes-or-no-p - (format "Buffer %S has a running process; kill it? " - (buffer-name (current-buffer))))))) - -(add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function) - -;; process plist management - -(defun process-get (process propname) - "Return the value of PROCESS' PROPNAME property. -This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'." - (plist-get (process-plist process) propname)) - -(defun process-put (process propname value) - "Change PROCESS' PROPNAME property to VALUE. -It can be retrieved with `(process-get PROCESS PROPNAME)'." - (set-process-plist process - (plist-put (process-plist process) propname value))) - - -;;;; Input and display facilities. - -(defconst read-key-empty-map (make-sparse-keymap)) - -(defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully. - -(defun read-key (&optional prompt) - "Read a key from the keyboard. -Contrary to `read-event' this will not return a raw event but instead will -obey the input decoding and translations usually done by `read-key-sequence'. -So escape sequences and keyboard encoding are taken into account. -When there's an ambiguity because the key looks like the prefix of -some sort of escape sequence, the ambiguity is resolved via `read-key-delay'." - ;; This overriding-terminal-local-map binding also happens to - ;; disable quail's input methods, so although read-key-sequence - ;; always inherits the input method, in practice read-key does not - ;; inherit the input method (at least not if it's based on quail). - (let ((overriding-terminal-local-map nil) - (overriding-local-map read-key-empty-map) - (echo-keystrokes 0) - (old-global-map (current-global-map)) - (timer (run-with-idle-timer - ;; Wait long enough that Emacs has the time to receive and - ;; process all the raw events associated with the single-key. - ;; But don't wait too long, or the user may find the delay - ;; annoying (or keep hitting more keys which may then get - ;; lost or misinterpreted). - ;; This is only relevant for keys which Emacs perceives as - ;; "prefixes", such as C-x (because of the C-x 8 map in - ;; key-translate-table and the C-x @ map in function-key-map) - ;; or ESC (because of terminal escape sequences in - ;; input-decode-map). - read-key-delay t - (lambda () - (let ((keys (this-command-keys-vector))) - (unless (zerop (length keys)) - ;; `keys' is non-empty, so the user has hit at least - ;; one key; there's no point waiting any longer, even - ;; though read-key-sequence thinks we should wait - ;; for more input to decide how to interpret the - ;; current input. - (throw 'read-key keys))))))) - (unwind-protect - (progn - (use-global-map - (let ((map (make-sparse-keymap))) - ;; Don't hide the menu-bar and tool-bar entries. - (define-key map [menu-bar] (lookup-key global-map [menu-bar])) - (define-key map [tool-bar] - ;; This hack avoids evaluating the :filter (Bug#9922). - (or (cdr (assq 'tool-bar global-map)) - (lookup-key global-map [tool-bar]))) - map)) - (let* ((keys - (catch 'read-key (read-key-sequence-vector prompt nil t))) - (key (aref keys 0))) - (if (and (> (length keys) 1) - (memq key '(mode-line header-line - left-fringe right-fringe))) - (aref keys 1) - key))) - (cancel-timer timer) - (use-global-map old-global-map)))) - -(defvar read-passwd-map - ;; BEWARE: `defconst' would purecopy it, breaking the sharing with - ;; minibuffer-local-map along the way! - (let ((map (make-sparse-keymap))) - (set-keymap-parent map minibuffer-local-map) - (define-key map "\C-u" #'delete-minibuffer-contents) ;bug#12570 - map) - "Keymap used while reading passwords.") - -(defun read-passwd (prompt &optional confirm default) - "Read a password, prompting with PROMPT, and return it. -If optional CONFIRM is non-nil, read the password twice to make sure. -Optional DEFAULT is a default password to use instead of empty input. - -This function echoes `.' for each character that the user types. -You could let-bind `read-hide-char' to another hiding character, though. - -Once the caller uses the password, it can erase the password -by doing (clear-string STRING)." - (if confirm - (let (success) - (while (not success) - (let ((first (read-passwd prompt nil default)) - (second (read-passwd "Confirm password: " nil default))) - (if (equal first second) - (progn - (and (arrayp second) (clear-string second)) - (setq success first)) - (and (arrayp first) (clear-string first)) - (and (arrayp second) (clear-string second)) - (message "Password not repeated accurately; please start over") - (sit-for 1)))) - success) - (let ((hide-chars-fun - (lambda (beg end _len) - (clear-this-command-keys) - (setq beg (min end (max (minibuffer-prompt-end) - beg))) - (dotimes (i (- end beg)) - (put-text-property (+ i beg) (+ 1 i beg) - 'display (string (or read-hide-char ?.)))))) - minibuf) - (minibuffer-with-setup-hook - (lambda () - (setq minibuf (current-buffer)) - ;; Turn off electricity. - (setq-local post-self-insert-hook nil) - (setq-local buffer-undo-list t) - (setq-local select-active-regions nil) - (use-local-map read-passwd-map) - (setq-local inhibit-modification-hooks nil) ;bug#15501. - (setq-local show-paren-mode nil) ;bug#16091. - (add-hook 'after-change-functions hide-chars-fun nil 'local)) - (unwind-protect - (let ((enable-recursive-minibuffers t) - (read-hide-char (or read-hide-char ?.))) - (read-string prompt nil t default)) ; t = "no history" - (when (buffer-live-p minibuf) - (with-current-buffer minibuf - ;; Not sure why but it seems that there might be cases where the - ;; minibuffer is not always properly reset later on, so undo - ;; whatever we've done here (bug#11392). - (remove-hook 'after-change-functions hide-chars-fun 'local) - (kill-local-variable 'post-self-insert-hook) - ;; And of course, don't keep the sensitive data around. - (erase-buffer)))))))) - -(defun read-number (prompt &optional default) - "Read a numeric value in the minibuffer, prompting with PROMPT. -DEFAULT specifies a default value to return if the user just types RET. -The value of DEFAULT is inserted into PROMPT. -This function is used by the `interactive' code letter `n'." - (let ((n nil) - (default1 (if (consp default) (car default) default))) - (when default1 - (setq prompt - (if (string-match "\\(\\):[ \t]*\\'" prompt) - (replace-match (format " (default %s)" default1) t t prompt 1) - (replace-regexp-in-string "[ \t]*\\'" - (format " (default %s) " default1) - prompt t t)))) - (while - (progn - (let ((str (read-from-minibuffer - prompt nil nil nil nil - (when default - (if (consp default) - (mapcar 'number-to-string (delq nil default)) - (number-to-string default)))))) - (condition-case nil - (setq n (cond - ((zerop (length str)) default1) - ((stringp str) (read str)))) - (error nil))) - (unless (numberp n) - (message "Please enter a number.") - (sit-for 1) - t))) - n)) - -(defun read-char-choice (prompt chars &optional inhibit-keyboard-quit) - "Read and return one of CHARS, prompting for PROMPT. -Any input that is not one of CHARS is ignored. - -If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore -keyboard-quit events while waiting for a valid input." - (unless (consp chars) - (error "Called `read-char-choice' without valid char choices")) - (let (char done show-help (helpbuf " *Char Help*")) - (let ((cursor-in-echo-area t) - (executing-kbd-macro executing-kbd-macro) - (esc-flag nil)) - (save-window-excursion ; in case we call help-form-show - (while (not done) - (unless (get-text-property 0 'face prompt) - (setq prompt (propertize prompt 'face 'minibuffer-prompt))) - (setq char (let ((inhibit-quit inhibit-keyboard-quit)) - (read-key prompt))) - (and show-help (buffer-live-p (get-buffer helpbuf)) - (kill-buffer helpbuf)) - (cond - ((not (numberp char))) - ;; If caller has set help-form, that's enough. - ;; They don't explicitly have to add help-char to chars. - ((and help-form - (eq char help-char) - (setq show-help t) - (help-form-show))) - ((memq char chars) - (setq done t)) - ((and executing-kbd-macro (= char -1)) - ;; read-event returns -1 if we are in a kbd macro and - ;; there are no more events in the macro. Attempt to - ;; get an event interactively. - (setq executing-kbd-macro nil)) - ((not inhibit-keyboard-quit) - (cond - ((and (null esc-flag) (eq char ?\e)) - (setq esc-flag t)) - ((memq char '(?\C-g ?\e)) - (keyboard-quit)))))))) - ;; Display the question with the answer. But without cursor-in-echo-area. - (message "%s%s" prompt (char-to-string char)) - char)) - -(defun sit-for (seconds &optional nodisp obsolete) - "Redisplay, then wait for SECONDS seconds. Stop when input is available. -SECONDS may be a floating-point value. -\(On operating systems that do not support waiting for fractions of a -second, floating-point values are rounded down to the nearest integer.) - -If optional arg NODISP is t, don't redisplay, just wait for input. -Redisplay does not happen if input is available before it starts. - -Value is t if waited the full time with no input arriving, and nil otherwise. - -An obsolete, but still supported form is -\(sit-for SECONDS &optional MILLISECONDS NODISP) -where the optional arg MILLISECONDS specifies an additional wait period, -in milliseconds; this was useful when Emacs was built without -floating point support." - (declare (advertised-calling-convention (seconds &optional nodisp) "22.1")) - ;; This used to be implemented in C until the following discussion: - ;; http://lists.gnu.org/archive/html/emacs-devel/2006-07/msg00401.html - ;; Then it was moved here using an implementation based on an idle timer, - ;; which was then replaced by the use of read-event. - (if (numberp nodisp) - (setq seconds (+ seconds (* 1e-3 nodisp)) - nodisp obsolete) - (if obsolete (setq nodisp obsolete))) - (cond - (noninteractive - (sleep-for seconds) - t) - ((input-pending-p t) - nil) - ((<= seconds 0) - (or nodisp (redisplay))) - (t - (or nodisp (redisplay)) - ;; FIXME: we should not read-event here at all, because it's much too - ;; difficult to reliably "undo" a read-event by pushing it onto - ;; unread-command-events. - ;; For bug#14782, we need read-event to do the keyboard-coding-system - ;; decoding (hence non-nil as second arg under POSIX ttys). - ;; For bug#15614, we need read-event not to inherit-input-method. - ;; So we temporarily suspend input-method-function. - (let ((read (let ((input-method-function nil)) - (read-event nil t seconds)))) - (or (null read) - (progn - ;; https://lists.gnu.org/archive/html/emacs-devel/2006-10/msg00394.html - ;; We want `read' appear in the next command's this-command-event - ;; but not in the current one. - ;; By pushing (cons t read), we indicate that `read' has not - ;; yet been recorded in this-command-keys, so it will be recorded - ;; next time it's read. - ;; And indeed the `seconds' argument to read-event correctly - ;; prevented recording this event in the current command's - ;; this-command-keys. - (push (cons t read) unread-command-events) - nil)))))) - -;; Behind display-popup-menus-p test. -(declare-function x-popup-dialog "menu.c" (position contents &optional header)) - -(defun y-or-n-p (prompt) - "Ask user a \"y or n\" question. Return t if answer is \"y\". -PROMPT is the string to display to ask the question. It should -end in a space; `y-or-n-p' adds \"(y or n) \" to it. - -No confirmation of the answer is requested; a single character is -enough. SPC also means yes, and DEL means no. - -To be precise, this function translates user input into responses -by consulting the bindings in `query-replace-map'; see the -documentation of that variable for more information. In this -case, the useful bindings are `act', `skip', `recenter', -`scroll-up', `scroll-down', and `quit'. -An `act' response means yes, and a `skip' response means no. -A `quit' response means to invoke `keyboard-quit'. -If the user enters `recenter', `scroll-up', or `scroll-down' -responses, perform the requested window recentering or scrolling -and ask again. - -Under a windowing system a dialog box will be used if `last-nonmenu-event' -is nil and `use-dialog-box' is non-nil." - ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state - ;; where all the keys were unbound (i.e. it somehow got triggered - ;; within read-key, apparently). I had to kill it. - (let ((answer 'recenter) - (padded (lambda (prompt &optional dialog) - (let ((l (length prompt))) - (concat prompt - (if (or (zerop l) (eq ?\s (aref prompt (1- l)))) - "" " ") - (if dialog "" "(y or n) ")))))) - (cond - (noninteractive - (setq prompt (funcall padded prompt)) - (let ((temp-prompt prompt)) - (while (not (memq answer '(act skip))) - (let ((str (read-string temp-prompt))) - (cond ((member str '("y" "Y")) (setq answer 'act)) - ((member str '("n" "N")) (setq answer 'skip)) - (t (setq temp-prompt (concat "Please answer y or n. " - prompt)))))))) - ((and (display-popup-menus-p) - (listp last-nonmenu-event) - use-dialog-box) - (setq prompt (funcall padded prompt t) - answer (x-popup-dialog t `(,prompt ("Yes" . act) ("No" . skip))))) - (t - (setq prompt (funcall padded prompt)) - (while - (let* ((scroll-actions '(recenter scroll-up scroll-down - scroll-other-window scroll-other-window-down)) - (key - (let ((cursor-in-echo-area t)) - (when minibuffer-auto-raise - (raise-frame (window-frame (minibuffer-window)))) - (read-key (propertize (if (memq answer scroll-actions) - prompt - (concat "Please answer y or n. " - prompt)) - 'face 'minibuffer-prompt))))) - (setq answer (lookup-key query-replace-map (vector key) t)) - (cond - ((memq answer '(skip act)) nil) - ((eq answer 'recenter) - (recenter) t) - ((eq answer 'scroll-up) - (ignore-errors (scroll-up-command)) t) - ((eq answer 'scroll-down) - (ignore-errors (scroll-down-command)) t) - ((eq answer 'scroll-other-window) - (ignore-errors (scroll-other-window)) t) - ((eq answer 'scroll-other-window-down) - (ignore-errors (scroll-other-window-down)) t) - ((or (memq answer '(exit-prefix quit)) (eq key ?\e)) - (signal 'quit nil) t) - (t t))) - (ding) - (discard-input)))) - (let ((ret (eq answer 'act))) - (unless noninteractive - (message "%s%c" prompt (if ret ?y ?n))) - ret))) - - -;;; Atomic change groups. - -(defmacro atomic-change-group (&rest body) - "Perform BODY as an atomic change group. -This means that if BODY exits abnormally, -all of its changes to the current buffer are undone. -This works regardless of whether undo is enabled in the buffer. - -This mechanism is transparent to ordinary use of undo; -if undo is enabled in the buffer and BODY succeeds, the -user can undo the change normally." - (declare (indent 0) (debug t)) - (let ((handle (make-symbol "--change-group-handle--")) - (success (make-symbol "--change-group-success--"))) - `(let ((,handle (prepare-change-group)) - ;; Don't truncate any undo data in the middle of this. - (undo-outer-limit nil) - (undo-limit most-positive-fixnum) - (undo-strong-limit most-positive-fixnum) - (,success nil)) - (unwind-protect - (progn - ;; This is inside the unwind-protect because - ;; it enables undo if that was disabled; we need - ;; to make sure that it gets disabled again. - (activate-change-group ,handle) - ,@body - (setq ,success t)) - ;; Either of these functions will disable undo - ;; if it was disabled before. - (if ,success - (accept-change-group ,handle) - (cancel-change-group ,handle)))))) - -(defun prepare-change-group (&optional buffer) - "Return a handle for the current buffer's state, for a change group. -If you specify BUFFER, make a handle for BUFFER's state instead. - -Pass the handle to `activate-change-group' afterward to initiate -the actual changes of the change group. - -To finish the change group, call either `accept-change-group' or -`cancel-change-group' passing the same handle as argument. Call -`accept-change-group' to accept the changes in the group as final; -call `cancel-change-group' to undo them all. You should use -`unwind-protect' to make sure the group is always finished. The call -to `activate-change-group' should be inside the `unwind-protect'. -Once you finish the group, don't use the handle again--don't try to -finish the same group twice. For a simple example of correct use, see -the source code of `atomic-change-group'. - -The handle records only the specified buffer. To make a multibuffer -change group, call this function once for each buffer you want to -cover, then use `nconc' to combine the returned values, like this: - - (nconc (prepare-change-group buffer-1) - (prepare-change-group buffer-2)) - -You can then activate that multibuffer change group with a single -call to `activate-change-group' and finish it with a single call -to `accept-change-group' or `cancel-change-group'." - - (if buffer - (list (cons buffer (with-current-buffer buffer buffer-undo-list))) - (list (cons (current-buffer) buffer-undo-list)))) - -(defun activate-change-group (handle) - "Activate a change group made with `prepare-change-group' (which see)." - (dolist (elt handle) - (with-current-buffer (car elt) - (if (eq buffer-undo-list t) - (setq buffer-undo-list nil))))) - -(defun accept-change-group (handle) - "Finish a change group made with `prepare-change-group' (which see). -This finishes the change group by accepting its changes as final." - (dolist (elt handle) - (with-current-buffer (car elt) - (if (eq (cdr elt) t) - (setq buffer-undo-list t))))) - -(defun cancel-change-group (handle) - "Finish a change group made with `prepare-change-group' (which see). -This finishes the change group by reverting all of its changes." - (dolist (elt handle) - (with-current-buffer (car elt) - (setq elt (cdr elt)) - (save-restriction - ;; Widen buffer temporarily so if the buffer was narrowed within - ;; the body of `atomic-change-group' all changes can be undone. - (widen) - (let ((old-car - (if (consp elt) (car elt))) - (old-cdr - (if (consp elt) (cdr elt)))) - ;; Temporarily truncate the undo log at ELT. - (when (consp elt) - (setcar elt nil) (setcdr elt nil)) - (unless (eq last-command 'undo) (undo-start)) - ;; Make sure there's no confusion. - (when (and (consp elt) (not (eq elt (last pending-undo-list)))) - (error "Undoing to some unrelated state")) - ;; Undo it all. - (save-excursion - (while (listp pending-undo-list) (undo-more 1))) - ;; Reset the modified cons cell ELT to its original content. - (when (consp elt) - (setcar elt old-car) - (setcdr elt old-cdr)) - ;; Revert the undo info to what it was when we grabbed the state. - (setq buffer-undo-list elt)))))) - -;;;; Display-related functions. - -;; For compatibility. -(define-obsolete-function-alias 'redraw-modeline - 'force-mode-line-update "24.3") - -(defun momentary-string-display (string pos &optional exit-char message) - "Momentarily display STRING in the buffer at POS. -Display remains until next event is input. -If POS is a marker, only its position is used; its buffer is ignored. -Optional third arg EXIT-CHAR can be a character, event or event -description list. EXIT-CHAR defaults to SPC. If the input is -EXIT-CHAR it is swallowed; otherwise it is then available as -input (as a command if nothing else). -Display MESSAGE (optional fourth arg) in the echo area. -If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there." - (or exit-char (setq exit-char ?\s)) - (let ((ol (make-overlay pos pos)) - (str (copy-sequence string))) - (unwind-protect - (progn - (save-excursion - (overlay-put ol 'after-string str) - (goto-char pos) - ;; To avoid trouble with out-of-bounds position - (setq pos (point)) - ;; If the string end is off screen, recenter now. - (if (<= (window-end nil t) pos) - (recenter (/ (window-height) 2)))) - (message (or message "Type %s to continue editing.") - (single-key-description exit-char)) - (let ((event (read-key))) - ;; `exit-char' can be an event, or an event description list. - (or (eq event exit-char) - (eq event (event-convert-list exit-char)) - (setq unread-command-events - (append (this-single-command-raw-keys)))))) - (delete-overlay ol)))) - - -;;;; Overlay operations - -(defun copy-overlay (o) - "Return a copy of overlay O." - (let ((o1 (if (overlay-buffer o) - (make-overlay (overlay-start o) (overlay-end o) - ;; FIXME: there's no easy way to find the - ;; insertion-type of the two markers. - (overlay-buffer o)) - (let ((o1 (make-overlay (point-min) (point-min)))) - (delete-overlay o1) - o1))) - (props (overlay-properties o))) - (while props - (overlay-put o1 (pop props) (pop props))) - o1)) - -(defun remove-overlays (&optional beg end name val) - "Clear BEG and END of overlays whose property NAME has value VAL. -Overlays might be moved and/or split. -BEG and END default respectively to the beginning and end of buffer." - ;; This speeds up the loops over overlays. - (unless beg (setq beg (point-min))) - (unless end (setq end (point-max))) - (overlay-recenter end) - (if (< end beg) - (setq beg (prog1 end (setq end beg)))) - (save-excursion - (dolist (o (overlays-in beg end)) - (when (eq (overlay-get o name) val) - ;; Either push this overlay outside beg...end - ;; or split it to exclude beg...end - ;; or delete it entirely (if it is contained in beg...end). - (if (< (overlay-start o) beg) - (if (> (overlay-end o) end) - (progn - (move-overlay (copy-overlay o) - (overlay-start o) beg) - (move-overlay o end (overlay-end o))) - (move-overlay o (overlay-start o) beg)) - (if (> (overlay-end o) end) - (move-overlay o end (overlay-end o)) - (delete-overlay o))))))) - -;;;; Miscellanea. - -(defvar suspend-hook nil - "Normal hook run by `suspend-emacs', before suspending.") - -(defvar suspend-resume-hook nil - "Normal hook run by `suspend-emacs', after Emacs is continued.") - -(defvar temp-buffer-show-hook nil - "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer. -When the hook runs, the temporary buffer is current, and the window it -was displayed in is selected.") - -(defvar temp-buffer-setup-hook nil - "Normal hook run by `with-output-to-temp-buffer' at the start. -When the hook runs, the temporary buffer is current. -This hook is normally set up with a function to put the buffer in Help -mode.") - -(defconst user-emacs-directory - (if (eq system-type 'ms-dos) - ;; MS-DOS cannot have initial dot. - "~/_emacs.d/" - "~/.emacs.d/") - "Directory beneath which additional per-user Emacs-specific files are placed. -Various programs in Emacs store information in this directory. -Note that this should end with a directory separator. -See also `locate-user-emacs-file'.") - -;;;; Misc. useful functions. - -(defsubst buffer-narrowed-p () - "Return non-nil if the current buffer is narrowed." - (/= (- (point-max) (point-min)) (buffer-size))) - -(defun find-tag-default-bounds () - "Determine the boundaries of the default tag, based on text at point. -Return a cons cell with the beginning and end of the found tag. -If there is no plausible default, return nil." - (let (from to bound) - (when (or (progn - ;; Look at text around `point'. - (save-excursion - (skip-syntax-backward "w_") (setq from (point))) - (save-excursion - (skip-syntax-forward "w_") (setq to (point))) - (> to from)) - ;; Look between `line-beginning-position' and `point'. - (save-excursion - (and (setq bound (line-beginning-position)) - (skip-syntax-backward "^w_" bound) - (> (setq to (point)) bound) - (skip-syntax-backward "w_") - (setq from (point)))) - ;; Look between `point' and `line-end-position'. - (save-excursion - (and (setq bound (line-end-position)) - (skip-syntax-forward "^w_" bound) - (< (setq from (point)) bound) - (skip-syntax-forward "w_") - (setq to (point))))) - (cons from to)))) - -(defun find-tag-default () - "Determine default tag to search for, based on text at point. -If there is no plausible default, return nil." - (let ((bounds (find-tag-default-bounds))) - (when bounds - (buffer-substring-no-properties (car bounds) (cdr bounds))))) - -(defun find-tag-default-as-regexp () - "Return regexp that matches the default tag at point. -If there is no tag at point, return nil. - -When in a major mode that does not provide its own -`find-tag-default-function', return a regexp that matches the -symbol at point exactly." - (let ((tag (funcall (or find-tag-default-function - (get major-mode 'find-tag-default-function) - 'find-tag-default)))) - (if tag (regexp-quote tag)))) - -(defun find-tag-default-as-symbol-regexp () - "Return regexp that matches the default tag at point as symbol. -If there is no tag at point, return nil. - -When in a major mode that does not provide its own -`find-tag-default-function', return a regexp that matches the -symbol at point exactly." - (let ((tag-regexp (find-tag-default-as-regexp))) - (if (and tag-regexp - (eq (or find-tag-default-function - (get major-mode 'find-tag-default-function) - 'find-tag-default) - 'find-tag-default)) - (format "\\_<%s\\_>" tag-regexp) - tag-regexp))) - -(defun play-sound (sound) - "SOUND is a list of the form `(sound KEYWORD VALUE...)'. -The following keywords are recognized: - - :file FILE - read sound data from FILE. If FILE isn't an -absolute file name, it is searched in `data-directory'. - - :data DATA - read sound data from string DATA. - -Exactly one of :file or :data must be present. - - :volume VOL - set volume to VOL. VOL must an integer in the -range 0..100 or a float in the range 0..1.0. If not specified, -don't change the volume setting of the sound device. - - :device DEVICE - play sound on DEVICE. If not specified, -a system-dependent default device name is used. - -Note: :data and :device are currently not supported on Windows." - (if (fboundp 'play-sound-internal) - (play-sound-internal sound) - (error "This Emacs binary lacks sound support"))) - -(declare-function w32-shell-dos-semantics "w32-fns" nil) - -(defun shell-quote-argument (argument) - "Quote ARGUMENT for passing as argument to an inferior shell." - (cond - ((eq system-type 'ms-dos) - ;; Quote using double quotes, but escape any existing quotes in - ;; the argument with backslashes. - (let ((result "") - (start 0) - end) - (if (or (null (string-match "[^\"]" argument)) - (< (match-end 0) (length argument))) - (while (string-match "[\"]" argument start) - (setq end (match-beginning 0) - result (concat result (substring argument start end) - "\\" (substring argument end (1+ end))) - start (1+ end)))) - (concat "\"" result (substring argument start) "\""))) - - ((and (eq system-type 'windows-nt) (w32-shell-dos-semantics)) - - ;; First, quote argument so that CommandLineToArgvW will - ;; understand it. See - ;; http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx - ;; After we perform that level of quoting, escape shell - ;; metacharacters so that cmd won't mangle our argument. If the - ;; argument contains no double quote characters, we can just - ;; surround it with double quotes. Otherwise, we need to prefix - ;; each shell metacharacter with a caret. - - (setq argument - ;; escape backslashes at end of string - (replace-regexp-in-string - "\\(\\\\*\\)$" - "\\1\\1" - ;; escape backslashes and quotes in string body - (replace-regexp-in-string - "\\(\\\\*\\)\"" - "\\1\\1\\\\\"" - argument))) - - (if (string-match "[%!\"]" argument) - (concat - "^\"" - (replace-regexp-in-string - "\\([%!()\"<>&|^]\\)" - "^\\1" - argument) - "^\"") - (concat "\"" argument "\""))) - - (t - (if (equal argument "") - "''" - ;; Quote everything except POSIX filename characters. - ;; This should be safe enough even for really weird shells. - (replace-regexp-in-string - "\n" "'\n'" - (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument)))) - )) - -(defun string-or-null-p (object) - "Return t if OBJECT is a string or nil. -Otherwise, return nil." - (or (stringp object) (null object))) - -(defun booleanp (object) - "Return t if OBJECT is one of the two canonical boolean values: t or nil. -Otherwise, return nil." - (and (memq object '(nil t)) t)) - -(defun special-form-p (object) - "Non-nil if and only if OBJECT is a special form." - (if (and (symbolp object) (fboundp object)) - (setq object (indirect-function object t))) - (and (subrp object) (eq (cdr (subr-arity object)) 'unevalled))) - -(defun macrop (object) - "Non-nil if and only if OBJECT is a macro." - (let ((def (indirect-function object t))) - (when (consp def) - (or (eq 'macro (car def)) - (and (autoloadp def) (memq (nth 4 def) '(macro t))))))) - -(defun field-at-pos (pos) - "Return the field at position POS, taking stickiness etc into account." - (let ((raw-field (get-char-property (field-beginning pos) 'field))) - (if (eq raw-field 'boundary) - (get-char-property (1- (field-end pos)) 'field) - raw-field))) - -(defun sha1 (object &optional start end binary) - "Return the SHA1 (Secure Hash Algorithm) of an OBJECT. -OBJECT is either a string or a buffer. Optional arguments START and -END are character positions specifying which portion of OBJECT for -computing the hash. If BINARY is non-nil, return a string in binary -form." - (secure-hash 'sha1 object start end binary)) - -(defun function-get (f prop &optional autoload) - "Return the value of property PROP of function F. -If AUTOLOAD is non-nil and F is autoloaded, try to autoload it -in the hope that it will set PROP. If AUTOLOAD is `macro', only do it -if it's an autoloaded macro." - (let ((val nil)) - (while (and (symbolp f) - (null (setq val (get f prop))) - (fboundp f)) - (let ((fundef (symbol-function f))) - (if (and autoload (autoloadp fundef) - (not (equal fundef - (autoload-do-load fundef f - (if (eq autoload 'macro) - 'macro))))) - nil ;Re-try `get' on the same `f'. - (setq f fundef)))) - val)) - -;;;; Support for yanking and text properties. -;; Why here in subr.el rather than in simple.el? --Stef - -(defvar yank-handled-properties) -(defvar yank-excluded-properties) - -(defun remove-yank-excluded-properties (start end) - "Process text properties between START and END, inserted for a `yank'. -Perform the handling specified by `yank-handled-properties', then -remove properties specified by `yank-excluded-properties'." - (let ((inhibit-read-only t)) - (dolist (handler yank-handled-properties) - (let ((prop (car handler)) - (fun (cdr handler)) - (run-start start)) - (while (< run-start end) - (let ((value (get-text-property run-start prop)) - (run-end (next-single-property-change - run-start prop nil end))) - (funcall fun value run-start run-end) - (setq run-start run-end))))) - (if (eq yank-excluded-properties t) - (set-text-properties start end nil) - (remove-list-of-text-properties start end yank-excluded-properties)))) - -(defvar yank-undo-function) - -(defun insert-for-yank (string) - "Call `insert-for-yank-1' repetitively for each `yank-handler' segment. - -See `insert-for-yank-1' for more details." - (let (to) - (while (setq to (next-single-property-change 0 'yank-handler string)) - (insert-for-yank-1 (substring string 0 to)) - (setq string (substring string to)))) - (insert-for-yank-1 string)) - -(defun insert-for-yank-1 (string) - "Insert STRING at point for the `yank' command. -This function is like `insert', except it honors the variables -`yank-handled-properties' and `yank-excluded-properties', and the -`yank-handler' text property. - -Properties listed in `yank-handled-properties' are processed, -then those listed in `yank-excluded-properties' are discarded. - -If STRING has a non-nil `yank-handler' property on its first -character, the normal insert behavior is altered. The value of -the `yank-handler' property must be a list of one to four -elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO). -FUNCTION, if non-nil, should be a function of one argument, an - object to insert; it is called instead of `insert'. -PARAM, if present and non-nil, replaces STRING as the argument to - FUNCTION or `insert'; e.g. if FUNCTION is `yank-rectangle', PARAM - may be a list of strings to insert as a rectangle. -If NOEXCLUDE is present and non-nil, the normal removal of - `yank-excluded-properties' is not performed; instead FUNCTION is - responsible for the removal. This may be necessary if FUNCTION - adjusts point before or after inserting the object. -UNDO, if present and non-nil, should be a function to be called - by `yank-pop' to undo the insertion of the current object. It is - given two arguments, the start and end of the region. FUNCTION - may set `yank-undo-function' to override UNDO." - (let* ((handler (and (stringp string) - (get-text-property 0 'yank-handler string))) - (param (or (nth 1 handler) string)) - (opoint (point)) - (inhibit-read-only inhibit-read-only) - end) - - (setq yank-undo-function t) - (if (nth 0 handler) ; FUNCTION - (funcall (car handler) param) - (insert param)) - (setq end (point)) - - ;; Prevent read-only properties from interfering with the - ;; following text property changes. - (setq inhibit-read-only t) - - (unless (nth 2 handler) ; NOEXCLUDE - (remove-yank-excluded-properties opoint end)) - - ;; If last inserted char has properties, mark them as rear-nonsticky. - (if (and (> end opoint) - (text-properties-at (1- end))) - (put-text-property (1- end) end 'rear-nonsticky t)) - - (if (eq yank-undo-function t) ; not set by FUNCTION - (setq yank-undo-function (nth 3 handler))) ; UNDO - (if (nth 4 handler) ; COMMAND - (setq this-command (nth 4 handler))))) - -(defun insert-buffer-substring-no-properties (buffer &optional start end) - "Insert before point a substring of BUFFER, without text properties. -BUFFER may be a buffer or a buffer name. -Arguments START and END are character positions specifying the substring. -They default to the values of (point-min) and (point-max) in BUFFER." - (let ((opoint (point))) - (insert-buffer-substring buffer start end) - (let ((inhibit-read-only t)) - (set-text-properties opoint (point) nil)))) - -(defun insert-buffer-substring-as-yank (buffer &optional start end) - "Insert before point a part of BUFFER, stripping some text properties. -BUFFER may be a buffer or a buffer name. -Arguments START and END are character positions specifying the substring. -They default to the values of (point-min) and (point-max) in BUFFER. -Before insertion, process text properties according to -`yank-handled-properties' and `yank-excluded-properties'." - ;; Since the buffer text should not normally have yank-handler properties, - ;; there is no need to handle them here. - (let ((opoint (point))) - (insert-buffer-substring buffer start end) - (remove-yank-excluded-properties opoint (point)))) - -(defun yank-handle-font-lock-face-property (face start end) - "If `font-lock-defaults' is nil, apply FACE as a `face' property. -START and END denote the start and end of the text to act on. -Do nothing if FACE is nil." - (and face - (null font-lock-defaults) - (put-text-property start end 'face face))) - -;; This removes `mouse-face' properties in *Help* buffer buttons: -;; http://lists.gnu.org/archive/html/emacs-devel/2002-04/msg00648.html -(defun yank-handle-category-property (category start end) - "Apply property category CATEGORY's properties between START and END." - (when category - (let ((start2 start)) - (while (< start2 end) - (let ((end2 (next-property-change start2 nil end)) - (original (text-properties-at start2))) - (set-text-properties start2 end2 (symbol-plist category)) - (add-text-properties start2 end2 original) - (setq start2 end2)))))) - - -;;;; Synchronous shell commands. - -(defun start-process-shell-command (name buffer &rest args) - "Start a program in a subprocess. Return the process object for it. -NAME is name for process. It is modified if necessary to make it unique. -BUFFER is the buffer (or buffer name) to associate with the process. - Process output goes at end of that buffer, unless you specify - an output stream or filter function to handle the output. - BUFFER may be also nil, meaning that this process is not associated - with any buffer -COMMAND is the shell command to run. - -An old calling convention accepted any number of arguments after COMMAND, -which were just concatenated to COMMAND. This is still supported but strongly -discouraged." - (declare (advertised-calling-convention (name buffer command) "23.1")) - ;; We used to use `exec' to replace the shell with the command, - ;; but that failed to handle (...) and semicolon, etc. - (start-process name buffer shell-file-name shell-command-switch - (mapconcat 'identity args " "))) - -(defun start-file-process-shell-command (name buffer &rest args) - "Start a program in a subprocess. Return the process object for it. -Similar to `start-process-shell-command', but calls `start-file-process'." - (declare (advertised-calling-convention (name buffer command) "23.1")) - (start-file-process - name buffer - (if (file-remote-p default-directory) "/bin/sh" shell-file-name) - (if (file-remote-p default-directory) "-c" shell-command-switch) - (mapconcat 'identity args " "))) - -(defun call-process-shell-command (command &optional infile buffer display - &rest args) - "Execute the shell command COMMAND synchronously in separate process. -The remaining arguments are optional. -The program's input comes from file INFILE (nil means `/dev/null'). -Insert output in BUFFER before point; t means current buffer; - nil for BUFFER means discard it; 0 means discard and don't wait. -BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case, -REAL-BUFFER says what to do with standard output, as above, -while STDERR-FILE says what to do with standard error in the child. -STDERR-FILE may be nil (discard standard error output), -t (mix it with ordinary output), or a file name string. - -Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted. -Wildcards and redirection are handled as usual in the shell. - -If BUFFER is 0, `call-process-shell-command' returns immediately with value nil. -Otherwise it waits for COMMAND to terminate and returns a numeric exit -status or a signal description string. -If you quit, the process is killed with SIGINT, or SIGKILL if you quit again. - -An old calling convention accepted any number of arguments after DISPLAY, -which were just concatenated to COMMAND. This is still supported but strongly -discouraged." - (declare (advertised-calling-convention - (command &optional infile buffer display) "24.5")) - ;; We used to use `exec' to replace the shell with the command, - ;; but that failed to handle (...) and semicolon, etc. - (call-process shell-file-name - infile buffer display - shell-command-switch - (mapconcat 'identity (cons command args) " "))) - -(defun process-file-shell-command (command &optional infile buffer display - &rest args) - "Process files synchronously in a separate process. -Similar to `call-process-shell-command', but calls `process-file'." - (declare (advertised-calling-convention - (command &optional infile buffer display) "24.5")) - (process-file - (if (file-remote-p default-directory) "/bin/sh" shell-file-name) - infile buffer display - (if (file-remote-p default-directory) "-c" shell-command-switch) - (mapconcat 'identity (cons command args) " "))) - -;;;; Lisp macros to do various things temporarily. - -(defmacro track-mouse (&rest body) - "Evaluate BODY with mouse movement events enabled. -Within a `track-mouse' form, mouse motion generates input events that - you can read with `read-event'. -Normally, mouse motion is ignored." - (declare (debug t) (indent 0)) - `(internal--track-mouse (lambda () ,@body))) - -(defmacro with-current-buffer (buffer-or-name &rest body) - "Execute the forms in BODY with BUFFER-OR-NAME temporarily current. -BUFFER-OR-NAME must be a buffer or the name of an existing buffer. -The value returned is the value of the last form in BODY. See -also `with-temp-buffer'." - (declare (indent 1) (debug t)) - `(save-current-buffer - (set-buffer ,buffer-or-name) - ,@body)) - -(defun internal--before-with-selected-window (window) - (let ((other-frame (window-frame window))) - (list window (selected-window) - ;; Selecting a window on another frame also changes that - ;; frame's frame-selected-window. We must save&restore it. - (unless (eq (selected-frame) other-frame) - (frame-selected-window other-frame)) - ;; Also remember the top-frame if on ttys. - (unless (eq (selected-frame) other-frame) - (tty-top-frame other-frame))))) - -(defun internal--after-with-selected-window (state) - ;; First reset frame-selected-window. - (when (window-live-p (nth 2 state)) - ;; We don't use set-frame-selected-window because it does not - ;; pass the `norecord' argument to Fselect_window. - (select-window (nth 2 state) 'norecord) - (and (frame-live-p (nth 3 state)) - (not (eq (tty-top-frame) (nth 3 state))) - (select-frame (nth 3 state) 'norecord))) - ;; Then reset the actual selected-window. - (when (window-live-p (nth 1 state)) - (select-window (nth 1 state) 'norecord))) - -(defmacro with-selected-window (window &rest body) - "Execute the forms in BODY with WINDOW as the selected window. -The value returned is the value of the last form in BODY. - -This macro saves and restores the selected window, as well as the -selected window of each frame. It does not change the order of -recently selected windows. If the previously selected window of -some frame is no longer live at the end of BODY, that frame's -selected window is left alone. If the selected window is no -longer live, then whatever window is selected at the end of BODY -remains selected. - -This macro uses `save-current-buffer' to save and restore the -current buffer, since otherwise its normal operation could -potentially make a different buffer current. It does not alter -the buffer list ordering." - (declare (indent 1) (debug t)) - `(let ((save-selected-window--state - (internal--before-with-selected-window ,window))) - (save-current-buffer - (unwind-protect - (progn (select-window (car save-selected-window--state) 'norecord) - ,@body) - (internal--after-with-selected-window save-selected-window--state))))) - -(defmacro with-selected-frame (frame &rest body) - "Execute the forms in BODY with FRAME as the selected frame. -The value returned is the value of the last form in BODY. - -This macro saves and restores the selected frame, and changes the -order of neither the recently selected windows nor the buffers in -the buffer list." - (declare (indent 1) (debug t)) - (let ((old-frame (make-symbol "old-frame")) - (old-buffer (make-symbol "old-buffer"))) - `(let ((,old-frame (selected-frame)) - (,old-buffer (current-buffer))) - (unwind-protect - (progn (select-frame ,frame 'norecord) - ,@body) - (when (frame-live-p ,old-frame) - (select-frame ,old-frame 'norecord)) - (when (buffer-live-p ,old-buffer) - (set-buffer ,old-buffer)))))) - -(defmacro save-window-excursion (&rest body) - "Execute BODY, then restore previous window configuration. -This macro saves the window configuration on the selected frame, -executes BODY, then calls `set-window-configuration' to restore -the saved window configuration. The return value is the last -form in BODY. The window configuration is also restored if BODY -exits nonlocally. - -BEWARE: Most uses of this macro introduce bugs. -E.g. it should not be used to try and prevent some code from opening -a new window, since that window may sometimes appear in another frame, -in which case `save-window-excursion' cannot help." - (declare (indent 0) (debug t)) - (let ((c (make-symbol "wconfig"))) - `(let ((,c (current-window-configuration))) - (unwind-protect (progn ,@body) - (set-window-configuration ,c))))) - -(defun internal-temp-output-buffer-show (buffer) - "Internal function for `with-output-to-temp-buffer'." - (with-current-buffer buffer - (set-buffer-modified-p nil) - (goto-char (point-min))) - - (if temp-buffer-show-function - (funcall temp-buffer-show-function buffer) - (with-current-buffer buffer - (let* ((window - (let ((window-combination-limit - ;; When `window-combination-limit' equals - ;; `temp-buffer' or `temp-buffer-resize' and - ;; `temp-buffer-resize-mode' is enabled in this - ;; buffer bind it to t so resizing steals space - ;; preferably from the window that was split. - (if (or (eq window-combination-limit 'temp-buffer) - (and (eq window-combination-limit - 'temp-buffer-resize) - temp-buffer-resize-mode)) - t - window-combination-limit))) - (display-buffer buffer))) - (frame (and window (window-frame window)))) - (when window - (unless (eq frame (selected-frame)) - (make-frame-visible frame)) - (setq minibuffer-scroll-window window) - (set-window-hscroll window 0) - ;; Don't try this with NOFORCE non-nil! - (set-window-start window (point-min) t) - ;; This should not be necessary. - (set-window-point window (point-min)) - ;; Run `temp-buffer-show-hook', with the chosen window selected. - (with-selected-window window - (run-hooks 'temp-buffer-show-hook)))))) - ;; Return nil. - nil) - -;; Doc is very similar to with-temp-buffer-window. -(defmacro with-output-to-temp-buffer (bufname &rest body) - "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer. - -This construct makes buffer BUFNAME empty before running BODY. -It does not make the buffer current for BODY. -Instead it binds `standard-output' to that buffer, so that output -generated with `prin1' and similar functions in BODY goes into -the buffer. - -At the end of BODY, this marks buffer BUFNAME unmodified and displays -it in a window, but does not select it. The normal way to do this is -by calling `display-buffer', then running `temp-buffer-show-hook'. -However, if `temp-buffer-show-function' is non-nil, it calls that -function instead (and does not run `temp-buffer-show-hook'). The -function gets one argument, the buffer to display. - -The return value of `with-output-to-temp-buffer' is the value of the -last form in BODY. If BODY does not finish normally, the buffer -BUFNAME is not displayed. - -This runs the hook `temp-buffer-setup-hook' before BODY, -with the buffer BUFNAME temporarily current. It runs the hook -`temp-buffer-show-hook' after displaying buffer BUFNAME, with that -buffer temporarily current, and the window that was used to display it -temporarily selected. But it doesn't run `temp-buffer-show-hook' -if it uses `temp-buffer-show-function'. - -By default, the setup hook puts the buffer into Help mode before running BODY. -If BODY does not change the major mode, the show hook makes the buffer -read-only, and scans it for function and variable names to make them into -clickable cross-references. - -See the related form `with-temp-buffer-window'." - (declare (debug t)) - (let ((old-dir (make-symbol "old-dir")) - (buf (make-symbol "buf"))) - `(let* ((,old-dir default-directory) - (,buf - (with-current-buffer (get-buffer-create ,bufname) - (prog1 (current-buffer) - (kill-all-local-variables) - ;; FIXME: delete_all_overlays - (setq default-directory ,old-dir) - (setq buffer-read-only nil) - (setq buffer-file-name nil) - (setq buffer-undo-list t) - (let ((inhibit-read-only t) - (inhibit-modification-hooks t)) - (erase-buffer) - (run-hooks 'temp-buffer-setup-hook))))) - (standard-output ,buf)) - (prog1 (progn ,@body) - (internal-temp-output-buffer-show ,buf))))) - -(defmacro with-temp-file (file &rest body) - "Create a new buffer, evaluate BODY there, and write the buffer to FILE. -The value returned is the value of the last form in BODY. -See also `with-temp-buffer'." - (declare (indent 1) (debug t)) - (let ((temp-file (make-symbol "temp-file")) - (temp-buffer (make-symbol "temp-buffer"))) - `(let ((,temp-file ,file) - (,temp-buffer - (get-buffer-create (generate-new-buffer-name " *temp file*")))) - (unwind-protect - (prog1 - (with-current-buffer ,temp-buffer - ,@body) - (with-current-buffer ,temp-buffer - (write-region nil nil ,temp-file nil 0))) - (and (buffer-name ,temp-buffer) - (kill-buffer ,temp-buffer)))))) - -(defmacro with-temp-message (message &rest body) - "Display MESSAGE temporarily if non-nil while BODY is evaluated. -The original message is restored to the echo area after BODY has finished. -The value returned is the value of the last form in BODY. -MESSAGE is written to the message log buffer if `message-log-max' is non-nil. -If MESSAGE is nil, the echo area and message log buffer are unchanged. -Use a MESSAGE of \"\" to temporarily clear the echo area." - (declare (debug t) (indent 1)) - (let ((current-message (make-symbol "current-message")) - (temp-message (make-symbol "with-temp-message"))) - `(let ((,temp-message ,message) - (,current-message)) - (unwind-protect - (progn - (when ,temp-message - (setq ,current-message (current-message)) - (message "%s" ,temp-message)) - ,@body) - (and ,temp-message - (if ,current-message - (message "%s" ,current-message) - (message nil))))))) - -(defmacro with-temp-buffer (&rest body) - "Create a temporary buffer, and evaluate BODY there like `progn'. -See also `with-temp-file' and `with-output-to-string'." - (declare (indent 0) (debug t)) - (let ((temp-buffer (make-symbol "temp-buffer"))) - `(let ((,temp-buffer (generate-new-buffer " *temp*"))) - ;; FIXME: kill-buffer can change current-buffer in some odd cases. - (with-current-buffer ,temp-buffer - (unwind-protect - (progn ,@body) - (and (buffer-name ,temp-buffer) - (kill-buffer ,temp-buffer))))))) - -(defmacro with-silent-modifications (&rest body) - "Execute BODY, pretending it does not modify the buffer. -If BODY performs real modifications to the buffer's text, other -than cosmetic ones, undo data may become corrupted. - -This macro will run BODY normally, but doesn't count its buffer -modifications as being buffer modifications. This affects things -like `buffer-modified-p', checking whether the file is locked by -someone else, running buffer modification hooks, and other things -of that nature. - -Typically used around modifications of text-properties which do -not really affect the buffer's content." - (declare (debug t) (indent 0)) - (let ((modified (make-symbol "modified"))) - `(let* ((,modified (buffer-modified-p)) - (buffer-undo-list t) - (inhibit-read-only t) - (inhibit-modification-hooks t)) - (unwind-protect - (progn - ,@body) - (unless ,modified - (restore-buffer-modified-p nil)))))) - -(defmacro with-output-to-string (&rest body) - "Execute BODY, return the text it sent to `standard-output', as a string." - (declare (indent 0) (debug t)) - `(let ((standard-output - (get-buffer-create (generate-new-buffer-name " *string-output*")))) - (unwind-protect - (progn - (let ((standard-output standard-output)) - ,@body) - (with-current-buffer standard-output - (buffer-string))) - (kill-buffer standard-output)))) - -(defmacro with-local-quit (&rest body) - "Execute BODY, allowing quits to terminate BODY but not escape further. -When a quit terminates BODY, `with-local-quit' returns nil but -requests another quit. That quit will be processed as soon as quitting -is allowed once again. (Immediately, if `inhibit-quit' is nil.)" - (declare (debug t) (indent 0)) - `(condition-case nil - (let ((inhibit-quit nil)) - ,@body) - (quit (setq quit-flag t) - ;; This call is to give a chance to handle quit-flag - ;; in case inhibit-quit is nil. - ;; Without this, it will not be handled until the next function - ;; call, and that might allow it to exit thru a condition-case - ;; that intends to handle the quit signal next time. - (eval '(ignore nil))))) - -(defmacro while-no-input (&rest body) - "Execute BODY only as long as there's no pending input. -If input arrives, that ends the execution of BODY, -and `while-no-input' returns t. Quitting makes it return nil. -If BODY finishes, `while-no-input' returns whatever value BODY produced." - (declare (debug t) (indent 0)) - (let ((catch-sym (make-symbol "input"))) - `(with-local-quit - (catch ',catch-sym - (let ((throw-on-input ',catch-sym)) - (or (input-pending-p) - (progn ,@body))))))) - -(defmacro condition-case-unless-debug (var bodyform &rest handlers) - "Like `condition-case' except that it does not prevent debugging. -More specifically if `debug-on-error' is set then the debugger will be invoked -even if this catches the signal." - (declare (debug condition-case) (indent 2)) - `(condition-case ,var - ,bodyform - ,@(mapcar (lambda (handler) - `((debug ,@(if (listp (car handler)) (car handler) - (list (car handler)))) - ,@(cdr handler))) - handlers))) - -(define-obsolete-function-alias 'condition-case-no-debug - 'condition-case-unless-debug "24.1") - -(defmacro with-demoted-errors (format &rest body) - "Run BODY and demote any errors to simple messages. -FORMAT is a string passed to `message' to format any error message. -It should contain a single %-sequence; e.g., \"Error: %S\". - -If `debug-on-error' is non-nil, run BODY without catching its errors. -This is to be used around code which is not expected to signal an error -but which should be robust in the unexpected case that an error is signaled. - -For backward compatibility, if FORMAT is not a constant string, it -is assumed to be part of BODY, in which case the message format -used is \"Error: %S\"." - (declare (debug t) (indent 1)) - (let ((err (make-symbol "err")) - (format (if (and (stringp format) body) format - (prog1 "Error: %S" - (if format (push format body)))))) - `(condition-case-unless-debug ,err - ,(macroexp-progn body) - (error (message ,format ,err) nil)))) - -(defmacro combine-after-change-calls (&rest body) - "Execute BODY, but don't call the after-change functions till the end. -If BODY makes changes in the buffer, they are recorded -and the functions on `after-change-functions' are called several times -when BODY is finished. -The return value is the value of the last form in BODY. - -If `before-change-functions' is non-nil, then calls to the after-change -functions can't be deferred, so in that case this macro has no effect. - -Do not alter `after-change-functions' or `before-change-functions' -in BODY." - (declare (indent 0) (debug t)) - `(unwind-protect - (let ((combine-after-change-calls t)) - . ,body) - (combine-after-change-execute))) - -(defmacro with-case-table (table &rest body) - "Execute the forms in BODY with TABLE as the current case table. -The value returned is the value of the last form in BODY." - (declare (indent 1) (debug t)) - (let ((old-case-table (make-symbol "table")) - (old-buffer (make-symbol "buffer"))) - `(let ((,old-case-table (current-case-table)) - (,old-buffer (current-buffer))) - (unwind-protect - (progn (set-case-table ,table) - ,@body) - (with-current-buffer ,old-buffer - (set-case-table ,old-case-table)))))) - -(defmacro with-file-modes (modes &rest body) - "Execute BODY with default file permissions temporarily set to MODES. -MODES is as for `set-default-file-modes'." - (declare (indent 1) (debug t)) - (let ((umask (make-symbol "umask"))) - `(let ((,umask (default-file-modes))) - (unwind-protect - (progn - (set-default-file-modes ,modes) - ,@body) - (set-default-file-modes ,umask))))) - - -;;; Matching and match data. - -(defvar save-match-data-internal) - -;; We use save-match-data-internal as the local variable because -;; that works ok in practice (people should not use that variable elsewhere). -;; We used to use an uninterned symbol; the compiler handles that properly -;; now, but it generates slower code. -(defmacro save-match-data (&rest body) - "Execute the BODY forms, restoring the global value of the match data. -The value returned is the value of the last form in BODY." - ;; It is better not to use backquote here, - ;; because that makes a bootstrapping problem - ;; if you need to recompile all the Lisp files using interpreted code. - (declare (indent 0) (debug t)) - (list 'let - '((save-match-data-internal (match-data))) - (list 'unwind-protect - (cons 'progn body) - ;; It is safe to free (evaporate) markers immediately here, - ;; as Lisp programs should not copy from save-match-data-internal. - '(set-match-data save-match-data-internal 'evaporate)))) - -(defun match-string (num &optional string) - "Return string of text matched by last search. -NUM specifies which parenthesized expression in the last regexp. - Value is nil if NUMth pair didn't match, or there were less than NUM pairs. -Zero means the entire text matched by the whole regexp or whole string. -STRING should be given if the last search was by `string-match' on STRING. -If STRING is nil, the current buffer should be the same buffer -the search/match was performed in." - (if (match-beginning num) - (if string - (substring string (match-beginning num) (match-end num)) - (buffer-substring (match-beginning num) (match-end num))))) - -(defun match-string-no-properties (num &optional string) - "Return string of text matched by last search, without text properties. -NUM specifies which parenthesized expression in the last regexp. - Value is nil if NUMth pair didn't match, or there were less than NUM pairs. -Zero means the entire text matched by the whole regexp or whole string. -STRING should be given if the last search was by `string-match' on STRING. -If STRING is nil, the current buffer should be the same buffer -the search/match was performed in." - (if (match-beginning num) - (if string - (substring-no-properties string (match-beginning num) - (match-end num)) - (buffer-substring-no-properties (match-beginning num) - (match-end num))))) - - -(defun match-substitute-replacement (replacement - &optional fixedcase literal string subexp) - "Return REPLACEMENT as it will be inserted by `replace-match'. -In other words, all back-references in the form `\\&' and `\\N' -are substituted with actual strings matched by the last search. -Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same -meaning as for `replace-match'." - (let ((match (match-string 0 string))) - (save-match-data - (set-match-data (mapcar (lambda (x) - (if (numberp x) - (- x (match-beginning 0)) - x)) - (match-data t))) - (replace-match replacement fixedcase literal match subexp)))) - - -(defun looking-back (regexp &optional limit greedy) - "Return non-nil if text before point matches regular expression REGEXP. -Like `looking-at' except matches before point, and is slower. -LIMIT if non-nil speeds up the search by specifying a minimum -starting position, to avoid checking matches that would start -before LIMIT. - -If GREEDY is non-nil, extend the match backwards as far as -possible, stopping when a single additional previous character -cannot be part of a match for REGEXP. When the match is -extended, its starting position is allowed to occur before -LIMIT. - -As a general recommendation, try to avoid using `looking-back' -wherever possible, since it is slow." - (let ((start (point)) - (pos - (save-excursion - (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t) - (point))))) - (if (and greedy pos) - (save-restriction - (narrow-to-region (point-min) start) - (while (and (> pos (point-min)) - (save-excursion - (goto-char pos) - (backward-char 1) - (looking-at (concat "\\(?:" regexp "\\)\\'")))) - (setq pos (1- pos))) - (save-excursion - (goto-char pos) - (looking-at (concat "\\(?:" regexp "\\)\\'"))))) - (not (null pos)))) - -(defsubst looking-at-p (regexp) - "\ -Same as `looking-at' except this function does not change the match data." - (let ((inhibit-changing-match-data t)) - (looking-at regexp))) - -(defsubst string-match-p (regexp string &optional start) - "\ -Same as `string-match' except this function does not change the match data." - (let ((inhibit-changing-match-data t)) - (string-match regexp string start))) - -(defun subregexp-context-p (regexp pos &optional start) - "Return non-nil if POS is in a normal subregexp context in REGEXP. -A subregexp context is one where a sub-regexp can appear. -A non-subregexp context is for example within brackets, or within a -repetition bounds operator `\\=\\{...\\}', or right after a `\\'. -If START is non-nil, it should be a position in REGEXP, smaller -than POS, and known to be in a subregexp context." - ;; Here's one possible implementation, with the great benefit that it - ;; reuses the regexp-matcher's own parser, so it understands all the - ;; details of the syntax. A disadvantage is that it needs to match the - ;; error string. - (condition-case err - (progn - (string-match (substring regexp (or start 0) pos) "") - t) - (invalid-regexp - (not (member (cadr err) '("Unmatched [ or [^" - "Unmatched \\{" - "Trailing backslash"))))) - ;; An alternative implementation: - ;; (defconst re-context-re - ;; (let* ((harmless-ch "[^\\[]") - ;; (harmless-esc "\\\\[^{]") - ;; (class-harmless-ch "[^][]") - ;; (class-lb-harmless "[^]:]") - ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?") - ;; (class-lb (concat "\\[\\(" class-lb-harmless - ;; "\\|" class-lb-colon-maybe-charclass "\\)")) - ;; (class - ;; (concat "\\[^?]?" - ;; "\\(" class-harmless-ch - ;; "\\|" class-lb "\\)*" - ;; "\\[?]")) ; special handling for bare [ at end of re - ;; (braces "\\\\{[0-9,]+\\\\}")) - ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc - ;; "\\|" class "\\|" braces "\\)*\\'")) - ;; "Matches any prefix that corresponds to a normal subregexp context.") - ;; (string-match re-context-re (substring regexp (or start 0) pos)) - ) - -;;;; split-string - -(defconst split-string-default-separators "[ \f\t\n\r\v]+" - "The default value of separators for `split-string'. - -A regexp matching strings of whitespace. May be locale-dependent -\(as yet unimplemented). Should not match non-breaking spaces. - -Warning: binding this to a different value and using it as default is -likely to have undesired semantics.") - -;; The specification says that if both SEPARATORS and OMIT-NULLS are -;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical -;; expression leads to the equivalent implementation that if SEPARATORS -;; is defaulted, OMIT-NULLS is treated as t. -(defun split-string (string &optional separators omit-nulls trim) - "Split STRING into substrings bounded by matches for SEPARATORS. - -The beginning and end of STRING, and each match for SEPARATORS, are -splitting points. The substrings matching SEPARATORS are removed, and -the substrings between the splitting points are collected as a list, -which is returned. - -If SEPARATORS is non-nil, it should be a regular expression matching text -which separates, but is not part of, the substrings. If nil it defaults to -`split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and -OMIT-NULLS is forced to t. - -If OMIT-NULLS is t, zero-length substrings are omitted from the list (so -that for the default value of SEPARATORS leading and trailing whitespace -are effectively trimmed). If nil, all zero-length substrings are retained, -which correctly parses CSV format, for example. - -If TRIM is non-nil, it should be a regular expression to match -text to trim from the beginning and end of each substring. If trimming -makes the substring empty, it is treated as null. - -If you want to trim whitespace from the substrings, the reliably correct -way is using TRIM. Making SEPARATORS match that whitespace gives incorrect -results when there is whitespace at the start or end of STRING. If you -see such calls to `split-string', please fix them. - -Note that the effect of `(split-string STRING)' is the same as -`(split-string STRING split-string-default-separators t)'. In the rare -case that you wish to retain zero-length substrings when splitting on -whitespace, use `(split-string STRING split-string-default-separators)'. - -Modifies the match data; use `save-match-data' if necessary." - (let* ((keep-nulls (not (if separators omit-nulls t))) - (rexp (or separators split-string-default-separators)) - (start 0) - this-start this-end - notfirst - (list nil) - (push-one - ;; Push the substring in range THIS-START to THIS-END - ;; onto LIST, trimming it and perhaps discarding it. - (lambda () - (when trim - ;; Discard the trim from start of this substring. - (let ((tem (string-match trim string this-start))) - (and (eq tem this-start) - (setq this-start (match-end 0))))) - - (when (or keep-nulls (< this-start this-end)) - (let ((this (substring string this-start this-end))) - - ;; Discard the trim from end of this substring. - (when trim - (let ((tem (string-match (concat trim "\\'") this 0))) - (and tem (< tem (length this)) - (setq this (substring this 0 tem))))) - - ;; Trimming could make it empty; check again. - (when (or keep-nulls (> (length this) 0)) - (push this list))))))) - - (while (and (string-match rexp string - (if (and notfirst - (= start (match-beginning 0)) - (< start (length string))) - (1+ start) start)) - (< start (length string))) - (setq notfirst t) - (setq this-start start this-end (match-beginning 0) - start (match-end 0)) - - (funcall push-one)) - - ;; Handle the substring at the end of STRING. - (setq this-start start this-end (length string)) - (funcall push-one) - - (nreverse list))) - -(defun combine-and-quote-strings (strings &optional separator) - "Concatenate the STRINGS, adding the SEPARATOR (default \" \"). -This tries to quote the strings to avoid ambiguity such that - (split-string-and-unquote (combine-and-quote-strings strs)) == strs -Only some SEPARATORs will work properly." - (let* ((sep (or separator " ")) - (re (concat "[\\\"]" "\\|" (regexp-quote sep)))) - (mapconcat - (lambda (str) - (if (string-match re str) - (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"") - str)) - strings sep))) - -(defun split-string-and-unquote (string &optional separator) - "Split the STRING into a list of strings. -It understands Emacs Lisp quoting within STRING, such that - (split-string-and-unquote (combine-and-quote-strings strs)) == strs -The SEPARATOR regexp defaults to \"\\s-+\"." - (let ((sep (or separator "\\s-+")) - (i (string-match "\"" string))) - (if (null i) - (split-string string sep t) ; no quoting: easy - (append (unless (eq i 0) (split-string (substring string 0 i) sep t)) - (let ((rfs (read-from-string string i))) - (cons (car rfs) - (split-string-and-unquote (substring string (cdr rfs)) - sep))))))) - - -;;;; Replacement in strings. - -(defun subst-char-in-string (fromchar tochar string &optional inplace) - "Replace FROMCHAR with TOCHAR in STRING each time it occurs. -Unless optional argument INPLACE is non-nil, return a new string." - (let ((i (length string)) - (newstr (if inplace string (copy-sequence string)))) - (while (> i 0) - (setq i (1- i)) - (if (eq (aref newstr i) fromchar) - (aset newstr i tochar))) - newstr)) - -(defun replace-regexp-in-string (regexp rep string &optional - fixedcase literal subexp start) - "Replace all matches for REGEXP with REP in STRING. - -Return a new string containing the replacements. - -Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the -arguments with the same names of function `replace-match'. If START -is non-nil, start replacements at that index in STRING. - -REP is either a string used as the NEWTEXT arg of `replace-match' or a -function. If it is a function, it is called with the actual text of each -match, and its value is used as the replacement text. When REP is called, -the match data are the result of matching REGEXP against a substring -of STRING. - -To replace only the first match (if any), make REGEXP match up to \\' -and replace a sub-expression, e.g. - (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1) - => \" bar foo\"" - - ;; To avoid excessive consing from multiple matches in long strings, - ;; don't just call `replace-match' continually. Walk down the - ;; string looking for matches of REGEXP and building up a (reversed) - ;; list MATCHES. This comprises segments of STRING which weren't - ;; matched interspersed with replacements for segments that were. - ;; [For a `large' number of replacements it's more efficient to - ;; operate in a temporary buffer; we can't tell from the function's - ;; args whether to choose the buffer-based implementation, though it - ;; might be reasonable to do so for long enough STRING.] - (let ((l (length string)) - (start (or start 0)) - matches str mb me) - (save-match-data - (while (and (< start l) (string-match regexp string start)) - (setq mb (match-beginning 0) - me (match-end 0)) - ;; If we matched the empty string, make sure we advance by one char - (when (= me mb) (setq me (min l (1+ mb)))) - ;; Generate a replacement for the matched substring. - ;; Operate only on the substring to minimize string consing. - ;; Set up match data for the substring for replacement; - ;; presumably this is likely to be faster than munging the - ;; match data directly in Lisp. - (string-match regexp (setq str (substring string mb me))) - (setq matches - (cons (replace-match (if (stringp rep) - rep - (funcall rep (match-string 0 str))) - fixedcase literal str subexp) - (cons (substring string start mb) ; unmatched prefix - matches))) - (setq start me)) - ;; Reconstruct a string from the pieces. - (setq matches (cons (substring string start l) matches)) ; leftover - (apply #'concat (nreverse matches))))) - -(defun string-prefix-p (prefix string &optional ignore-case) - "Return non-nil if PREFIX is a prefix of STRING. -If IGNORE-CASE is non-nil, the comparison is done without paying attention -to case differences." - (let ((prefix-length (length prefix))) - (if (> prefix-length (length string)) nil - (eq t (compare-strings prefix 0 prefix-length string - 0 prefix-length ignore-case))))) - -(defun string-suffix-p (suffix string &optional ignore-case) - "Return non-nil if SUFFIX is a suffix of STRING. -If IGNORE-CASE is non-nil, the comparison is done without paying -attention to case differences." - (let ((start-pos (- (length string) (length suffix)))) - (and (>= start-pos 0) - (eq t (compare-strings suffix nil nil - string start-pos nil ignore-case))))) - -(defun bidi-string-mark-left-to-right (str) - "Return a string that can be safely inserted in left-to-right text. - -Normally, inserting a string with right-to-left (RTL) script into -a buffer may cause some subsequent text to be displayed as part -of the RTL segment (usually this affects punctuation characters). -This function returns a string which displays as STR but forces -subsequent text to be displayed as left-to-right. - -If STR contains any RTL character, this function returns a string -consisting of STR followed by an invisible left-to-right mark -\(LRM) character. Otherwise, it returns STR." - (unless (stringp str) - (signal 'wrong-type-argument (list 'stringp str))) - (if (string-match "\\cR" str) - (concat str (propertize (string ?\x200e) 'invisible t)) - str)) - -;;;; Specifying things to do later. - -(defun load-history-regexp (file) - "Form a regexp to find FILE in `load-history'. -FILE, a string, is described in the function `eval-after-load'." - (if (file-name-absolute-p file) - (setq file (file-truename file))) - (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)") - (regexp-quote file) - (if (file-name-extension file) - "" - ;; Note: regexp-opt can't be used here, since we need to call - ;; this before Emacs has been fully started. 2006-05-21 - (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?")) - "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|") - "\\)?\\'")) - -(defun load-history-filename-element (file-regexp) - "Get the first elt of `load-history' whose car matches FILE-REGEXP. -Return nil if there isn't one." - (let* ((loads load-history) - (load-elt (and loads (car loads)))) - (save-match-data - (while (and loads - (or (null (car load-elt)) - (not (string-match file-regexp (car load-elt))))) - (setq loads (cdr loads) - load-elt (and loads (car loads))))) - load-elt)) - -(put 'eval-after-load 'lisp-indent-function 1) -(defun eval-after-load (file form) - "Arrange that if FILE is loaded, FORM will be run immediately afterwards. -If FILE is already loaded, evaluate FORM right now. -FORM can be an Elisp expression (in which case it's passed to `eval'), -or a function (in which case it's passed to `funcall' with no argument). - -If a matching file is loaded again, FORM will be evaluated again. - -If FILE is a string, it may be either an absolute or a relative file -name, and may have an extension (e.g. \".el\") or may lack one, and -additionally may or may not have an extension denoting a compressed -format (e.g. \".gz\"). - -When FILE is absolute, this first converts it to a true name by chasing -symbolic links. Only a file of this name (see next paragraph regarding -extensions) will trigger the evaluation of FORM. When FILE is relative, -a file whose absolute true name ends in FILE will trigger evaluation. - -When FILE lacks an extension, a file name with any extension will trigger -evaluation. Otherwise, its extension must match FILE's. A further -extension for a compressed format (e.g. \".gz\") on FILE will not affect -this name matching. - -Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM -is evaluated at the end of any file that `provide's this feature. -If the feature is provided when evaluating code not associated with a -file, FORM is evaluated immediately after the provide statement. - -Usually FILE is just a library name like \"font-lock\" or a feature name -like 'font-lock. - -This function makes or adds to an entry on `after-load-alist'." - (declare (compiler-macro - (lambda (whole) - (if (eq 'quote (car-safe form)) - ;; Quote with lambda so the compiler can look inside. - `(eval-after-load ,file (lambda () ,(nth 1 form))) - whole)))) - ;; Add this FORM into after-load-alist (regardless of whether we'll be - ;; evaluating it now). - (let* ((regexp-or-feature - (if (stringp file) - (setq file (purecopy (load-history-regexp file))) - file)) - (elt (assoc regexp-or-feature after-load-alist)) - (func - (if (functionp form) form - ;; Try to use the "current" lexical/dynamic mode for `form'. - (eval `(lambda () ,form) lexical-binding)))) - (unless elt - (setq elt (list regexp-or-feature)) - (push elt after-load-alist)) - ;; Is there an already loaded file whose name (or `provide' name) - ;; matches FILE? - (prog1 (if (if (stringp file) - (load-history-filename-element regexp-or-feature) - (featurep file)) - (funcall func)) - (let ((delayed-func - (if (not (symbolp regexp-or-feature)) func - ;; For features, the after-load-alist elements get run when - ;; `provide' is called rather than at the end of the file. - ;; So add an indirection to make sure that `func' is really run - ;; "after-load" in case the provide call happens early. - (lambda () - (if (not load-file-name) - ;; Not being provided from a file, run func right now. - (funcall func) - (let ((lfn load-file-name) - ;; Don't use letrec, because equal (in - ;; add/remove-hook) would get trapped in a cycle. - (fun (make-symbol "eval-after-load-helper"))) - (fset fun (lambda (file) - (when (equal file lfn) - (remove-hook 'after-load-functions fun) - (funcall func)))) - (add-hook 'after-load-functions fun 'append))))))) - ;; Add FORM to the element unless it's already there. - (unless (member delayed-func (cdr elt)) - (nconc elt (list delayed-func))))))) - -(defmacro with-eval-after-load (file &rest body) - "Execute BODY after FILE is loaded. -FILE is normally a feature name, but it can also be a file name, -in case that file does not provide any feature." - (declare (indent 1) (debug t)) - `(eval-after-load ,file (lambda () ,@body))) - -(defvar after-load-functions nil - "Special hook run after loading a file. -Each function there is called with a single argument, the absolute -name of the file just loaded.") - -(defun do-after-load-evaluation (abs-file) - "Evaluate all `eval-after-load' forms, if any, for ABS-FILE. -ABS-FILE, a string, should be the absolute true name of a file just loaded. -This function is called directly from the C code." - ;; Run the relevant eval-after-load forms. - (dolist (a-l-element after-load-alist) - (when (and (stringp (car a-l-element)) - (string-match-p (car a-l-element) abs-file)) - ;; discard the file name regexp - (mapc #'funcall (cdr a-l-element)))) - ;; Complain when the user uses obsolete files. - (when (save-match-data - (and (string-match "/obsolete/\\([^/]*\\)\\'" abs-file) - (not (equal "loaddefs.el" (match-string 1 abs-file))))) - ;; Maybe we should just use display-warning? This seems yucky... - (let* ((file (file-name-nondirectory abs-file)) - (msg (format "Package %s is obsolete!" - (substring file 0 - (string-match "\\.elc?\\>" file))))) - ;; Cribbed from cl--compiling-file. - (if (and (boundp 'byte-compile--outbuffer) - (bufferp (symbol-value 'byte-compile--outbuffer)) - (equal (buffer-name (symbol-value 'byte-compile--outbuffer)) - " *Compiler Output*")) - ;; Don't warn about obsolete files using other obsolete files. - (unless (and (stringp byte-compile-current-file) - (string-match-p "/obsolete/[^/]*\\'" - (expand-file-name - byte-compile-current-file - byte-compile-root-dir))) - (byte-compile-log-warning msg)) - (run-with-timer 0 nil - (lambda (msg) - (message "%s" msg)) - msg)))) - - ;; Finally, run any other hook. - (run-hook-with-args 'after-load-functions abs-file)) - -(defun eval-next-after-load (file) - "Read the following input sexp, and run it whenever FILE is loaded. -This makes or adds to an entry on `after-load-alist'. -FILE should be the name of a library, with no directory name." - (declare (obsolete eval-after-load "23.2")) - (eval-after-load file (read))) - - -(defun display-delayed-warnings () - "Display delayed warnings from `delayed-warnings-list'. -Used from `delayed-warnings-hook' (which see)." - (dolist (warning (nreverse delayed-warnings-list)) - (apply 'display-warning warning)) - (setq delayed-warnings-list nil)) - -(defun collapse-delayed-warnings () - "Remove duplicates from `delayed-warnings-list'. -Collapse identical adjacent warnings into one (plus count). -Used from `delayed-warnings-hook' (which see)." - (let ((count 1) - collapsed warning) - (while delayed-warnings-list - (setq warning (pop delayed-warnings-list)) - (if (equal warning (car delayed-warnings-list)) - (setq count (1+ count)) - (when (> count 1) - (setcdr warning (cons (format "%s [%d times]" (cadr warning) count) - (cddr warning))) - (setq count 1)) - (push warning collapsed))) - (setq delayed-warnings-list (nreverse collapsed)))) - -;; At present this is only used for Emacs internals. -;; Ref http://lists.gnu.org/archive/html/emacs-devel/2012-02/msg00085.html -(defvar delayed-warnings-hook '(collapse-delayed-warnings - display-delayed-warnings) - "Normal hook run to process and display delayed warnings. -By default, this hook contains functions to consolidate the -warnings listed in `delayed-warnings-list', display them, and set -`delayed-warnings-list' back to nil.") - -(defun delay-warning (type message &optional level buffer-name) - "Display a delayed warning. -Aside from going through `delayed-warnings-list', this is equivalent -to `display-warning'." - (push (list type message level buffer-name) delayed-warnings-list)) - - -;;;; invisibility specs - -(defun add-to-invisibility-spec (element) - "Add ELEMENT to `buffer-invisibility-spec'. -See documentation for `buffer-invisibility-spec' for the kind of elements -that can be added." - (if (eq buffer-invisibility-spec t) - (setq buffer-invisibility-spec (list t))) - (setq buffer-invisibility-spec - (cons element buffer-invisibility-spec))) - -(defun remove-from-invisibility-spec (element) - "Remove ELEMENT from `buffer-invisibility-spec'." - (if (consp buffer-invisibility-spec) - (setq buffer-invisibility-spec - (delete element buffer-invisibility-spec)))) - -;;;; Syntax tables. - -(defmacro with-syntax-table (table &rest body) - "Evaluate BODY with syntax table of current buffer set to TABLE. -The syntax table of the current buffer is saved, BODY is evaluated, and the -saved table is restored, even in case of an abnormal exit. -Value is what BODY returns." - (declare (debug t) (indent 1)) - (let ((old-table (make-symbol "table")) - (old-buffer (make-symbol "buffer"))) - `(let ((,old-table (syntax-table)) - (,old-buffer (current-buffer))) - (unwind-protect - (progn - (set-syntax-table ,table) - ,@body) - (save-current-buffer - (set-buffer ,old-buffer) - (set-syntax-table ,old-table)))))) - -(defun make-syntax-table (&optional oldtable) - "Return a new syntax table. -Create a syntax table which inherits from OLDTABLE (if non-nil) or -from `standard-syntax-table' otherwise." - (let ((table (make-char-table 'syntax-table nil))) - (set-char-table-parent table (or oldtable (standard-syntax-table))) - table)) - -(defun syntax-after (pos) - "Return the raw syntax descriptor for the char after POS. -If POS is outside the buffer's accessible portion, return nil." - (unless (or (< pos (point-min)) (>= pos (point-max))) - (let ((st (if parse-sexp-lookup-properties - (get-char-property pos 'syntax-table)))) - (if (consp st) st - (aref (or st (syntax-table)) (char-after pos)))))) - -(defun syntax-class (syntax) - "Return the code for the syntax class described by SYNTAX. - -SYNTAX should be a raw syntax descriptor; the return value is a -integer which encodes the corresponding syntax class. See Info -node `(elisp)Syntax Table Internals' for a list of codes. - -If SYNTAX is nil, return nil." - (and syntax (logand (car syntax) 65535))) - -;; Utility motion commands - -;; Whitespace - -(defun forward-whitespace (arg) - "Move point to the end of the next sequence of whitespace chars. -Each such sequence may be a single newline, or a sequence of -consecutive space and/or tab characters. -With prefix argument ARG, do it ARG times if positive, or move -backwards ARG times if negative." - (interactive "^p") - (if (natnump arg) - (re-search-forward "[ \t]+\\|\n" nil 'move arg) - (while (< arg 0) - (if (re-search-backward "[ \t]+\\|\n" nil 'move) - (or (eq (char-after (match-beginning 0)) ?\n) - (skip-chars-backward " \t"))) - (setq arg (1+ arg))))) - -;; Symbols - -(defun forward-symbol (arg) - "Move point to the next position that is the end of a symbol. -A symbol is any sequence of characters that are in either the -word constituent or symbol constituent syntax class. -With prefix argument ARG, do it ARG times if positive, or move -backwards ARG times if negative." - (interactive "^p") - (if (natnump arg) - (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg) - (while (< arg 0) - (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move) - (skip-syntax-backward "w_")) - (setq arg (1+ arg))))) - -;; Syntax blocks - -(defun forward-same-syntax (&optional arg) - "Move point past all characters with the same syntax class. -With prefix argument ARG, do it ARG times if positive, or move -backwards ARG times if negative." - (interactive "^p") - (or arg (setq arg 1)) - (while (< arg 0) - (skip-syntax-backward - (char-to-string (char-syntax (char-before)))) - (setq arg (1+ arg))) - (while (> arg 0) - (skip-syntax-forward (char-to-string (char-syntax (char-after)))) - (setq arg (1- arg)))) - - -;;;; Text clones - -(defvar text-clone--maintaining nil) - -(defun text-clone--maintain (ol1 after beg end &optional _len) - "Propagate the changes made under the overlay OL1 to the other clones. -This is used on the `modification-hooks' property of text clones." - (when (and after (not undo-in-progress) - (not text-clone--maintaining) - (overlay-start ol1)) - (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0))) - (setq beg (max beg (+ (overlay-start ol1) margin))) - (setq end (min end (- (overlay-end ol1) margin))) - (when (<= beg end) - (save-excursion - (when (overlay-get ol1 'text-clone-syntax) - ;; Check content of the clone's text. - (let ((cbeg (+ (overlay-start ol1) margin)) - (cend (- (overlay-end ol1) margin))) - (goto-char cbeg) - (save-match-data - (if (not (re-search-forward - (overlay-get ol1 'text-clone-syntax) cend t)) - ;; Mark the overlay for deletion. - (setq end cbeg) - (when (< (match-end 0) cend) - ;; Shrink the clone at its end. - (setq end (min end (match-end 0))) - (move-overlay ol1 (overlay-start ol1) - (+ (match-end 0) margin))) - (when (> (match-beginning 0) cbeg) - ;; Shrink the clone at its beginning. - (setq beg (max (match-beginning 0) beg)) - (move-overlay ol1 (- (match-beginning 0) margin) - (overlay-end ol1))))))) - ;; Now go ahead and update the clones. - (let ((head (- beg (overlay-start ol1))) - (tail (- (overlay-end ol1) end)) - (str (buffer-substring beg end)) - (nothing-left t) - (text-clone--maintaining t)) - (dolist (ol2 (overlay-get ol1 'text-clones)) - (let ((oe (overlay-end ol2))) - (unless (or (eq ol1 ol2) (null oe)) - (setq nothing-left nil) - (let ((mod-beg (+ (overlay-start ol2) head))) - ;;(overlay-put ol2 'modification-hooks nil) - (goto-char (- (overlay-end ol2) tail)) - (unless (> mod-beg (point)) - (save-excursion (insert str)) - (delete-region mod-beg (point))) - ;;(overlay-put ol2 'modification-hooks '(text-clone--maintain)) - )))) - (if nothing-left (delete-overlay ol1)))))))) - -(defun text-clone-create (start end &optional spreadp syntax) - "Create a text clone of START...END at point. -Text clones are chunks of text that are automatically kept identical: -changes done to one of the clones will be immediately propagated to the other. - -The buffer's content at point is assumed to be already identical to -the one between START and END. -If SYNTAX is provided it's a regexp that describes the possible text of -the clones; the clone will be shrunk or killed if necessary to ensure that -its text matches the regexp. -If SPREADP is non-nil it indicates that text inserted before/after the -clone should be incorporated in the clone." - ;; To deal with SPREADP we can either use an overlay with `nil t' along - ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay - ;; (with a one-char margin at each end) with `t nil'. - ;; We opted for a larger overlay because it behaves better in the case - ;; where the clone is reduced to the empty string (we want the overlay to - ;; stay when the clone's content is the empty string and we want to use - ;; `evaporate' to make sure those overlays get deleted when needed). - ;; - (let* ((pt-end (+ (point) (- end start))) - (start-margin (if (or (not spreadp) (bobp) (<= start (point-min))) - 0 1)) - (end-margin (if (or (not spreadp) - (>= pt-end (point-max)) - (>= start (point-max))) - 0 1)) - ;; FIXME: Reuse overlays at point to extend dups! - (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t)) - (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t)) - (dups (list ol1 ol2))) - (overlay-put ol1 'modification-hooks '(text-clone--maintain)) - (when spreadp (overlay-put ol1 'text-clone-spreadp t)) - (when syntax (overlay-put ol1 'text-clone-syntax syntax)) - ;;(overlay-put ol1 'face 'underline) - (overlay-put ol1 'evaporate t) - (overlay-put ol1 'text-clones dups) - ;; - (overlay-put ol2 'modification-hooks '(text-clone--maintain)) - (when spreadp (overlay-put ol2 'text-clone-spreadp t)) - (when syntax (overlay-put ol2 'text-clone-syntax syntax)) - ;;(overlay-put ol2 'face 'underline) - (overlay-put ol2 'evaporate t) - (overlay-put ol2 'text-clones dups))) - -;;;; Mail user agents. - -;; Here we include just enough for other packages to be able -;; to define them. - -(defun define-mail-user-agent (symbol composefunc sendfunc - &optional abortfunc hookvar) - "Define a symbol to identify a mail-sending package for `mail-user-agent'. - -SYMBOL can be any Lisp symbol. Its function definition and/or -value as a variable do not matter for this usage; we use only certain -properties on its property list, to encode the rest of the arguments. - -COMPOSEFUNC is program callable function that composes an outgoing -mail message buffer. This function should set up the basics of the -buffer without requiring user interaction. It should populate the -standard mail headers, leaving the `to:' and `subject:' headers blank -by default. - -COMPOSEFUNC should accept several optional arguments--the same -arguments that `compose-mail' takes. See that function's documentation. - -SENDFUNC is the command a user would run to send the message. - -Optional ABORTFUNC is the command a user would run to abort the -message. For mail packages that don't have a separate abort function, -this can be `kill-buffer' (the equivalent of omitting this argument). - -Optional HOOKVAR is a hook variable that gets run before the message -is actually sent. Callers that use the `mail-user-agent' may -install a hook function temporarily on this hook variable. -If HOOKVAR is nil, `mail-send-hook' is used. - -The properties used on SYMBOL are `composefunc', `sendfunc', -`abortfunc', and `hookvar'." - (put symbol 'composefunc composefunc) - (put symbol 'sendfunc sendfunc) - (put symbol 'abortfunc (or abortfunc 'kill-buffer)) - (put symbol 'hookvar (or hookvar 'mail-send-hook))) - -(defvar called-interactively-p-functions nil - "Special hook called to skip special frames in `called-interactively-p'. -The functions are called with 3 arguments: (I FRAME1 FRAME2), -where FRAME1 is a \"current frame\", FRAME2 is the next frame, -I is the index of the frame after FRAME2. It should return nil -if those frames don't seem special and otherwise, it should return -the number of frames to skip (minus 1).") - -(defconst internal--funcall-interactively - (symbol-function 'funcall-interactively)) - -(defun called-interactively-p (&optional kind) - "Return t if the containing function was called by `call-interactively'. -If KIND is `interactive', then only return t if the call was made -interactively by the user, i.e. not in `noninteractive' mode nor -when `executing-kbd-macro'. -If KIND is `any', on the other hand, it will return t for any kind of -interactive call, including being called as the binding of a key or -from a keyboard macro, even in `noninteractive' mode. - -This function is very brittle, it may fail to return the intended result when -the code is debugged, advised, or instrumented in some form. Some macros and -special forms (such as `condition-case') may also sometimes wrap their bodies -in a `lambda', so any call to `called-interactively-p' from those bodies will -indicate whether that lambda (rather than the surrounding function) was called -interactively. - -Instead of using this function, it is cleaner and more reliable to give your -function an extra optional argument whose `interactive' spec specifies -non-nil unconditionally (\"p\" is a good way to do this), or via -\(not (or executing-kbd-macro noninteractive)). - -The only known proper use of `interactive' for KIND is in deciding -whether to display a helpful message, or how to display it. If you're -thinking of using it for any other purpose, it is quite likely that -you're making a mistake. Think: what do you want to do when the -command is called from a keyboard macro?" - (declare (advertised-calling-convention (kind) "23.1")) - (when (not (and (eq kind 'interactive) - (or executing-kbd-macro noninteractive))) - (let* ((i 1) ;; 0 is the called-interactively-p frame. - frame nextframe - (get-next-frame - (lambda () - (setq frame nextframe) - (setq nextframe (backtrace-frame i 'called-interactively-p)) - ;; (message "Frame %d = %S" i nextframe) - (setq i (1+ i))))) - (funcall get-next-frame) ;; Get the first frame. - (while - ;; FIXME: The edebug and advice handling should be made modular and - ;; provided directly by edebug.el and nadvice.el. - (progn - ;; frame =(backtrace-frame i-2) - ;; nextframe=(backtrace-frame i-1) - (funcall get-next-frame) - ;; `pcase' would be a fairly good fit here, but it sometimes moves - ;; branches within local functions, which then messes up the - ;; `backtrace-frame' data we get, - (or - ;; Skip special forms (from non-compiled code). - (and frame (null (car frame))) - ;; Skip also `interactive-p' (because we don't want to know if - ;; interactive-p was called interactively but if it's caller was) - ;; and `byte-code' (idem; this appears in subexpressions of things - ;; like condition-case, which are wrapped in a separate bytecode - ;; chunk). - ;; FIXME: For lexical-binding code, this is much worse, - ;; because the frames look like "byte-code -> funcall -> #[...]", - ;; which is not a reliable signature. - (memq (nth 1 frame) '(interactive-p 'byte-code)) - ;; Skip package-specific stack-frames. - (let ((skip (run-hook-with-args-until-success - 'called-interactively-p-functions - i frame nextframe))) - (pcase skip - (`nil nil) - (`0 t) - (_ (setq i (+ i skip -1)) (funcall get-next-frame))))))) - ;; Now `frame' should be "the function from which we were called". - (pcase (cons frame nextframe) - ;; No subr calls `interactive-p', so we can rule that out. - (`((,_ ,(pred (lambda (f) (subrp (indirect-function f)))) . ,_) . ,_) nil) - ;; In case # without going through the - ;; `funcall-interactively' symbol (bug#3984). - (`(,_ . (t ,(pred (lambda (f) - (eq internal--funcall-interactively - (indirect-function f)))) - . ,_)) - t))))) - -(defun interactive-p () - "Return t if the containing function was run directly by user input. -This means that the function was called with `call-interactively' -\(which includes being called as the binding of a key) -and input is currently coming from the keyboard (not a keyboard macro), -and Emacs is not running in batch mode (`noninteractive' is nil). - -The only known proper use of `interactive-p' is in deciding whether to -display a helpful message, or how to display it. If you're thinking -of using it for any other purpose, it is quite likely that you're -making a mistake. Think: what do you want to do when the command is -called from a keyboard macro or in batch mode? - -To test whether your function was called with `call-interactively', -either (i) add an extra optional argument and give it an `interactive' -spec that specifies non-nil unconditionally (such as \"p\"); or (ii) -use `called-interactively-p'." - (declare (obsolete called-interactively-p "23.2")) - (called-interactively-p 'interactive)) - -(defun internal-push-keymap (keymap symbol) - (let ((map (symbol-value symbol))) - (unless (memq keymap map) - (unless (memq 'add-keymap-witness (symbol-value symbol)) - (setq map (make-composed-keymap nil (symbol-value symbol))) - (push 'add-keymap-witness (cdr map)) - (set symbol map)) - (push keymap (cdr map))))) - -(defun internal-pop-keymap (keymap symbol) - (let ((map (symbol-value symbol))) - (when (memq keymap map) - (setf (cdr map) (delq keymap (cdr map)))) - (let ((tail (cddr map))) - (and (or (null tail) (keymapp tail)) - (eq 'add-keymap-witness (nth 1 map)) - (set symbol tail))))) - -(define-obsolete-function-alias - 'set-temporary-overlay-map 'set-transient-map "24.4") - -(defun set-transient-map (map &optional keep-pred on-exit) - "Set MAP as a temporary keymap taking precedence over other keymaps. -Normally, MAP is used only once, to look up the very next key. -However, if the optional argument KEEP-PRED is t, MAP stays -active if a key from MAP is used. KEEP-PRED can also be a -function of no arguments: it is called from `pre-command-hook' and -if it returns non-nil, then MAP stays active. - -Optional arg ON-EXIT, if non-nil, specifies a function that is -called, with no arguments, after MAP is deactivated. - -This uses `overriding-terminal-local-map' which takes precedence over all other -keymaps. As usual, if no match for a key is found in MAP, the normal key -lookup sequence then continues. - -This returns an \"exit function\", which can be called with no argument -to deactivate this transient map, regardless of KEEP-PRED." - (let* ((clearfun (make-symbol "clear-transient-map")) - (exitfun - (lambda () - (internal-pop-keymap map 'overriding-terminal-local-map) - (remove-hook 'pre-command-hook clearfun) - (when on-exit (funcall on-exit))))) - ;; Don't use letrec, because equal (in add/remove-hook) would get trapped - ;; in a cycle. - (fset clearfun - (lambda () - (with-demoted-errors "set-transient-map PCH: %S" - (unless (cond - ((null keep-pred) nil) - ((not (eq map (cadr overriding-terminal-local-map))) - ;; There's presumably some other transient-map in - ;; effect. Wait for that one to terminate before we - ;; remove ourselves. - ;; For example, if isearch and C-u both use transient - ;; maps, then the lifetime of the C-u should be nested - ;; within isearch's, so the pre-command-hook of - ;; isearch should be suspended during the C-u one so - ;; we don't exit isearch just because we hit 1 after - ;; C-u and that 1 exits isearch whereas it doesn't - ;; exit C-u. - t) - ((eq t keep-pred) - (eq this-command - (lookup-key map (this-command-keys-vector)))) - (t (funcall keep-pred))) - (funcall exitfun))))) - (add-hook 'pre-command-hook clearfun) - (internal-push-keymap map 'overriding-terminal-local-map) - exitfun)) - -;;;; Progress reporters. - -;; Progress reporter has the following structure: -;; -;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME -;; MIN-VALUE -;; MAX-VALUE -;; MESSAGE -;; MIN-CHANGE -;; MIN-TIME]) -;; -;; This weirdness is for optimization reasons: we want -;; `progress-reporter-update' to be as fast as possible, so -;; `(car reporter)' is better than `(aref reporter 0)'. -;; -;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple -;; digits of precision, it doesn't really matter here. On the other -;; hand, it greatly simplifies the code. - -(defsubst progress-reporter-update (reporter &optional value) - "Report progress of an operation in the echo area. -REPORTER should be the result of a call to `make-progress-reporter'. - -If REPORTER is a numerical progress reporter---i.e. if it was - made using non-nil MIN-VALUE and MAX-VALUE arguments to - `make-progress-reporter'---then VALUE should be a number between - MIN-VALUE and MAX-VALUE. - -If REPORTER is a non-numerical reporter, VALUE should be nil. - -This function is relatively inexpensive. If the change since -last update is too small or insufficient time has passed, it does -nothing." - (when (or (not (numberp value)) ; For pulsing reporter - (>= value (car reporter))) ; For numerical reporter - (progress-reporter-do-update reporter value))) - -(defun make-progress-reporter (message &optional min-value max-value - current-value min-change min-time) - "Return progress reporter object for use with `progress-reporter-update'. - -MESSAGE is shown in the echo area, with a status indicator -appended to the end. When you call `progress-reporter-done', the -word \"done\" is printed after the MESSAGE. You can change the -MESSAGE of an existing progress reporter by calling -`progress-reporter-force-update'. - -MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete) -and final (100% complete) states of operation; the latter should -be larger. In this case, the status message shows the percentage -progress. - -If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status -message shows a \"spinning\", non-numeric indicator. - -Optional CURRENT-VALUE is the initial progress; the default is -MIN-VALUE. -Optional MIN-CHANGE is the minimal change in percents to report; -the default is 1%. -CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE -and/or MAX-VALUE are nil. - -Optional MIN-TIME specifies the minimum interval time between -echo area updates (default is 0.2 seconds.) If the function -`float-time' is not present, time is not tracked at all. If the -OS is not capable of measuring fractions of seconds, this -parameter is effectively rounded up." - (when (string-match "[[:alnum:]]\\'" message) - (setq message (concat message "..."))) - (unless min-time - (setq min-time 0.2)) - (let ((reporter - ;; Force a call to `message' now - (cons (or min-value 0) - (vector (if (and (fboundp 'float-time) - (>= min-time 0.02)) - (float-time) nil) - min-value - max-value - message - (if min-change (max (min min-change 50) 1) 1) - min-time)))) - (progress-reporter-update reporter (or current-value min-value)) - reporter)) - -(defun progress-reporter-force-update (reporter &optional value new-message) - "Report progress of an operation in the echo area unconditionally. - -The first two arguments are the same as in `progress-reporter-update'. -NEW-MESSAGE, if non-nil, sets a new message for the reporter." - (let ((parameters (cdr reporter))) - (when new-message - (aset parameters 3 new-message)) - (when (aref parameters 0) - (aset parameters 0 (float-time))) - (progress-reporter-do-update reporter value))) - -(defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"] - "Characters to use for pulsing progress reporters.") - -(defun progress-reporter-do-update (reporter value) - (let* ((parameters (cdr reporter)) - (update-time (aref parameters 0)) - (min-value (aref parameters 1)) - (max-value (aref parameters 2)) - (text (aref parameters 3)) - (enough-time-passed - ;; See if enough time has passed since the last update. - (or (not update-time) - (when (>= (float-time) update-time) - ;; Calculate time for the next update - (aset parameters 0 (+ update-time (aref parameters 5))))))) - (cond ((and min-value max-value) - ;; Numerical indicator - (let* ((one-percent (/ (- max-value min-value) 100.0)) - (percentage (if (= max-value min-value) - 0 - (truncate (/ (- value min-value) - one-percent))))) - ;; Calculate NEXT-UPDATE-VALUE. If we are not printing - ;; message because not enough time has passed, use 1 - ;; instead of MIN-CHANGE. This makes delays between echo - ;; area updates closer to MIN-TIME. - (setcar reporter - (min (+ min-value (* (+ percentage - (if enough-time-passed - ;; MIN-CHANGE - (aref parameters 4) - 1)) - one-percent)) - max-value)) - (when (integerp value) - (setcar reporter (ceiling (car reporter)))) - ;; Only print message if enough time has passed - (when enough-time-passed - (if (> percentage 0) - (message "%s%d%%" text percentage) - (message "%s" text))))) - ;; Pulsing indicator - (enough-time-passed - (let ((index (mod (1+ (car reporter)) 4)) - (message-log-max nil)) - (setcar reporter index) - (message "%s %s" - text - (aref progress-reporter--pulse-characters - index))))))) - -(defun progress-reporter-done (reporter) - "Print reporter's message followed by word \"done\" in echo area." - (message "%sdone" (aref (cdr reporter) 3))) - -(defmacro dotimes-with-progress-reporter (spec message &rest body) - "Loop a certain number of times and report progress in the echo area. -Evaluate BODY with VAR bound to successive integers running from -0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get -the return value (nil if RESULT is omitted). - -At each iteration MESSAGE followed by progress percentage is -printed in the echo area. After the loop is finished, MESSAGE -followed by word \"done\" is printed. This macro is a -convenience wrapper around `make-progress-reporter' and friends. - -\(fn (VAR COUNT [RESULT]) MESSAGE BODY...)" - (declare (indent 2) (debug ((symbolp form &optional form) form body))) - (let ((temp (make-symbol "--dotimes-temp--")) - (temp2 (make-symbol "--dotimes-temp2--")) - (start 0) - (end (nth 1 spec))) - `(let ((,temp ,end) - (,(car spec) ,start) - (,temp2 (make-progress-reporter ,message ,start ,end))) - (while (< ,(car spec) ,temp) - ,@body - (progress-reporter-update ,temp2 - (setq ,(car spec) (1+ ,(car spec))))) - (progress-reporter-done ,temp2) - nil ,@(cdr (cdr spec))))) - - -;;;; Comparing version strings. - -(defconst version-separator "." - "Specify the string used to separate the version elements. - -Usually the separator is \".\", but it can be any other string.") - - -(defconst version-regexp-alist - '(("^[-_+ ]?snapshot$" . -4) - ;; treat "1.2.3-20050920" and "1.2-3" as snapshot releases - ("^[-_+]$" . -4) - ;; treat "1.2.3-CVS" as snapshot release - ("^[-_+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)$" . -4) - ("^[-_+ ]?alpha$" . -3) - ("^[-_+ ]?beta$" . -2) - ("^[-_+ ]?\\(pre\\|rc\\)$" . -1)) - "Specify association between non-numeric version and its priority. - -This association is used to handle version string like \"1.0pre2\", -\"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the -non-numeric part of a version string to an integer. For example: - - String Version Integer List Version - \"0.9snapshot\" (0 9 -4) - \"1.0-git\" (1 0 -4) - \"1.0pre2\" (1 0 -1 2) - \"1.0PRE2\" (1 0 -1 2) - \"22.8beta3\" (22 8 -2 3) - \"22.8 Beta3\" (22 8 -2 3) - \"0.9alpha1\" (0 9 -3 1) - \"0.9AlphA1\" (0 9 -3 1) - \"0.9 alpha\" (0 9 -3) - -Each element has the following form: - - (REGEXP . PRIORITY) - -Where: - -REGEXP regexp used to match non-numeric part of a version string. - It should begin with the `^' anchor and end with a `$' to - prevent false hits. Letter-case is ignored while matching - REGEXP. - -PRIORITY a negative integer specifying non-numeric priority of REGEXP.") - - -(defun version-to-list (ver) - "Convert version string VER into a list of integers. - -The version syntax is given by the following EBNF: - - VERSION ::= NUMBER ( SEPARATOR NUMBER )*. - - NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+. - - SEPARATOR ::= `version-separator' (which see) - | `version-regexp-alist' (which see). - -The NUMBER part is optional if SEPARATOR is a match for an element -in `version-regexp-alist'. - -Examples of valid version syntax: - - 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta - -Examples of invalid version syntax: - - 1.0prepre2 1.0..7.5 22.8X3 alpha3.2 .5 - -Examples of version conversion: - - Version String Version as a List of Integers - \"1.0.7.5\" (1 0 7 5) - \"1.0pre2\" (1 0 -1 2) - \"1.0PRE2\" (1 0 -1 2) - \"22.8beta3\" (22 8 -2 3) - \"22.8Beta3\" (22 8 -2 3) - \"0.9alpha1\" (0 9 -3 1) - \"0.9AlphA1\" (0 9 -3 1) - \"0.9alpha\" (0 9 -3) - \"0.9snapshot\" (0 9 -4) - \"1.0-git\" (1 0 -4) - -See documentation for `version-separator' and `version-regexp-alist'." - (or (and (stringp ver) (> (length ver) 0)) - (error "Invalid version string: '%s'" ver)) - ;; Change .x.y to 0.x.y - (if (and (>= (length ver) (length version-separator)) - (string-equal (substring ver 0 (length version-separator)) - version-separator)) - (setq ver (concat "0" ver))) - (save-match-data - (let ((i 0) - (case-fold-search t) ; ignore case in matching - lst s al) - (while (and (setq s (string-match "[0-9]+" ver i)) - (= s i)) - ;; handle numeric part - (setq lst (cons (string-to-number (substring ver i (match-end 0))) - lst) - i (match-end 0)) - ;; handle non-numeric part - (when (and (setq s (string-match "[^0-9]+" ver i)) - (= s i)) - (setq s (substring ver i (match-end 0)) - i (match-end 0)) - ;; handle alpha, beta, pre, etc. separator - (unless (string= s version-separator) - (setq al version-regexp-alist) - (while (and al (not (string-match (caar al) s))) - (setq al (cdr al))) - (cond (al - (push (cdar al) lst)) - ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc. - ((string-match "^[-_+ ]?\\([a-zA-Z]\\)$" s) - (push (- (aref (downcase (match-string 1 s)) 0) ?a -1) - lst)) - (t (error "Invalid version syntax: '%s'" ver)))))) - (if (null lst) - (error "Invalid version syntax: '%s'" ver) - (nreverse lst))))) - - -(defun version-list-< (l1 l2) - "Return t if L1, a list specification of a version, is lower than L2. - -Note that a version specified by the list (1) is equal to (1 0), -\(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant. -Also, a version given by the list (1) is higher than (1 -1), which in -turn is higher than (1 -2), which is higher than (1 -3)." - (while (and l1 l2 (= (car l1) (car l2))) - (setq l1 (cdr l1) - l2 (cdr l2))) - (cond - ;; l1 not null and l2 not null - ((and l1 l2) (< (car l1) (car l2))) - ;; l1 null and l2 null ==> l1 length = l2 length - ((and (null l1) (null l2)) nil) - ;; l1 not null and l2 null ==> l1 length > l2 length - (l1 (< (version-list-not-zero l1) 0)) - ;; l1 null and l2 not null ==> l2 length > l1 length - (t (< 0 (version-list-not-zero l2))))) - - -(defun version-list-= (l1 l2) - "Return t if L1, a list specification of a version, is equal to L2. - -Note that a version specified by the list (1) is equal to (1 0), -\(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant. -Also, a version given by the list (1) is higher than (1 -1), which in -turn is higher than (1 -2), which is higher than (1 -3)." - (while (and l1 l2 (= (car l1) (car l2))) - (setq l1 (cdr l1) - l2 (cdr l2))) - (cond - ;; l1 not null and l2 not null - ((and l1 l2) nil) - ;; l1 null and l2 null ==> l1 length = l2 length - ((and (null l1) (null l2))) - ;; l1 not null and l2 null ==> l1 length > l2 length - (l1 (zerop (version-list-not-zero l1))) - ;; l1 null and l2 not null ==> l2 length > l1 length - (t (zerop (version-list-not-zero l2))))) - - -(defun version-list-<= (l1 l2) - "Return t if L1, a list specification of a version, is lower or equal to L2. - -Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0), -etc. That is, the trailing zeroes are insignificant. Also, integer -list (1) is greater than (1 -1) which is greater than (1 -2) -which is greater than (1 -3)." - (while (and l1 l2 (= (car l1) (car l2))) - (setq l1 (cdr l1) - l2 (cdr l2))) - (cond - ;; l1 not null and l2 not null - ((and l1 l2) (< (car l1) (car l2))) - ;; l1 null and l2 null ==> l1 length = l2 length - ((and (null l1) (null l2))) - ;; l1 not null and l2 null ==> l1 length > l2 length - (l1 (<= (version-list-not-zero l1) 0)) - ;; l1 null and l2 not null ==> l2 length > l1 length - (t (<= 0 (version-list-not-zero l2))))) - -(defun version-list-not-zero (lst) - "Return the first non-zero element of LST, which is a list of integers. - -If all LST elements are zeros or LST is nil, return zero." - (while (and lst (zerop (car lst))) - (setq lst (cdr lst))) - (if lst - (car lst) - ;; there is no element different of zero - 0)) - - -(defun version< (v1 v2) - "Return t if version V1 is lower (older) than V2. - -Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\", -etc. That is, the trailing \".0\"s are insignificant. Also, version -string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\", -which is higher than \"1alpha\", which is higher than \"1snapshot\". -Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions." - (version-list-< (version-to-list v1) (version-to-list v2))) - -(defun version<= (v1 v2) - "Return t if version V1 is lower (older) than or equal to V2. - -Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\", -etc. That is, the trailing \".0\"s are insignificant. Also, version -string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\", -which is higher than \"1alpha\", which is higher than \"1snapshot\". -Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions." - (version-list-<= (version-to-list v1) (version-to-list v2))) - -(defun version= (v1 v2) - "Return t if version V1 is equal to V2. - -Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\", -etc. That is, the trailing \".0\"s are insignificant. Also, version -string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\", -which is higher than \"1alpha\", which is higher than \"1snapshot\". -Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions." - (version-list-= (version-to-list v1) (version-to-list v2))) - -(defvar package--builtin-versions - ;; Mostly populated by loaddefs.el via autoload-builtin-package-versions. - (purecopy `((emacs . ,(version-to-list emacs-version)))) - "Alist giving the version of each versioned builtin package. -I.e. each element of the list is of the form (NAME . VERSION) where -NAME is the package name as a symbol, and VERSION is its version -as a list.") - -(defun package--description-file (dir) - (concat (let ((subdir (file-name-nondirectory - (directory-file-name dir)))) - (if (string-match "\\([^.].*?\\)-\\([0-9]+\\(?:[.][0-9]+\\|\\(?:pre\\|beta\\|alpha\\)[0-9]+\\)*\\)" subdir) - (match-string 1 subdir) subdir)) - "-pkg.el")) - - -;;; Misc. -(defconst menu-bar-separator '("--") - "Separator for menus.") - -;; The following statement ought to be in print.c, but `provide' can't -;; be used there. -;; http://lists.gnu.org/archive/html/emacs-devel/2009-08/msg00236.html -(when (hash-table-p (car (read-from-string - (prin1-to-string (make-hash-table))))) - (provide 'hashtable-print-readable)) - -;; This is used in lisp/Makefile.in and in leim/Makefile.in to -;; generate file names for autoloads, custom-deps, and finder-data. -(defun unmsys--file-name (file) - "Produce the canonical file name for FILE from its MSYS form. - -On systems other than MS-Windows, just returns FILE. -On MS-Windows, converts /d/foo/bar form of file names -passed by MSYS Make into d:/foo/bar that Emacs can grok. - -This function is called from lisp/Makefile and leim/Makefile." - (when (and (eq system-type 'windows-nt) - (string-match "\\`/[a-zA-Z]/" file)) - (setq file (concat (substring file 1 2) ":" (substring file 2)))) - file) - - -;;; subr.el ends here diff --git a/third_party/pygments/tests/examplefiles/swig_java.swg b/third_party/pygments/tests/examplefiles/swig_java.swg deleted file mode 100644 index 6126a55e5..000000000 --- a/third_party/pygments/tests/examplefiles/swig_java.swg +++ /dev/null @@ -1,1329 +0,0 @@ -/* ----------------------------------------------------------------------------- - * java.swg - * - * Java typemaps - * ----------------------------------------------------------------------------- */ - -%include - -/* The jni, jtype and jstype typemaps work together and so there should be one of each. - * The jni typemap contains the JNI type used in the JNI (C/C++) code. - * The jtype typemap contains the Java type used in the JNI intermediary class. - * The jstype typemap contains the Java type used in the Java proxy classes, type wrapper classes and module class. */ - -/* Fragments */ -%fragment("SWIG_PackData", "header") { -/* Pack binary data into a string */ -SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - register const unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; -} -} - -%fragment("SWIG_UnPackData", "header") { -/* Unpack binary data from a string */ -SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - register unsigned char *u = (unsigned char *) ptr; - register const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - register char d = *(c++); - register unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = ((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = ((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; -} -} - -/* Primitive types */ -%typemap(jni) bool, const bool & "jboolean" -%typemap(jni) char, const char & "jchar" -%typemap(jni) signed char, const signed char & "jbyte" -%typemap(jni) unsigned char, const unsigned char & "jshort" -%typemap(jni) short, const short & "jshort" -%typemap(jni) unsigned short, const unsigned short & "jint" -%typemap(jni) int, const int & "jint" -%typemap(jni) unsigned int, const unsigned int & "jlong" -%typemap(jni) long, const long & "jint" -%typemap(jni) unsigned long, const unsigned long & "jlong" -%typemap(jni) long long, const long long & "jlong" -%typemap(jni) unsigned long long, const unsigned long long & "jobject" -%typemap(jni) float, const float & "jfloat" -%typemap(jni) double, const double & "jdouble" -%typemap(jni) void "void" - -%typemap(jtype) bool, const bool & "boolean" -%typemap(jtype) char, const char & "char" -%typemap(jtype) signed char, const signed char & "byte" -%typemap(jtype) unsigned char, const unsigned char & "short" -%typemap(jtype) short, const short & "short" -%typemap(jtype) unsigned short, const unsigned short & "int" -%typemap(jtype) int, const int & "int" -%typemap(jtype) unsigned int, const unsigned int & "long" -%typemap(jtype) long, const long & "int" -%typemap(jtype) unsigned long, const unsigned long & "long" -%typemap(jtype) long long, const long long & "long" -%typemap(jtype) unsigned long long, const unsigned long long & "java.math.BigInteger" -%typemap(jtype) float, const float & "float" -%typemap(jtype) double, const double & "double" -%typemap(jtype) void "void" - -%typemap(jstype) bool, const bool & "boolean" -%typemap(jstype) char, const char & "char" -%typemap(jstype) signed char, const signed char & "byte" -%typemap(jstype) unsigned char, const unsigned char & "short" -%typemap(jstype) short, const short & "short" -%typemap(jstype) unsigned short, const unsigned short & "int" -%typemap(jstype) int, const int & "int" -%typemap(jstype) unsigned int, const unsigned int & "long" -%typemap(jstype) long, const long & "int" -%typemap(jstype) unsigned long, const unsigned long & "long" -%typemap(jstype) long long, const long long & "long" -%typemap(jstype) unsigned long long, const unsigned long long & "java.math.BigInteger" -%typemap(jstype) float, const float & "float" -%typemap(jstype) double, const double & "double" -%typemap(jstype) void "void" - -%typemap(jni) char *, char *&, char[ANY], char[] "jstring" -%typemap(jtype) char *, char *&, char[ANY], char[] "String" -%typemap(jstype) char *, char *&, char[ANY], char[] "String" - -/* JNI types */ -%typemap(jni) jboolean "jboolean" -%typemap(jni) jchar "jchar" -%typemap(jni) jbyte "jbyte" -%typemap(jni) jshort "jshort" -%typemap(jni) jint "jint" -%typemap(jni) jlong "jlong" -%typemap(jni) jfloat "jfloat" -%typemap(jni) jdouble "jdouble" -%typemap(jni) jstring "jstring" -%typemap(jni) jobject "jobject" -%typemap(jni) jbooleanArray "jbooleanArray" -%typemap(jni) jcharArray "jcharArray" -%typemap(jni) jbyteArray "jbyteArray" -%typemap(jni) jshortArray "jshortArray" -%typemap(jni) jintArray "jintArray" -%typemap(jni) jlongArray "jlongArray" -%typemap(jni) jfloatArray "jfloatArray" -%typemap(jni) jdoubleArray "jdoubleArray" -%typemap(jni) jobjectArray "jobjectArray" - -%typemap(jtype) jboolean "boolean" -%typemap(jtype) jchar "char" -%typemap(jtype) jbyte "byte" -%typemap(jtype) jshort "short" -%typemap(jtype) jint "int" -%typemap(jtype) jlong "long" -%typemap(jtype) jfloat "float" -%typemap(jtype) jdouble "double" -%typemap(jtype) jstring "String" -%typemap(jtype) jobject "Object" -%typemap(jtype) jbooleanArray "boolean[]" -%typemap(jtype) jcharArray "char[]" -%typemap(jtype) jbyteArray "byte[]" -%typemap(jtype) jshortArray "short[]" -%typemap(jtype) jintArray "int[]" -%typemap(jtype) jlongArray "long[]" -%typemap(jtype) jfloatArray "float[]" -%typemap(jtype) jdoubleArray "double[]" -%typemap(jtype) jobjectArray "Object[]" - -%typemap(jstype) jboolean "boolean" -%typemap(jstype) jchar "char" -%typemap(jstype) jbyte "byte" -%typemap(jstype) jshort "short" -%typemap(jstype) jint "int" -%typemap(jstype) jlong "long" -%typemap(jstype) jfloat "float" -%typemap(jstype) jdouble "double" -%typemap(jstype) jstring "String" -%typemap(jstype) jobject "Object" -%typemap(jstype) jbooleanArray "boolean[]" -%typemap(jstype) jcharArray "char[]" -%typemap(jstype) jbyteArray "byte[]" -%typemap(jstype) jshortArray "short[]" -%typemap(jstype) jintArray "int[]" -%typemap(jstype) jlongArray "long[]" -%typemap(jstype) jfloatArray "float[]" -%typemap(jstype) jdoubleArray "double[]" -%typemap(jstype) jobjectArray "Object[]" - -/* Non primitive types */ -%typemap(jni) SWIGTYPE "jlong" -%typemap(jtype) SWIGTYPE "long" -%typemap(jstype) SWIGTYPE "$&javaclassname" - -%typemap(jni) SWIGTYPE [] "jlong" -%typemap(jtype) SWIGTYPE [] "long" -%typemap(jstype) SWIGTYPE [] "$javaclassname" - -%typemap(jni) SWIGTYPE * "jlong" -%typemap(jtype) SWIGTYPE * "long" -%typemap(jstype) SWIGTYPE * "$javaclassname" - -%typemap(jni) SWIGTYPE & "jlong" -%typemap(jtype) SWIGTYPE & "long" -%typemap(jstype) SWIGTYPE & "$javaclassname" - -/* pointer to a class member */ -%typemap(jni) SWIGTYPE (CLASS::*) "jstring" -%typemap(jtype) SWIGTYPE (CLASS::*) "String" -%typemap(jstype) SWIGTYPE (CLASS::*) "$javaclassname" - -/* The following are the in, out, freearg, argout typemaps. These are the JNI code generating typemaps for converting from Java to C and visa versa. */ - -/* primitive types */ -%typemap(in) bool -%{ $1 = $input ? true : false; %} - -%typemap(directorout) bool -%{ $result = $input ? true : false; %} - -%typemap(javadirectorin) bool "$jniinput" -%typemap(javadirectorout) bool "$javacall" - -%typemap(in) char, - signed char, - unsigned char, - short, - unsigned short, - int, - unsigned int, - long, - unsigned long, - long long, - float, - double -%{ $1 = ($1_ltype)$input; %} - -%typemap(directorout) char, - signed char, - unsigned char, - short, - unsigned short, - int, - unsigned int, - long, - unsigned long, - long long, - float, - double -%{ $result = ($1_ltype)$input; %} - -%typemap(directorin, descriptor="Z") bool "$input = (jboolean) $1;" -%typemap(directorin, descriptor="C") char "$input = (jint) $1;" -%typemap(directorin, descriptor="B") signed char "$input = (jbyte) $1;" -%typemap(directorin, descriptor="S") unsigned char "$input = (jshort) $1;" -%typemap(directorin, descriptor="S") short "$input = (jshort) $1;" -%typemap(directorin, descriptor="I") unsigned short "$input = (jint) $1;" -%typemap(directorin, descriptor="I") int "$input = (jint) $1;" -%typemap(directorin, descriptor="J") unsigned int "$input = (jlong) $1;" -%typemap(directorin, descriptor="I") long "$input = (jint) $1;" -%typemap(directorin, descriptor="J") unsigned long "$input = (jlong) $1;" -%typemap(directorin, descriptor="J") long long "$input = (jlong) $1;" -%typemap(directorin, descriptor="F") float "$input = (jfloat) $1;" -%typemap(directorin, descriptor="D") double "$input = (jdouble) $1;" - -%typemap(javadirectorin) char, - signed char, - unsigned char, - short, - unsigned short, - int, - unsigned int, - long, - unsigned long, - long long, - float, - double - "$jniinput" - -%typemap(javadirectorout) char, - signed char, - unsigned char, - short, - unsigned short, - int, - unsigned int, - long, - unsigned long, - long long, - float, - double - "$javacall" - -%typemap(out) bool %{ $result = (jboolean)$1; %} -%typemap(out) char %{ $result = (jchar)$1; %} -%typemap(out) signed char %{ $result = (jbyte)$1; %} -%typemap(out) unsigned char %{ $result = (jshort)$1; %} -%typemap(out) short %{ $result = (jshort)$1; %} -%typemap(out) unsigned short %{ $result = (jint)$1; %} -%typemap(out) int %{ $result = (jint)$1; %} -%typemap(out) unsigned int %{ $result = (jlong)$1; %} -%typemap(out) long %{ $result = (jint)$1; %} -%typemap(out) unsigned long %{ $result = (jlong)$1; %} -%typemap(out) long long %{ $result = (jlong)$1; %} -%typemap(out) float %{ $result = (jfloat)$1; %} -%typemap(out) double %{ $result = (jdouble)$1; %} - -/* unsigned long long */ -/* Convert from BigInteger using the toByteArray member function */ -%typemap(in) unsigned long long { - jclass clazz; - jmethodID mid; - jbyteArray ba; - jbyte* bae; - jsize sz; - int i; - - if (!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); - return $null; - } - clazz = JCALL1(GetObjectClass, jenv, $input); - mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); - ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); - bae = JCALL2(GetByteArrayElements, jenv, ba, 0); - sz = JCALL1(GetArrayLength, jenv, ba); - $1 = 0; - for(i=0; i", "([B)V"); - jobject bigint; - int i; - - bae[0] = 0; - for(i=1; i<9; i++ ) { - bae[i] = (jbyte)($1>>8*(8-i)); - } - - JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); - bigint = JCALL3(NewObject, jenv, clazz, mid, ba); - $result = bigint; -} - -/* Convert to BigInteger (see out typemap) */ -%typemap(directorin, descriptor="Ljava/math/BigInteger;") unsigned long long, const unsigned long long & { - jbyteArray ba = JCALL1(NewByteArray, jenv, 9); - jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0); - jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger"); - jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "", "([B)V"); - jobject bigint; - int swig_i; - - bae[0] = 0; - for(swig_i=1; swig_i<9; swig_i++ ) { - bae[swig_i] = (jbyte)($1>>8*(8-swig_i)); - } - - JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); - bigint = JCALL3(NewObject, jenv, clazz, mid, ba); - $input = bigint; -} - -%typemap(javadirectorin) unsigned long long "$jniinput" -%typemap(javadirectorout) unsigned long long "$javacall" - -/* char * - treat as String */ -%typemap(in, noblock=1) char * { - $1 = 0; - if ($input) { - $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); - if (!$1) return $null; - } -} - -%typemap(directorout, noblock=1, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) char * { - $1 = 0; - if ($input) { - $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); - if (!$result) return $null; - } -} - -%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * { - $input = 0; - if ($1) { - $input = JCALL1(NewStringUTF, jenv, (const char *)$1); - if (!$input) return $null; - } -} - -%typemap(freearg, noblock=1) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); } -%typemap(out, noblock=1) char * { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); } -%typemap(javadirectorin) char * "$jniinput" -%typemap(javadirectorout) char * "$javacall" - -/* char *& - treat as String */ -%typemap(in, noblock=1) char *& ($*1_ltype temp = 0) { - $1 = 0; - if ($input) { - temp = ($*1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); - if (!temp) return $null; - } - $1 = &temp; -} -%typemap(freearg, noblock=1) char *& { if ($1 && *$1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)*$1); } -%typemap(out, noblock=1) char *& { if (*$1) $result = JCALL1(NewStringUTF, jenv, (const char *)*$1); } - -%typemap(out) void "" -%typemap(javadirectorin) void "$jniinput" -%typemap(javadirectorout) void "$javacall" -%typemap(directorin, descriptor="V") void "" - -/* primitive types by reference */ -%typemap(in) const bool & ($*1_ltype temp) -%{ temp = $input ? true : false; - $1 = &temp; %} - -%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const bool & -%{ static $*1_ltype temp; - temp = $input ? true : false; - $result = &temp; %} - -%typemap(javadirectorin) const bool & "$jniinput" -%typemap(javadirectorout) const bool & "$javacall" - -%typemap(in) const char & ($*1_ltype temp), - const signed char & ($*1_ltype temp), - const unsigned char & ($*1_ltype temp), - const short & ($*1_ltype temp), - const unsigned short & ($*1_ltype temp), - const int & ($*1_ltype temp), - const unsigned int & ($*1_ltype temp), - const long & ($*1_ltype temp), - const unsigned long & ($*1_ltype temp), - const long long & ($*1_ltype temp), - const float & ($*1_ltype temp), - const double & ($*1_ltype temp) -%{ temp = ($*1_ltype)$input; - $1 = &temp; %} - -%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const char &, - const signed char &, - const unsigned char &, - const short &, - const unsigned short &, - const int &, - const unsigned int &, - const long &, - const unsigned long &, - const long long &, - const float &, - const double & -%{ static $*1_ltype temp; - temp = ($*1_ltype)$input; - $result = &temp; %} - -%typemap(directorin, descriptor="Z") const bool & "$input = (jboolean)$1;" -%typemap(directorin, descriptor="C") const char & "$input = (jchar)$1;" -%typemap(directorin, descriptor="B") const signed char & "$input = (jbyte)$1;" -%typemap(directorin, descriptor="S") const unsigned char & "$input = (jshort)$1;" -%typemap(directorin, descriptor="S") const short & "$input = (jshort)$1;" -%typemap(directorin, descriptor="I") const unsigned short & "$input = (jint)$1;" -%typemap(directorin, descriptor="I") const int & "$input = (jint)$1;" -%typemap(directorin, descriptor="J") const unsigned int & "$input = (jlong)$1;" -%typemap(directorin, descriptor="I") const long & "$input = (jint)$1;" -%typemap(directorin, descriptor="J") const unsigned long & "$input = (jlong)$1;" -%typemap(directorin, descriptor="J") const long long & "$input = (jlong)$1;" -%typemap(directorin, descriptor="F") const float & "$input = (jfloat)$1;" -%typemap(directorin, descriptor="D") const double & "$input = (jdouble)$1;" - -%typemap(javadirectorin) const char & ($*1_ltype temp), - const signed char & ($*1_ltype temp), - const unsigned char & ($*1_ltype temp), - const short & ($*1_ltype temp), - const unsigned short & ($*1_ltype temp), - const int & ($*1_ltype temp), - const unsigned int & ($*1_ltype temp), - const long & ($*1_ltype temp), - const unsigned long & ($*1_ltype temp), - const long long & ($*1_ltype temp), - const float & ($*1_ltype temp), - const double & ($*1_ltype temp) - "$jniinput" - -%typemap(javadirectorout) const char & ($*1_ltype temp), - const signed char & ($*1_ltype temp), - const unsigned char & ($*1_ltype temp), - const short & ($*1_ltype temp), - const unsigned short & ($*1_ltype temp), - const int & ($*1_ltype temp), - const unsigned int & ($*1_ltype temp), - const long & ($*1_ltype temp), - const unsigned long & ($*1_ltype temp), - const long long & ($*1_ltype temp), - const float & ($*1_ltype temp), - const double & ($*1_ltype temp) - "$javacall" - - -%typemap(out) const bool & %{ $result = (jboolean)*$1; %} -%typemap(out) const char & %{ $result = (jchar)*$1; %} -%typemap(out) const signed char & %{ $result = (jbyte)*$1; %} -%typemap(out) const unsigned char & %{ $result = (jshort)*$1; %} -%typemap(out) const short & %{ $result = (jshort)*$1; %} -%typemap(out) const unsigned short & %{ $result = (jint)*$1; %} -%typemap(out) const int & %{ $result = (jint)*$1; %} -%typemap(out) const unsigned int & %{ $result = (jlong)*$1; %} -%typemap(out) const long & %{ $result = (jint)*$1; %} -%typemap(out) const unsigned long & %{ $result = (jlong)*$1; %} -%typemap(out) const long long & %{ $result = (jlong)*$1; %} -%typemap(out) const float & %{ $result = (jfloat)*$1; %} -%typemap(out) const double & %{ $result = (jdouble)*$1; %} - -/* const unsigned long long & */ -/* Similar to unsigned long long */ -%typemap(in) const unsigned long long & ($*1_ltype temp) { - jclass clazz; - jmethodID mid; - jbyteArray ba; - jbyte* bae; - jsize sz; - int i; - - if (!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); - return $null; - } - clazz = JCALL1(GetObjectClass, jenv, $input); - mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); - ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); - bae = JCALL2(GetByteArrayElements, jenv, ba, 0); - sz = JCALL1(GetArrayLength, jenv, ba); - $1 = &temp; - temp = 0; - for(i=0; i", "([B)V"); - jobject bigint; - int i; - - bae[0] = 0; - for(i=1; i<9; i++ ) { - bae[i] = (jbyte)(*$1>>8*(8-i)); - } - - JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); - bigint = JCALL3(NewObject, jenv, clazz, mid, ba); - $result = bigint; -} - -%typemap(javadirectorin) const unsigned long long & "$jniinput" -%typemap(javadirectorout) const unsigned long long & "$javacall" - -/* Default handling. Object passed by value. Convert to a pointer */ -%typemap(in) SWIGTYPE ($&1_type argp) -%{ argp = *($&1_ltype*)&$input; - if (!argp) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type"); - return $null; - } - $1 = *argp; %} - -%typemap(directorout) SWIGTYPE ($&1_type argp) -%{ argp = *($&1_ltype*)&$input; - if (!argp) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); - return $null; - } - $result = *argp; %} - -%typemap(out) SWIGTYPE -#ifdef __cplusplus -%{ *($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %} -#else -{ - $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype)); - memmove($1ptr, &$1, sizeof($1_type)); - *($&1_ltype*)&$result = $1ptr; -} -#endif - -%typemap(directorin,descriptor="L$packagepath/$&javaclassname;") SWIGTYPE -%{ $input = 0; - *(($&1_ltype*)&$input) = &$1; %} -%typemap(javadirectorin) SWIGTYPE "new $&javaclassname($jniinput, false)" -%typemap(javadirectorout) SWIGTYPE "$&javaclassname.getCPtr($javacall)" - -/* Generic pointers and references */ -%typemap(in) SWIGTYPE * %{ $1 = *($&1_ltype)&$input; %} -%typemap(in, fragment="SWIG_UnPackData") SWIGTYPE (CLASS::*) { - const char *temp = 0; - if ($input) { - temp = JCALL2(GetStringUTFChars, jenv, $input, 0); - if (!temp) return $null; - } - SWIG_UnpackData(temp, (void *)&$1, sizeof($1)); -} -%typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input; - if (!$1) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null"); - return $null; - } %} -%typemap(out) SWIGTYPE * -%{ *($&1_ltype)&$result = $1; %} -%typemap(out, fragment="SWIG_PackData", noblock=1) SWIGTYPE (CLASS::*) { - char buf[128]; - char *data = SWIG_PackData(buf, (void *)&$1, sizeof($1)); - *data = '\0'; - $result = JCALL1(NewStringUTF, jenv, buf); -} -%typemap(out) SWIGTYPE & -%{ *($&1_ltype)&$result = $1; %} - -%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE * -%{ $result = *($&1_ltype)&$input; %} -%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE (CLASS::*) -%{ $result = *($&1_ltype)&$input; %} - -%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE * -%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} -%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE (CLASS::*) -%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} - -%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE & -%{ if (!$input) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); - return $null; - } - $result = *($&1_ltype)&$input; %} -%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE & -%{ *($&1_ltype)&$input = ($1_ltype) &$1; %} - -%typemap(javadirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($jniinput == 0) ? null : new $javaclassname($jniinput, false)" -%typemap(javadirectorin) SWIGTYPE & "new $javaclassname($jniinput, false)" -%typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$javaclassname.getCPtr($javacall)" - -/* Default array handling */ -%typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %} -%typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %} -%typemap(freearg) SWIGTYPE [ANY], SWIGTYPE [] "" - -/* char arrays - treat as String */ -%typemap(in, noblock=1) char[ANY], char[] { - $1 = 0; - if ($input) { - $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); - if (!$1) return $null; - } -} - -%typemap(directorout, noblock=1) char[ANY], char[] { - $1 = 0; - if ($input) { - $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); - if (!$result) return $null; - } -} - -%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char[ANY], char[] { - $input = 0; - if ($1) { - $input = JCALL1(NewStringUTF, jenv, (const char *)$1); - if (!$input) return $null; - } -} - -%typemap(argout) char[ANY], char[] "" -%typemap(freearg, noblock=1) char[ANY], char[] { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); } -%typemap(out, noblock=1) char[ANY], char[] { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); } -%typemap(javadirectorin) char[ANY], char[] "$jniinput" -%typemap(javadirectorout) char[ANY], char[] "$javacall" - -/* JNI types */ -%typemap(in) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray -%{ $1 = $input; %} - -%typemap(directorout) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray -%{ $result = $input; %} - -%typemap(out) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray -%{ $result = $1; %} - -%typemap(directorin,descriptor="Z") jboolean "$input = $1;" -%typemap(directorin,descriptor="C") jchar "$input = $1;" -%typemap(directorin,descriptor="B") jbyte "$input = $1;" -%typemap(directorin,descriptor="S") jshort "$input = $1;" -%typemap(directorin,descriptor="I") jint "$input = $1;" -%typemap(directorin,descriptor="J") jlong "$input = $1;" -%typemap(directorin,descriptor="F") jfloat "$input = $1;" -%typemap(directorin,descriptor="D") jdouble "$input = $1;" -%typemap(directorin,descriptor="Ljava/lang/String;") jstring "$input = $1;" -%typemap(directorin,descriptor="Ljava/lang/Object;",nouse="1") jobject "$input = $1;" -%typemap(directorin,descriptor="[Z") jbooleanArray "$input = $1;" -%typemap(directorin,descriptor="[C") jcharArray "$input = $1;" -%typemap(directorin,descriptor="[B") jbyteArray "$input = $1;" -%typemap(directorin,descriptor="[S") jshortArray "$input = $1;" -%typemap(directorin,descriptor="[I") jintArray "$input = $1;" -%typemap(directorin,descriptor="[J") jlongArray "$input = $1;" -%typemap(directorin,descriptor="[F") jfloatArray "$input = $1;" -%typemap(directorin,descriptor="[D") jdoubleArray "$input = $1;" -%typemap(directorin,descriptor="[Ljava/lang/Object;",nouse="1") jobjectArray "$input = $1;" - -%typemap(javadirectorin) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray - "$jniinput" - -%typemap(javadirectorout) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray - "$javacall" - -/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions - * that cannot be overloaded in Java as more than one C++ type maps to a single Java type */ - -%typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */ - jboolean, - bool, - const bool & - "" - -%typecheck(SWIG_TYPECHECK_CHAR) /* Java char */ - jchar, - char, - const char & - "" - -%typecheck(SWIG_TYPECHECK_INT8) /* Java byte */ - jbyte, - signed char, - const signed char & - "" - -%typecheck(SWIG_TYPECHECK_INT16) /* Java short */ - jshort, - unsigned char, - short, - const unsigned char &, - const short & - "" - -%typecheck(SWIG_TYPECHECK_INT32) /* Java int */ - jint, - unsigned short, - int, - long, - const unsigned short &, - const int &, - const long & - "" - -%typecheck(SWIG_TYPECHECK_INT64) /* Java long */ - jlong, - unsigned int, - unsigned long, - long long, - const unsigned int &, - const unsigned long &, - const long long & - "" - -%typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */ - unsigned long long, - const unsigned long long & - "" - -%typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */ - jfloat, - float, - const float & - "" - -%typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */ - jdouble, - double, - const double & - "" - -%typecheck(SWIG_TYPECHECK_STRING) /* Java String */ - jstring, - char *, - char *&, - char[ANY], - char [] - "" - -%typecheck(SWIG_TYPECHECK_BOOL_ARRAY) /* Java boolean[] */ - jbooleanArray - "" - -%typecheck(SWIG_TYPECHECK_CHAR_ARRAY) /* Java char[] */ - jcharArray - "" - -%typecheck(SWIG_TYPECHECK_INT8_ARRAY) /* Java byte[] */ - jbyteArray - "" - -%typecheck(SWIG_TYPECHECK_INT16_ARRAY) /* Java short[] */ - jshortArray - "" - -%typecheck(SWIG_TYPECHECK_INT32_ARRAY) /* Java int[] */ - jintArray - "" - -%typecheck(SWIG_TYPECHECK_INT64_ARRAY) /* Java long[] */ - jlongArray - "" - -%typecheck(SWIG_TYPECHECK_FLOAT_ARRAY) /* Java float[] */ - jfloatArray - "" - -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY) /* Java double[] */ - jdoubleArray - "" - -%typecheck(SWIG_TYPECHECK_OBJECT_ARRAY) /* Java jobject[] */ - jobjectArray - "" - -%typecheck(SWIG_TYPECHECK_POINTER) /* Default */ - SWIGTYPE, - SWIGTYPE *, - SWIGTYPE &, - SWIGTYPE *const&, - SWIGTYPE [], - SWIGTYPE (CLASS::*) - "" - - -/* Exception handling */ - -%typemap(throws) int, - long, - short, - unsigned int, - unsigned long, - unsigned short -%{ char error_msg[256]; - sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1); - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg); - return $null; %} - -%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] -%{ (void)$1; - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); - return $null; %} - -%typemap(throws) char * -%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1); - return $null; %} - - -/* Typemaps for code generation in proxy classes and Java type wrapper classes */ - -/* The javain typemap is used for converting function parameter types from the type - * used in the proxy, module or type wrapper class to the type used in the JNI class. */ -%typemap(javain) bool, const bool &, - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double & - "$javainput" -%typemap(javain) char *, char *&, char[ANY], char[] "$javainput" -%typemap(javain) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray - "$javainput" -%typemap(javain) SWIGTYPE "$&javaclassname.getCPtr($javainput)" -%typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$javaclassname.getCPtr($javainput)" -%typemap(javain) SWIGTYPE (CLASS::*) "$javaclassname.getCMemberPtr($javainput)" - -/* The javaout typemap is used for converting function return types from the return type - * used in the JNI class to the type returned by the proxy, module or type wrapper class. */ -%typemap(javaout) bool, const bool &, - char, const char &, - signed char, const signed char &, - unsigned char, const unsigned char &, - short, const short &, - unsigned short, const unsigned short &, - int, const int &, - unsigned int, const unsigned int &, - long, const long &, - unsigned long, const unsigned long &, - long long, const long long &, - unsigned long long, const unsigned long long &, - float, const float &, - double, const double & { - return $jnicall; - } -%typemap(javaout) char *, char *&, char[ANY], char[] { - return $jnicall; - } -%typemap(javaout) jboolean, - jchar, - jbyte, - jshort, - jint, - jlong, - jfloat, - jdouble, - jstring, - jobject, - jbooleanArray, - jcharArray, - jbyteArray, - jshortArray, - jintArray, - jlongArray, - jfloatArray, - jdoubleArray, - jobjectArray { - return $jnicall; - } -%typemap(javaout) void { - $jnicall; - } -%typemap(javaout) SWIGTYPE { - return new $&javaclassname($jnicall, true); - } -%typemap(javaout) SWIGTYPE & { - return new $javaclassname($jnicall, $owner); - } -%typemap(javaout) SWIGTYPE *, SWIGTYPE [] { - long cPtr = $jnicall; - return (cPtr == 0) ? null : new $javaclassname(cPtr, $owner); - } -%typemap(javaout) SWIGTYPE (CLASS::*) { - String cMemberPtr = $jnicall; - return (cMemberPtr == null) ? null : new $javaclassname(cMemberPtr, $owner); - } - -/* Pointer reference typemaps */ -%typemap(jni) SWIGTYPE *const& "jlong" -%typemap(jtype) SWIGTYPE *const& "long" -%typemap(jstype) SWIGTYPE *const& "$*javaclassname" -%typemap(javain) SWIGTYPE *const& "$*javaclassname.getCPtr($javainput)" -%typemap(javaout) SWIGTYPE *const& { - long cPtr = $jnicall; - return (cPtr == 0) ? null : new $*javaclassname(cPtr, $owner); - } -%typemap(in) SWIGTYPE *const& ($*1_ltype temp = 0) -%{ temp = *($1_ltype)&$input; - $1 = ($1_ltype)&temp; %} -%typemap(out) SWIGTYPE *const& -%{ *($1_ltype)&$result = *$1; %} - -/* Typemaps used for the generation of proxy and type wrapper class code */ -%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(javaclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" -%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(javaimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" -%typemap(javainterfaces) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" - -/* javabody typemaps */ - -%define SWIG_JAVABODY_METHODS(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE) %enddef // legacy name - -%define SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) -// Base proxy classes -%typemap(javabody) TYPE %{ - private long swigCPtr; - protected boolean swigCMemOwn; - - PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { - swigCMemOwn = cMemoryOwn; - swigCPtr = cPtr; - } - - CPTR_VISIBILITY static long getCPtr($javaclassname obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } -%} - -// Derived proxy classes -%typemap(javabody_derived) TYPE %{ - private long swigCPtr; - - PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { - super($imclassname.$javaclazznameSWIGUpcast(cPtr), cMemoryOwn); - swigCPtr = cPtr; - } - - CPTR_VISIBILITY static long getCPtr($javaclassname obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } -%} -%enddef - -%define SWIG_JAVABODY_TYPEWRAPPER(PTRCTOR_VISIBILITY, DEFAULTCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) -// Typewrapper classes -%typemap(javabody) TYPE *, TYPE &, TYPE [] %{ - private long swigCPtr; - - PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean futureUse) { - swigCPtr = cPtr; - } - - DEFAULTCTOR_VISIBILITY $javaclassname() { - swigCPtr = 0; - } - - CPTR_VISIBILITY static long getCPtr($javaclassname obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } -%} - -%typemap(javabody) TYPE (CLASS::*) %{ - private String swigCMemberPtr; - - PTRCTOR_VISIBILITY $javaclassname(String cMemberPtr, boolean futureUse) { - swigCMemberPtr = cMemberPtr; - } - - DEFAULTCTOR_VISIBILITY $javaclassname() { - swigCMemberPtr = null; - } - - CPTR_VISIBILITY static String getCMemberPtr($javaclassname obj) { - return obj.swigCMemberPtr; - } -%} -%enddef - -/* Set the default javabody typemaps to use protected visibility. - Use the macros to change to public if using multiple modules. */ -SWIG_JAVABODY_PROXY(protected, protected, SWIGTYPE) -SWIG_JAVABODY_TYPEWRAPPER(protected, protected, protected, SWIGTYPE) - -%typemap(javafinalize) SWIGTYPE %{ - protected void finalize() { - delete(); - } -%} - -/* - * Java constructor typemaps: - * - * The javaconstruct typemap is inserted when a proxy class's constructor is generated. - * This typemap allows control over what code is executed in the constructor as - * well as specifying who owns the underlying C/C++ object. Normally, Java has - * ownership and the underlying C/C++ object is deallocated when the Java object - * is finalized (swigCMemOwn is true.) If swigCMemOwn is false, C/C++ is - * ultimately responsible for deallocating the underlying object's memory. - * - * The SWIG_PROXY_CONSTRUCTOR macro defines the javaconstruct typemap for a proxy - * class for a particular TYPENAME. OWNERSHIP is passed as the value of - * swigCMemOwn to the pointer constructor method. WEAKREF determines which kind - * of Java object reference will be used by the C++ director class (WeakGlobalRef - * vs. GlobalRef.) - * - * The SWIG_DIRECTOR_OWNED macro sets the ownership of director-based proxy - * classes and the weak reference flag to false, meaning that the underlying C++ - * object will be reclaimed by C++. - */ - -%define SWIG_PROXY_CONSTRUCTOR(OWNERSHIP, WEAKREF, TYPENAME...) -%typemap(javaconstruct,directorconnect="\n $imclassname.$javaclazznamedirector_connect(this, swigCPtr, swigCMemOwn, WEAKREF);") TYPENAME { - this($imcall, OWNERSHIP);$directorconnect - } -%enddef - -%define SWIG_DIRECTOR_OWNED(TYPENAME...) -SWIG_PROXY_CONSTRUCTOR(true, false, TYPENAME) -%enddef - -// Set the default for SWIGTYPE: Java owns the C/C++ object. -SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE) - -%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE { - if (swigCPtr != 0) { - if (swigCMemOwn) { - swigCMemOwn = false; - $jnicall; - } - swigCPtr = 0; - } - } - -%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE { - if (swigCPtr != 0) { - if (swigCMemOwn) { - swigCMemOwn = false; - $jnicall; - } - swigCPtr = 0; - } - super.delete(); - } - -%typemap(directordisconnect, methodname="swigDirectorDisconnect") SWIGTYPE %{ - protected void $methodname() { - swigCMemOwn = false; - $jnicall; - } -%} - -%typemap(directorowner_release, methodname="swigReleaseOwnership") SWIGTYPE %{ - public void $methodname() { - swigCMemOwn = false; - $jnicall; - } -%} - -%typemap(directorowner_take, methodname="swigTakeOwnership") SWIGTYPE %{ - public void $methodname() { - swigCMemOwn = true; - $jnicall; - } -%} - -/* Java specific directives */ -#define %javaconst(flag) %feature("java:const","flag") -#define %javaconstvalue(value) %feature("java:constvalue",value) -#define %javaenum(wrapapproach) %feature("java:enum","wrapapproach") -#define %javamethodmodifiers %feature("java:methodmodifiers") -#define %javaexception(exceptionclasses) %feature("except",throws=exceptionclasses) -#define %nojavaexception %feature("except","0",throws="") -#define %clearjavaexception %feature("except","",throws="") - -%pragma(java) jniclassclassmodifiers="public class" -%pragma(java) moduleclassmodifiers="public class" - -/* Some ANSI C typemaps */ - -%apply unsigned long { size_t }; -%apply const unsigned long & { const size_t & }; - -/* Array reference typemaps */ -%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } - -/* const pointers */ -%apply SWIGTYPE * { SWIGTYPE *const } - -/* String & length */ -%typemap(jni) (char *STRING, size_t LENGTH) "jbyteArray" -%typemap(jtype) (char *STRING, size_t LENGTH) "byte[]" -%typemap(jstype) (char *STRING, size_t LENGTH) "byte[]" -%typemap(javain) (char *STRING, size_t LENGTH) "$javainput" -%typemap(freearg) (char *STRING, size_t LENGTH) "" -%typemap(in) (char *STRING, size_t LENGTH) { - if ($input) { - $1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0); - $2 = (size_t) JCALL1(GetArrayLength, jenv, $input); - } else { - $1 = 0; - $2 = 0; - } -} -%typemap(argout) (char *STRING, size_t LENGTH) { - if ($input) JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *)$1, 0); -} -%typemap(directorin, descriptor="[B") (char *STRING, size_t LENGTH) { - jbyteArray jb = (jenv)->NewByteArray($2); - (jenv)->SetByteArrayRegion(jb, 0, $2, (jbyte *)$1); - $input = jb; -} -%typemap(directorargout) (char *STRING, size_t LENGTH) -%{(jenv)->GetByteArrayRegion($input, 0, $2, (jbyte *)$1); %} -%apply (char *STRING, size_t LENGTH) { (char *STRING, int LENGTH) } - -/* java keywords */ -%include - -// Default enum handling -%include - diff --git a/third_party/pygments/tests/examplefiles/swig_std_vector.i b/third_party/pygments/tests/examplefiles/swig_std_vector.i deleted file mode 100644 index baecf8507..000000000 --- a/third_party/pygments/tests/examplefiles/swig_std_vector.i +++ /dev/null @@ -1,225 +0,0 @@ -// -// std::vector -// - -%include - -// Vector - -%define %std_vector_methods(vector...) - %std_sequence_methods(vector) - - void reserve(size_type n); - size_type capacity() const; -%enddef - - -%define %std_vector_methods_val(vector...) - %std_sequence_methods_val(vector) - - void reserve(size_type n); - size_type capacity() const; -%enddef - - -// ------------------------------------------------------------------------ -// std::vector -// -// The aim of all that follows would be to integrate std::vector with -// as much as possible, namely, to allow the user to pass and -// be returned tuples or lists. -// const declarations are used to guess the intent of the function being -// exported; therefore, the following rationale is applied: -// -// -- f(std::vector), f(const std::vector&): -// the parameter being read-only, either a sequence or a -// previously wrapped std::vector can be passed. -// -- f(std::vector&), f(std::vector*): -// the parameter may be modified; therefore, only a wrapped std::vector -// can be passed. -// -- std::vector f(), const std::vector& f(): -// the vector is returned by copy; therefore, a sequence of T:s -// is returned which is most easily used in other functions -// -- std::vector& f(), std::vector* f(): -// the vector is returned by reference; therefore, a wrapped std::vector -// is returned -// -- const std::vector* f(), f(const std::vector*): -// for consistency, they expect and return a plain vector pointer. -// ------------------------------------------------------------------------ - -%{ -#include -%} - -// exported classes - - -namespace std { - - template > - class vector { - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef _Tp value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef _Tp& reference; - typedef const _Tp& const_reference; - typedef _Alloc allocator_type; - - %traits_swigtype(_Tp); - %traits_enum(_Tp); - - %fragment(SWIG_Traits_frag(std::vector<_Tp, _Alloc >), "header", - fragment=SWIG_Traits_frag(_Tp), - fragment="StdVectorTraits") { - namespace swig { - template <> struct traits > { - typedef pointer_category category; - static const char* type_name() { - return "std::vector<" #_Tp "," #_Alloc " >"; - } - }; - } - } - - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp, _Alloc >); - -#ifdef %swig_vector_methods - // Add swig/language extra methods - %swig_vector_methods(std::vector<_Tp, _Alloc >); -#endif - - %std_vector_methods(vector); - }; - - // *** - // This specialization should disappear or get simplified when - // a 'const SWIGTYPE*&' can be defined - // *** - template - class vector<_Tp*, _Alloc > { - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef _Tp* value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type reference; - typedef value_type const_reference; - typedef _Alloc allocator_type; - - %traits_swigtype(_Tp); - - %fragment(SWIG_Traits_frag(std::vector<_Tp*, _Alloc >), "header", - fragment=SWIG_Traits_frag(_Tp), - fragment="StdVectorTraits") { - namespace swig { - template <> struct traits > { - typedef value_category category; - static const char* type_name() { - return "std::vector<" #_Tp " *," #_Alloc " >"; - } - }; - } - } - - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp*, _Alloc >); - -#ifdef %swig_vector_methods_val - // Add swig/language extra methods - %swig_vector_methods_val(std::vector<_Tp*, _Alloc >); -#endif - - %std_vector_methods_val(vector); - }; - - // *** - // const pointer specialization - // *** - template - class vector<_Tp const *, _Alloc > { - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef _Tp const * value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type reference; - typedef value_type const_reference; - typedef _Alloc allocator_type; - - %traits_swigtype(_Tp); - - %fragment(SWIG_Traits_frag(std::vector<_Tp const*, _Alloc >), "header", - fragment=SWIG_Traits_frag(_Tp), - fragment="StdVectorTraits") { - namespace swig { - template <> struct traits > { - typedef value_category category; - static const char* type_name() { - return "std::vector<" #_Tp " const*," #_Alloc " >"; - } - }; - } - } - - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp const*, _Alloc >); - -#ifdef %swig_vector_methods_val - // Add swig/language extra methods - %swig_vector_methods_val(std::vector<_Tp const*, _Alloc >); -#endif - - %std_vector_methods_val(vector); - }; - - // *** - // bool specialization - // *** - - template - class vector { - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef bool value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type reference; - typedef value_type const_reference; - typedef _Alloc allocator_type; - - %traits_swigtype(bool); - - %fragment(SWIG_Traits_frag(std::vector), "header", - fragment=SWIG_Traits_frag(bool), - fragment="StdVectorTraits") { - namespace swig { - template <> struct traits > { - typedef value_category category; - static const char* type_name() { - return "std::vector"; - } - }; - } - } - - %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector); - - -#ifdef %swig_vector_methods_val - // Add swig/language extra methods - %swig_vector_methods_val(std::vector); -#endif - - %std_vector_methods_val(vector); - -#if defined(SWIG_STD_MODERN_STL) && !defined(SWIG_STD_NOMODERN_STL) - void flip(); -#endif - - }; - -} diff --git a/third_party/pygments/tests/examplefiles/tads3_example.t b/third_party/pygments/tests/examplefiles/tads3_example.t deleted file mode 100644 index 41881c93d..000000000 --- a/third_party/pygments/tests/examplefiles/tads3_example.t +++ /dev/null @@ -1,1248 +0,0 @@ -#charset "utf-8" - -#include -#include - -extern function extern_function; -extern method extern_method; -extern function extern_function(a, b=a, c='<>', d:, e:=1, f?, ...); -extern method extern_method(a, b=a, c='<>', d:, e:=1, f?, [g]);; -extern class extern_class; -extern object extern_object; -intrinsic 't3vm' { }; -#ifndef PropDefAny -intrinsic class Object 'root-object/030004' { }; -#endif -object /**//**/ // /* \\ -#define Room Unthing - template [lst]; - -/* - * Quotations from "Le Roman de la Rose" are transcribed from MS. Douce 195, - * owned by Bodleian Library, University of Oxford - * (http://image.ox.ac.uk/show?collection=bodleian&manuscript=msdouce195). - */ - -versionInfo: GameID - IFID = '17d8efc3-07da-4dde-a837-ff7c4e386a77' - name = 'Pygmentalion' - byline = 'by David Corbett' - htmlByline = 'by David - Corbett' - version = '1' - authorEmail = 'David Corbett\040' - desc = 'You have fallen in love with a statue\x2e' - htmlDesc = 'You have fallen in love with a statue\x2E' -; - -/* - * Pymalion fu ẽtailleꝛꝛes. - * Poᷣtrayãs en fus ⁊ en peꝛꝛeˢ - * En metaulx en os ⁊ en cyꝛes - * Et en touteˢ aultres matires. - * Quon peult a tel oeuure trouuer. - * Poᷣ ſon grant engin eſpꝛouuer. - * Car maiſtre en fu bien dire loz. - * Ainſi com poᷣ acquerre loz - * Se voult a poᷣtraire deduyꝛe - * Si fiſt vng ymage diuuyꝛe - * Et miſt au faire tel entente - * Quel fu ſi plaiſãt et ſi gente - * Quel ſembloit eſtre auſſi viue. - * Com la plus belle riens q̇ viue - * (MS. Douce 195, fol. 149r) - */ - -modify _init() -{ - ({: local r, r = randomize, r})(); - replaced(); -} - -gameMain: GameMainDef - initialPlayerChar: Actor { - desc = "You look the same as usual, but you feel unusually - sentimental. " - location = entrance - } - showIntro - { - "The statue is undeniably a masterpiece: the most skillful carving you - have ever done, and the most beautiful woman you have ever seen. - Unfortunately, she is also an inanimate block, and now you can neither - work nor rest for unrequitable love.\b - Once again you stumble into your studio, hoping and praying to find - your statue brought to life.\b - <>\r\n - <>\b"; - } -; - -enum token token, tokOp, token; - -modify cmdTokenizer - rules_ = static - [ - ['whitespace', new RexPattern('%s+'), nil, &tokCvtSkip, nil], - ['punctuation', new RexPattern('[.,;:?!]'), tokPunct, nil, nil], - ['spelled number', - new RexPattern('(twenty|thirty|forty|fifty|sixty|' - + 'seventy|eighty|ninety)-' - + '(one|two|three|four|five|six|seven|eight|nine)' - + '(?!)'), - tokWord, &tokCvtSpelledNumber, nil], - ['spelled operator', new RexPattern( - '(plus|positive|minus|negat(iv)?e|not|inverse(%s+of)?|' - + 'times|over|divided%s+by|mod(ulo)?|and|xor|or|[al]?sh[lr])' - + '(?!)'), - tokOp, &tokCvtSpelledOperator, nil], - ['operator', R'[-!~+*/%&^|]|<<|>>>?', tokOp, nil, nil], - ['word', new RexPattern('*'), - tokWord, nil, nil], - ['string ascii-quote', R"""([`\'"])(.*)%1(?!)""", - tokString, nil, nil], - ['string back-quote', R"`(.*)'(?!%w)", tokString, nil, nil], - ['string curly single-quote', new RexPattern('\u2018(.*)\u2019'), - tokString, nil, nil], - ['string curly double-quote', new RexPattern('\u201C(.*)\u201D'), - tokString, nil, nil], - ['string unterminated', R'''([`\'"\u2018\u201C](.*)''', tokString, - nil, nil], - ['integer', new RexPattern('[0-9]+'), tokInt, nil, nil] - ] - replace tokCvtSpelledOperator(txt, typ, toks) - { - toks.append([rexReplace(R'%s+', txt.toLower(), '\\'), typ, txt]); - } -; - -/* Tokens */ - -/* - * Puiˢ li reueſt en maĩteˢ guiſes. - * Robeˢ faicteˢ ꝑ grãˢ maiſtriſeˢ. - * De biaulx dꝛaps de ſoye ⁊ de laĩe. - * Deſcarlate de tiretaine - * De vert de pers ⁊ de bꝛunecte - * De couleᷣ freſche fine ⁊ necte - * Ou moult a riches paneˢ miſes. - * Herminees vaires et griſes - * Puis les li roſte puis reſſaye. - * Cõmant li ſiet robbe de ſaye - * Sendaulx meloguins galebꝛunˢ. - * Indes vermeilz iaunes ⁊ bꝛunˢ. - * [...] - * Aultre foiz luy repꝛẽd courage. - * De tout oſter ⁊ mectre guindeˢ. - * Iaunes vermeilles vers ⁊ indeˢ. - * (MS. Douce 195, fol. 150r) - */ - -class Token: Achievement -{ - points = 1; - desc = "<><><>"; - before = before = '', before_ - after = (after = '', after_) -} - -Token template inherited 'before_' 'after_' 'desc_'; - -#define DefineToken(name, before, after) name##Token: Token before after #@name - -DefineToken(builtin, '', ''); -DefineToken(comment, '', ''); -DefineToken(decorator, '', ''); -DefineToken(error, '', ''); -DefineToken(escape, '', ''); -DefineToken(float, '', ''); -DefineToken(keyword, '', ''); -DefineToken(label, '', ''); -DefineToken(long, '', ''); -DefineToken(name, '', ''); -DefineToken(operator, '', ''); -DefineToken(string, '', ''); -DefineToken(whitespace, '', ''); - -function highlightToken(tokenString) -{ - local token = [ - 'built in' -> builtinToken, - 'comment' -> commentToken, - 'decorator' -> decoratorToken, - 'error' -> errorToken, - 'escape' -> escapeToken, - 'float' -> floatToken, - 'keyword' -> keywordToken, - 'label' -> labelToken, - 'long' -> longToken, - 'name' -> nameToken, - 'operator' -> operatorToken, - 'string' -> stringToken, - 'white space' -> whitespaceToken, - * -> nil - ][tokenString.toLower()]; - if (!token) - return tokenString; - token.awardPointsOnce(); - return '<><><>'; -} - -string /**//**/ // /* \\ -#define Room Unthing - template <> highlightToken; - -/* Grammar for materials */ - -dictionary property material; -grammar adjWord(material): ->adj_ : AdjPhraseWithVocab - getVocabMatchList(resolver, results, extraFlags) - { - return getWordMatches(adj_, &material, resolver, extraFlags, - VocabTruncated); - } - getAdjustedTokens() - { - return [adj_, &material]; - } -; - -/* Rooms and objects */ - -+ property location; - -entrance: Room 'Entrance' - "You are in the entrance to your studio. This is where you carve great - works of art, not that you have felt like making any lately. A door leads - outside, and the studio itself is to the north and the east. " - north = workbenchRoom - northeast = sinkRoom - east = altarRoom - south = door - out asExit(south) -; - -+ door: LockableWithKey, Door 'door' 'door' - "It is a simple wooden door. " - material = 'wood' 'wooden' - keyList = [key] - cannotOpenLockedMsg = '{The dobj/He} {is} locked. You cannot - <>! ' -; - -key: PresentLater, Key 'key' 'key' @altar - "It is a <>grimy<> bronze key. <>On it is \ - etched the word <>. " - material = 'bronze' - clean = nil - keyword = (keyword = randomGreekWord(), targetprop) - dobjFor(Clean) { verify { } action { askForIobj(CleanWith); } } - dobjFor(CleanWith) - { - verify - { - if (clean) - illogicalAlready('{The dobj/He} {is} already clean. '); - } - action - { - gDobj.clean = true; - "{You/He} clean{s} {the dobj/him}, revealing an inscription. "; - } - } - dobjFor(Read) { verify { nonObvious; } } -; - -workbenchRoom: Room 'At the Workbench' - "This workbench, in the northwest part of the studio, was where you would - create works of art. Now you just come here to contemplate your - creation’s beauty and lament your hopeless situation.\b - The statue stands on a plinth beside the workbench. " - east = sinkRoom - southeast = altarRoom - south = entrance - getDestName(actor, origin) { return 'the workbench'; } -; - -+ workbench: Fixture, Surface - 'workbench/bench/material/materials/tool/tools' 'workbench' - "Normally, the workbench would be scattered with half-finished projects, - but now your tools and materials lie abandoned. " -; - -+ plinth: Fixture, Thing 'marble plinth/pedestal' 'plinth' - "It’s a smoothed block of marble about a cubit high. " -; - -replace grammar predicate(Screw): ' ': object; -replace grammar predicate(ScrewWith): ' ': object; -+ + statue: Fixture, Surface - '"creation\'s" beauty/carving/creation/galatea/statue/woman' 'statue' - "This is a<>n untitled<> statue of a woman - carved from <>flawless <> - <>milk-white <>ivory. - <>Her - <>long <>hair is done up in a - chignon<>, with a few strands falling down her - neck<><>, and \v<>.<><> - <>She radiates an aura of contrapposto grace. - <><>\bYou wonder what she - <>is going to<>will<> be like as a - woman. - <>Maybe she’ll be a painter and expand - your business.<> - <>Maybe she’ll have a head for figures - and will put the accounts in order.<> - <>She’ll love you, obviously, but beyond - that you don’t know.<><> - <>If only Aphrodite would bring her to life - without this silly puzzle about tokens and mirrors!<> " - material = 'ivory' - propertyset 'is*' - { - propertyset 'H*' - { - im = nil\ - er = true; - } - It = true - } - iobjFor(PutOn) - { - check - { - if (gDobj not /**//**/ // /* \\ -#define Room Unthing - in (necklace, __objref(necklace, warn))) - "How rude! You don’t know what you were thinking. "; - } - } - iobjFor(GiveTo) remapTo(PutOn, DirectObject, IndirectObject) -; - -+++ necklace: Wearable - 'pearl necklace/string pearls' '<> of pearls' - "This is a masterfully crafted pearl necklace. You hope the statue - won’t mind if you hold onto it for a while. " - initDesc = "You gave the statue this pearl necklace yesterday. " - isPlural = true -; - -altarRoom: Room 'At the Altar' - "Light from the window illuminates a crude altar. Until recently, this - corner was your bedroom. The rest of the studio lies north and west. " - north = sinkRoom - northwest = workbenchRoom - west = entrance - getDestName(actor, origin) { return 'the altar'; } -; - -+ window: Fixture 'window' 'window' - "It’s just a window above the altar. <>The space under the - window is blank; as an interior <>, you can’t - help but think the wall would benefit from a bas-relief, but – - sigh &endash you are too lovelorn to wield the chisel. <<||>>The - wall right below it is a boring <>. <>" -; - -+ altar: Fixture, Surface 'crude rough altar/banker/slab' 'altar' - "A rough marble slab lies on a wooden banker. In your rush to construct an - altar, you neglected the usual surface finish and friezes, but you pray at - it anyway. You are sure the gods will understand. " - material = 'marble' 'wood' 'wooden' - bulkCapacity = 1 - dobjFor(PrayAt) - { - verify { } - action() - { - /* - * Biaulx dieux diſt il tout ce poez. - * Sil voꝰ plaiſt ma requeſte oez - * [...] - * Et la belle q̇ mon cueᷣ emble - * Qui ſi bien yuoyꝛe reſſemble. - * Deuiengne ma loyal amye - * De fẽme ait coꝛps ame et vie - * (MS. Douce 195, fol. 151r) - */ - local offering; - foreach (offering in contents); - if (!keywordToken.scoreCount) - "<>O Aphrodite, you say, comforter of - hopeless lovers, hear my prayer! May she to whom I have given - my heart be given body, soul, and life. And a colorful - personality. And&mdash\b - You are interrupted by a shimmering about the altar. As you - watch, it takes the form of a callipygian goddess.\b - Mortal, I have heard your heart-felt and oft-repeated plea, - and I will take pity on you, says Aphrodite. If you give - me a token of your love as an offering, I will give you the - <> of life. Speak this word in the - presence of a mirror, and I will grant your request.\b - She fades away, adding, As for her colorful personality, - just look around you. <><>"; - else if (key.location) - "O Aphrodite, you say, what am I supposed to do - again?\bThe goddess reappears and reminds you to speak the - keyword of life at a mirror. <>What’s the - keyword, then? Gods help those who help themselves. - Figure it out yourself.<>Why a mirror? I like - mirrors.<> "; - else if (offering == necklace) - { - "Aphrodite reappears. A necklace! Perfect! The necklace - disappears in a bright flash. When your eyes readjust, you see - a key lying in its place. "; - necklace.moveInto(nil); - key.makePresent(); - } - else if (+offering) - "Aphrodite reappears. She eyes <> - skeptically. <>No <>.<>You - call that a token of love?<>\^<>? - Really?<>Come on, mortal, it’s not that - difficult!<> "; - else - "I heard you the first time, says Aphrodite. Prove - your devotion by offering a token of your love at the altar, - or the deal’s off. "; - } - } - iobjFor(GiveTo) remapTo(PutOn, DirectObject, IndirectObject) -; - -aphrodite: Unthing - '(love) aphrodite/cytherea/god/goddess/venus love' 'Aphrodite' - '<>You can only pray to a god. - <>You need an altar to interact with a god. ' - location = (gPlayerChar) - isProperName = true - isHer = true - iobjFor(GiveTo) - { - verify - { - illogical('She isn’t here. You’ll have to leave {the - dobj/him} somewhere she can find it. '); - } - } - dobjFor(PrayAt) maybeRemapTo(gActor.canSee(altar), PrayAt, altar) -; - -sinkRoom: Room 'Washroom' - "Sculpting marble is a dusty business. You use this sink to clean off after - a hard day’s work. Beside the sink is a small end table, and on the - wall is a calculator. The rest of the studio is south and west. " - south = altarRoom - southwest = entrance - west = workbenchRoom -; - -property level, overflowing; -export overflowing; -export level 'waterLevel'; -+ sink: Fixture '(auto) (mop) auto-sink/autosink/bowl/drain/faucet/sink' 'sink' - "This is a state-of-the-art mop sink with anti-miasmic coating and bronze - backsplash. It is so modern, there are no handles or other obvious ways to - turn it on.\b - <>It is overflowing. - <>It is full to the brim with water. - <= 15000>>It is full of water. - <>It is half full of water. - <= 2000>>There is some water in the sink. - < 0>>A small puddle has formed at the bottom of the sink. - <>It is empty. - <>It looks like it hasn’t been used in a - <> time. " - level = not in ([lst]) { return argcount; } - not = in() - overflowing = nil - current = self - setLevel(level:) - { - targetobj.current.overflowing = level == nil; - targetobj.current.level = min(level ?? 0, 20000); - if (sink.overflowing || sink.level > 0e+1) - sinkWater.makePresent(); - if (basin.overflowing || basin.level > 0e-1) - basinWater.makePresent(); - } - iobjFor(CleanWith) remapTo(CleanWith, DirectObject, sinkWater) -; - -++ sinkWater: PresentLater, Fixture - '(sink) water sink water' 'water' "<>" - disambigName = 'water in the sink' - dobjFor(Drink) - { - verify { illogical('''{You're} not thirsty. '''); } - } - iobjFor(CleanWith) - { - preCond = [] - verify { - if (!location) - illogicalNow('There is no water in the sink. '); - if (!sink.overflowing && sink.level < 1e2) - illogicalNow('There is not enough water in the sink. '); - } - } -; - -+ table: Fixture, Surface 'small end bracket/table' 'table' - "<>Upon closer inspection, you see that \v<>The table is - bracketed to the wall. " -; - -++ Readable '"operator\'s" manual' 'manual' - "
    <>’s Manual<\center>\b - To control the auto-sink, use the calculator add-on to enter the - desired volume of water. For example,\n - \t\t<>\n - to fill the basin with <<% ,d 0x69 * 0105>> kochliaria -]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -]]> - -]]> - -]> - - diff --git a/third_party/pygments/tests/examplefiles/test.ebnf b/third_party/pygments/tests/examplefiles/test.ebnf deleted file mode 100644 index a96171b08..000000000 --- a/third_party/pygments/tests/examplefiles/test.ebnf +++ /dev/null @@ -1,31 +0,0 @@ -letter = "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" ; -digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; -symbol = "[" | "]" | "{" | "}" | "(" | ")" | "<" | ">" - | "'" | '"' | "=" | "|" | "." | "," | ";" ; -character = letter | digit | symbol | " " ; - -identifier = letter , { letter | digit | " " } ; -terminal = "'" , character , { character } , "'" - | '"' , character , { character } , '"' ; - -special = "?" , any , "?" ; - -comment = (* this is a comment "" *) "(*" , any-symbol , "*)" ; -any-symbol = ? any visible character ? ; (* ? ... ? *) - -lhs = identifier ; -rhs = identifier - | terminal - | comment , rhs - | rhs , comment - | "[" , rhs , "]" - | "{" , rhs , "}" - | "(" , rhs , ")" - | rhs , "|" , rhs - | rhs , "," , rhs ; - -rule = lhs , "=" , rhs , ";" | comment ; -grammar = { rule } ; diff --git a/third_party/pygments/tests/examplefiles/test.ec b/third_party/pygments/tests/examplefiles/test.ec deleted file mode 100644 index 37868b52f..000000000 --- a/third_party/pygments/tests/examplefiles/test.ec +++ /dev/null @@ -1,605 +0,0 @@ -namespace gui; - -import "Window" - -public struct AnchorValue -{ - AnchorValueType type; - - union - { - int distance; - float percent; - }; - property int - { - set { distance = value; type = offset; } - get { return distance; } - } - property double - { - set { percent = (float) value; type = relative; } - get { return (double) percent; } - } - - char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) - { - if(type == offset) - { - sprintf(stringOutput, "%d", distance); - } - else if(type == relative) - { - int c; - int last = 0; - sprintf(stringOutput, "%f", percent); - c = strlen(stringOutput)-1; - for( ; c >= 0; c--) - { - if(stringOutput[c] != '0') - last = Max(last, c); - if(stringOutput[c] == '.') - { - if(last == c) - { - stringOutput[c+1] = '0'; - stringOutput[c+2] = 0; - } - else - stringOutput[last+1] = 0; - break; - } - } - } - if(needClass) *needClass = false; - return stringOutput; - } - - bool OnGetDataFromString(char * stringOutput) - { - char * end; - if(strchr(stringOutput, '.')) - { - float percent = (float)strtod(stringOutput, &end); - - if(end != stringOutput) - { - this.percent = percent; - type = relative; - return true; - } - } - else if(stringOutput[0]) - { - int distance = strtol(stringOutput, &end, 0); - if(end != stringOutput) - { - this.distance = distance; - type = offset; - return true; - } - } - else - { - distance = 0; - type = 0; - } - return false; - } -}; - -public struct MiddleAnchorValue -{ - AnchorValueType type; - - union - { - int distance; - float percent; - }; - property int - { - set { distance = value; type = none; } - get { return distance; } - } - property double - { - set { percent = (float) value; type = middleRelative; } - get { return (double) percent; } - } - - char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) - { - if(type == middleRelative) - { - int c; - int last = 0; - sprintf(stringOutput, "%f", percent); - c = strlen(stringOutput)-1; - for( ; c >= 0; c--) - { - if(stringOutput[c] != '0') - last = Max(last, c); - if(stringOutput[c] == '.') - { - if(last == c) - { - stringOutput[c+1] = '0'; - stringOutput[c+2] = 0; - } - else - stringOutput[last+1] = 0; - break; - } - } - } - else if(type == none && distance) - { - sprintf(stringOutput, "%d", distance); - } - if(needClass) *needClass = false; - return stringOutput; - } - - bool OnGetDataFromString(char * stringOutput) - { - if(strchr(stringOutput, '.')) - { - percent = (float)strtod(stringOutput, null); - type = middleRelative; - } - else - { - distance = strtol(stringOutput, null, 0); - type = none; - } - return true; - } -}; - -public enum AnchorValueType { none, offset, relative, middleRelative, cascade, vTiled, hTiled }; - -public struct Anchor -{ - union { AnchorValue left; MiddleAnchorValue horz; }; - union { AnchorValue top; MiddleAnchorValue vert; }; - AnchorValue right, bottom; - - char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) - { - char tempString[256]; - char * anchorValue; - bool subNeedClass; - - tempString[0] = '\0'; - anchorValue = left.OnGetString(tempString, null, &subNeedClass); - if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "left = "); strcat(stringOutput, anchorValue); } - - //if(((!left.type && !right.type) && horz.distance) || horz.type == middleRelative) - if(!right.type && ((!left.type && horz.distance) || horz.type == middleRelative)) - { - tempString[0] = '\0'; - anchorValue = horz.OnGetString(tempString, null, &subNeedClass); - if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "horz = "); strcat(stringOutput, anchorValue); } - } - - tempString[0] = '\0'; - anchorValue = top.OnGetString(tempString, null, &subNeedClass); - if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "top = "); strcat(stringOutput, anchorValue); } - - tempString[0] = '\0'; - anchorValue = right.OnGetString(tempString, null, &subNeedClass); - if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "right = "); strcat(stringOutput, anchorValue); } - - // if(((!top.type && !bottom.type) && vert.distance) || vert.type == middleRelative) - if(!bottom.type && ((!top.type && vert.distance) || vert.type == middleRelative)) - { - tempString[0] = '\0'; - anchorValue = vert.OnGetString(tempString, null, &subNeedClass); - if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "vert = "); strcat(stringOutput, anchorValue); } - } - - tempString[0] = '\0'; - anchorValue = bottom.OnGetString(tempString, null, &subNeedClass); - if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "bottom = "); strcat(stringOutput, anchorValue); } - - return stringOutput; - } - - bool OnGetDataFromString(char * string) - { - this = Anchor {}; - return class::OnGetDataFromString(string); - } - - bool OnSaveEdit(DropBox dropBox, void * object) - { - return dropBox.Save(); - } - - Window OnEdit(Window listBox, Window master, int x, int y, int w, int h, Window control) - { - char * string = ""; - AnchorDropBox comboBox - { - editText = true; - parent = listBox; - master = master; - position = Point { x, y }; - //clientSize = Size { h = h }; - //size.w = w; - size = { w, h }; - anchorValue = this; - control = control; - borderStyle = 0; - }; - - comboBox.Create(); - - { - char tempString[MAX_F_STRING] = ""; - bool needClass = false; - char * result = OnGetString(tempString, null, &needClass); - if(result) string = result; - } - comboBox.contents = string; - return comboBox; - } -}; - -private class AnchorButton : Button -{ - toggle = true, bevel = false; - - void OnRedraw(Surface surface) - { - int cw = clientSize.w; - int ch = clientSize.h; - - surface.SetForeground(black); - if(checked) - { - surface.SetBackground(Color { 85,85,85 }); - surface.Area(0,0, cw-1, ch-1); - } - else - surface.LineStipple(0xAAAA); - - surface.Rectangle(0,0,cw-1,ch-1); - - if(active) - { - surface.LineStipple(0xAAAA); - surface.Rectangle(2,2,cw-3,ch-3); - } - } - - bool AnchorEditor::NotifyClicked(Button button, int x, int y, Modifiers mods) - { - AnchorDropBox anchorDropBox = (AnchorDropBox)master; - Anchor anchor = anchorDropBox.anchorValue; - Window control = anchorDropBox.control; - DataBox dropMaster = (DataBox)anchorDropBox.master; - int id = button.id; - - switch(id) - { - case 0: anchor.left.type = button.checked ? offset : none; break; - case 1: anchor.top.type = button.checked ? offset : none; break; - case 2: anchor.right.type = button.checked ? offset : none; break; - case 3: anchor.bottom.type = button.checked ? offset : none; break; - } - - if(anchor.horz.type == middleRelative && (id == 0 || id == 2)) - { - anchorDropBox.relButtons[0].checked = false; - anchorDropBox.relButtons[2].checked = false; - } - if(anchor.vert.type == middleRelative && (id == 1 || id == 3)) - { - anchorDropBox.relButtons[1].checked = false; - anchorDropBox.relButtons[3].checked = false; - } - anchorDropBox.relButtons[id].checked = false; - - //anchor.horz.type = none; - //anchor.vert.type = none; - - { - int vpw, vph; - int x,y,w,h; - Window parent = control.parent; - - // Fix Anchor - x = control.position.x; - y = control.position.y; - w = control.size.w; - h = control.size.h; - - vpw = parent.clientSize.w; - vph = parent.clientSize.h; - if(control.nonClient) - { - vpw = parent.size.w; - vph = parent.size.h; - } - else if(((BorderBits)control.borderStyle).fixed) - { - if(!control.dontScrollHorz && parent.scrollArea.w) vpw = parent.scrollArea.w; - if(!control.dontScrollVert && parent.scrollArea.h) vph = parent.scrollArea.h; - } - - if(anchor.left.type == offset) anchor.left.distance = x; - else if(anchor.left.type == relative) anchor.left.percent = (float)x / vpw; - if(anchor.top.type == offset) anchor.top.distance = y; - else if(anchor.top.type == relative) anchor.top.percent = (float)y / vph; - if(anchor.right.type == offset) anchor.right.distance = vpw - (x + w); - //else if(anchor.right.type == relative) anchor.right.percent = (float) (x + w) / vpw; - else if(anchor.right.type == relative) anchor.right.percent = (float) (vpw - (x + w)) / vpw; - if(anchor.bottom.type == offset) anchor.bottom.distance = vph - (y + h); - //else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (y + h) / vph; - else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (vph - (y + h)) / vph; - - if(!anchor.left.type && !anchor.right.type) - { - anchor.horz.distance = (x + w / 2) - (vpw / 2); - //anchor.horz.type = anchor.horz.distance ? offset : 0; - } - else if(anchor.horz.type == middleRelative) anchor.horz.percent = (float) ((x + w / 2) - (vpw / 2)) / vpw; - if(!anchor.top.type && !anchor.bottom.type) - { - anchor.vert.distance = (y + h / 2) - (vph / 2); - //anchor.vert.type = anchor.vert.distance ? offset : 0; - } - else if(anchor.vert.type == middleRelative) anchor.vert.percent = (float)((y + h / 2) - (vph / 2)) / vph; - } - - { - char tempString[1024] = ""; - bool needClass = false; - char * string = anchor.OnGetString(tempString, null, &needClass); - anchorDropBox.contents = string; - } - - dropMaster.SetData(&anchor, false); - anchorDropBox.anchorValue = anchor; - return true; - } -} - -private class AnchorRelButton : Button -{ - toggle = true; - bevel = false; - text = "%"; - //bevelOver = true; - - void OnRedraw(Surface surface) - { - int cw = clientSize.w; - int ch = clientSize.h; - - if(checked) - { - surface.SetForeground(black); - } - else - { - surface.SetForeground(Color{170,170,170}); - } - surface.WriteText(5,2, "%", 1); - - if(active) - { - surface.LineStipple(0xAAAA); - surface.Rectangle(3,3,cw-4,ch-4); - } - } - - bool AnchorEditor::NotifyClicked(Button button, int x, int y, Modifiers mods) - { - AnchorDropBox anchorDropBox = (AnchorDropBox)master; - Anchor anchor = anchorDropBox.anchorValue; - Window control = anchorDropBox.control; - DataBox dropMaster = (DataBox)anchorDropBox.master; - int id = button.id; - - if((id == 0 || id == 2) && ((!anchor.left.type && !anchor.right.type) || anchor.left.type == middleRelative)) - { - if(button.checked) anchor.horz.type = middleRelative; else anchor.horz.type = none; - anchorDropBox.relButtons[(id + 2)%4].checked = button.checked; - } - else if((id == 1 || id == 3) && ((!anchor.top.type && !anchor.bottom.type) || anchor.top.type == middleRelative)) - { - if(button.checked) anchor.vert.type = middleRelative; else anchor.vert.type = none; - anchorDropBox.relButtons[(id + 2)%4].checked = button.checked; - } - else - { - switch(id) - { - case 0: anchor.left.type = button.checked ? relative : (anchor.left.type ? offset : none); break; - case 1: anchor.top.type = button.checked ? relative : (anchor.top.type ? offset : none); break; - case 2: anchor.right.type = button.checked ? relative : (anchor.right.type ? offset : none); break; - case 3: anchor.bottom.type = button.checked ? relative : (anchor.bottom.type ? offset : none); break; - } - anchorDropBox.buttons[id].checked = true; - if(anchor.horz.type == middleRelative) anchor.horz.type = none; - if(anchor.vert.type == middleRelative) anchor.vert.type = none; - } - - { - int vpw, vph; - int x,y,w,h; - Window parent = control.parent; - - // Fix Anchor - x = control.position.x; - y = control.position.y; - w = control.size.w; - h = control.size.h; - - vpw = parent.clientSize.w; - vph = parent.clientSize.h; - if(control.nonClient) - { - vpw = parent.size.w; - vph = parent.size.h; - } - else if(((BorderBits)control.borderStyle).fixed) - { - if(!control.dontScrollHorz && parent.scrollArea.w) vpw = parent.scrollArea.w; - if(!control.dontScrollVert && parent.scrollArea.h) vph = parent.scrollArea.h; - } - - if(anchor.left.type == offset) anchor.left.distance = x; - else if(anchor.left.type == relative) anchor.left.percent = (float)x / vpw; - if(anchor.top.type == offset) anchor.top.distance = y; - else if(anchor.top.type == relative) anchor.top.percent = (float)y / vph; - if(anchor.right.type == offset) anchor.right.distance = vpw - (x + w); - //else if(anchor.right.type == relative) anchor.right.percent = (float) (x + w) / vpw; - else if(anchor.right.type == relative) anchor.right.percent = (float) (vpw - (x + w)) / vpw; - if(anchor.bottom.type == offset) anchor.bottom.distance = vph - (y + h); - //else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (y + h) / vph; - else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (vph - (y + h)) / vph; - - if(!anchor.left.type && !anchor.right.type) - { - anchor.horz.distance = (x + w / 2) - (vpw / 2); - //anchor.horz.type = anchor.horz.distance ? offset : none; - } - else if(anchor.horz.type == middleRelative) anchor.horz.percent = (float) ((x + w / 2) - (vpw / 2)) / vpw; - if(!anchor.top.type && !anchor.bottom.type) - { - anchor.vert.distance = (y + h / 2) - (vph / 2); - //anchor.vert.type = anchor.vert.distance ? offset : none; - } - else if(anchor.vert.type == middleRelative) anchor.vert.percent = (float)((y + h / 2) - (vph / 2)) / vph; - } - - { - char tempString[1024] = ""; - bool needClass = false; - char * string = anchor.OnGetString(tempString, null, &needClass); - anchorDropBox.contents = string; - } - - dropMaster.SetData(&anchor, false); - anchorDropBox.anchorValue = anchor; - return true; - } -} - -private class AnchorEditor : Window -{ - interim = true; - borderStyle = deepContour; - size.h = 92; - - bool OnKeyDown(Key key, unichar ch) - { - if(key == escape) - return master.OnKeyDown(key, ch); - return true; - } -} - -private class AnchorDropBox : DropBox -{ - Anchor anchorValue; - Window control; - Button relButtons[4], buttons[4]; - - AnchorEditor anchorEditor - { - master = this; - autoCreate = false; - }; - - Window OnDropDown() - { - int c; - Button - { - anchorEditor, - anchor = Anchor { left = 28, top = 28, right = 28, bottom = 28 }, - inactive = true, disabled = true - }; - for(c = 0; c<4; c++) - { - Button button = buttons[c] = AnchorButton - { - anchorEditor, id = c, - size = Size { (c%2)?10:28, (c%2)?28:10 } - }; - Button relButton = relButtons[c] = AnchorRelButton - { - anchorEditor, id = c; - }; - - switch(c) - { - case 0: - if(anchorValue.left.type && anchorValue.left.type != middleRelative) button.checked = true; - if(anchorValue.left.type == relative || anchorValue.horz.type == middleRelative) relButton.checked = true; - - button.anchor = Anchor { left = 0 }; - relButton.anchor = Anchor { left = 5, vert = 16 }; - break; - case 1: - if(anchorValue.top.type && anchorValue.top.type != middleRelative) button.checked = true; - if(anchorValue.top.type == relative || anchorValue.vert.type == middleRelative) relButton.checked = true; - - button.anchor = Anchor { top = 0 }; - relButton.anchor = Anchor { top = 5, horz = 16 }; - break; - case 2: - if(anchorValue.right.type && anchorValue.right.type != middleRelative) button.checked = true; - if(anchorValue.right.type == relative || anchorValue.horz.type == middleRelative) relButton.checked = true; - - button.anchor = Anchor { right = 0 }; - relButton.anchor = Anchor { right = 5, vert = 16 }; - break; - case 3: - if(anchorValue.bottom.type && anchorValue.bottom.type != middleRelative) button.checked = true; - if(anchorValue.bottom.type == relative || anchorValue.vert.type == middleRelative) relButton.checked = true; - - button.anchor = Anchor { bottom = 0 }; - relButton.anchor = Anchor { bottom = 5, horz = 16 }; - break; - } - } - anchorEditor.Create(); - return anchorEditor; - } - - void OnCloseDropDown(Window anchorEditor) - { - // TOFIX: Patch for update bug - master.Update(null); - anchorEditor.Destroy(0); - } - - bool DataBox::NotifyTextEntry(AnchorDropBox dropBox, char * string, bool save) - { - Anchor anchor = dropBox.anchorValue; - Window control = dropBox.control; - - if(save) - { - if(anchor.OnGetDataFromString(string)) - { - SetData(&anchor, false); - dropBox.anchorValue = anchor; - } - } - else - { - char tempString[1024] = ""; - bool needClass = false; - char * string = anchor.OnGetString(tempString, null, &needClass); - dropBox.contents = string; - } - return true; - } -} diff --git a/third_party/pygments/tests/examplefiles/test.eh b/third_party/pygments/tests/examplefiles/test.eh deleted file mode 100644 index 1ed173fb9..000000000 --- a/third_party/pygments/tests/examplefiles/test.eh +++ /dev/null @@ -1,315 +0,0 @@ -/* A Bison parser, made by GNU Bison 2.0. */ - -/* Skeleton parser for Yacc-like parsing with Bison, - Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004 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 as published by - the Free Software Foundation; either version 2, 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, write to the Free Software - Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. */ - -/* As a special exception, when this file is copied by Bison into a - Bison output file, you may use that output file without restriction. - This special exception was added by the Free Software Foundation - in version 1.24 of Bison. */ - -/* Tokens. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - /* Put the tokens into the symbol table, so that GDB and other debuggers - know about them. */ - enum yytokentype { - IDENTIFIER = 258, - CONSTANT = 259, - STRING_LITERAL = 260, - SIZEOF = 261, - PTR_OP = 262, - INC_OP = 263, - DEC_OP = 264, - LEFT_OP = 265, - RIGHT_OP = 266, - LE_OP = 267, - GE_OP = 268, - EQ_OP = 269, - NE_OP = 270, - AND_OP = 271, - OR_OP = 272, - MUL_ASSIGN = 273, - DIV_ASSIGN = 274, - MOD_ASSIGN = 275, - ADD_ASSIGN = 276, - SUB_ASSIGN = 277, - LEFT_ASSIGN = 278, - RIGHT_ASSIGN = 279, - AND_ASSIGN = 280, - XOR_ASSIGN = 281, - OR_ASSIGN = 282, - TYPE_NAME = 283, - TYPEDEF = 284, - EXTERN = 285, - STATIC = 286, - AUTO = 287, - REGISTER = 288, - CHAR = 289, - SHORT = 290, - INT = 291, - UINT = 292, - INT64 = 293, - LONG = 294, - SIGNED = 295, - UNSIGNED = 296, - FLOAT = 297, - DOUBLE = 298, - CONST = 299, - VOLATILE = 300, - VOID = 301, - VALIST = 302, - STRUCT = 303, - UNION = 304, - ENUM = 305, - ELLIPSIS = 306, - CASE = 307, - DEFAULT = 308, - IF = 309, - SWITCH = 310, - WHILE = 311, - DO = 312, - FOR = 313, - GOTO = 314, - CONTINUE = 315, - BREAK = 316, - RETURN = 317, - IFX = 318, - ELSE = 319, - CLASS = 320, - THISCLASS = 321, - CLASS_NAME = 322, - PROPERTY = 323, - SETPROP = 324, - GETPROP = 325, - NEWOP = 326, - RENEW = 327, - DELETE = 328, - EXT_DECL = 329, - EXT_STORAGE = 330, - IMPORT = 331, - DEFINE = 332, - VIRTUAL = 333, - EXT_ATTRIB = 334, - PUBLIC = 335, - PRIVATE = 336, - TYPED_OBJECT = 337, - ANY_OBJECT = 338, - _INCREF = 339, - EXTENSION = 340, - ASM = 341, - TYPEOF = 342, - WATCH = 343, - STOPWATCHING = 344, - FIREWATCHERS = 345, - WATCHABLE = 346, - CLASS_DESIGNER = 347, - CLASS_NO_EXPANSION = 348, - CLASS_FIXED = 349, - ISPROPSET = 350, - CLASS_DEFAULT_PROPERTY = 351, - PROPERTY_CATEGORY = 352, - CLASS_DATA = 353, - CLASS_PROPERTY = 354, - SUBCLASS = 355, - NAMESPACE = 356, - NEW0OP = 357, - RENEW0 = 358, - VAARG = 359, - DBTABLE = 360, - DBFIELD = 361, - DBINDEX = 362, - DATABASE_OPEN = 363 - }; -#endif -#define IDENTIFIER 258 -#define CONSTANT 259 -#define STRING_LITERAL 260 -#define SIZEOF 261 -#define PTR_OP 262 -#define INC_OP 263 -#define DEC_OP 264 -#define LEFT_OP 265 -#define RIGHT_OP 266 -#define LE_OP 267 -#define GE_OP 268 -#define EQ_OP 269 -#define NE_OP 270 -#define AND_OP 271 -#define OR_OP 272 -#define MUL_ASSIGN 273 -#define DIV_ASSIGN 274 -#define MOD_ASSIGN 275 -#define ADD_ASSIGN 276 -#define SUB_ASSIGN 277 -#define LEFT_ASSIGN 278 -#define RIGHT_ASSIGN 279 -#define AND_ASSIGN 280 -#define XOR_ASSIGN 281 -#define OR_ASSIGN 282 -#define TYPE_NAME 283 -#define TYPEDEF 284 -#define EXTERN 285 -#define STATIC 286 -#define AUTO 287 -#define REGISTER 288 -#define CHAR 289 -#define SHORT 290 -#define INT 291 -#define UINT 292 -#define INT64 293 -#define LONG 294 -#define SIGNED 295 -#define UNSIGNED 296 -#define FLOAT 297 -#define DOUBLE 298 -#define CONST 299 -#define VOLATILE 300 -#define VOID 301 -#define VALIST 302 -#define STRUCT 303 -#define UNION 304 -#define ENUM 305 -#define ELLIPSIS 306 -#define CASE 307 -#define DEFAULT 308 -#define IF 309 -#define SWITCH 310 -#define WHILE 311 -#define DO 312 -#define FOR 313 -#define GOTO 314 -#define CONTINUE 315 -#define BREAK 316 -#define RETURN 317 -#define IFX 318 -#define ELSE 319 -#define CLASS 320 -#define THISCLASS 321 -#define CLASS_NAME 322 -#define PROPERTY 323 -#define SETPROP 324 -#define GETPROP 325 -#define NEWOP 326 -#define RENEW 327 -#define DELETE 328 -#define EXT_DECL 329 -#define EXT_STORAGE 330 -#define IMPORT 331 -#define DEFINE 332 -#define VIRTUAL 333 -#define EXT_ATTRIB 334 -#define PUBLIC 335 -#define PRIVATE 336 -#define TYPED_OBJECT 337 -#define ANY_OBJECT 338 -#define _INCREF 339 -#define EXTENSION 340 -#define ASM 341 -#define TYPEOF 342 -#define WATCH 343 -#define STOPWATCHING 344 -#define FIREWATCHERS 345 -#define WATCHABLE 346 -#define CLASS_DESIGNER 347 -#define CLASS_NO_EXPANSION 348 -#define CLASS_FIXED 349 -#define ISPROPSET 350 -#define CLASS_DEFAULT_PROPERTY 351 -#define PROPERTY_CATEGORY 352 -#define CLASS_DATA 353 -#define CLASS_PROPERTY 354 -#define SUBCLASS 355 -#define NAMESPACE 356 -#define NEW0OP 357 -#define RENEW0 358 -#define VAARG 359 -#define DBTABLE 360 -#define DBFIELD 361 -#define DBINDEX 362 -#define DATABASE_OPEN 363 - - - - -#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED) -#line 42 "grammar.y" -typedef union YYSTYPE { - SpecifierType specifierType; - int i; - AccessMode declMode; - Identifier id; - Expression exp; - Specifier specifier; - OldList * list; - Enumerator enumerator; - Declarator declarator; - Pointer pointer; - Initializer initializer; - InitDeclarator initDeclarator; - TypeName typeName; - Declaration declaration; - Statement stmt; - FunctionDefinition function; - External external; - Context context; - AsmField asmField; - - Instantiation instance; - MembersInit membersInit; - MemberInit memberInit; - ClassFunction classFunction; - ClassDefinition _class; - ClassDef classDef; - PropertyDef prop; - char * string; - Symbol symbol; - PropertyWatch propertyWatch; - TemplateParameter templateParameter; - TemplateArgument templateArgument; - TemplateDatatype templateDatatype; - - DBTableEntry dbtableEntry; - DBIndexItem dbindexItem; - DBTableDef dbtableDef; -} YYSTYPE; -/* Line 1318 of yacc.c. */ -#line 293 "grammar.eh" -# define yystype YYSTYPE /* obsolescent; will be withdrawn */ -# define YYSTYPE_IS_DECLARED 1 -# define YYSTYPE_IS_TRIVIAL 1 -#endif - -extern YYSTYPE yylval; - -#if ! defined (YYLTYPE) && ! defined (YYLTYPE_IS_DECLARED) -typedef struct YYLTYPE -{ - int first_line; - int first_column; - int last_line; - int last_column; -} YYLTYPE; -# define yyltype YYLTYPE /* obsolescent; will be withdrawn */ -# define YYLTYPE_IS_DECLARED 1 -# define YYLTYPE_IS_TRIVIAL 1 -#endif - -extern YYLTYPE yylloc; - - diff --git a/third_party/pygments/tests/examplefiles/test.erl b/third_party/pygments/tests/examplefiles/test.erl deleted file mode 100644 index 5b983e759..000000000 --- a/third_party/pygments/tests/examplefiles/test.erl +++ /dev/null @@ -1,169 +0,0 @@ --module(test). --export([listen/1, - handle_client/1, - maintain_clients/1, - start/1, - stop/0, - controller/1]). - --author("jerith"). - --define(TCP_OPTIONS,[list, {packet, 0}, {active, false}, {reuseaddr, true}]). - --record(player, {name=none, socket, mode}). - -%% To allow incoming connections, we need to listen on a TCP port. -%% This is also the entry point for our server as a whole, so it -%% starts the client_manager process and gives it a name so the rest -%% of the code can get to it easily. - -listen(Port) -> - {ok, LSocket} = gen_tcp:listen(Port, ?TCP_OPTIONS), - register(client_manager, spawn(?MODULE, maintain_clients, [[]])), - do_accept(LSocket). - -%% Accepting a connection gives us a connection socket with the -%% newly-connected client on the other end. Since we want to accept -%% more than one client, we spawn a new process for each and then wait -%% for another connection on our listening socket. - -do_accept(LSocket) -> - case gen_tcp:accept(LSocket) of - {ok, Socket} -> - spawn(?MODULE, handle_client, [Socket]), - client_manager ! {connect, Socket}; - {error, Reason} -> - io:format("Socket accept error: ~s~n", [Reason]) - end, - do_accept(LSocket). - -%% All the client-socket process needs to do is wait for data and -%% forward it to the client_manager process which decides what to do -%% with it. If the client disconnects, we let client_manager know and -%% then quietly go away. - -handle_client(Socket) -> - case gen_tcp:recv(Socket, 0) of - {ok, Data} -> - client_manager ! {data, Socket, Data}, - handle_client(Socket); - {error, closed} -> - client_manager ! {disconnect, Socket} - end. - -%% This is the main loop of the client_manager process. It maintains -%% the list of "players" and calls the handler for client input. - -maintain_clients(Players) -> - io:format("Players:~n", []), - lists:foreach(fun(P) -> io:format(">>> ~w~n", [P]) end, Players), - receive - {connect, Socket} -> - Player = #player{socket=Socket, mode=connect}, - send_prompt(Player), - io:format("client connected: ~w~n", [Player]), - NewPlayers = [Player | Players]; - {disconnect, Socket} -> - Player = find_player(Socket, Players), - io:format("client disconnected: ~w~n", [Player]), - NewPlayers = lists:delete(Player, Players); - {data, Socket, Data} -> - Player = find_player(Socket, Players), - NewPlayers = parse_data(Player, Players, Data), - NewPlayer = find_player(Socket, NewPlayers), - send_prompt(NewPlayer) - end, - maintain_clients(NewPlayers). - -%% find_player is a utility function to get a player record associated -%% with a particular socket out of the player list. - -find_player(Socket, Players) -> - {value, Player} = lists:keysearch(Socket, #player.socket, Players), - Player. - -%% delete_player returns the player list without the given player. It -%% deletes the player from the list based on the socket rather than -%% the whole record because the list might hold a different version. - -delete_player(Player, Players) -> - lists:keydelete(Player#player.socket, #player.socket, Players). - -%% Sends an appropriate prompt to the player. Currently the only -%% prompt we send is the initial "Name: " when the player connects. - -send_prompt(Player) -> - case Player#player.mode of - connect -> - gen_tcp:send(Player#player.socket, "Name: "); - active -> - ok - end. - -%% Sends the given data to all players in active mode. - -send_to_active(Prefix, Players, Data) -> - ActivePlayers = lists:filter(fun(P) -> P#player.mode == active end, - Players), - lists:foreach(fun(P) -> gen_tcp:send(P#player.socket, Prefix ++ Data) end, - ActivePlayers), - ok. - -%% We don't really do much parsing, but that will probably change as -%% more features are added. Currently this handles naming the player -%% when he first connects and treats everything else as a message to -%% send. - -parse_data(Player, Players, Data) -> - case Player#player.mode of - active -> - send_to_active(Player#player.name ++ ": ", - delete_player(Player, Players), Data), - Players; - connect -> - UPlayer = Player#player{name=bogostrip(Data), mode=active}, - [UPlayer | delete_player(Player, Players)] - end. - -%% Utility methods to clean up the name before we apply it. Called -%% bogostrip rather than strip because it returns the first continuous -%% block of non-matching characters rather stripping matching -%% characters off the front and back. - -bogostrip(String) -> - bogostrip(String, "\r\n\t "). - -bogostrip(String, Chars) -> - LStripped = string:substr(String, string:span(String, Chars)+1), - string:substr(LStripped, 1, string:cspan(LStripped, Chars)). - -%% Here we have some extra code to test other bits of pygments' Erlang -%% lexer. - -get_timestamp() -> - {{Year,Month,Day},{Hour,Min,Sec}} = erlang:universaltime(), - lists:flatten(io_lib:format( - "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", - [Year, Month, Day, Hour, Min, Sec])). - -a_binary() -> - << 100:16/integer, 16#7f >>. - -a_list_comprehension() -> - [X*2 || X <- [1,2,3]]. - -map(Fun, [H|T]) -> - [Fun(H) | map(Fun, T)]; - -map(Fun, []) -> - []. - -%% pmap, just because it's cool. - -pmap(F, L) -> - Parent = self(), - [receive {Pid, Result} -> - Result - end || Pid <- [spawn(fun() -> - Parent ! {self(), F(X)} - end) || X <- L]]. diff --git a/third_party/pygments/tests/examplefiles/test.evoque b/third_party/pygments/tests/examplefiles/test.evoque deleted file mode 100644 index 5a98d3bb8..000000000 --- a/third_party/pygments/tests/examplefiles/test.evoque +++ /dev/null @@ -1,33 +0,0 @@ -$overlay{name=site_base} - -$begin{table_row} - $for{ col in row } - ${col}\ - $else - empty row - $rof -$end{table_row} - - - $for{ i, row in enumerate(rows) } - #[ "odd" rows get a special style ]# - $evoque{#table_row} - $evoque{ - #table_row - } - $evoque{'#table_row'} - $evoque{ '#table_row', collection=None, quoting="str"} - $evoque{name="#table_row"} - $evoque{name=var_table_row} - $evoque{%#table_row%} - $evoque{% #table_row %} - - $rof -
    - -$evoque{disclaimer, collection="legals"} -$evoque{ disclaimer , collection="legals", abc=123} -$evoque{% disclaimer, collection="legals"%} - -$test{% site_base="site.html", - rows=[("a", "b", 3.0, {"one":1}, "", "i", "j")] %} diff --git a/third_party/pygments/tests/examplefiles/test.fan b/third_party/pygments/tests/examplefiles/test.fan deleted file mode 100644 index 00e80b608..000000000 --- a/third_party/pygments/tests/examplefiles/test.fan +++ /dev/null @@ -1,818 +0,0 @@ -// -// Copyright (c) 2008, Brian Frank and Andy Frank -// Licensed under the Academic Free License version 3.0 -// -// History: -// 17 Nov 08 Brian Frank Creation -// - -using compiler - -** -** JavaBridge is the compiler plugin for bringing Java -** classes into the Fantom type system. -** -class JavaBridge : CBridge -{ - -////////////////////////////////////////////////////////////////////////// -// Constructor -////////////////////////////////////////////////////////////////////////// - - ** - ** Construct a JavaBridge for current environment - ** - new make(Compiler c, ClassPath cp := ClassPath.makeForCurrent) - : super(c) - { - this.cp = cp - } - -////////////////////////////////////////////////////////////////////////// -// Namespace -////////////////////////////////////////////////////////////////////////// - - ** - ** Map a FFI "podName" to a Java package. - ** - override CPod resolvePod(Str name, Loc? loc) - { - // the empty package is used to represent primitives - if (name == "") return primitives - - // look for package name in classpatch - classes := cp.classes[name] - if (classes == null) - throw CompilerErr("Java package '$name' not found", loc) - - // map package to JavaPod - return JavaPod(this, name, classes) - } - - ** - ** Map class meta-data and Java members to Fantom slots - ** for the specified JavaType. - ** - virtual Void loadType(JavaType type, Str:CSlot slots) - { - JavaReflect.loadType(type, slots) - } - -////////////////////////////////////////////////////////////////////////// -// Call Resolution -////////////////////////////////////////////////////////////////////////// - - ** - ** Resolve a construction call to a Java constructor. - ** - override Expr resolveConstruction(CallExpr call) - { - // if the last argument is an it-block, then we know - // right away that we will not be passing it thru to Java, - // so strip it off to be appended as call to Obj.with - itBlock := call.args.last as ClosureExpr - if (itBlock != null && itBlock.isItBlock) - call.args.removeAt(-1) - else - itBlock = null - - // if this is an interop array like IntArray/int[] use make - // factory otherwise look for Java constructor called - JavaType base := call.target.ctype - if (base.isInteropArray) - call.method = base.method("make") - else - call.method = base.method("") - - // call resolution to deal with overloading - call = resolveCall(call) - - // we need to create an implicit target for the Java runtime - // to perform the new opcode to ensure it is on the stack - // before the args (we don't do this for interop Array classes) - if (!base.isInteropArray) - { - loc := call.loc - call.target = CallExpr.makeWithMethod(loc, null, base.newMethod) { synthetic=true } - } - - // if we stripped an it-block argument, - // add it as trailing call to Obj.with - if (itBlock != null) return itBlock.toWith(call) - return call - } - - ** - ** Resolve a construction chain call where a Fantom constructor - ** calls the super-class constructor. Type check the arguments - ** and insert any conversions needed. - ** - override Expr resolveConstructorChain(CallExpr call) - { - // we don't allow chaining to a this ctor for Java FFI - if (call.target.id !== ExprId.superExpr) - throw err("Must use super constructor call in Java FFI", call.loc) - - // route to a superclass constructor - JavaType base := call.target.ctype.deref - call.method = base.method("") - - // call resolution to deal with overloading - return resolveCall(call) - } - - ** - ** Given a dot operator slot access on the given foreign - ** base type, determine the appopriate slot to use based on - ** whether parens were used - ** base.name => noParens = true - ** base.name() => noParens = false - ** - ** In Java a given name could be bound to both a field and - ** a method. In this case we only resolve the field if - ** no parens are used. We also handle the special case of - ** Java annotations here because their element methods are - ** also mapped as Fantom fields (instance based mixin field). - ** - override CSlot? resolveSlotAccess(CType base, Str name, Bool noParens) - { - // first try to resolve as a field - field := base.field(name) - if (field != null) - { - // if no () we used and this isn't an annotation field - if (noParens && (field.isStatic || !base.isMixin)) - return field - - // if we did find a field, then make sure we use that - // field's parent type to resolve a method (becuase the - // base type might be a sub-class of a Java type in which - // case it is unware of field/method overloads) - return field.parent.method(name) - } - - // lookup method - return base.method(name) - } - - ** - ** Resolve a method call: try to find the best match - ** and apply any coercions needed. - ** - override CallExpr resolveCall(CallExpr call) - { - // try to match against all the overloaded methods - matches := CallMatch[,] - CMethod? m := call.method - while (m != null) - { - match := matchCall(call, m) - if (match != null) matches.add(match) - m = m is JavaMethod ? ((JavaMethod)m).next : null - } - - // if we have exactly one match use then use that one - if (matches.size == 1) return matches[0].apply(call) - - // if we have multiple matches; resolve to - // most specific match according to JLS rules - // TODO: this does not correct resolve when using Fantom implicit casting - if (matches.size > 1) - { - best := resolveMostSpecific(matches) - if (best != null) return best.apply(call) - } - - // zero or multiple ambiguous matches is a compiler error - s := StrBuf() - s.add(matches.isEmpty ? "Invalid args " : "Ambiguous call ") - s.add(call.name).add("(") - s.add(call.args.join(", ") |Expr arg->Str| { return arg.toTypeStr }) - s.add(")") - throw err(s.toStr, call.loc) - } - - ** - ** Check if the call matches the specified overload method. - ** If so return method and coerced args otherwise return null. - ** - internal CallMatch? matchCall(CallExpr call, CMethod m) - { - // first check if have matching numbers of args and params - args := call.args - if (m.params.size < args.size) return null - - // check if each argument is ok or can be coerced - isErr := false - newArgs := args.dup - m.params.each |CParam p, Int i| - { - if (i >= args.size) - { - // param has a default value, then that is ok - if (!p.hasDefault) isErr = true - } - else - { - // ensure arg fits parameter type (or auto-cast) - newArgs[i] = coerce(args[i], p.paramType) |->| { isErr = true } - } - } - if (isErr) return null - return CallMatch { it.method = m; it.args = newArgs } - } - - ** - ** Given a list of overloaed methods find the most specific method - ** according to Java Language Specification 15.11.2.2. The "informal - ** intuition" rule is that a method is more specific than another - ** if the first could be could be passed onto the second one. - ** - internal static CallMatch? resolveMostSpecific(CallMatch[] matches) - { - CallMatch? best := matches[0] - for (i:=1; iBool| - { - bp := b.method.params[i] - return ap.paramType.fits(bp.paramType) - } - } - -////////////////////////////////////////////////////////////////////////// -// Overrides -////////////////////////////////////////////////////////////////////////// - - ** - ** Called during Inherit step when a Fantom slot overrides a FFI slot. - ** Log and throw compiler error if there is a problem. - ** - override Void checkOverride(TypeDef t, CSlot base, SlotDef def) - { - // we don't allow Fantom to override Java methods with multiple - // overloaded versions since the Fantom type system can't actually - // override all the overloaded versions - jslot := base as JavaSlot - if (jslot?.next != null) - throw err("Cannot override Java overloaded method: '$jslot.name'", def.loc) - - // route to method override checking - if (base is JavaMethod && def is MethodDef) - checkMethodOverride(t, base, def) - } - - ** - ** Called on method/method overrides in the checkOverride callback. - ** - private Void checkMethodOverride(TypeDef t, JavaMethod base, MethodDef def) - { - // bail early if we know things aren't going to work out - if (base.params.size != def.params.size) return - - // if the return type is primitive or Java array and the - // Fantom declaration matches how it is inferred into the Fan - // type system, then just change the return type - the compiler - // will impliclty do all the return coercions - if (isOverrideInferredType(base.returnType, def.returnType)) - { - def.ret = def.inheritedRet = base.returnType - } - - // if any of the parameters is a primitive or Java array - // and the Fantom declaration matches how it is inferred into - // the Fantom type type, then change the parameter type to - // the Java override type and make the Fantom type a local - // variable: - // Java: void foo(int a) { ... } - // Fantom: Void foo(Int a) { ... } - // Result: Void foo(int a_$J) { Int a := a_$J; ... } - // - base.params.eachr |CParam bp, Int i| - { - dp := def.paramDefs[i] - if (!isOverrideInferredType(bp.paramType, dp.paramType)) return - - // add local variable: Int bar := bar_$J - local := LocalDefStmt(def.loc) - local.ctype = dp.paramType - local.name = dp.name - local.init = UnknownVarExpr(def.loc, null, dp.name + "_\$J") - def.code.stmts.insert(0, local) - - // rename parameter Int bar -> int bar_$J - dp.name = dp.name + "_\$J" - dp.paramType = bp.paramType - } - } - - ** - ** When overriding a Java method check if the base type is - ** is a Java primitive or array and the override definition is - ** matches how the Java type is inferred in the Fantom type system. - ** If we have a match return true and we'll swizzle things in - ** checkMethodOverride. - ** - static private Bool isOverrideInferredType(CType base, CType def) - { - // check if base class slot is a JavaType - java := base.toNonNullable as JavaType - if (java != null) - { - // allow primitives is it matches the inferred type - if (java.isPrimitive) return java.inferredAs == def - - // allow arrays if mapped as Foo[] -> Foo?[]? - if (java.isArray) return java.inferredAs == def.toNonNullable && def.isNullable - } - return false - } - -////////////////////////////////////////////////////////////////////////// -// CheckErrors -////////////////////////////////////////////////////////////////////////// - - ** - ** Called during CheckErrors step for a type which extends - ** a FFI class or implements any FFI mixins. - ** - override Void checkType(TypeDef def) - { - // can't subclass a primitive array like ByteArray/byte[] - if (def.base.deref is JavaType && def.base.deref->isInteropArray) - { - err("Cannot subclass from Java interop array: $def.base", def.loc) - return - } - - // we don't allow deep inheritance of Java classes because - // the Fantom constructor and Java constructor model don't match - // up past one level of inheritance - // NOTE: that that when we remove this restriction we need to - // test how field initialization works because instance$init - // is almost certain to break with the current emit design - javaBase := def.base - while (javaBase != null && !javaBase.isForeign) javaBase = javaBase.base - if (javaBase != null && javaBase !== def.base) - { - err("Cannot subclass Java class more than one level: $javaBase", def.loc) - return - } - - // ensure that when we map Fantom constructors to Java - // constructors that we don't have duplicate signatures - ctors := def.ctorDefs - ctors.each |MethodDef a, Int i| - { - ctors.each |MethodDef b, Int j| - { - if (i > j && areParamsSame(a, b)) - err("Duplicate Java FFI constructor signatures: '$b.name' and '$a.name'", a.loc) - } - } - } - - ** - ** Do the two methods have the exact same parameter types. - ** - static Bool areParamsSame(CMethod a, CMethod b) - { - if (a.params.size != b.params.size) return false - for (i:=0; i| { fits=false } - return fits - } - - ** - ** Coerce expression to expected type. If not a type match - ** then run the onErr function. - ** - override Expr coerce(Expr expr, CType expected, |->| onErr) - { - // handle easy case - actual := expr.ctype - expected = expected.deref - if (actual == expected) return expr - - // handle null literal - if (expr.id === ExprId.nullLiteral && expected.isNullable) - return expr - - // handle Fantom to Java primitives - if (expected.pod == primitives) - return coerceToPrimitive(expr, expected, onErr) - - // handle Java primitives to Fan - if (actual.pod == primitives) - return coerceFromPrimitive(expr, expected, onErr) - - // handle Java array to Fantom list - if (actual.name[0] == '[') - return coerceFromArray(expr, expected, onErr) - - // handle Fantom list to Java array - if (expected.name[0] == '[') - return coerceToArray(expr, expected, onErr) - - // handle sys::Func -> Java interface - if (actual is FuncType && expected.isMixin && expected.toNonNullable is JavaType) - return coerceFuncToInterface(expr, expected.toNonNullable, onErr) - - // handle special classes and interfaces for built-in Fantom - // classes which actually map directly to Java built-in types - if (actual.isBool && boolTypes.contains(expected.toNonNullable.signature)) return box(expr) - if (actual.isInt && intTypes.contains(expected.toNonNullable.signature)) return box(expr) - if (actual.isFloat && floatTypes.contains(expected.toNonNullable.signature)) return box(expr) - if (actual.isDecimal && decimalTypes.contains(expected.toNonNullable.signature)) return expr - if (actual.isStr && strTypes.contains(expected.toNonNullable.signature)) return expr - - // use normal Fantom coercion behavior - return super.coerce(expr, expected, onErr) - } - - ** - ** Ensure value type is boxed. - ** - private Expr box(Expr expr) - { - if (expr.ctype.isVal) - return TypeCheckExpr.coerce(expr, expr.ctype.toNullable) - else - return expr - } - - ** - ** Coerce a fan expression to a Java primitive (other - ** than the ones we support natively) - ** - Expr coerceToPrimitive(Expr expr, JavaType expected, |->| onErr) - { - actual := expr.ctype - - // sys::Int (long) -> int, short, byte - if (actual.isInt && expected.isPrimitiveIntLike) - return TypeCheckExpr.coerce(expr, expected) - - // sys::Float (double) -> float - if (actual.isFloat && expected.isPrimitiveFloat) - return TypeCheckExpr.coerce(expr, expected) - - // no coercion - type error - onErr() - return expr - } - - ** - ** Coerce a Java primitive to a Fantom type. - ** - Expr coerceFromPrimitive(Expr expr, CType expected, |->| onErr) - { - actual := (JavaType)expr.ctype - - // int, short, byte -> sys::Int (long) - if (actual.isPrimitiveIntLike) - { - if (expected.isInt || expected.isObj) - return TypeCheckExpr.coerce(expr, expected) - } - - // float -> sys::Float (float) - if (actual.isPrimitiveFloat) - { - if (expected.isFloat || expected.isObj) - return TypeCheckExpr.coerce(expr, expected) - } - - // no coercion - type error - onErr() - return expr - } - - ** - ** Coerce a Java array to a Fantom list. - ** - Expr coerceFromArray(Expr expr, CType expected, |->| onErr) - { - actual := (JavaType)expr.ctype.toNonNullable - - // if expected is array type - if (expected is JavaType && ((JavaType)expected).isArray) - if (actual.arrayOf.fits(((JavaType)expected).arrayOf)) return expr - - // if expected is Obj - if (expected.isObj) return arrayToList(expr, actual.inferredArrayOf) - - // if expected is list type - if (expected.toNonNullable is ListType) - { - expectedOf := ((ListType)expected.toNonNullable).v - if (actual.inferredArrayOf.fits(expectedOf)) return arrayToList(expr, expectedOf) - } - - // no coercion available - onErr() - return expr - } - - ** - ** Generate List.make(of, expr) where expr is Object[] - ** - private Expr arrayToList(Expr expr, CType of) - { - loc := expr.loc - ofExpr := LiteralExpr(loc, ExprId.typeLiteral, ns.typeType, of) - call := CallExpr.makeWithMethod(loc, null, listMakeFromArray, [ofExpr, expr]) - call.synthetic = true - return call - } - - ** - ** Coerce a Fantom list to Java array. - ** - Expr coerceToArray(Expr expr, CType expected, |->| onErr) - { - loc := expr.loc - expectedOf := ((JavaType)expected.toNonNullable).inferredArrayOf - actual := expr.ctype - - // if actual is list type - if (actual.toNonNullable is ListType) - { - actualOf := ((ListType)actual.toNonNullable).v - if (actualOf.fits(expectedOf)) - { - // (Foo[])list.asArray(cls) - clsLiteral := CallExpr.makeWithMethod(loc, null, JavaType.classLiteral(this, expectedOf)) - asArray := CallExpr.makeWithMethod(loc, expr, listAsArray, [clsLiteral]) - return TypeCheckExpr.coerce(asArray, expected) - } - } - - // no coercion available - onErr() - return expr - } - - ** - ** Attempt to coerce a parameterized sys::Func expr to a Java - ** interface if the interface supports exactly one matching method. - ** - Expr coerceFuncToInterface(Expr expr, JavaType expected, |->| onErr) - { - // check if we have exactly one abstract method in the expected type - loc := expr.loc - abstracts := expected.methods.findAll |CMethod m->Bool| { return m.isAbstract } - if (abstracts.size != 1) { onErr(); return expr } - method := abstracts.first - - // check if we have a match - FuncType funcType := (FuncType)expr.ctype - if (!isFuncToInterfaceMatch(funcType, method)) { onErr(); return expr } - - // check if we've already generated a wrapper for this combo - key := "${funcType.signature}+${method.qname}" - ctor := funcWrappers[key] - if (ctor == null) - { - ctor = generateFuncToInterfaceWrapper(expr.loc, funcType, expected, method) - funcWrappers[key] = ctor - } - - // replace expr with FuncWrapperX(expr) - call := CallExpr.makeWithMethod(loc, null, ctor, [expr]) - call.synthetic = true - return call - } - - ** - ** Return if the specified function type can be used to implement - ** the specified interface method. - ** - Bool isFuncToInterfaceMatch(FuncType funcType, CMethod method) - { - // sanity check to map to callX method - can't handle more than 8 args - if (method.params.size > 8) return false - - // check if method is match for function; first check is that - // method must supply all the arguments required by the function - if (funcType.params.size > method.params.size) return false - - // check that func return type fits method return - retOk := method.returnType.isVoid || fits(funcType.ret, method.returnType) - if (!retOk) return false - - // check all the method parameters fit the function parameters - paramsOk := funcType.params.all |CType f, Int i->Bool| { return fits(f, method.params[i].paramType) } - if (!paramsOk) return false - - return true - } - - ** - ** Generate the wrapper which implements the specified expected interface - ** and overrides the specified method which calls the function. - ** - CMethod generateFuncToInterfaceWrapper(Loc loc, FuncType funcType, CType expected, CMethod method) - { - // Fantom: func typed as |Str| - // Java: interface Foo { void bar(String) } - // Result: FuncWrapperX(func) - // - // class FuncWrapperX : Foo - // { - // new make(Func f) { _func = f } - // override Void bar(Str a) { _func.call(a) } - // Func _func - // } - - // generate FuncWrapper class - name := "FuncWrapper" + funcWrappers.size - cls := TypeDef(ns, loc, compiler.types[0].unit, name, FConst.Internal + FConst.Synthetic) - cls.base = ns.objType - cls.mixins = [expected] - addTypeDef(cls) - - // generate FuncWrapper._func field - field := FieldDef(loc, cls) - ((SlotDef)field).name = "_func" - ((DefNode)field).flags = FConst.Private + FConst.Storage + FConst.Synthetic - field.fieldType = funcType - cls.addSlot(field) - - // generate FuncWrapper.make constructor - ctor := MethodDef(loc, cls, "make", FConst.Internal + FConst.Ctor + FConst.Synthetic) - ctor.ret = ns.voidType - ctor.paramDefs = [ParamDef(loc, funcType, "f")] - ctor.code = Block.make(loc) - ctor.code.stmts.add(BinaryExpr.makeAssign( - FieldExpr(loc, ThisExpr(loc), field), - UnknownVarExpr(loc, null, "f")).toStmt) - ctor.code.stmts.add(ReturnStmt.make(loc)) - cls.addSlot(ctor) - - // generate FuncWrapper override of abstract method - over := MethodDef(loc, cls, method.name, FConst.Public + FConst.Override + FConst.Synthetic) - over.ret = method.returnType - over.paramDefs = ParamDef[,] - over.code = Block.make(loc) - callArity := "call" - call := CallExpr.makeWithMethod(loc, FieldExpr(loc, ThisExpr(loc), field), funcType.method(callArity)) - method.params.each |CParam param, Int i| - { - paramName := "p$i" - over.params.add(ParamDef(loc, param.paramType, paramName)) - if (i < funcType.params.size) - call.args.add(UnknownVarExpr(loc, null, paramName)) - } - if (method.returnType.isVoid) - over.code.stmts.add(call.toStmt).add(ReturnStmt(loc)) - else - over.code.stmts.add(ReturnStmt(loc, call)) - cls.addSlot(over) - - // return the ctor which we use for coercion - return ctor - } - -////////////////////////////////////////////////////////////////////////// -// Reflection -////////////////////////////////////////////////////////////////////////// - - ** - ** Get a CMethod representation for 'List.make(Type, Object[])' - ** - once CMethod listMakeFromArray() - { - return JavaMethod( - this.ns.listType, - "make", - FConst.Public + FConst.Static, - this.ns.listType.toNullable, - [ - JavaParam("of", this.ns.typeType), - JavaParam("array", objectArrayType) - ]) - } - - ** - ** Get a CMethod representation for 'Object[] List.asArray()' - ** - once CMethod listAsArray() - { - return JavaMethod( - this.ns.listType, - "asArray", - FConst.Public, - objectArrayType, - [JavaParam("cls", classType)]) - } - - ** - ** Get a CType representation for 'java.lang.Class' - ** - once JavaType classType() - { - return ns.resolveType("[java]java.lang::Class") - } - - ** - ** Get a CType representation for 'java.lang.Object[]' - ** - once JavaType objectArrayType() - { - return ns.resolveType("[java]java.lang::[Object") - } - -////////////////////////////////////////////////////////////////////////// -// Fields -////////////////////////////////////////////////////////////////////////// - - const static Str[] boolTypes := Str[ - "[java]java.io::Serializable", - "[java]java.lang::Comparable", - ] - - const static Str[] intTypes := Str[ - "[java]java.lang::Number", - "[java]java.io::Serializable", - "[java]java.lang::Comparable", - ] - - const static Str[] floatTypes := Str[ - "[java]java.lang::Number", - "[java]java.io::Serializable", - "[java]java.lang::Comparable", - ] - - const static Str[] decimalTypes := Str[ - "[java]java.lang::Number", - "[java]java.io::Serializable", - "[java]java.lang::Comparable", - ] - - const static Str[] strTypes := Str[ - "[java]java.io::Serializable", - "[java]java.lang::CharSequence", - "[java]java.lang::Comparable", - ] - - JavaPrimitives primitives := JavaPrimitives(this) - ClassPath cp - - private Str:CMethod funcWrappers := Str:CMethod[:] // funcType+method:ctor - -} - -************************************************************************** -** CallMatch -************************************************************************** - -internal class CallMatch -{ - CallExpr apply(CallExpr call) - { - call.args = args - call.method = method - call.ctype = method.isCtor ? method.parent : method.returnType - return call - } - - override Str toStr() { return method.signature } - - CMethod? method // matched method - Expr[]? args // coerced arguments -} \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/test.flx b/third_party/pygments/tests/examplefiles/test.flx deleted file mode 100644 index 4c8a667b4..000000000 --- a/third_party/pygments/tests/examplefiles/test.flx +++ /dev/null @@ -1,57 +0,0 @@ -type tiny = "%i8"; -type int = "%i32"; -typedef bool = 2; -fun add : int*int -> int = "%add"; -fun sub : int*int -> int = "%sub"; -fun eq : int*int -> bool = "%eq"; -fun lnot : bool -> bool = "%lnot"; -proc exit : int = "exit"; - -// comment 1 -/* - /* - foo bar - */ -asdas -*/ - -noinline fun foo (x:int) = { - val y = 6; - return x + y; -} - -noinline proc fake_exit (x:int) { - exit x; - return; -} - -noinline fun bar (x:int) = { - var y = 10; - noinline proc baz () { - y = 20; - return; - } - baz (); - return x + y; -} - -noinline fun x (a:int, b:int, c:tiny) = { - val x1 = a; - val x2 = b; - val x3 = c; - noinline fun y (d:int, e:int, f:tiny) = { - val y1 = x1; - val y2 = x2; - val y3 = f; - noinline fun z (g:int, h:int, i:tiny) = { - val z1 = x1; - val z2 = x2; - val z3 = i; - return z1; - } - return z (y1,y2,y3); - } - return y (x1,x2,x3); -} - -fake_exit $ (foo 2) + (bar 3) + (x (1,2,3t)); diff --git a/third_party/pygments/tests/examplefiles/test.gdc b/third_party/pygments/tests/examplefiles/test.gdc deleted file mode 100644 index c7e36b813..000000000 --- a/third_party/pygments/tests/examplefiles/test.gdc +++ /dev/null @@ -1,13 +0,0 @@ -# Execute the date dimension MAQL script -ExecuteMaql(maqlFile="examples/quotes/quote_date.maql"); - -# load the stock quotes data file -# the data file config has been generated -LoadCsv(csvDataFile="examples/quotes/quotes.csv", - header="true", - configFile="examples/quotes/quotes.config.xml"); - -# transfer the stock quotes data -TransferLastSnapshot(); - -LoadGoogleAnalytics(configFile="examples/ga/ga.config.xml",username="example@gmail.com",password="******",profileId="ga:7468896",dimensions="ga:date|ga:browser|ga:browserVersion|ga:country|ga:isMobile",metrics="ga:bounces|ga:newVisits|ga:pageViews|ga:visits",startDate="2008-01-01",endDate="2010-06-15"); diff --git a/third_party/pygments/tests/examplefiles/test.gradle b/third_party/pygments/tests/examplefiles/test.gradle deleted file mode 100644 index 0bc834c1e..000000000 --- a/third_party/pygments/tests/examplefiles/test.gradle +++ /dev/null @@ -1,20 +0,0 @@ -apply plugin: 'java' - -repositories { - mavenCentral() -} - -dependencies { - testCompile 'junit:junit:4.12' -} - -task sayHello << { - def x = SomeClass.worldString - println "Hello ${x}" -} - -private class SomeClass { - public static String getWorldString() { - return "world" - } -} diff --git a/third_party/pygments/tests/examplefiles/test.groovy b/third_party/pygments/tests/examplefiles/test.groovy deleted file mode 100644 index 903863d27..000000000 --- a/third_party/pygments/tests/examplefiles/test.groovy +++ /dev/null @@ -1,97 +0,0 @@ -// This source code comes from http://www.odelia-technologies.com/node/200 - -package com.odelia.groovy.simpleworkflow - - -class SimpleWorkflowEngine { - def workflowMap = [:] - def context = [:] - def beforeActivityName = 'beforeActivity' - def afterActivityName = 'afterActivity' - - SimpleWorkflowEngine(workflow, context = [:]) { - this.context = context - parseWorkflow(workflow) - } - - def parseWorkflow(workflow) { - workflowMap = new WorkflowParser().parse(workflow) - } - - def getActivityValue(activity) { - assert activity instanceof String - if (!workflowMap[activity]) - throw new RuntimeException("$activity activity doesn't exist") - workflowMap[activity] - } - - def execute(activity, pause) { - if (workflowMap[beforeActivityName]) { - getActivityValue(beforeActivityName)(context, activity) - } - - def activityValue = getActivityValue(activity) - - // Determine the next activity to execute - def nextActivity - switch (activityValue) { - case String: nextActivity = activityValue; break - case Closure: nextActivity = activityValue(context); break - case Class: nextActivity = activityValue.newInstance()(context) - } - - if (workflowMap[afterActivityName]) { - getActivityValue(afterActivityName)(context, activity, nextActivity) - } - - if (!pause && nextActivity) - call(nextActivity) - else - nextActivity - } - - def call(activity) { - execute(activity, false) - } - - def nextActivity(activity) { - execute(activity, true) - } - - static void main(String[] args) { - if (args.size() != 2) { - println 'Usage: com.odelia.groovy.simpleworkflow.SimpleWorkflowEngine ' - return - } - SimpleWorkflowEngine.newInstance(new File(args[0]))(args[1]) - } - -} - -private class WorkflowParser { - def map = [:] - - def methodMissing(String name, args) { - map[name] = args[0] - } - - def parse(Closure wf) { - wf.delegate = this - wf.resolveStrategy = Closure.DELEGATE_FIRST - wf() - map - } - - def workflow = { it -> - it.delegate = this - it.resolveStrategy = Closure.DELEGATE_FIRST - it() - } - - def parse(File workflowDef) { - def binding = new Binding([workflow: workflow]) - def shell = new GroovyShell(binding) - shell.evaluate(workflowDef) - map - } -} \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/test.html b/third_party/pygments/tests/examplefiles/test.html deleted file mode 100644 index b22f0c61f..000000000 --- a/third_party/pygments/tests/examplefiles/test.html +++ /dev/null @@ -1,339 +0,0 @@ - - - - - - -
    # -*- coding: utf-8 -*-
    -"""
    -    pocoo.pkg.core.acl
    -    ~~~~~~~~~~~~~~~~~~
    -
    -    Pocoo ACL System.
    -
    -"""
    -
    -from pocoo.db import meta
    -
    -from pocoo.pkg.core.forum import Site, Forum, Thread
    -from pocoo.pkg.core.user import User, Group
    -
    -from pocoo.pkg.core.db import users, groups, group_members, privileges, \
    -     forums, posts, acl_mapping, acl_subjects, acl_objects
    -
    -
    -class AclManager(object):
    -    """
    -    Manager object to manage ALCs.
    -    """
    -    STRONG_NO = -1
    -
    -    WEAK_NO = 0
    -    WEAK_YES = 1
    -    STRONG_YES = 2
    -
    -    def __init__(self, ctx, subject):
    -        self.ctx = ctx
    -
    -        self.subject = subject
    -        if isinstance(subject, User):
    -            self._type = 'user'
    -
    -        elif isinstance(subject, Group):
    -            self._type = 'group'
    -
    -        else:
    -            raise ValueError('neither user or group specified')
    -
    -    def allow(self, privilege, obj, force=False):
    -        """Allows the subject privilege on obj."""
    -
    -        return self._set(privilege, obj, 1 + bool(force))
    -
    -    def default(self, privilege, obj):
    -        """Sets the state for privilege on obj back to weak yes."""
    -
    -        return self._set(privilege, obj, 0)
    -
    -    def deny(self, privilege, obj, force=False):
    -        """Denies the subject privilege on obj."""
    -
    -        return self._set(privilege, obj, -1 - bool(force))
    -
    -    def can_access(self, privilege, obj):
    -        """Checks if the current subject with the required privilege
    -        somehow. Either directly or when the subject is a user and
    -        one of its groups can access it."""
    -
    -        #XXX: maybe this could be one big query instead of 4
    -        #XXX: this currently does not work correctly, therefore return True
    -        return True
    -
    -        if not isinstance(obj, (Forum, Thread, Site.__class__)):
    -            raise TypeError('obj must be a forum, thread or site')
    -        privilege = privilege.upper()
    -        s = self._get_subject_join().alias('s').c
    -
    -        def do_check(obj, tendency):
    -            db = self.ctx.engine
    -
    -            o = self._get_object_join(obj).alias('o').c
    -
    -            # self check
    -            r = db.execute(meta.select([acl_mapping.c.state],
    -                (acl_mapping.c.priv_id == privileges.c.priv_id) &
    -
    -                (acl_mapping.c.subject_id == s.subject_id) &
    -                (acl_mapping.c.object_id == o.object_id) &
    -
    -                (privileges.c.name == privilege)
    -            ))
    -            row = r.fetchone()
    -            if row is not None:
    -                if row['state'] in (self.STRONG_NO, self.STRONG_YES):
    -                    return row['state'] == self.STRONG_YES
    -
    -                tendency = row['state']
    -
    -            # if the controlled subject is a user check all groups
    -            if isinstance(self.subject, User):
    -                r = db.execute(meta.select([acl_mapping.c.state],
    -                    (acl_mapping.c.object_id == o.object_id) &
    -
    -                    (acl_mapping.c.subject_id == groups.c.subject_id) &
    -
    -                    (groups.c.group_id == group_members.c.group_id) &
    -
    -                    (group_members.c.user_id == self.subject.user_id)
    -                ))
    -                while True:
    -                    row = r.fetchone()
    -                    if row is None:
    -                        break
    -
    -                    state = row[0]
    -                    if state in (self.STRONG_YES, self.STRONG_NO):
    -                        return state == self.STRONG_YES
    -
    -                    if tendency is None:
    -                        tendency = state
    -                    elif tendency == self.WEAK_NO and state == self.WEAK_YES:
    -                        tendency = self.WEAK_YES
    -
    -            # check related objects
    -            if isinstance(obj, Thread):
    -                return do_check(obj.forum, tendency)
    -            elif isinstance(obj, Forum):
    -                return do_check(Site, tendency)
    -            else:
    -                return tendency
    -
    -        return do_check(obj, None) in (self.WEAK_YES, self.STRONG_YES)
    -
    -    def _set(self, privilege, obj, state):
    -        """Helper functions for settings privileges."""
    -
    -        privilege = privilege.upper()
    -        if self.subject.subject_id is None:
    -            self._bootstrap()
    -        if obj.object_id is None:
    -            self._bootstrap_object(obj)
    -        # special state "0" which means delete
    -
    -        if not state:
    -            p = meta.select([privileges.c.priv_id], privileges.c.name == privilege)
    -            self.ctx.engine.execute(acl_mapping.delete(
    -                (acl_mapping.c.priv_id == p.c.priv_id) &
    -
    -                (acl_mapping.c.subject_id == self.subject.subject_id) &
    -
    -                (acl_mapping.c.object_id == obj.object_id)
    -            ))
    -            return
    -        # touch privilege and check existing mapping
    -
    -        priv_id = self._fetch_privilege(privilege)
    -        r = self.ctx.engine.execute(meta.select([acl_mapping.c.state],
    -            (acl_mapping.c.priv_id == priv_id) &
    -
    -            (acl_mapping.c.subject_id == self.subject.subject_id) &
    -
    -            (acl_mapping.c.object_id == obj.object_id)
    -        ))
    -        row = r.fetchone()
    -        if row is not None:
    -            # this rule exists already
    -
    -            if row['state'] == state:
    -                return
    -            # goddamn, same rule - different state, delete old first
    -            self._set(privilege, obj, 0)
    -        # insert new rule
    -
    -        self.ctx.engine.execute(acl_mapping.insert(),
    -            priv_id = priv_id,
    -            subject_id = self.subject.subject_id,
    -            object_id = obj.object_id,
    -            state = state
    -
    -        )
    -
    -    def _bootstrap(self):
    -        """This method is automatically called when subject_id is
    -        None and an subject_id is required."""
    -        r = self.ctx.engine.execute(acl_subjects.insert(),
    -            subject_type = self._type
    -
    -        )
    -        self.subject.subject_id = r.last_inserted_ids()[0]
    -        self.subject.save()
    -
    -    def _bootstrap_object(self, obj):
    -        """Like _bootstrap but works for objects."""
    -
    -        objtype = self._get_object_type(obj)
    -        r = self.ctx.engine.execute(acl_objects.insert(),
    -            object_type = objtype
    -
    -        )
    -        obj.object_id = r.last_inserted_ids()[0]
    -        obj.save()
    -
    -    def _get_object_type(self, obj):
    -        if isinstance(obj, Forum):
    -            return 'forum'
    -
    -        elif isinstance(obj, Thread):
    -            return 'thread'
    -        elif obj is Site:
    -            return 'site'
    -
    -        raise TypeError('obj isn\'t a forum or thread')
    -
    -    def _get_object_join(self, obj):
    -        """Returns a subjoin for the object id."""
    -
    -        t = self._get_object_type(obj)
    -        if t == 'forum':
    -            return meta.select([forums.c.object_id],
    -                forums.c.forum_id == obj.forum_id
    -
    -            )
    -        elif t == 'thread':
    -            return meta.select([posts.c.object_id],
    -                posts.c.post_id == obj.post_id
    -
    -            )
    -        else:
    -            # XXX: it works ^^
    -            # i really want something like meta.select('0 as group_id')
    -            class Fake(object):
    -                def alias(self, n):
    -                    class _C(object):
    -                        class c(object):
    -                            object_id = 0
    -
    -                    return _C
    -            return Fake()
    -
    -    def _get_subject_join(self):
    -        """Returns a subjoin for the subject id."""
    -
    -        if self._type == 'user':
    -            return meta.select([users.c.subject_id],
    -                users.c.user_id == self.subject.user_id
    -
    -            )
    -        return meta.select([groups.c.subject_id],
    -            groups.c.group_id == self.subject.group_id
    -
    -        )
    -
    -    def _fetch_privilege(self, name):
    -        """Returns the priv_id for the given privilege. If it
    -        doesn\'t exist by now the system will create a new
    -        privilege."""
    -        r = self.ctx.engine.execute(meta.select([privileges.c.priv_id],
    -            privileges.c.name == name
    -
    -        ))
    -        row = r.fetchone()
    -        if row is not None:
    -            return row[0]
    -        r = self.ctx.engine.execute(privileges.insert(),
    -            name = name
    -
    -        )
    -        return r.last_inserted_ids()[0]
    -
    -    def __repr__(self):
    -        if self._type == 'user':
    -            id_ = self.subject.user_id
    -
    -        else:
    -            id_ = self.subject.group_id
    -        if self.subject.subject_id is None:
    -            return '<%s %s:%d inactive>' % (
    -                self.__class__.__name__,
    -                self._type,
    -                id_
    -
    -            )
    -        return '<%s %s:%d active as %d>' % (
    -            self.__class__.__name__,
    -            self._type,
    -            id_,
    -            self.subject.subject_id
    -
    -        )
    -
    diff --git a/third_party/pygments/tests/examplefiles/test.idr b/third_party/pygments/tests/examplefiles/test.idr
    deleted file mode 100644
    index fd008d31c..000000000
    --- a/third_party/pygments/tests/examplefiles/test.idr
    +++ /dev/null
    @@ -1,101 +0,0 @@
    -module Main
    -
    -data Ty = TyInt | TyBool | TyFun Ty Ty
    -
    -interpTy : Ty -> Type
    -interpTy TyInt       = Int
    -interpTy TyBool      = Bool
    -interpTy (TyFun s t) = interpTy s -> interpTy t
    -
    -using (G : Vect n Ty)
    -
    -  data Env : Vect n Ty -> Type where
    -      Nil  : Env Nil
    -      (::) : interpTy a -> Env G -> Env (a :: G)
    -
    -  data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where
    -      stop : HasType fZ (t :: G) t
    -      pop  : HasType k G t -> HasType (fS k) (u :: G) t
    -
    -  lookup : HasType i G t -> Env G -> interpTy t
    -  lookup stop    (x :: xs) = x
    -  lookup (pop k) (x :: xs) = lookup k xs
    -
    -  data Expr : Vect n Ty -> Ty -> Type where
    -      Var : HasType i G t -> Expr G t
    -      Val : (x : Int) -> Expr G TyInt
    -      Lam : Expr (a :: G) t -> Expr G (TyFun a t)
    -      App : Expr G (TyFun a t) -> Expr G a -> Expr G t
    -      Op  : (interpTy a -> interpTy b -> interpTy c) -> Expr G a -> Expr G b ->
    -            Expr G c
    -      If  : Expr G TyBool -> Expr G a -> Expr G a -> Expr G a
    -      Bind : Expr G a -> (interpTy a -> Expr G b) -> Expr G b
    -
    -  dsl expr
    -      lambda      = Lam
    -      variable    = Var
    -      index_first = stop
    -      index_next  = pop
    -
    -  (<$>) : |(f : Expr G (TyFun a t)) -> Expr G a -> Expr G t
    -  (<$>) = \f, a => App f a
    -
    -  pure : Expr G a -> Expr G a
    -  pure = id
    -
    -  syntax IF [x] THEN [t] ELSE [e] = If x t e
    -
    -  (==) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool
    -  (==) = Op (==)
    -
    -  (<) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool
    -  (<) = Op (<)
    -
    -  instance Num (Expr G TyInt) where
    -    (+) x y = Op (+) x y
    -    (-) x y = Op (-) x y
    -    (*) x y = Op (*) x y
    -
    -    abs x = IF (x < 0) THEN (-x) ELSE x
    -
    -    fromInteger = Val . fromInteger
    -
    -  ||| Evaluates an expression in the given context.
    -  interp : Env G -> {static} Expr G t -> interpTy t
    -  interp env (Var i)     = lookup i env
    -  interp env (Val x)     = x
    -  interp env (Lam sc)    = \x => interp (x :: env) sc
    -  interp env (App f s)   = (interp env f) (interp env s)
    -  interp env (Op op x y) = op (interp env x) (interp env y)
    -  interp env (If x t e)  = if (interp env x) then (interp env t) else (interp env e)
    -  interp env (Bind v f)  = interp env (f (interp env v))
    -
    -  eId : Expr G (TyFun TyInt TyInt)
    -  eId = expr (\x => x)
    -
    -  eTEST : Expr G (TyFun TyInt (TyFun TyInt TyInt))
    -  eTEST = expr (\x, y => y)
    -
    -  eAdd : Expr G (TyFun TyInt (TyFun TyInt TyInt))
    -  eAdd = expr (\x, y => Op (+) x y)
    -
    -  eDouble : Expr G (TyFun TyInt TyInt)
    -  eDouble = expr (\x => App (App eAdd x) (Var stop))
    -
    -  eFac : Expr G (TyFun TyInt TyInt)
    -  eFac = expr (\x => IF x == 0 THEN 1 ELSE [| eFac (x - 1) |] * x)
    -
    -testFac : Int
    -testFac = interp [] eFac 4
    -
    ---testFacTooBig : Int
    ---testFacTooBig = interp [] eFac 100000
    -
    - {-testFacTooBig2 : Int
    -testFacTooBig2 = interp [] eFac 1000
    --}
    -
    -main : IO ()
    -main = print testFac
    -
    -
    diff --git a/third_party/pygments/tests/examplefiles/test.ini b/third_party/pygments/tests/examplefiles/test.ini
    deleted file mode 100644
    index a447803de..000000000
    --- a/third_party/pygments/tests/examplefiles/test.ini
    +++ /dev/null
    @@ -1,10 +0,0 @@
    -[section]
    -
    -foo = bar
    -continued = foo
    -  baz
    -conttwo =
    -  foo
    -; comment
    -# comment
    -
    diff --git a/third_party/pygments/tests/examplefiles/test.java b/third_party/pygments/tests/examplefiles/test.java
    deleted file mode 100644
    index 64c08531f..000000000
    --- a/third_party/pygments/tests/examplefiles/test.java
    +++ /dev/null
    @@ -1,653 +0,0 @@
    -/*
    - * Created on 13-Mar-2004
    - * Created by James Yeh
    - * Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved.
    - *
    - * 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 2
    - * 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, write to the Free Software
    - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    - * 
    - * AELITIS, SAS au capital de 46,603.30 euros
    - * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
    - *
    - */
    -
    -package org.gudy.azureus2.platform.macosx;
    -
    -import org.gudy.azureus2.core3.logging.*;
    -import org.gudy.azureus2.core3.util.AEMonitor;
    -import org.gudy.azureus2.core3.util.Debug;
    -import org.gudy.azureus2.core3.util.SystemProperties;
    -import org.gudy.azureus2.platform.PlatformManager;
    -import org.gudy.azureus2.platform.PlatformManagerCapabilities;
    -import org.gudy.azureus2.platform.PlatformManagerListener;
    -import org.gudy.azureus2.platform.macosx.access.jnilib.OSXAccess;
    -
    -import org.gudy.azureus2.plugins.platform.PlatformManagerException;
    -
    -import java.io.BufferedReader;
    -import java.io.File;
    -import java.io.IOException;
    -import java.io.InputStreamReader;
    -import java.text.MessageFormat;
    -import java.util.HashSet;
    -
    -
    -/**
    - * Performs platform-specific operations with Mac OS X
    - *
    - * @author James Yeh
    - * @version 1.0 Initial Version
    - * @see PlatformManager
    - */
    -public class PlatformManagerImpl implements PlatformManager
    -{
    -    private static final LogIDs LOGID = LogIDs.CORE;
    -
    -    protected static PlatformManagerImpl singleton;
    -    protected static AEMonitor class_mon = new AEMonitor("PlatformManager");
    -
    -    private static final String USERDATA_PATH = new File(System.getProperty("user.home") + "/Library/Application Support/").getPath();
    -
    -    //T: PlatformManagerCapabilities
    -    private final HashSet capabilitySet = new HashSet();
    -
    -    /**
    -     * Gets the platform manager singleton, which was already initialized
    -     */
    -    public static PlatformManagerImpl getSingleton()
    -    {
    -        return singleton;
    -    }
    -
    -    /**
    -     * Tries to enable cocoa-java access and instantiates the singleton
    -     */
    -    static
    -    {
    -        initializeSingleton();
    -    }
    -
    -    /**
    -     * Instantiates the singleton
    -     */
    -    private static void initializeSingleton()
    -    {
    -        try
    -        {
    -            class_mon.enter();
    -            singleton = new PlatformManagerImpl();
    -        }
    -        catch (Throwable e)
    -        {
    -        	Logger.log(new LogEvent(LOGID, "Failed to initialize platform manager"
    -					+ " for Mac OS X", e));
    -        }
    -        finally
    -        {
    -            class_mon.exit();
    -        }
    -    }
    -
    -    /**
    -     * Creates a new PlatformManager and initializes its capabilities
    -     */
    -    public PlatformManagerImpl()
    -    {
    -        capabilitySet.add(PlatformManagerCapabilities.RecoverableFileDelete);
    -        capabilitySet.add(PlatformManagerCapabilities.ShowFileInBrowser);
    -        capabilitySet.add(PlatformManagerCapabilities.ShowPathInCommandLine);
    -        capabilitySet.add(PlatformManagerCapabilities.CreateCommandLineProcess);
    -        capabilitySet.add(PlatformManagerCapabilities.GetUserDataDirectory);
    -        capabilitySet.add(PlatformManagerCapabilities.UseNativeScripting);
    -        capabilitySet.add(PlatformManagerCapabilities.PlaySystemAlert);
    -        
    -        if (OSXAccess.isLoaded()) {
    -	        capabilitySet.add(PlatformManagerCapabilities.GetVersion);
    -        }
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public int getPlatformType()
    -    {
    -        return PT_MACOSX;
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public String getVersion() throws PlatformManagerException
    -    {
    -    	if (!OSXAccess.isLoaded()) {
    -        throw new PlatformManagerException("Unsupported capability called on platform manager");
    -    	}
    -    	
    -    	return OSXAccess.getVersion();
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     * @see org.gudy.azureus2.core3.util.SystemProperties#getUserPath()
    -     */
    -    public String getUserDataDirectory() throws PlatformManagerException
    -    {
    -        return USERDATA_PATH;
    -    }
    -
    -	public File
    -	getLocation(
    -		long	location_id )
    -	
    -		throws PlatformManagerException
    -	{
    -		if ( location_id == LOC_USER_DATA ){
    -			
    -			return( new File( USERDATA_PATH ));
    -		}
    -		
    -		return( null );
    -	}
    -    /**
    -     * Not implemented; returns True
    -     */
    -    public boolean isApplicationRegistered() throws PlatformManagerException
    -    {
    -        return true;
    -    }
    -
    -    
    -	public String
    -	getApplicationCommandLine()
    -		throws PlatformManagerException
    -	{
    -		try{	    
    -			String	bundle_path = System.getProperty("user.dir") +SystemProperties.SEP+ SystemProperties.getApplicationName() + ".app";
    -
    -			File osx_app_bundle = new File( bundle_path ).getAbsoluteFile();
    -			
    -			if( !osx_app_bundle.exists() ) {
    -				String msg = "OSX app bundle not found: [" +osx_app_bundle.toString()+ "]";
    -				System.out.println( msg );
    -				if (Logger.isEnabled())
    -					Logger.log(new LogEvent(LOGID, msg));		
    -				throw new PlatformManagerException( msg );
    -			}
    -			
    -			return "open -a \"" +osx_app_bundle.toString()+ "\"";
    -			//return osx_app_bundle.toString() +"/Contents/MacOS/JavaApplicationStub";
    -			
    -		}
    -		catch( Throwable t ){	
    -			t.printStackTrace();
    -			return null;
    -		}
    -	}
    -	
    -	
    -	public boolean
    -	isAdditionalFileTypeRegistered(
    -		String		name,				// e.g. "BitTorrent"
    -		String		type )				// e.g. ".torrent"
    -	
    -		throws PlatformManagerException
    -	{
    -	    throw new PlatformManagerException("Unsupported capability called on platform manager");
    -	}
    -	
    -	public void
    -	unregisterAdditionalFileType(
    -		String		name,				// e.g. "BitTorrent"
    -		String		type )				// e.g. ".torrent"
    -		
    -		throws PlatformManagerException
    -	{
    -		throw new PlatformManagerException("Unsupported capability called on platform manager");
    -	}
    -	
    -	public void
    -	registerAdditionalFileType(
    -		String		name,				// e.g. "BitTorrent"
    -		String		description,		// e.g. "BitTorrent File"
    -		String		type,				// e.g. ".torrent"
    -		String		content_type )		// e.g. "application/x-bittorrent"
    -	
    -		throws PlatformManagerException
    -	{
    -	   throw new PlatformManagerException("Unsupported capability called on platform manager");
    -	}
    -	
    -    /**
    -     * Not implemented; does nothing
    -     */
    -    public void registerApplication() throws PlatformManagerException
    -    {
    -        // handled by LaunchServices and/0r user interaction
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public void createProcess(String cmd, boolean inheritsHandles) throws PlatformManagerException
    -    {
    -        try
    -        {
    -            performRuntimeExec(cmd.split(" "));
    -        }
    -        catch (Throwable e)
    -        {
    -            throw new PlatformManagerException("Failed to create process", e);
    -        }
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public void performRecoverableFileDelete(String path) throws PlatformManagerException
    -    {
    -        File file = new File(path);
    -        if(!file.exists())
    -        {
    -	        	if (Logger.isEnabled())
    -							Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
    -									+ file.getName()));
    -            return;
    -        }
    -
    -        boolean useOSA = !NativeInvocationBridge.sharedInstance().isEnabled() || !NativeInvocationBridge.sharedInstance().performRecoverableFileDelete(file);
    -
    -        if(useOSA)
    -        {
    -            try
    -            {
    -                StringBuffer sb = new StringBuffer();
    -                sb.append("tell application \"");
    -                sb.append("Finder");
    -                sb.append("\" to move (posix file \"");
    -                sb.append(path);
    -                sb.append("\" as alias) to the trash");
    -
    -                performOSAScript(sb);
    -            }
    -            catch (Throwable e)
    -            {
    -                throw new PlatformManagerException("Failed to move file", e);
    -            }
    -        }
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public boolean hasCapability(PlatformManagerCapabilities capability)
    -    {
    -        return capabilitySet.contains(capability);
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public void dispose()
    -    {
    -        NativeInvocationBridge.sharedInstance().dispose();
    -    }
    -
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public void setTCPTOSEnabled(boolean enabled) throws PlatformManagerException
    -    {
    -        throw new PlatformManagerException("Unsupported capability called on platform manager");
    -    }
    -
    -	public void
    -    copyFilePermissions(
    -		String	from_file_name,
    -		String	to_file_name )
    -	
    -		throws PlatformManagerException
    -	{
    -	    throw new PlatformManagerException("Unsupported capability called on platform manager");		
    -	}
    -	
    -    /**
    -     * {@inheritDoc}
    -     */
    -    public void showFile(String path) throws PlatformManagerException
    -    {
    -        File file = new File(path);
    -        if(!file.exists())
    -        {
    -        	if (Logger.isEnabled())
    -        		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
    -        				+ file.getName()));
    -            throw new PlatformManagerException("File not found");
    -        }
    -
    -        showInFinder(file);
    -    }
    -
    -    // Public utility methods not shared across the interface
    -
    -    /**
    -     * Plays the system alert (the jingle is specified by the user in System Preferences)
    -     */
    -    public void playSystemAlert()
    -    {
    -        try
    -        {
    -            performRuntimeExec(new String[]{"beep"});
    -        }
    -        catch (IOException e)
    -        {
    -        	if (Logger.isEnabled())
    -        		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING,
    -						"Cannot play system alert"));
    -        	Logger.log(new LogEvent(LOGID, "", e));
    -        }
    -    }
    -
    -    /**
    -     * 

    Shows the given file or directory in Finder

    - * @param path Absolute path to the file or directory - */ - public void showInFinder(File path) - { - boolean useOSA = !NativeInvocationBridge.sharedInstance().isEnabled() || !NativeInvocationBridge.sharedInstance().showInFinder(path); - - if(useOSA) - { - StringBuffer sb = new StringBuffer(); - sb.append("tell application \""); - sb.append(getFileBrowserName()); - sb.append("\" to reveal (posix file \""); - sb.append(path); - sb.append("\" as alias)"); - - try - { - performOSAScript(sb); - } - catch (IOException e) - { - Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, e - .getMessage())); - } - } - } - - /** - *

    Shows the given file or directory in Terminal by executing cd /absolute/path/to

    - * @param path Absolute path to the file or directory - */ - public void showInTerminal(String path) - { - showInTerminal(new File(path)); - } - - /** - *

    Shows the given file or directory in Terminal by executing cd /absolute/path/to

    - * @param path Absolute path to the file or directory - */ - public void showInTerminal(File path) - { - if (path.isFile()) - { - path = path.getParentFile(); - } - - if (path != null && path.isDirectory()) - { - StringBuffer sb = new StringBuffer(); - sb.append("tell application \""); - sb.append("Terminal"); - sb.append("\" to do script \"cd "); - sb.append(path.getAbsolutePath().replaceAll(" ", "\\ ")); - sb.append("\""); - - try - { - performOSAScript(sb); - } - catch (IOException e) - { - Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, e - .getMessage())); - } - } - else - { - if (Logger.isEnabled()) - Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find " - + path.getName())); - } - } - - // Internal utility methods - - /** - * Compiles a new AppleScript instance and runs it - * @param cmd AppleScript command to execute; do not surround command with extra quotation marks - * @return Output of the script - * @throws IOException If the script failed to execute - */ - protected static String performOSAScript(CharSequence cmd) throws IOException - { - return performOSAScript(new CharSequence[]{cmd}); - } - - /** - * Compiles a new AppleScript instance and runs it - * @param cmds AppleScript Sequence of commands to execute; do not surround command with extra quotation marks - * @return Output of the script - * @throws IOException If the script failed to execute - */ - protected static String performOSAScript(CharSequence[] cmds) throws IOException - { - long start = System.currentTimeMillis(); - Debug.outNoStack("Executing OSAScript: "); - for (int i = 0; i < cmds.length; i++) - { - Debug.outNoStack("\t" + cmds[i]); - } - - String[] cmdargs = new String[2 * cmds.length + 1]; - cmdargs[0] = "osascript"; - for (int i = 0; i < cmds.length; i++) - { - cmdargs[i * 2 + 1] = "-e"; - cmdargs[i * 2 + 2] = String.valueOf(cmds[i]); - } - - Process osaProcess = performRuntimeExec(cmdargs); - BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getInputStream())); - String line = reader.readLine(); - reader.close(); - Debug.outNoStack("OSAScript Output: " + line); - - reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream())); - String errorMsg = reader.readLine(); - reader.close(); - - Debug.outNoStack("OSAScript Error (if any): " + errorMsg); - - Debug.outNoStack(MessageFormat.format("OSAScript execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)})); - - if (errorMsg != null) - { - throw new IOException(errorMsg); - } - - return line; - } - - /** - * Compiles a new AppleScript instance and runs it - * @param script AppleScript file (.scpt) to execute - * @return Output of the script - * @throws IOException If the script failed to execute - */ - protected static String performOSAScript(File script) throws IOException - { - long start = System.currentTimeMillis(); - Debug.outNoStack("Executing OSAScript from file: " + script.getPath()); - - Process osaProcess = performRuntimeExec(new String[]{"osascript", script.getPath()}); - BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getInputStream())); - String line = reader.readLine(); - reader.close(); - Debug.outNoStack("OSAScript Output: " + line); - - reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream())); - String errorMsg = reader.readLine(); - reader.close(); - - Debug.outNoStack("OSAScript Error (if any): " + errorMsg); - - Debug.outNoStack(MessageFormat.format("OSAScript execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)})); - - if (errorMsg != null) - { - throw new IOException(errorMsg); - } - - return line; - } - - /** - * Compiles a new AppleScript instance to the specified location - * @param cmd Command to compile; do not surround command with extra quotation marks - * @param destination Destination location of the AppleScript file - * @return True if compiled successfully - */ - protected static boolean compileOSAScript(CharSequence cmd, File destination) - { - return compileOSAScript(new CharSequence[]{cmd}, destination); - } - - /** - * Compiles a new AppleScript instance to the specified location - * @param cmds Sequence of commands to compile; do not surround command with extra quotation marks - * @param destination Destination location of the AppleScript file - * @return True if compiled successfully - */ - protected static boolean compileOSAScript(CharSequence[] cmds, File destination) - { - long start = System.currentTimeMillis(); - Debug.outNoStack("Compiling OSAScript: " + destination.getPath()); - for (int i = 0; i < cmds.length; i++) - { - Debug.outNoStack("\t" + cmds[i]); - } - - String[] cmdargs = new String[2 * cmds.length + 3]; - cmdargs[0] = "osacompile"; - for (int i = 0; i < cmds.length; i++) - { - cmdargs[i * 2 + 1] = "-e"; - cmdargs[i * 2 + 2] = String.valueOf(cmds[i]); - } - - cmdargs[cmdargs.length - 2] = "-o"; - cmdargs[cmdargs.length - 1] = destination.getPath(); - - String errorMsg; - try - { - Process osaProcess = performRuntimeExec(cmdargs); - - BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream())); - errorMsg = reader.readLine(); - reader.close(); - } - catch (IOException e) - { - Debug.outNoStack("OSACompile Execution Failed: " + e.getMessage()); - Debug.printStackTrace(e); - return false; - } - - Debug.outNoStack("OSACompile Error (if any): " + errorMsg); - - Debug.outNoStack(MessageFormat.format("OSACompile execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)})); - - return (errorMsg == null); - } - - /** - * @see Runtime#exec(String[]) - */ - protected static Process performRuntimeExec(String[] cmdargs) throws IOException - { - try - { - return Runtime.getRuntime().exec(cmdargs); - } - catch (IOException e) - { - Logger.log(new LogAlert(LogAlert.UNREPEATABLE, e.getMessage(), e)); - throw e; - } - } - - /** - *

    Gets the preferred file browser name

    - *

    Currently supported browsers are Path Finder and Finder. If Path Finder is currently running - * (not just installed), then "Path Finder is returned; else, "Finder" is returned.

    - * @return "Path Finder" if it is currently running; else "Finder" - */ - private static String getFileBrowserName() - { - try - { - // slowwwwwwww - if ("true".equalsIgnoreCase(performOSAScript("tell application \"System Events\" to exists process \"Path Finder\""))) - { - Debug.outNoStack("Path Finder is running"); - - return "Path Finder"; - } - else - { - return "Finder"; - } - } - catch (IOException e) - { - Debug.printStackTrace(e); - Logger.log(new LogEvent(LOGID, e.getMessage(), e)); - - return "Finder"; - } - } - - public boolean - testNativeAvailability( - String name ) - - throws PlatformManagerException - { - throw new PlatformManagerException("Unsupported capability called on platform manager"); - } - - public void - addListener( - PlatformManagerListener listener ) - { - } - - public void - removeListener( - PlatformManagerListener listener ) - { - } -} diff --git a/third_party/pygments/tests/examplefiles/test.jsp b/third_party/pygments/tests/examplefiles/test.jsp deleted file mode 100644 index 1c6664dab..000000000 --- a/third_party/pygments/tests/examplefiles/test.jsp +++ /dev/null @@ -1,24 +0,0 @@ - -<%= var x = 1; -%> -<%! int i = 0; %> -<%! int a, b, c; %> -<%! Circle a = new Circle(2.0); %> - -<% - String name = null; - if (request.getParameter("name") == null) { -%> -<%@ include file="error.html" %> -<% - } else { - foo.setName(request.getParameter("name")); - if (foo.getName().equalsIgnoreCase("integra")) - name = "acura"; - if (name.equalsIgnoreCase( "acura" )) { -%> - - -

    -Calendar of -

    diff --git a/third_party/pygments/tests/examplefiles/test.lean b/third_party/pygments/tests/examplefiles/test.lean deleted file mode 100644 index a7b7e2617..000000000 --- a/third_party/pygments/tests/examplefiles/test.lean +++ /dev/null @@ -1,217 +0,0 @@ -/- -Theorems/Exercises from "Logical Investigations, with the Nuprl Proof Assistant" -by Robert L. Constable and Anne Trostle -http://www.nuprl.org/MathLibrary/LogicalInvestigations/ --/ -import logic - --- 2. The Minimal Implicational Calculus -theorem thm1 {A B : Prop} : A → B → A := -assume Ha Hb, Ha - -theorem thm2 {A B C : Prop} : (A → B) → (A → B → C) → (A → C) := -assume Hab Habc Ha, - Habc Ha (Hab Ha) - -theorem thm3 {A B C : Prop} : (A → B) → (B → C) → (A → C) := -assume Hab Hbc Ha, - Hbc (Hab Ha) - --- 3. False Propositions and Negation -theorem thm4 {P Q : Prop} : ¬P → P → Q := -assume Hnp Hp, - absurd Hp Hnp - -theorem thm5 {P : Prop} : P → ¬¬P := -assume (Hp : P) (HnP : ¬P), - absurd Hp HnP - -theorem thm6 {P Q : Prop} : (P → Q) → (¬Q → ¬P) := -assume (Hpq : P → Q) (Hnq : ¬Q) (Hp : P), - have Hq : Q, from Hpq Hp, - show false, from absurd Hq Hnq - -theorem thm7 {P Q : Prop} : (P → ¬P) → (P → Q) := -assume Hpnp Hp, - absurd Hp (Hpnp Hp) - -theorem thm8 {P Q : Prop} : ¬(P → Q) → (P → ¬Q) := -assume (Hn : ¬(P → Q)) (Hp : P) (Hq : Q), - -- Rermak we don't even need the hypothesis Hp - have H : P → Q, from assume H', Hq, - absurd H Hn - --- 4. Conjunction and Disjunction -theorem thm9 {P : Prop} : (P ∨ ¬P) → (¬¬P → P) := -assume (em : P ∨ ¬P) (Hnn : ¬¬P), - or_elim em - (assume Hp, Hp) - (assume Hn, absurd Hn Hnn) - -theorem thm10 {P : Prop} : ¬¬(P ∨ ¬P) := -assume Hnem : ¬(P ∨ ¬P), - have Hnp : ¬P, from - assume Hp : P, - have Hem : P ∨ ¬P, from or_inl Hp, - absurd Hem Hnem, - have Hem : P ∨ ¬P, from or_inr Hnp, - absurd Hem Hnem - -theorem thm11 {P Q : Prop} : ¬P ∨ ¬Q → ¬(P ∧ Q) := -assume (H : ¬P ∨ ¬Q) (Hn : P ∧ Q), - or_elim H - (assume Hnp : ¬P, absurd (and_elim_left Hn) Hnp) - (assume Hnq : ¬Q, absurd (and_elim_right Hn) Hnq) - -theorem thm12 {P Q : Prop} : ¬(P ∨ Q) → ¬P ∧ ¬Q := -assume H : ¬(P ∨ Q), - have Hnp : ¬P, from assume Hp : P, absurd (or_inl Hp) H, - have Hnq : ¬Q, from assume Hq : Q, absurd (or_inr Hq) H, - and_intro Hnp Hnq - -theorem thm13 {P Q : Prop} : ¬P ∧ ¬Q → ¬(P ∨ Q) := -assume (H : ¬P ∧ ¬Q) (Hn : P ∨ Q), - or_elim Hn - (assume Hp : P, absurd Hp (and_elim_left H)) - (assume Hq : Q, absurd Hq (and_elim_right H)) - -theorem thm14 {P Q : Prop} : ¬P ∨ Q → P → Q := -assume (Hor : ¬P ∨ Q) (Hp : P), - or_elim Hor - (assume Hnp : ¬P, absurd Hp Hnp) - (assume Hq : Q, Hq) - -theorem thm15 {P Q : Prop} : (P → Q) → ¬¬(¬P ∨ Q) := -assume (Hpq : P → Q) (Hn : ¬(¬P ∨ Q)), - have H1 : ¬¬P ∧ ¬Q, from thm12 Hn, - have Hnp : ¬P, from mt Hpq (and_elim_right H1), - absurd Hnp (and_elim_left H1) - -theorem thm16 {P Q : Prop} : (P → Q) ∧ ((P ∨ ¬P) ∨ (Q ∨ ¬Q)) → ¬P ∨ Q := -assume H : (P → Q) ∧ ((P ∨ ¬P) ∨ (Q ∨ ¬Q)), - have Hpq : P → Q, from and_elim_left H, - or_elim (and_elim_right H) - (assume Hem1 : P ∨ ¬P, or_elim Hem1 - (assume Hp : P, or_inr (Hpq Hp)) - (assume Hnp : ¬P, or_inl Hnp)) - (assume Hem2 : Q ∨ ¬Q, or_elim Hem2 - (assume Hq : Q, or_inr Hq) - (assume Hnq : ¬Q, or_inl (mt Hpq Hnq))) - --- 5. First-Order Logic: All and Exists -section -parameters {T : Type} {C : Prop} {P : T → Prop} -theorem thm17a : (C → ∀x, P x) → (∀x, C → P x) := -assume H : C → ∀x, P x, - take x : T, assume Hc : C, - H Hc x - -theorem thm17b : (∀x, C → P x) → (C → ∀x, P x) := -assume (H : ∀x, C → P x) (Hc : C), - take x : T, - H x Hc - -theorem thm18a : ((∃x, P x) → C) → (∀x, P x → C) := -assume H : (∃x, P x) → C, - take x, assume Hp : P x, - have Hex : ∃x, P x, from exists_intro x Hp, - H Hex - -theorem thm18b : (∀x, P x → C) → (∃x, P x) → C := -assume (H1 : ∀x, P x → C) (H2 : ∃x, P x), - obtain (w : T) (Hw : P w), from H2, - H1 w Hw - -theorem thm19a : (C ∨ ¬C) → (∃x : T, true) → (C → (∃x, P x)) → (∃x, C → P x) := -assume (Hem : C ∨ ¬C) (Hin : ∃x : T, true) (H1 : C → ∃x, P x), - or_elim Hem - (assume Hc : C, - obtain (w : T) (Hw : P w), from H1 Hc, - have Hr : C → P w, from assume Hc, Hw, - exists_intro w Hr) - (assume Hnc : ¬C, - obtain (w : T) (Hw : true), from Hin, - have Hr : C → P w, from assume Hc, absurd Hc Hnc, - exists_intro w Hr) - -theorem thm19b : (∃x, C → P x) → C → (∃x, P x) := -assume (H : ∃x, C → P x) (Hc : C), - obtain (w : T) (Hw : C → P w), from H, - exists_intro w (Hw Hc) - -theorem thm20a : (C ∨ ¬C) → (∃x : T, true) → ((¬∀x, P x) → ∃x, ¬P x) → ((∀x, P x) → C) → (∃x, P x → C) := -assume Hem Hin Hnf H, - or_elim Hem - (assume Hc : C, - obtain (w : T) (Hw : true), from Hin, - exists_intro w (assume H : P w, Hc)) - (assume Hnc : ¬C, - have H1 : ¬(∀x, P x), from mt H Hnc, - have H2 : ∃x, ¬P x, from Hnf H1, - obtain (w : T) (Hw : ¬P w), from H2, - exists_intro w (assume H : P w, absurd H Hw)) - -theorem thm20b : (∃x, P x → C) → (∀ x, P x) → C := -assume Hex Hall, - obtain (w : T) (Hw : P w → C), from Hex, - Hw (Hall w) - -theorem thm21a : (∃x : T, true) → ((∃x, P x) ∨ C) → (∃x, P x ∨ C) := -assume Hin H, - or_elim H - (assume Hex : ∃x, P x, - obtain (w : T) (Hw : P w), from Hex, - exists_intro w (or_inl Hw)) - (assume Hc : C, - obtain (w : T) (Hw : true), from Hin, - exists_intro w (or_inr Hc)) - -theorem thm21b : (∃x, P x ∨ C) → ((∃x, P x) ∨ C) := -assume H, - obtain (w : T) (Hw : P w ∨ C), from H, - or_elim Hw - (assume H : P w, or_inl (exists_intro w H)) - (assume Hc : C, or_inr Hc) - -theorem thm22a : (∀x, P x) ∨ C → ∀x, P x ∨ C := -assume H, take x, - or_elim H - (assume Hl, or_inl (Hl x)) - (assume Hr, or_inr Hr) - -theorem thm22b : (C ∨ ¬C) → (∀x, P x ∨ C) → ((∀x, P x) ∨ C) := -assume Hem H1, - or_elim Hem - (assume Hc : C, or_inr Hc) - (assume Hnc : ¬C, - have Hx : ∀x, P x, from - take x, - have H1 : P x ∨ C, from H1 x, - resolve_left H1 Hnc, - or_inl Hx) - -theorem thm23a : (∃x, P x) ∧ C → (∃x, P x ∧ C) := -assume H, - have Hex : ∃x, P x, from and_elim_left H, - have Hc : C, from and_elim_right H, - obtain (w : T) (Hw : P w), from Hex, - exists_intro w (and_intro Hw Hc) - -theorem thm23b : (∃x, P x ∧ C) → (∃x, P x) ∧ C := -assume H, - obtain (w : T) (Hw : P w ∧ C), from H, - have Hex : ∃x, P x, from exists_intro w (and_elim_left Hw), - and_intro Hex (and_elim_right Hw) - -theorem thm24a : (∀x, P x) ∧ C → (∀x, P x ∧ C) := -assume H, take x, - and_intro (and_elim_left H x) (and_elim_right H) - -theorem thm24b : (∃x : T, true) → (∀x, P x ∧ C) → (∀x, P x) ∧ C := -assume Hin H, - obtain (w : T) (Hw : true), from Hin, - have Hc : C, from and_elim_right (H w), - have Hx : ∀x, P x, from take x, and_elim_left (H x), - and_intro Hx Hc - -end -- of section diff --git a/third_party/pygments/tests/examplefiles/test.maql b/third_party/pygments/tests/examplefiles/test.maql deleted file mode 100644 index a44935fd2..000000000 --- a/third_party/pygments/tests/examplefiles/test.maql +++ /dev/null @@ -1,45 +0,0 @@ -# MAQL script -CREATE DATASET {dataset.quotes} VISUAL(TITLE "St\\tock Qu\totes Data"); - -# A comment -CREATE DATASET {dataset.quotes} VISUAL(TITLE "Stock Qu\"otes Data"); - -CREATE DATASET {dataset.quotes} VISUAL(TITLE "Stock Quotes Data"); - -ALTER DATASET {dataset.quotes} ADD {attribute.sector}; - -ALTER DATASET {dataset.quotes} DROP {attribute.symbol}; - -ALTER DATASET {dataset.quotes} VISUAL(TITLE "Internal Quotes Data"); - -CREATE ATTRIBUTE {attr.quotes.symbol} - VISUAL(TITLE "Symbol", FOLDER {folder.quotes.attr}) - AS {d_quotes_symbol.nm_symbol}; - -ALTER ATTRIBUTE {attr.quotes.symbol} - ADD LABELS {attr.quotes.company} VISUAL(TITLE "Company") - AS {d_quotes_symbol.nm_company}; - -CREATE FACT {fact.quotes.open_price} - VISUAL( TITLE "Open Price", FOLDER {folder.quotes.fact}) AS {f_quotes.f_open_price}; - -ALTER FACT {fact.quotes.open_price} ADD {f_quotes2.f_open_price}; - -CREATE FOLDER {folder.quotes.attr} - VISUAL ( TITLE "Stock Quotes Data", - DESCRIPTION "Stock quotes data obtained from John Doe etc." ) - TYPE ATTRIBUTE; - -ALTER DATATYPE {d_quotes_symbol.nm_symbol} VARCHAR(4), - {d_quotes_symbol.nm_symbol} VARCHAR(80), - {f_quotes.f_open_price} DECIMAL(10,2); - -INCLUDE TEMPLATE "URN:GOODDATA:DATE" MODIFY (IDENTIFIER "my-date", TITLE "quote") - -ALTER ATTRIBUTE {attr.quotes.symbol} ADD KEYS {d_quotes_symbol.nm_symbol} PRIMARY; - -ALTER ATTRIBUTE {attr.quotes.symbol} DROP KEYS {d_quotes_symbol.nm_symbol}; - -ALTER FACT {fact.quotes.open_price} ADD {f_quotes2.f_open_price}; - -# Another comment diff --git a/third_party/pygments/tests/examplefiles/test.mask b/third_party/pygments/tests/examplefiles/test.mask deleted file mode 100644 index 39134d746..000000000 --- a/third_party/pygments/tests/examplefiles/test.mask +++ /dev/null @@ -1,41 +0,0 @@ - -// comment -h4.class-1#id.class-2.other checked='true' disabled name = x param > 'Enter ..' -input placeholder=Password type=password > - :dualbind x-signal='dom:create' value=user.passord; -% each='flowers' > - div style=' - position: absolute; - display: inline-block; - background: url("image.png") center center no-repeat; - '; -#skippedDiv.other { - img src='~[url]'; - div style="text-align:center;" { - '~[: $obj.foo("username", name) + 2]' - "~[Localize: stringId]" - } - - p > """ - - Hello "world" - """ - - p > ' - Hello "world" - ' - - p > "Hello 'world'" - - :customComponent x-value='tt'; - /* footer > '(c) 2014' */ -} - -.skippedDiv > - span > - #skipped > - table > - td > - tr > ';)' - -br; \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/test.mod b/third_party/pygments/tests/examplefiles/test.mod deleted file mode 100644 index ba972e304..000000000 --- a/third_party/pygments/tests/examplefiles/test.mod +++ /dev/null @@ -1,374 +0,0 @@ -(* LIFO Storage Library - * - * @file LIFO.mod - * LIFO implementation - * - * Universal Dynamic Stack - * - * Author: Benjamin Kowarsch - * - * Copyright (C) 2009 Benjamin Kowarsch. All rights reserved. - * - * License: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met - * - * 1) NO FEES may be charged for the provision of the software. The software - * may NOT be published on websites that contain advertising, unless - * specific prior written permission has been obtained. - * - * 2) Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 3) Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and other materials provided with the distribution. - * - * 4) Neither the author's name nor the names of any contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * 5) Where this list of conditions or the following disclaimer, in part or - * as a whole is overruled or nullified by applicable law, no permission - * is granted to use the software. - * - * 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. - * - *) - - -IMPLEMENTATION (* OF *) MODULE LIFO; - -FROM SYSTEM IMPORT ADDRESS, ADR, TSIZE; -FROM Storage IMPORT ALLOCATE, DEALLOCATE; - - -(* --------------------------------------------------------------------------- -// Private type : ListEntry -// --------------------------------------------------------------------------- -*) -TYPE ListPtr = POINTER TO ListEntry; - -TYPE ListEntry = RECORD - value : DataPtr; - next : ListPtr -END; (* ListEntry *) - - -(* --------------------------------------------------------------------------- -// Opaque type : LIFO.Stack -// --------------------------------------------------------------------------- -// CAUTION: Modula-2 does not support the use of variable length array fields -// in records. VLAs can only be implemented using pointer arithmetic which -// means there is no type checking and no boundary checking on the array. -// It also means that array notation cannot be used on the array which makes -// the code difficult to read and maintain. As a result, Modula-2 is less -// safe and less readable than C when it comes to using VLAs. Great care must -// be taken to make sure that the code accessing VLA fields is safe. Boundary -// checks must be inserted manually. Size checks must be inserted manually to -// compensate for the absence of type checks. *) - -TYPE Stack = POINTER TO StackDescriptor; - -TYPE StackDescriptor = RECORD - overflow : ListPtr; - entryCount : StackSize; - arraySize : StackSize; - array : ADDRESS (* ARRAY OF DataPtr *) -END; (* StackDescriptor *) - - -(* --------------------------------------------------------------------------- -// function: LIFO.new( initial_size, status ) -// --------------------------------------------------------------------------- -// -// Creates and returns a new LIFO stack object with an initial capacity of -// . If zero is passed in for , then the stack -// will be created with an initial capacity of LIFO.defaultStackSize. The -// function fails if a value greater than LIFO.maximumStackSize is passed -// in for or if memory could not be allocated. -// -// The initial capacity of a stack is the number of entries that can be stored -// in the stack without enlargement. -// -// The status of the operation is passed back in . *) - -PROCEDURE new ( initialSize : StackSize; VAR status : Status ) : Stack; - -VAR - newStack : Stack; - -BEGIN - - (* zero size means default *) - IF initialSize = 0 THEN - initialSize := defaultStackSize; - END; (* IF *) - - (* bail out if initial size is too high *) - IF initialSize > maximumStackSize THEN - status := invalidSize; - RETURN NIL; - END; (* IF *) - - (* allocate new stack object *) - ALLOCATE(newStack, TSIZE(Stack) + TSIZE(DataPtr) * (initialSize - 1)); - - (* bail out if allocation failed *) - IF newStack = NIL THEN - status := allocationFailed; - RETURN NIL; - END; (* IF *) - - (* initialise meta data *) - newStack^.arraySize := initialSize; - newStack^.entryCount := 0; - newStack^.overflow := NIL; - - (* pass status and new stack to caller *) - status := success; - RETURN newStack - -END new; - - -(* --------------------------------------------------------------------------- -// function: LIFO.push( stack, value, status ) -// --------------------------------------------------------------------------- -// -// Adds a new entry to the top of stack . The new entry is -// added by reference, no data is copied. However, no entry is added if the -// the stack is full, that is when the number of entries stored in the stack -// has reached LIFO.maximumStackSize. The function fails if NIL is passed in -// for or , or if memory could not be allocated. -// -// New entries are allocated dynamically if the number of entries exceeds the -// initial capacity of the stack. -// -// The status of the operation is passed back in . *) - -PROCEDURE push ( VAR stack : Stack; value : DataPtr; VAR status : Status ); -VAR - newEntry : ListPtr; - valuePtr : POINTER TO DataPtr; - -BEGIN - - (* bail out if stack is NIL *) - IF stack = NIL THEN - status := invalidStack; - RETURN; - END; (* IF *) - - (* bail out if value is NIL *) - IF value = NIL THEN - status := invalidData; - RETURN; - END; (* IF *) - - (* bail out if stack is full *) - IF stack^.entryCount >= maximumStackSize THEN - status := stackFull; - RETURN; - END; (* IF *) - - (* check if index falls within array segment *) - IF stack^.entryCount < stack^.arraySize THEN - - (* store value in array segment *) - - (* stack^.array^[stack^.entryCount] := value; *) - valuePtr := ADR(stack^.array) + TSIZE(DataPtr) * stack^.entryCount; - valuePtr^ := value; - - ELSE (* index falls within overflow segment *) - - (* allocate new entry slot *) - NEW(newEntry); - - (* bail out if allocation failed *) - IF newEntry = NIL THEN - status := allocationFailed; - RETURN; - END; (* IF *) - - (* initialise new entry *) - newEntry^.value := value; - - (* link new entry into overflow list *) - newEntry^.next := stack^.overflow; - stack^.overflow := newEntry; - - END; (* IF *) - - (* update entry counter *) - INC(stack^.entryCount); - - (* pass status to caller *) - status := success; - RETURN - -END push; - - -(* --------------------------------------------------------------------------- -// function: LIFO.pop( stack, status ) -// --------------------------------------------------------------------------- -// -// Removes the top most value from stack and returns it. If the stack -// is empty, that is when the number of entries stored in the stack has -// reached zero, then NIL is returned. -// -// Entries which were allocated dynamically (above the initial capacity) are -// deallocated when their values are popped. -// -// The status of the operation is passed back in . *) - -PROCEDURE pop ( VAR stack : Stack; VAR status : Status ) : DataPtr; - -VAR - thisValue : DataPtr; - thisEntry : ListPtr; - valuePtr : POINTER TO DataPtr; - -BEGIN - - (* bail out if stack is NIL *) - IF stack = NIL THEN - status := invalidStack; - RETURN NIL; - END; (* IF *) - - (* bail out if stack is empty *) - IF stack^.entryCount = 0 THEN - status := stackEmpty; - RETURN NIL; - END; (* IF *) - - DEC(stack^.entryCount); - - (* check if index falls within array segment *) - IF stack^.entryCount < stack^.arraySize THEN - - (* obtain value at index entryCount in array segment *) - - (* thisValue := stack^.array^[stack^.entryCount]; *) - valuePtr := ADR(stack^.array) + TSIZE(DataPtr) * stack^.entryCount; - thisValue := valuePtr^; - - ELSE (* index falls within overflow segment *) - - (* obtain value of first entry in overflow list *) - thisValue := stack^.overflow^.value; - - (* isolate first entry in overflow list *) - thisEntry := stack^.overflow; - stack^.overflow := stack^.overflow^.next; - - (* remove the entry from overflow list *) - DISPOSE(thisEntry); - - END; (* IF *) - - (* return value and status to caller *) - status := success; - RETURN thisValue - -END pop; - - -(* --------------------------------------------------------------------------- -// function: LIFO.stackSize( stack ) -// --------------------------------------------------------------------------- -// -// Returns the current capacity of . The current capacity is the total -// number of allocated entries. Returns zero if NIL is passed in for . -*) -PROCEDURE stackSize( VAR stack : Stack ) : StackSize; - -BEGIN - - (* bail out if stack is NIL *) - IF stack = NIL THEN - RETURN 0; - END; (* IF *) - - IF stack^.entryCount < stack^.arraySize THEN - RETURN stack^.arraySize; - ELSE - RETURN stack^.entryCount; - END; (* IF *) - -END stackSize; - - -(* --------------------------------------------------------------------------- -// function: LIFO.stackEntries( stack ) -// --------------------------------------------------------------------------- -// -// Returns the number of entries stored in stack , returns zero if -// NIL is passed in for . *) - -PROCEDURE stackEntries( VAR stack : Stack ) : StackSize; - -BEGIN - - (* bail out if stack is NIL *) - IF stack = NIL THEN - RETURN 0; - END; (* IF *) - - RETURN stack^.entryCount - -END stackEntries; - - -(* --------------------------------------------------------------------------- -// function: LIFO.dispose( stack ) -// --------------------------------------------------------------------------- -// -// Disposes of LIFO stack object . Returns NIL. *) - -PROCEDURE dispose ( VAR stack : Stack ) : Stack; - -VAR - thisEntry : ListPtr; - -BEGIN - - (* bail out if stack is NIL *) - IF stack = NIL THEN - RETURN NIL; - END; (* IF *) - - (* deallocate any entries in stack's overflow list *) - WHILE stack^.overflow # NIL DO - - (* isolate first entry in overflow list *) - thisEntry := stack^.overflow; - stack^.overflow := stack^.overflow^.next; - - (* deallocate the entry *) - DISPOSE(thisEntry); - - END; (* WHILE *) - - (* deallocate stack object and pass NIL to caller *) - DEALLOCATE(stack, TSIZE(Stack) + TSIZE(DataPtr) * (stack^.arraySize - 1)); - RETURN NIL - -END dispose; - - -END LIFO. diff --git a/third_party/pygments/tests/examplefiles/test.moo b/third_party/pygments/tests/examplefiles/test.moo deleted file mode 100644 index dec71ba8e..000000000 --- a/third_party/pygments/tests/examplefiles/test.moo +++ /dev/null @@ -1,51 +0,0 @@ -you_lose_msg = "Either that person does not exist, or has a different password."; -if (!(caller in {#0, this})) - return E_PERM; - "...caller isn't :do_login_command..."; -elseif (args && (args[1] == "test")) - return this:test(@listdelete(args, 1)); -elseif (!(length(args) in {1, 2})) - notify(player, tostr("Usage: ", verb, " ")); -elseif (!valid(candidate = this:_match_player(name = strsub(args[1], " ", "_")))) - if (name == "guest") - "must be no guests"; - this:notify_lines(this:registration_text("guest")); - else - notify(player, you_lose_msg); - endif - "...unknown player..."; -elseif (is_clear_property(candidate, "password") || ((typeof(candidate.password) == STR) && ((length(candidate.password) < 2) || (crypt({@args, ""}[2], candidate.password) != candidate.password)))) - notify(player, you_lose_msg); - "...bad password..."; - server_log(tostr("FAILED CONNECT: ", args[1], " (", candidate, ") on ", connection_name(player), ($string_utils:connection_hostname(connection_name(player)) in candidate.all_connect_places) ? "" | "******")); -elseif (((candidate.name == "guest") && this.sitematch_guests) && valid(foreigner = $country_db:get_guest())) - notify(player, tostr("Okay,... Logging you in as `", foreigner:name(), "'")); - this:record_connection(foreigner); - return foreigner; -elseif ((parent(candidate) == $guest) && (!valid(candidate = candidate:defer()))) - if (candidate == #-3) - notify(player, "Sorry, guest characters are not allowed from your site right now."); - elseif (candidate == #-2) - this:notify_lines(this:registration_text("blacklisted", "Sorry, guest characters are not allowed from your site.")); - elseif (candidate == #-4) - this:notify_lines(this:registration_text("guest")); - else - notify(player, "Sorry, all of our guest characters are in use right now."); - endif -else - if ((!(name in candidate.aliases)) && (name != tostr(candidate))) - notify(player, tostr("Okay,... ", name, " is in use. Logging you in as `", candidate:name(), "'")); - endif - if (this:is_newted(candidate)) - notify(player, ""); - notify(player, this:newt_message_for(candidate)); - notify(player, ""); - else - this:record_connection(candidate); - if (verb[1] == "s") - candidate.use_do_command = 0; - endif - return candidate; - endif -endif -return 0; \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/test.myt b/third_party/pygments/tests/examplefiles/test.myt deleted file mode 100644 index 1668f7a60..000000000 --- a/third_party/pygments/tests/examplefiles/test.myt +++ /dev/null @@ -1,166 +0,0 @@ -<%doc>formatting.myt - Provides section formatting elements, syntax-highlighted code blocks, and other special filters. - -<%global> - import string, re - import highlight - - -<%method section> -<%doc>Main section formatting element. -<%args> - toc - path - description=None - onepage=False - -<%init> - item = toc.get_by_path(path) - if item is None: - raise "path: " + path - - - - -
    - -<%python> - content = m.content() - re2 = re.compile(r"'''PYESC(.+?)PYESC'''", re.S) - content = re2.sub(lambda m: m.group(1), content) - - -% if item.depth > 1: -

    <% description or item.description %>

    -% - -
    - <% content %> -
    - -% if onepage or item.depth > 1: -% if (item.next and item.next.depth >= item.depth): - back to section top -% -% else: - back to section top - <& nav.myt:pagenav, item=item, onepage=onepage &> -% -
    - - - - -<%method formatplain> - <%filter> - import re - f = re.sub(r'\n[\s\t]*\n[\s\t]*', '

    \n

    ', f) - f = "

    " + f + "

    " - return f - -<% m.content() | h%> - - - - - -<%method codeline trim="both"> -<% m.content() %> - - -<%method code autoflush=False> -<%args> - title = None - syntaxtype = 'python' - html_escape = False - use_sliders = False - - -<%init> - def fix_indent(f): - f =string.expandtabs(f, 4) - g = '' - lines = string.split(f, "\n") - whitespace = None - for line in lines: - if whitespace is None: - match = re.match(r"^([ ]*).+", line) - if match is not None: - whitespace = match.group(1) - - if whitespace is not None: - line = re.sub(r"^%s" % whitespace, "", line) - - if whitespace is not None or re.search(r"\w", line) is not None: - g += (line + "\n") - - - return g.rstrip() - - p = re.compile(r'
    (.*?)
    ', re.S) - def hlight(match): - return "
    " + highlight.highlight(fix_indent(match.group(1)), html_escape = html_escape, syntaxtype = syntaxtype) + "
    " - content = p.sub(hlight, "
    " + m.content() + "
    ") - -
    "> -% if title is not None: -
    <% title %>
    -% -<% content %>
    - - - - - -<%method popboxlink trim="both"> - <%args> - name=None - show='show' - hide='hide' - - <%init> - if name is None: - name = m.attributes.setdefault('popbox_name', 0) - name += 1 - m.attributes['popbox_name'] = name - name = "popbox_" + repr(name) - -javascript:togglePopbox('<% name %>', '<% show %>', '<% hide %>') - - -<%method popbox trim="both"> -<%args> - name = None - class_ = None - -<%init> - if name is None: - name = 'popbox_' + repr(m.attributes['popbox_name']) - - - - -<%method poplink trim="both"> - <%args> - link='sql' - - <%init> - href = m.scomp('SELF:popboxlink') - - '''PYESC<& nav.myt:link, href=href, text=link, class_="codepoplink" &>PYESC''' - - -<%method codepopper trim="both"> - <%init> - c = m.content() - c = re.sub(r'\n', '
    \n', c.strip()) - -
    <&|SELF:popbox, class_="codepop" &><% c %>
    -
    -
    -<%method poppedcode trim="both">
    -	<%init>
    -		c = m.content()
    -		c = re.sub(r'\n', '
    \n', c.strip()) - -
    <% c %>
    -
    diff --git a/third_party/pygments/tests/examplefiles/test.nim b/third_party/pygments/tests/examplefiles/test.nim
    deleted file mode 100644
    index 20610bb69..000000000
    --- a/third_party/pygments/tests/examplefiles/test.nim
    +++ /dev/null
    @@ -1,93 +0,0 @@
    -import re
    -
    -for x in lines("myfile.txt"):
    -  if x =~ re"(\w+)=(.*)":
    -    echo "Key: ", matches[0],
    -         " Value: ", matches[1]
    -
    -Echo("What's your name? ")
    -var name: string = readLine(stdin)
    -if name == "":
    -  echo("Poor soul, you lost your name?")
    -elif name == "name":
    -  echo("Very funny, your name is name.")
    -else:
    -  Echo("Hi, ", name, "!")
    -
    -var name = readLine(stdin)
    -case name
    -of "":
    -  echo("Poor soul, you lost your name?")
    -of "name":
    -  echo("Very funny, your name is name.")
    -else:
    -  Echo("Hi, ", name, "!")
    -
    -from strutils import parseInt
    -
    -Echo("A number please: ")
    -var n = parseInt(readLine(stdin))
    -case n
    -of 0..2, 4..7: Echo("The number is in the set: {0, 1, 2, 4, 5, 6, 7}")
    -of 3, 8: Echo("The number is 3 or 8")
    -
    -Echo("Counting to 10: ")
    -var i = 1
    -while i <= 10:
    -  Echo($i)
    -  inc(i)
    -
    -proc yes(question: string): bool =
    -  Echo(question, " (y/n)")
    -  while true:
    -    case readLine(stdin)
    -    of "y", "Y", "yes", "Yes": return true
    -    of "n", "N", "no", "No": return false
    -    else: Echo("Please be clear: yes or no")
    -
    -proc even(n: int): bool
    -
    -proc odd(n: int): bool =
    -  if n == 1: return true
    -  else: return even(n-1)
    -
    -iterator countup(a, b: int): int =
    -  var res = a
    -  while res <= b:
    -    yield res
    -    inc(res)
    -
    -type
    -  TPerson = object of TObject
    -    name*: string  # the * means that `name` is accessible from other modules
    -    age: int       # no * means that the field is hidden from other modules
    -
    -  TStudent = object of TPerson # TStudent inherits from TPerson
    -    id: int                    # with an id field
    -
    -var
    -  student: TStudent
    -  person: TPerson
    -assert(student is TStudent)
    -
    -echo({'a', 'b', 'c'}.card)
    -stdout.writeln("Hallo")
    -var
    -  f: TFile
    -if open(f, "numbers.txt"):
    -  try:
    -    var a = readLine(f)
    -    var b = readLine(f)
    -    echo("sum: " & $(parseInt(a) + parseInt(b)))
    -  except EOverflow:
    -    echo("overflow!")
    -  except EInvalidValue:
    -    echo("could not convert string to integer")
    -  except EIO:
    -    echo("IO error!")
    -  except:
    -    echo("Unknown exception!")
    -    # reraise the unknown exception:
    -    raise
    -  finally:
    -    close(f)
    \ No newline at end of file
    diff --git a/third_party/pygments/tests/examplefiles/test.odin b/third_party/pygments/tests/examplefiles/test.odin
    deleted file mode 100644
    index 05b01d22f..000000000
    --- a/third_party/pygments/tests/examplefiles/test.odin
    +++ /dev/null
    @@ -1,43 +0,0 @@
    ---
    --- Example of a fragment of an openEHR Archetype, written in the Object Data Instance Notation (ODIN)
    --- Definition available here: https://github.com/openEHR/odin
    --- Author: Thomas Beale
    ---
    -
    -    original_author = <
    -        ["name"] = <"Dr J Joyce">
    -        ["organisation"] = <"NT Health Service">
    -        ["date"] = <2003-08-03>
    -    >
    -    term_bindings = <
    -        ["umls"] = <
    -            ["id1"] =  -- apgar result
    -            ["id2"] =  -- 1-minute event 
    -        >
    -    >
    -    lifecycle_state =  <"initial">
    -    resource_package_uri =  <"http://www.aihw.org.au/data_sets/diabetic_archetypes.html">
    -
    -    details = <
    -        ["en"] = <
    -            language = <[iso_639-1::en]>
    -            purpose =  <"archetype for diabetic patient review">
    -            use = <"used for all hospital or clinic-based diabetic reviews, 
    -                including first time. Optional sections are removed according to the particular review"
    -            >
    -            misuse = <"not appropriate for pre-diagnosis use">
    -            original_resource_uri = <"http://www.healthdata.org.au/data_sets/diabetic_review_data_set_1.html">
    -        >
    -        ["de"] = <
    -            language = <[iso_639-1::de]>
    -            purpose =  <"Archetyp für die Untersuchung von Patienten mit Diabetes">
    -            use = <"wird benutzt für alle Diabetes-Untersuchungen im
    -                    Krankenhaus, inklusive der ersten Vorstellung. Optionale
    -                    Abschnitte werden in Abhängigkeit von der speziellen
    -                    Vorstellung entfernt."
    -            >
    -            misuse = <"nicht geeignet für Benutzung vor Diagnosestellung">
    -            original_resource_uri = <"http://www.healthdata.org.au/data_sets/diabetic_review_data_set_1.html">
    -        >
    -    >
    -	
    diff --git a/third_party/pygments/tests/examplefiles/test.opa b/third_party/pygments/tests/examplefiles/test.opa
    deleted file mode 100644
    index ec287ac5e..000000000
    --- a/third_party/pygments/tests/examplefiles/test.opa
    +++ /dev/null
    @@ -1,10 +0,0 @@
    -function sample_page() {
    -  
    -

    HTML in Opa

    -
    -
    -
    -

    Learning by examples.

    -
    -
    -} diff --git a/third_party/pygments/tests/examplefiles/test.orc b/third_party/pygments/tests/examplefiles/test.orc deleted file mode 100644 index 367253427..000000000 --- a/third_party/pygments/tests/examplefiles/test.orc +++ /dev/null @@ -1,257 +0,0 @@ -// This is a Csound orchestra file for testing a Pygments -// lexer. Csound single-line comments can be preceded by a pair of forward -// slashes... -; ...or a semicolon. - -/* Block comments begin with /* and end with */ - -// Orchestras begin with a header of audio parameters. -nchnls = 1 -nchnls_i = 1 -sr = 44100 -0dbfs = 1 -ksmps = 10 - -// The control rate kr = sr / ksmps can be omitted when the number of audio -// samples in a control period (ksmps) is set, but kr may appear in older -// orchestras. -kr = 4410 - -// Orchestras contain instruments. These begin with the keyword instr followed -// by a comma-separated list of numbers or names of the instrument. Instruments -// end at the endin keyword and cannot be nested. -instr 1, N_a_M_e_, +Name - // Instruments contain statements. Here is a typical statement: - aSignal oscil 0dbfs, 440, 1 - // Statements are terminated with a newline (possibly preceded by a comment). - // To write a statement on several lines, precede the newline with a - // backslash. - prints \ - "hello, world\n";comment - - // Csound 6 introduced function syntax for opcodes with one or zero outputs. - // The oscil statement above is the same as - aSignal = oscil(0dbfs, 440, 1) - - // Instruments can contain control structures. - kNote = p3 - if (kNote == 0) then - kFrequency = 220 - elseif kNote == 1 then // Parentheses around binary expressions are optional. - kFrequency = 440 - endif - - // Csound 6 introduced looping structures. - iIndex = 0 - while iIndex < 5 do - print iIndex - iIndex += 1 - od - iIndex = 0 - until iIndex >= 5 do - print iIndex - iIndex += 1 - enduntil - // Both kinds of loops can be terminated by either od or enduntil. - - // Single-line strings are enclosed in double-quotes. - prints "string\\\r\n\t\"" - // Multi-line strings are enclosed in pairs of curly braces. - prints {{ - hello, - - world - }} - - // Instruments often end with a statement containing an output opcode. - outc aSignal -endin - -// Orchestras can also contain user-defined opcodes (UDOs). Here is an -// oscillator with one audio-rate output and two control-rate inputs: -opcode anOscillator, a, kk - kAmplitude, kFrequency xin - aSignal vco2 kAmplitude, kFrequency - xout aSignal -endop -instr TestOscillator - outc(anOscillator(0dbfs, 110)) -endin - -// Python can be executed in Csound -// . So can Lua -// . -pyruni {{ -import random - -pool = [(1 + i / 10.0) ** 1.2 for i in range(100)] - -def get_number_from_pool(n, p): - if random.random() < p: - i = int(random.random() * len(pool)) - pool[i] = n - return random.choice(pool) -}} - -// The Csound preprocessor supports conditional compilation and including files. -#ifdef DEBUG -#undef DEBUG -#include "filename.orc" -#endif - -// The preprocessor also supports object- and function-like macros. This is an -// object-like macro that defines a number: -#define A_HZ #440# - -// This is a function-like macro: -#define OSCIL_MACRO(VOLUME'FREQUENCY'TABLE) #oscil $VOLUME, $FREQUENCY, $TABLE# - -// Bodies of macros are enclosed in # and can contain newlines. The arguments of -// function-like macros are separated by single-quotes. Uses of macros are -// prefixed with a dollar sign. -instr TestMacro - aSignal $OSCIL_MACRO(1'$A_HZ'1) - // Not unlike PHP, macros expand in double-quoted strings. - prints "The frequency of the oscillator is $A_HZ Hz.\n" - out aSignal -endin - -// Here are other things to note about Csound. - -// There are two bitwise NOT operators, ~ and ¬ (U+00AC). The latter is common -// on keyboards in the United Kingdom -// . -instr TestBitwiseNOT - print ~42 - print ¬42 -endin - -// Csound uses # for bitwise XOR, which the Csound manual calls bitwise -// non-equivalence . -instr TestBitwiseXOR - print 0 # 0 - print 0 # 1 - print 1 # 0 - print 1 # 1 -endin - -// Loops and if-then statements are relatively recent additions to Csound. There -// are many flow-control opcodes that involve goto and labels. -instr TestGoto - // This... - if p3 > 0 goto if_label - goto else_label -if_label: - prints "if branch\n" - goto endif_label -else_label: - prints "else branch\n" -endif_label: - - // ...is the same as this. - if p3 > 0 then - prints "if branch\n" - else - prints "else branch\n" - endif - - // This... - iIndex = 0 -loop_label: - print iIndex - iIndex += 1 - if iIndex < 10 goto loop_label - - // ...is the same as this... - iIndex = 0 -loop_lt_label: - print iIndex - loop_lt iIndex, 1, 10, loop_lt_label - - // ...and this. - iIndex = 0 - while iIndex < 10 do - print iIndex - iIndex += 1 - od -endin - -// The prints and printks opcodes -// , arguably -// the primary methods of logging output, treat certain sequences of characters -// different from printf in C. -instr TestPrints - // ^ prints an ESCAPE character (U+001B), not a CIRCUMFLEX ACCENT character - // (U+005E). ^^ prints a CIRCUMFLEX ACCENT. - prints "^^\n" - // ~ prints an ESCAPE character (U+001B) followed by a [, not a TILDE - // character (U+007E). ~~ prints a TILDE. - prints "~~\n" - // \A, \B, \N, \R, and \T correspond to the escaped lowercase characters (that - // is, BELL (U+0007), BACKSPACE (U+0008), new line (U+000A), CARRIAGE RETURN - // (U+000D), and tab (U+0009)). - prints "\T\R\N" - // %n, %r, and %t are the same as \n, \r, and \t, as are %N, %R, and %T. - prints "%t%r%n" - // %! prints a semicolon. This is a hold-over from old versions of Csound that - // allowed comments to begin in strings. - prints "; %!\n" -endin - -// The arguments of function-like macros can be separated by # instead of '. -// These two lines define the same macro. -#define OSCIL_MACRO(VOLUME'FREQUENCY'TABLE) #oscil $VOLUME, $FREQUENCY, $TABLE# -#define OSCIL_MACRO(VOLUME#FREQUENCY#TABLE) #oscil $VOLUME, $FREQUENCY, $TABLE# - -// Uses of macros can optionally be suffixed with a period. -instr TestMacroPeriodSuffix - aSignal $OSCIL_MACRO.(1'$A_HZ'1) - prints "The frequency of the oscillator is $A_HZ.Hz.\n" - out aSignal -endin - -// Csound has @ and @@ operator-like macros that, when followed by a literal -// non-negative integer, expand to the next power of 2 and the next power of 2 -// plus 1: -// @x = 2^(ceil(log2(x + 1))), x >= 0 -// @@0 = 2 -// @@x = 2^(ceil(log2(x))) + 1, x > 0 -// These macros are in -// (and -// ) -// and are described at . -instr TestAt - prints "%d %2d %2d\n", 0, @0, @@0 - prints "%d %2d %2d\n", 1, @1, @@1 - prints "%d %2d %2d\n", 2, @2, @@2 - prints "%d %2d %2d\n", 3, @3, @@3 - prints "%d %2d %2d\n", 4, @4, @@4 - prints "%d %2d %2d\n", 5, @5, @@5 - prints "%d %2d %2d\n", 6, @6, @@6 - prints "%d %2d %2d\n", 7, @7, @@7 - prints "%d %2d %2d\n", 8, @8, @@8 - prints "%d %2d %2d\n", 9, @9, @@9 -endin - -// Including newlines in macros can lead to confusing code, but it tests the -// lexer. -instr MacroAbuse - if 1 == 1 then - prints "on\n" -#define FOO# -BAR -#endif // This ends the if statement. It is not a preprocessor directive. -endin - -scoreline_i {{ -f 1 0 16384 10 1 -i "N_a_M_e_" 0 2 -i "TestOscillator" 2 2 -i "TestBitwiseNOT" 0 1 -i "TestBitwiseXOR" 0 1 -i "TestGoto" 0 1 -i "TestMacroPeriodSuffix" 4 1 -i "TestAt" 0 1 -i "MacroAbuse" 0 1 -e -}} diff --git a/third_party/pygments/tests/examplefiles/test.p6 b/third_party/pygments/tests/examplefiles/test.p6 deleted file mode 100644 index 3d12b56c5..000000000 --- a/third_party/pygments/tests/examplefiles/test.p6 +++ /dev/null @@ -1,252 +0,0 @@ -#!/usr/bin/env perl6 - -use v6; - -my $string = 'I look like a # comment!'; - -if $string eq 'foo' { - say 'hello'; -} - -regex http-verb { - 'GET' - | 'POST' - | 'PUT' - | 'DELETE' - | 'TRACE' - | 'OPTIONS' - | 'HEAD' -} - -# a sample comment - -say 'Hello from Perl 6!' - - -#`{ -multi-line comment! -} - -say 'here'; - -#`( -multi-line comment! -) - -say 'here'; - -#`{{{ -I'm a special comment! -}}} - -say 'there'; - -#`{{ -I'm { even } specialer! -}} - -say 'there'; - -#`{{ -does {{nesting}} work? -}} - -#`«< -trying mixed delimiters -» - -my $string = qq; -my $string = qq«Hooray, arbitrary delimiter!»; -my $string = q ; -my $string = qq<>; - -my %hash := Hash.new; - -=begin pod - -Here's some POD! Wooo - -=end pod - -=for Testing - This is POD (see? role isn't highlighted) - -say('this is not!'); - -=table - Of role things - -say('not in your table'); -#= A single line declarator "block" (with a keyword like role) -#| Another single line declarator "block" (with a keyword like role) -#={ - A declarator block (with a keyword like role) - } -#|{ - Another declarator block (with a keyword like role) - } -#= { A single line declarator "block" with a brace (with a keyword like role) -#=« - More declarator blocks! (with a keyword like role) - » -#|« - More declarator blocks! (with a keyword like role) - » - -say 'Moar code!'; - -my $don't = 16; - -sub don't($x) { - !$x -} - -say don't 'foo'; - -my %hash = ( - :foo(1), -); - -say %hash; -say %hash<>; -say %hash«foo»; - -say %*hash; -say %*hash<>; -say %*hash«foo»; - -say $; -say $; - -for (@A Z @B) -> $a, $b { - say $a + $b; -} - -Q:PIR { - .loadlib "somelib" -} - -my $longstring = q/ - lots - of - text -/; - -my $heredoc = q:to/END_SQL/; -SELECT * FROM Users -WHERE first_name = 'Rob' -END_SQL -my $hello; - -# Fun with regexen - -if 'food' ~~ /foo/ { - say 'match!' -} - -my $re = /foo/; -my $re2 = m/ foo /; -my $re3 = m:i/ FOO /; - -call-a-sub(/ foo /); -call-a-sub(/ foo \/ bar /); - -my $re4 = rx/something | something-else/; -my $result = ms/regexy stuff/; -my $sub0 = s/regexy stuff/more stuff/; -my $sub = ss/regexy stuff/more stuff/; -my $trans = tr/regexy stuff/more stuff/; - -my @values = ; -call-sub(); -call-sub ; - -my $result = $a < $b; - -for -> $letter { - say $letter; -} - -sub test-sub { - say @_; - say $!; - say $/; - say $0; - say $1; - say @*ARGS; - say $*ARGFILES; - say &?BLOCK; - say ::?CLASS; - say $?CLASS; - say @=COMMENT; - say %?CONFIG; - say $*CWD; - say $=data; - say %?DEEPMAGIC; - say $?DISTRO; - say $*DISTRO; - say $*EGID; - say %*ENV; - say $*ERR; - say $*EUID; - say $*EXECUTABLE_NAME; - say $?FILE; - say $?GRAMMAR; - say $*GID; - say $*IN; - say @*INC; - say %?LANG; - say $*LANG; - say $?LINE; - say %*META-ARGS; - say $?MODULE; - say %*OPTS; - say %*OPT; - say $?KERNEL; - say $*KERNEL; - say $*OUT; - say $?PACKAGE; - say $?PERL; - say $*PERL; - say $*PID; - say %=pod; - say $*PROGRAM_NAME; - say %*PROTOCOLS; - say ::?ROLE; - say $?ROLE; - say &?ROUTINE; - say $?SCOPE; - say $*TZ; - say $*UID; - say $?USAGE; - say $?VM; - say $?XVM; -} - -say ; - -my $perl5_re = m:P5/ fo{2} /; -my $re5 = rx«something | something-else»; - -my $M := %*COMPILING<%?OPTIONS>; - -say $M; - -sub regex-name { ... } -my $pair = role-name => 'foo'; -$pair = rolesque => 'foo'; - -my sub something(Str:D $value) { ... } - -my $s = q«< -some -string -stuff -»; - -my $regex = m«< some chars »; -# after - -say $/; - -roleq; diff --git a/third_party/pygments/tests/examplefiles/test.pan b/third_party/pygments/tests/examplefiles/test.pan deleted file mode 100644 index 56c8bd628..000000000 --- a/third_party/pygments/tests/examplefiles/test.pan +++ /dev/null @@ -1,54 +0,0 @@ -object template pantest; - -# Very simple pan test file -"/long/decimal" = 123; -"/long/octal" = 0755; -"/long/hexadecimal" = 0xFF; - -"/double/simple" = 0.01; -"/double/pi" = 3.14159; -"/double/exponent" = 1e-8; -"/double/scientific" = 1.3E10; - -"/string/single" = 'Faster, but escapes like \t, \n and \x3d don''t work, but '' should work.'; -"/string/double" = "Slower, but escapes like \t, \n and \x3d do work"; - -variable TEST = 2; - -"/x2" = to_string(TEST); -"/x2" ?= 'Default value'; - -"/x3" = 1 + 2 + value("/long/decimal"); - -"/x4" = undef; - -"/x5" = null; - -variable e ?= error("Test error message"); - -# include gmond config for services-monitoring -include { 'site/ganglia/gmond/services-monitoring' }; - -"/software/packages"=pkg_repl("httpd","2.2.3-43.sl5.3",PKG_ARCH_DEFAULT); -"/software/packages"=pkg_repl("php"); - -# Example function -function show_things_view_for_stuff = { - thing = ARGV[0]; - foreach( i; mything; STUFF ) { - if ( thing == mything ) { - return( true ); - } else { - return SELF; - }; - }; - false; -}; - -variable HERE = < '\' then - RootFolder := RootFolder + '\'; - ZeroMemory(@wfd, sizeof(wfd)); - wfd.dwFileAttributes := FILE_ATTRIBUTE_NORMAL; - if Recurse then - begin - hFindFile := FindFirstFile(pointer(RootFolder + '*.*'), wfd); - if hFindFile <> 0 then - try - repeat - if wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then - begin - if (string(wfd.cFileName) <> '.') and (string(wfd.cFileName) <> '..') then - begin - CountFolders(Handle, RootFolder + wfd.cFileName, Recurse); - end; - end; - until FindNextFile(hFindFile, wfd) = False; - Inc(CntFolders); - finally - Windows.FindClose(hFindFile); - end; - end; -end; - -//////////////////////////////////////////////////////////////////////////////// -// -// FindAllFiles -// -procedure FindAllFiles(Handle: THandle; RootFolder: string; Mask: string; Recurse: Boolean = True); -var - hFindFile : THandle; - wfd : TWin32FindData; -begin - if RootFolder[length(RootFolder)] <> '\' then - RootFolder := RootFolder + '\'; - ZeroMemory(@wfd, sizeof(wfd)); - wfd.dwFileAttributes := FILE_ATTRIBUTE_NORMAL; - if Recurse then - begin - hFindFile := FindFirstFile(pointer(RootFolder + '*.*'), wfd); - if hFindFile <> 0 then - try - repeat - if wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then - begin - if (string(wfd.cFileName) <> '.') and (string(wfd.cFileName) <> '..') then - begin - FindAllFiles(Handle, RootFolder + wfd.cFileName, Mask, Recurse); - end; - end; - until FindNextFile(hFindFile, wfd) = False; - Inc(NumFolder); - SendMessage(Handle, FFM_ONDIRFOUND, NumFolder, lParam(string(RootFolder))); - finally - Windows.FindClose(hFindFile); - end; - end; - hFindFile := FindFirstFile(pointer(RootFolder + Mask), wfd); - if hFindFile <> INVALID_HANDLE_VALUE then - try - repeat - if (wfd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> FILE_ATTRIBUTE_DIRECTORY) then - begin - SendMessage(Handle, FFM_ONFILEFOUND, 0, lParam(string(RootFolder + wfd.cFileName))); - end; - until FindNextFile(hFindFile, wfd) = False; - finally - Windows.FindClose(hFindFile); - end; -end; - - -property test: boolean read ftest write ftest; -procedure test: boolean read ftest write ftest; - -// -// This sourcecode is part of omorphia -// - -Function IsValidHandle(Const Handle: THandle): Boolean; {$IFDEF OMORPHIA_FEATURES_USEASM} Assembler; -Asm - TEST EAX, EAX - JZ @@Finish - NOT EAX - TEST EAX, EAX - SETNZ AL - - {$IFDEF WINDOWS} - JZ @@Finish - - //Save the handle against modifications or loss - PUSH EAX - - //reserve some space for a later duplicate - PUSH EAX - - //Check if we are working on NT-Platform - CALL IsWindowsNTSystem - TEST EAX, EAX - JZ @@NoNTSystem - - PUSH DWORD PTR [ESP] - LEA EAX, DWORD PTR [ESP+$04] - PUSH EAX - CALL GetHandleInformation - TEST EAX, EAX - JNZ @@Finish2 - -@@NoNTSystem: - //Result := DuplicateHandle(GetCurrentProcess, Handle, GetCurrentProcess, - // @Duplicate, 0, False, DUPLICATE_SAME_ACCESS); - PUSH DUPLICATE_SAME_ACCESS - PUSH $00000000 - PUSH $00000000 - LEA EAX, DWORD PTR [ESP+$0C] - PUSH EAX - CALL GetCurrentProcess - PUSH EAX - PUSH DWORD PTR [ESP+$18] - PUSH EAX - CALL DuplicateHandle - - TEST EAX, EAX - JZ @@Finish2 - - // Result := CloseHandle(Duplicate); - PUSH DWORD PTR [ESP] - CALL CloseHandle - -@@Finish2: - POP EDX - POP EDX - - PUSH EAX - PUSH $00000000 - CALL SetLastError - POP EAX - {$ENDIF} - -@@Finish: -End; -{$ELSE} -Var - Duplicate: THandle; - Flags: DWORD; -Begin - If IsWinNT Then - Result := GetHandleInformation(Handle, Flags) - Else - Result := False; - If Not Result Then - Begin - // DuplicateHandle is used as an additional check for those object types not - // supported by GetHandleInformation (e.g. according to the documentation, - // GetHandleInformation doesn't support window stations and desktop although - // tests show that it does). GetHandleInformation is tried first because its - // much faster. Additionally GetHandleInformation is only supported on NT... - Result := DuplicateHandle(GetCurrentProcess, Handle, GetCurrentProcess, - @Duplicate, 0, False, DUPLICATE_SAME_ACCESS); - If Result Then - Result := CloseHandle(Duplicate); - End; -End; -{$ENDIF} - - - - -{*******************************************************} -{ } -{ Delphi Supplemental Components } -{ ZLIB Data Compression Interface Unit } -{ } -{ Copyright (c) 1997 Borland International } -{ } -{*******************************************************} - -{ Modified for zlib 1.1.3 by Davide Moretti Z_STREAM_END do - begin - P := OutBuf; - Inc(OutBytes, 256); - ReallocMem(OutBuf, OutBytes); - strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); - strm.avail_out := 256; - end; - finally - CCheck(deflateEnd(strm)); - end; - ReallocMem(OutBuf, strm.total_out); - OutBytes := strm.total_out; - except - FreeMem(OutBuf); - raise - end; -end; - - -procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; - OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); -var - strm: TZStreamRec; - P: Pointer; - BufInc: Integer; -begin - FillChar(strm, sizeof(strm), 0); - BufInc := (InBytes + 255) and not 255; - if OutEstimate = 0 then - OutBytes := BufInc - else - OutBytes := OutEstimate; - GetMem(OutBuf, OutBytes); - try - strm.next_in := InBuf; - strm.avail_in := InBytes; - strm.next_out := OutBuf; - strm.avail_out := OutBytes; - DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); - try - while DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END do - begin - P := OutBuf; - Inc(OutBytes, BufInc); - ReallocMem(OutBuf, OutBytes); - strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); - strm.avail_out := BufInc; - end; - finally - DCheck(inflateEnd(strm)); - end; - ReallocMem(OutBuf, strm.total_out); - OutBytes := strm.total_out; - except - FreeMem(OutBuf); - raise - end; -end; - - -// TCustomZlibStream - -constructor TCustomZLibStream.Create(Strm: TStream); -begin - inherited Create; - FStrm := Strm; - FStrmPos := Strm.Position; -end; - -procedure TCustomZLibStream.Progress(Sender: TObject); -begin - if Assigned(FOnProgress) then FOnProgress(Sender); -end; - - -// TCompressionStream - -constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel; - Dest: TStream); -const - Levels: array [TCompressionLevel] of ShortInt = - (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION); -begin - inherited Create(Dest); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec))); -end; - -destructor TCompressionStream.Destroy; -begin - FZRec.next_in := nil; - FZRec.avail_in := 0; - try - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END) - and (FZRec.avail_out = 0) do - begin - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - end; - if FZRec.avail_out < sizeof(FBuffer) then - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out); - finally - deflateEnd(FZRec); - end; - inherited Destroy; -end; - -function TCompressionStream.Read(var Buffer; Count: Longint): Longint; -begin - raise ECompressionError.Create('Invalid stream operation'); -end; - -function TCompressionStream.Write(const Buffer; Count: Longint): Longint; -begin - FZRec.next_in := @Buffer; - FZRec.avail_in := Count; - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (FZRec.avail_in > 0) do - begin - CCheck(deflate(FZRec, 0)); - if FZRec.avail_out = 0 then - begin - FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); - FZRec.next_out := FBuffer; - FZRec.avail_out := sizeof(FBuffer); - FStrmPos := FStrm.Position; - Progress(Self); - end; - end; - Result := Count; -end; - -function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; -begin - if (Offset = 0) and (Origin = soFromCurrent) then - Result := FZRec.total_in - else - raise ECompressionError.Create('Invalid stream operation'); -end; - -function TCompressionStream.GetCompressionRate: Single; -begin - if FZRec.total_in = 0 then - Result := 0 - else - Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0; -end; - - -// TDecompressionStream - -constructor TDecompressionStream.Create(Source: TStream); -begin - inherited Create(Source); - FZRec.next_in := FBuffer; - FZRec.avail_in := 0; - DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec))); -end; - -destructor TDecompressionStream.Destroy; -begin - inflateEnd(FZRec); - inherited Destroy; -end; - -function TDecompressionStream.Read(var Buffer; Count: Longint): Longint; -begin - FZRec.next_out := @Buffer; - FZRec.avail_out := Count; - if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; - while (FZRec.avail_out > 0) do - begin - if FZRec.avail_in = 0 then - begin - FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer)); - if FZRec.avail_in = 0 then - begin - Result := Count - FZRec.avail_out; - Exit; - end; - FZRec.next_in := FBuffer; - FStrmPos := FStrm.Position; - Progress(Self); - end; - DCheck(inflate(FZRec, 0)); - end; - Result := Count; -end; - -function TDecompressionStream.Write(const Buffer; Count: Longint): Longint; -begin - raise EDecompressionError.Create('Invalid stream operation'); -end; - -function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint; -var - I: Integer; - Buf: array [0..4095] of Char; -begin - if (Offset = 0) and (Origin = soFromBeginning) then - begin - DCheck(inflateReset(FZRec)); - FZRec.next_in := FBuffer; - FZRec.avail_in := 0; - FStrm.Position := 0; - FStrmPos := 0; - end - else if ( (Offset >= 0) and (Origin = soFromCurrent)) or - ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then - begin - if Origin = soFromBeginning then Dec(Offset, FZRec.total_out); - if Offset > 0 then - begin - for I := 1 to Offset div sizeof(Buf) do - ReadBuffer(Buf, sizeof(Buf)); - ReadBuffer(Buf, Offset mod sizeof(Buf)); - end; - end - else - raise EDecompressionError.Create('Invalid stream operation'); - Result := FZRec.total_out; -end; - -end. diff --git a/third_party/pygments/tests/examplefiles/test.php b/third_party/pygments/tests/examplefiles/test.php deleted file mode 100644 index 2ce4023eb..000000000 --- a/third_party/pygments/tests/examplefiles/test.php +++ /dev/null @@ -1,515 +0,0 @@ - - * @copyright Copyright (c) 2006, Manni - * @version 1.0 - * @link http://www.pkware.com/business_and_developers/developer/popups/appnote.txt - * @link http://mannithedark.is-a-geek.net/ - * @since 1.0 - * @package fnord.bb - * @subpackage archive - */ -class Zip extends Archive { - /** - * Outputs the zip file - * - * This function creates the zip file with the dirs and files given. - * If the optional parameter $file is given, the zip file is will be - * saved at that location. Otherwise the function returns the zip file's content. - * - * @access public - * - * @link http://www.pkware.com/business_and_developers/developer/popups/appnote.txt - * @param string $filename The path where the zip file will be saved - * - * @return bool|string Returns either true if the fil is sucessfully created or the content of the zip file - */ - function out($filename = false) { - // Empty output - $file_data = array(); // Data of the file part - $cd_data = array(); // Data of the central directory - - // Sort dirs and files by path length - uksort($this->dirs, 'sort_by_length'); - uksort($this->files, 'sort_by_length'); - - // Handle dirs - foreach($this->dirs as $dir) { - $dir .= '/'; - // File part - - // Reset dir data - $dir_data = ''; - - // Local file header - $dir_data .= "\x50\x4b\x03\x04"; // Local file header signature - $dir_data .= pack("v", 10); // Version needed to extract - $dir_data .= pack("v", 0); // General purpose bit flag - $dir_data .= pack("v", 0); // Compression method - $dir_data .= pack("v", 0); // Last mod file time - $dir_data .= pack("v", 0); // Last mod file date - $dir_data .= pack("V", 0); // crc-32 - $dir_data .= pack("V", 0); // Compressed size - $dir_data .= pack("V", 0); // Uncompressed size - $dir_data .= pack("v", strlen($dir)); // File name length - $dir_data .= pack("v", 0); // Extra field length - - $dir_data .= $dir; // File name - $dir_data .= ''; // Extra field (is empty) - - // File data - $dir_data .= ''; // Dirs have no file data - - // Data descriptor - $dir_data .= pack("V", 0); // crc-32 - $dir_data .= pack("V", 0); // Compressed size - $dir_data .= pack("V", 0); // Uncompressed size - - // Save current offset - $offset = strlen(implode('', $file_data)); - - // Append dir data to the file part - $file_data[] = $dir_data; - - // Central directory - - // Reset dir data - $dir_data = ''; - - // File header - $dir_data .= "\x50\x4b\x01\x02"; // Local file header signature - $dir_data .= pack("v", 0); // Version made by - $dir_data .= pack("v", 10); // Version needed to extract - $dir_data .= pack("v", 0); // General purpose bit flag - $dir_data .= pack("v", 0); // Compression method - $dir_data .= pack("v", 0); // Last mod file time - $dir_data .= pack("v", 0); // Last mod file date - $dir_data .= pack("V", 0); // crc-32 - $dir_data .= pack("V", 0); // Compressed size - $dir_data .= pack("V", 0); // Uncompressed size - $dir_data .= pack("v", strlen($dir)); // File name length - $dir_data .= pack("v", 0); // Extra field length - $dir_data .= pack("v", 0); // File comment length - $dir_data .= pack("v", 0); // Disk number start - $dir_data .= pack("v", 0); // Internal file attributes - $dir_data .= pack("V", 16); // External file attributes - $dir_data .= pack("V", $offset); // Relative offset of local header - - $dir_data .= $dir; // File name - $dir_data .= ''; // Extra field (is empty) - $dir_data .= ''; // File comment (is empty) - - /* - // Data descriptor - $dir_data .= pack("V", 0); // crc-32 - $dir_data .= pack("V", 0); // Compressed size - $dir_data .= pack("V", 0); // Uncompressed size - */ - - // Append dir data to the central directory data - $cd_data[] = $dir_data; - } - - // Handle files - foreach($this->files as $name => $file) { - // Get values - $content = $file[0]; - - // File part - - // Reset file data - $fd = ''; - - // Detect possible compressions - // Use deflate - if(function_exists('gzdeflate')) { - $method = 8; - - // Compress file content - $compressed_data = gzdeflate($content); - - // Use bzip2 - } elseif(function_exists('bzcompress')) { - $method = 12; - - // Compress file content - $compressed_data = bzcompress($content); - - // No compression - } else { - $method = 0; - - // Do not compress the content :P - $compressed_data = $content; - } - - // Local file header - $fd .= "\x50\x4b\x03\x04"; // Local file header signature - $fd .= pack("v", 20); // Version needed to extract - $fd .= pack("v", 0); // General purpose bit flag - $fd .= pack("v", $method); // Compression method - $fd .= pack("v", 0); // Last mod file time - $fd .= pack("v", 0); // Last mod file date - $fd .= pack("V", crc32($content)); // crc-32 - $fd .= pack("V", strlen($compressed_data)); // Compressed size - $fd .= pack("V", strlen($content)); // Uncompressed size - $fd .= pack("v", strlen($name)); // File name length - $fd .= pack("v", 0); // Extra field length - - $fd .= $name; // File name - $fd .= ''; // Extra field (is empty) - - // File data - $fd .= $compressed_data; - - // Data descriptor - $fd .= pack("V", crc32($content)); // crc-32 - $fd .= pack("V", strlen($compressed_data)); // Compressed size - $fd .= pack("V", strlen($content)); // Uncompressed size - - // Save current offset - $offset = strlen(implode('', $file_data)); - - // Append file data to the file part - $file_data[] = $fd; - - // Central directory - - // Reset file data - $fd = ''; - - // File header - $fd .= "\x50\x4b\x01\x02"; // Local file header signature - $fd .= pack("v", 0); // Version made by - $fd .= pack("v", 20); // Version needed to extract - $fd .= pack("v", 0); // General purpose bit flag - $fd .= pack("v", $method); // Compression method - $fd .= pack("v", 0); // Last mod file time - $fd .= pack("v", 0); // Last mod file date - $fd .= pack("V", crc32($content)); // crc-32 - $fd .= pack("V", strlen($compressed_data)); // Compressed size - $fd .= pack("V", strlen($content)); // Uncompressed size - $fd .= pack("v", strlen($name)); // File name length - $fd .= pack("v", 0); // Extra field length - $fd .= pack("v", 0); // File comment length - $fd .= pack("v", 0); // Disk number start - $fd .= pack("v", 0); // Internal file attributes - $fd .= pack("V", 32); // External file attributes - $fd .= pack("V", $offset); // Relative offset of local header - - $fd .= $name; // File name - $fd .= ''; // Extra field (is empty) - $fd .= ''; // File comment (is empty) - - /* - // Data descriptor - $fd .= pack("V", crc32($content)); // crc-32 - $fd .= pack("V", strlen($compressed_data)); // Compressed size - $fd .= pack("V", strlen($content)); // Uncompressed size - */ - - // Append file data to the central directory data - $cd_data[] = $fd; - } - - // Digital signature - $digital_signature = ''; - $digital_signature .= "\x50\x4b\x05\x05"; // Header signature - $digital_signature .= pack("v", 0); // Size of data - $digital_signature .= ''; // Signature data (is empty) - - $tmp_file_data = implode('', $file_data); // File data - $tmp_cd_data = implode('', $cd_data). // Central directory - $digital_signature; // Digital signature - - // End of central directory - $eof_cd = ''; - $eof_cd .= "\x50\x4b\x05\x06"; // End of central dir signature - $eof_cd .= pack("v", 0); // Number of this disk - $eof_cd .= pack("v", 0); // Number of the disk with the start of the central directory - $eof_cd .= pack("v", count($cd_data)); // Total number of entries in the central directory on this disk - $eof_cd .= pack("v", count($cd_data)); // Total number of entries in the central directory - $eof_cd .= pack("V", strlen($tmp_cd_data)); // Size of the central directory - $eof_cd .= pack("V", strlen($tmp_file_data)); // Offset of start of central directory with respect to the starting disk number - $eof_cd .= pack("v", 0); // .ZIP file comment length - $eof_cd .= ''; // .ZIP file comment (is empty) - - // Content of the zip file - $data = $tmp_file_data. - // $extra_data_record. - $tmp_cd_data. - $eof_cd; - - // Return content? - if(!$filename) - return $data; - - // Write to file - return file_put_contents($filename, $data); - } - - /** - * Load a zip file - * - * This function loads the files and dirs from a zip file from the harddrive. - * - * @access public - * - * @param string $file The path to the zip file - * @param bool $reset Reset the files and dirs before adding the zip file's content? - * - * @return bool Returns true if the file was loaded sucessfully - */ - function load_file($file, $reset = true) { - // Check whether the file exists - if(!file_exists($file)) - return false; - - // Load the files content - $content = @file_get_contents($file); - - // Return false if the file cannot be opened - if(!$content) - return false; - - // Read the zip - return $this->load_string($content, $reset); - } - - /** - * Load a zip string - * - * This function loads the files and dirs from a string - * - * @access public - * - * @param string $string The string the zip is generated from - * @param bool $reset Reset the files and dirs before adding the zip file's content? - * - * @return bool Returns true if the string was loaded sucessfully - */ - function load_string($string, $reset = true) { - // Reset the zip? - if($reset) { - $this->dirs = array(); - $this->files = array(); - } - - // Get the starting position of the end of central directory record - $start = strpos($string, "\x50\x4b\x05\x06"); - - // Error - if($start === false) - die('Could not find the end of central directory record'); - - // Get the ecdr - $eof_cd = substr($string, $start+4, 18); - - // Unpack the ecdr infos - $eof_cd = unpack('vdisc1/'. - 'vdisc2/'. - 'ventries1/'. - 'ventries2/'. - 'Vsize/'. - 'Voffset/'. - 'vcomment_lenght', $eof_cd); - - // Do not allow multi disc zips - if($eof_cd['disc1'] != 0) - die('multi disk stuff is not yet implemented :/'); - - // Save the interesting values - $cd_entries = $eof_cd['entries1']; - $cd_size = $eof_cd['size']; - $cd_offset = $eof_cd['offset']; - - // Get the central directory record - $cdr = substr($string, $cd_offset, $cd_size); - - // Reset the position and the list of the entries - $pos = 0; - $entries = array(); - - // Handle cdr - while($pos < strlen($cdr)) { - // Check header signature - // Digital signature - if(substr($cdr, $pos, 4) == "\x50\x4b\x05\x05") { - // Get digital signature size - $tmp_info = unpack('vsize', substr($cdr, $pos + 4, 2)); - - // Read out the digital signature - $digital_sig = substr($header, $pos + 6, $tmp_info['size']); - - break; - } - - // Get file header - $header = substr($cdr, $pos, 46); - - // Unpack the header information - $header_info = @unpack('Vheader/'. - 'vversion_made_by/'. - 'vversion_needed/'. - 'vgeneral_purpose/'. - 'vcompression_method/'. - 'vlast_mod_time/'. - 'vlast_mod_date/'. - 'Vcrc32/'. - 'Vcompressed_size/'. - 'Vuncompressed_size/'. - 'vname_length/'. - 'vextra_length/'. - 'vcomment_length/'. - 'vdisk_number/'. - 'vinternal_attributes/'. - 'Vexternal_attributes/'. - 'Voffset', - $header); - - // Valid header? - if($header_info['header'] != 33639248) - return false; - - // New position - $pos += 46; - - // Read out the file name - $header_info['name'] = substr($cdr, $pos, $header_info['name_length']); - - // New position - $pos += $header_info['name_length']; - - // Read out the extra stuff - $header_info['extra'] = substr($cdr, $pos, $header_info['extra_length']); - - // New position - $pos += $header_info['extra_length']; - - // Read out the comment - $header_info['comment'] = substr($cdr, $pos, $header_info['comment_length']); - - // New position - $pos += $header_info['comment_length']; - - // Append this file/dir to the entry list - $entries[] = $header_info; - } - - // Check whether all entries where read sucessfully - if(count($entries) != $cd_entries) - return false; - - // Handle files/dirs - foreach($entries as $entry) { - // Is a dir? - if($entry['external_attributes'] & 16) { - $this->add_dir($entry['name']); - continue; - } - - // Get local file header - $header = substr($string, $entry['offset'], 30); - - // Unpack the header information - $header_info = @unpack('Vheader/'. - 'vversion_needed/'. - 'vgeneral_purpose/'. - 'vcompression_method/'. - 'vlast_mod_time/'. - 'vlast_mod_date/'. - 'Vcrc32/'. - 'Vcompressed_size/'. - 'Vuncompressed_size/'. - 'vname_length/'. - 'vextra_length', - $header); - - // Valid header? - if($header_info['header'] != 67324752) - return false; - - // Get content start position - $start = $entry['offset'] + 30 + $header_info['name_length'] + $header_info['extra_length']; - - // Get the compressed data - $data = substr($string, $start, $header_info['compressed_size']); - - // Detect compression type - switch($header_info['compression_method']) { - // No compression - case 0: - // Ne decompression needed - $content = $data; - break; - - // Gzip - case 8: - if(!function_exists('gzinflate')) - return false; - - // Uncompress data - $content = gzinflate($data); - break; - - // Bzip2 - case 12: - if(!function_exists('bzdecompress')) - return false; - - // Decompress data - $content = bzdecompress($data); - break; - - // Compression not supported -> error - default: - return false; - } - - // Try to add file - if(!$this->add_file($entry['name'], $content)) - return false; - } - - return true; - } -} - -function &byref() { - $x = array(); - return $x; -} - - echo << - diff --git a/third_party/pygments/tests/examplefiles/test.pig b/third_party/pygments/tests/examplefiles/test.pig deleted file mode 100644 index f67b0268b..000000000 --- a/third_party/pygments/tests/examplefiles/test.pig +++ /dev/null @@ -1,148 +0,0 @@ -/** - * This script is an example recommender (using made up data) showing how you might modify item-item links - * by defining similar relations between items in a dataset and customizing the change in weighting. - * This example creates metadata by using the genre field as the metadata_field. The items with - * the same genre have it's weight cut in half in order to boost the signals of movies that do not have the same genre. - * This technique requires a customization of the standard GetItemItemRecommendations macro - */ -import 'recommenders.pig'; - - - -%default INPUT_PATH_PURCHASES '../data/retail/purchases.json' -%default INPUT_PATH_WISHLIST '../data/retail/wishlists.json' -%default INPUT_PATH_INVENTORY '../data/retail/inventory.json' -%default OUTPUT_PATH '../data/retail/out/modify_item_item' - - -/******** Custom GetItemItemRecommnedations *********/ -define recsys__GetItemItemRecommendations_ModifyCustom(user_item_signals, metadata) returns item_item_recs { - - -- Convert user_item_signals to an item_item_graph - ii_links_raw, item_weights = recsys__BuildItemItemGraph( - $user_item_signals, - $LOGISTIC_PARAM, - $MIN_LINK_WEIGHT, - $MAX_LINKS_PER_USER - ); - -- NOTE this function is added in order to combine metadata with item-item links - -- See macro for more detailed explination - ii_links_metadata = recsys__AddMetadataToItemItemLinks( - ii_links_raw, - $metadata - ); - - /********* Custom Code starts here ********/ - - --The code here should adjust the weights based on an item-item link and the equality of metadata. - -- In this case, if the metadata is the same, the weight is reduced. Otherwise the weight is left alone. - ii_links_adjusted = foreach ii_links_metadata generate item_A, item_B, - -- the amount of weight adjusted is dependant on the domain of data and what is expected - -- It is always best to adjust the weight by multiplying it by a factor rather than addition with a constant - (metadata_B == metadata_A ? (weight * 0.5): weight) as weight; - - - /******** Custom Code stops here *********/ - - -- remove negative numbers just incase - ii_links_adjusted_filt = foreach ii_links_adjusted generate item_A, item_B, - (weight <= 0 ? 0: weight) as weight; - -- Adjust the weights of the graph to improve recommendations. - ii_links = recsys__AdjustItemItemGraphWeight( - ii_links_adjusted_filt, - item_weights, - $BAYESIAN_PRIOR - ); - - -- Use the item-item graph to create item-item recommendations. - $item_item_recs = recsys__BuildItemItemRecommendationsFromGraph( - ii_links, - $NUM_RECS_PER_ITEM, - $NUM_RECS_PER_ITEM - ); -}; - - -/******* Load Data **********/ - ---Get purchase signals -purchase_input = load '$INPUT_PATH_PURCHASES' using org.apache.pig.piggybank.storage.JsonLoader( - 'row_id: int, - movie_id: chararray, - movie_name: chararray, - user_id: chararray, - purchase_price: int'); - ---Get wishlist signals -wishlist_input = load '$INPUT_PATH_WISHLIST' using org.apache.pig.piggybank.storage.JsonLoader( - 'row_id: int, - movie_id: chararray, - movie_name: chararray, - user_id: chararray'); - - -/******* Convert Data to Signals **********/ - --- Start with choosing 1 as max weight for a signal. -purchase_signals = foreach purchase_input generate - user_id as user, - movie_name as item, - 1.0 as weight; - - --- Start with choosing 0.5 as weight for wishlist items because that is a weaker signal than --- purchasing an item. -wishlist_signals = foreach wishlist_input generate - user_id as user, - movie_name as item, - 0.5 as weight; - -user_signals = union purchase_signals, wishlist_signals; - - -/******** Changes for Modifying item-item links ******/ -inventory_input = load '$INPUT_PATH_INVENTORY' using org.apache.pig.piggybank.storage.JsonLoader( - 'movie_title: chararray, - genres: bag{tuple(content:chararray)}'); - - -metadata = foreach inventory_input generate - FLATTEN(genres) as metadata_field, - movie_title as item; --- requires the macro to be written seperately - --NOTE this macro is defined within this file for clarity -item_item_recs = recsys__GetItemItemRecommendations_ModifyCustom(user_signals, metadata); -/******* No more changes ********/ - - -user_item_recs = recsys__GetUserItemRecommendations(user_signals, item_item_recs); - ---Completely unrelated code stuck in the middle -data = LOAD 's3n://my-s3-bucket/path/to/responses' - USING org.apache.pig.piggybank.storage.JsonLoader(); -responses = FOREACH data GENERATE object#'response' AS response: map[]; -out = FOREACH responses - GENERATE response#'id' AS id: int, response#'thread' AS thread: chararray, - response#'comments' AS comments: {t: (comment: chararray)}; -STORE out INTO 's3n://path/to/output' USING PigStorage('|'); - - -/******* Store recommendations **********/ - --- If your output folder exists already, hadoop will refuse to write data to it. - -rmf $OUTPUT_PATH/item_item_recs; -rmf $OUTPUT_PATH/user_item_recs; - -store item_item_recs into '$OUTPUT_PATH/item_item_recs' using PigStorage(); -store user_item_recs into '$OUTPUT_PATH/user_item_recs' using PigStorage(); - --- STORE the item_item_recs into dynamo -STORE item_item_recs - INTO '$OUTPUT_PATH/unused-ii-table-data' -USING com.mortardata.pig.storage.DynamoDBStorage('$II_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY'); - --- STORE the user_item_recs into dynamo -STORE user_item_recs - INTO '$OUTPUT_PATH/unused-ui-table-data' -USING com.mortardata.pig.storage.DynamoDBStorage('$UI_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY'); diff --git a/third_party/pygments/tests/examplefiles/test.plot b/third_party/pygments/tests/examplefiles/test.plot deleted file mode 100644 index cef0f908e..000000000 --- a/third_party/pygments/tests/examplefiles/test.plot +++ /dev/null @@ -1,333 +0,0 @@ -# -# $Id: prob2.dem,v 1.9 2006/06/14 03:24:09 sfeam Exp $ -# -# Demo Statistical Approximations version 1.1 -# -# Copyright (c) 1991, Jos van der Woude, jvdwoude@hut.nl - -# History: -# -- --- 1991 Jos van der Woude: 1st version -# 06 Jun 2006 Dan Sebald: Added plot methods for better visual effect. - -print "" -print "" -print "" -print "" -print "" -print "" -print " Statistical Approximations, version 1.1" -print "" -print " Copyright (c) 1991, 1992, Jos van de Woude, jvdwoude@hut.nl" -print "" -print "" -print "" -print "" -print "" -print "" -print "" -print "" -print "" -print "" -print "" -print " NOTE: contains 10 plots and consequently takes some time to run" -print " Press Ctrl-C to exit right now" -print "" -pause -1 " Press Return to start demo ..." - -load "stat.inc" -rnd(x) = floor(x+0.5) -r_xmin = -1 -r_sigma = 4.0 - -# Binomial PDF using normal approximation -n = 25; p = 0.15 -mu = n * p -sigma = sqrt(n * p * (1.0 - p)) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * binom(floor((n+1)*p), n, p) #mode of binomial PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "binomial PDF using normal approximation" -set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot binom(rnd(x), n, p) with histeps, normal(x, mu, sigma) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Binomial PDF using poisson approximation -n = 50; p = 0.1 -mu = n * p -sigma = sqrt(mu) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * binom(floor((n+1)*p), n, p) #mode of binomial PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample (xmax - xmin + 3) -set title "binomial PDF using poisson approximation" -set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot binom(x, n, p) with histeps, poisson(x, mu) with histeps -pause -1 "Hit return to continue" -unset arrow -unset label - -# Geometric PDF using gamma approximation -p = 0.3 -mu = (1.0 - p) / p -sigma = sqrt(mu / p) -lambda = p -rho = 1.0 - p -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * p -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "geometric PDF using gamma approximation" -set arrow from mu, 0 to mu, gmm(mu, rho, lambda) nohead -set arrow from mu, gmm(mu + sigma, rho, lambda) \ - to mu + sigma, gmm(mu + sigma, rho, lambda) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, gmm(mu + sigma, rho, lambda) -plot geometric(rnd(x),p) with histeps, gmm(x, rho, lambda) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Geometric PDF using normal approximation -p = 0.3 -mu = (1.0 - p) / p -sigma = sqrt(mu / p) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * p -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "geometric PDF using normal approximation" -set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot geometric(rnd(x),p) with histeps, normal(x, mu, sigma) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Hypergeometric PDF using binomial approximation -nn = 75; mm = 25; n = 10 -p = real(mm) / nn -mu = n * p -sigma = sqrt(real(nn - n) / (nn - 1.0) * n * p * (1.0 - p)) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * hypgeo(floor(mu), nn, mm, n) #mode of binom PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample (xmax - xmin + 3) -set title "hypergeometric PDF using binomial approximation" -set arrow from mu, 0 to mu, binom(floor(mu), n, p) nohead -set arrow from mu, binom(floor(mu + sigma), n, p) \ - to mu + sigma, binom(floor(mu + sigma), n, p) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, binom(floor(mu + sigma), n, p) -plot hypgeo(x, nn, mm, n) with histeps, binom(x, n, p) with histeps -pause -1 "Hit return to continue" -unset arrow -unset label - -# Hypergeometric PDF using normal approximation -nn = 75; mm = 25; n = 10 -p = real(mm) / nn -mu = n * p -sigma = sqrt(real(nn - n) / (nn - 1.0) * n * p * (1.0 - p)) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * hypgeo(floor(mu), nn, mm, n) #mode of binom PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "hypergeometric PDF using normal approximation" -set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot hypgeo(rnd(x), nn, mm, n) with histeps, normal(x, mu, sigma) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Negative binomial PDF using gamma approximation -r = 8; p = 0.6 -mu = r * (1.0 - p) / p -sigma = sqrt(mu / p) -lambda = p -rho = r * (1.0 - p) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * gmm((rho - 1) / lambda, rho, lambda) #mode of gamma PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "negative binomial PDF using gamma approximation" -set arrow from mu, 0 to mu, gmm(mu, rho, lambda) nohead -set arrow from mu, gmm(mu + sigma, rho, lambda) \ - to mu + sigma, gmm(mu + sigma, rho, lambda) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, gmm(mu + sigma, rho, lambda) -plot negbin(rnd(x), r, p) with histeps, gmm(x, rho, lambda) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Negative binomial PDF using normal approximation -r = 8; p = 0.4 -mu = r * (1.0 - p) / p -sigma = sqrt(mu / p) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * negbin(floor((r-1)*(1-p)/p), r, p) #mode of gamma PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "negative binomial PDF using normal approximation" -set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot negbin(rnd(x), r, p) with histeps, normal(x, mu, sigma) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Normal PDF using logistic approximation -mu = 1.0; sigma = 1.5 -a = mu -lambda = pi / (sqrt(3.0) * sigma) -xmin = mu - r_sigma * sigma -xmax = mu + r_sigma * sigma -ymax = 1.1 * logistic(mu, a, lambda) #mode of logistic PDF used -set key box -unset zeroaxis -set xrange [xmin: xmax] -set yrange [0 : ymax] -set xlabel "x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%.1f" -set format y "%.2f" -set sample 200 -set title "normal PDF using logistic approximation" -set arrow from mu,0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot logistic(x, a, lambda), normal(x, mu, sigma) -pause -1 "Hit return to continue" -unset arrow -unset label - -# Poisson PDF using normal approximation -mu = 5.0 -sigma = sqrt(mu) -xmin = floor(mu - r_sigma * sigma) -xmin = xmin < r_xmin ? r_xmin : xmin -xmax = ceil(mu + r_sigma * sigma) -ymax = 1.1 * poisson(mu, mu) #mode of poisson PDF used -set key box -unset zeroaxis -set xrange [xmin - 1 : xmax + 1] -set yrange [0 : ymax] -set xlabel "k, x ->" -set ylabel "probability density ->" -set ytics 0, ymax / 10.0, ymax -set format x "%2.0f" -set format y "%3.2f" -set sample 200 -set title "poisson PDF using normal approximation" -set arrow from mu, 0 to mu, normal(mu, mu, sigma) nohead -set arrow from mu, normal(mu + sigma, mu, sigma) \ - to mu + sigma, normal(mu + sigma, mu, sigma) nohead -set label "mu" at mu + 0.5, ymax / 10 -set label "sigma" at mu + 0.5 + sigma, normal(mu + sigma, mu, sigma) -plot poisson(rnd(x), mu) with histeps, normal(x, mu, sigma) -pause -1 "Hit return to continue" -reset diff --git a/third_party/pygments/tests/examplefiles/test.ps1 b/third_party/pygments/tests/examplefiles/test.ps1 deleted file mode 100644 index 385fb6f42..000000000 --- a/third_party/pygments/tests/examplefiles/test.ps1 +++ /dev/null @@ -1,108 +0,0 @@ -<# -.SYNOPSIS -Runs a T-SQL Query and optional outputs results to a delimited file. -.DESCRIPTION -Invoke-Sql script will run a T-SQL query or stored procedure and optionally outputs a delimited file. -.EXAMPLE -PowerShell.exe -File "C:\Scripts\Invoke-Sql.ps1" -ServerInstance "Z003\sqlprod2" -Database orders -Query "EXEC usp_accounts '12445678'" -This example connects to Z003\sqlprod2.Orders and executes a stored procedure which does not return a result set -.EXAMPLE -PowerShell.exe -File "C:\Scripts\Invoke-Sql.ps1" -ServerInstance "Z003\sqlprod2" -Database orders -Query "SELECT * FROM dbo.accounts" -FilePath "C:\Scripts\accounts.txt" -Delimiter "," -This example connects to Z003\sqlprod2.Orders and selects the records from the accounts tables, the data is outputed to a CSV file -.NOTES -Version History -v1.0 - Chad Miller - 12/14/2010 - Initial release -IMPORTANT!!! The EventLog source which is set to the application needs to be registered with -the Event log: -New-EventLog -LogName Application -Source $Application -#> -param( -#ServerInstance is Mandatory! -[Parameter(Position=0, Mandatory=$false)] [string]$ServerInstance, -#Database is Mandatory! -[Parameter(Position=1, Mandatory=$false)] [string]$Database, -#Query is Mandatory! -[Parameter(Position=2, Mandatory=$false)] [string]$Query, -[Parameter(Position=3, Mandatory=$false)] [string]$Application="Invoke-Sql.ps1", -[Parameter(Position=4, Mandatory=$false)] [string]$FilePath, -[Parameter(Position=7, Mandatory=$false)] [string]$Delimiter="|", -#If UserName isn't supplied a trusted connection will be used -[Parameter(Position=5, Mandatory=$false)] [string]$UserName, -[Parameter(Position=6, Mandatory=$false)] [string]$Password, -[Parameter(Position=8, Mandatory=$false)] [Int32]$QueryTimeout=600, -[Parameter(Position=9, Mandatory=$false)] [Int32]$ConnectionTimeout=15 -) - - -#This must be run as administrator on Windows 2008 and higher! -New-EventLog -LogName Application -Source $Application -EA SilentlyContinue -$Error.Clear() - -####################### -function Invoke-SqlCmd2 -{ - param( - [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, - [Parameter(Position=1, Mandatory=$true)] [string]$Database, - [Parameter(Position=2, Mandatory=$true)] [string]$Query, - [Parameter(Position=3, Mandatory=$false)] [string]$UserName, - [Parameter(Position=4, Mandatory=$false)] [string]$Password, - [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout, - [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout - ) - - try { - if ($Username) - { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } - else - { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } - $conn=new-object System.Data.SqlClient.SQLConnection - $conn.ConnectionString=$ConnectionString - $conn.Open() - $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) - $cmd.CommandTimeout=$QueryTimeout - $ds=New-Object system.Data.DataSet - $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) - [void]$da.fill($ds) - Write-Output ($ds.Tables[0]) - } - finally { - $conn.Dispose() - } - -} #Invoke-SqlCmd2 - -####################### -# MAIN # -####################### -if ($PSBoundParameters.Count -eq 0) -{ - get-help $myInvocation.MyCommand.Path -full - break -} - -try { - $msg = $null - $msg += "Application/Job Name: $Application`n" - $msg += "Query: $Query`n" - $msg += "ServerInstance: $ServerInstance`n" - $msg += "Database: $Database`n" - $msg += "FilePath: $FilePath`n" - - Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Starting`n$msg" - $dt = Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database $Database -Query $Query -UserName $UserName -Password $Password -QueryTimeOut $QueryTimeOut -ConnectionTimeout $ConnectionTimeout - if ($FilePath) - { - if ($dt) - { $dt | export-csv -Delimiter $Delimiter -Path $FilePath -NoTypeInformation } - else #Query Returned No Output! - {Write-EventLog -LogName Application -Source "$Application" -EntryType Warning -EventId 12345 -Message "NoOutput`n$msg" } - } - - Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Completed`n$msg" -} -catch { - $Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" ) - Write-EventLog -LogName Application -Source "$Application" -EntryType Error -EventId 12345 -Message "Error`n$msg`n$Exception" - throw -} diff --git a/third_party/pygments/tests/examplefiles/test.psl b/third_party/pygments/tests/examplefiles/test.psl deleted file mode 100644 index 3ac994985..000000000 --- a/third_party/pygments/tests/examplefiles/test.psl +++ /dev/null @@ -1,182 +0,0 @@ -// This is a comment - -// 1. Basics - -// Functions -func Add(X : Univ_Integer; Y : Univ_Integer) -> Univ_Integer is - return X + Y; -end func Add; -// End of line semi-colons are optional -// +, +=, -, -=, *, *=, /, /= -// all do what you'd expect (/ is integer division) - -// If you find Univ_Integer to be too verbose you can import Short_Names -// which defines aliases like Int for Univ_Integer and String for Univ_String -import PSL::Short_Names::*, * - -func Greetings() is - const S : String := "Hello, World!" - Println(S) -end func Greetings -// All declarations are 'const', 'var', or 'ref' -// Assignment is :=, equality checks are ==, and != is not equals - -func Boolean_Examples(B : Bool) is - const And := B and #true // Parallel execution of operands - const And_Then := B and then #true // Short-Circuit - const Or := B or #false // Parallel execution of operands - const Or_Else := B or else #false // Short-Cirtuit - const Xor := B xor #true - var Result : Bool := #true; - Result and= #false; - Result or= #true; - Result xor= #false; -end func Boolean_Examples -// Booleans are a special type of enumeration -// All enumerations are preceded by a sharp '#' - -func Fib(N : Int) {N >= 0} -> Int is - if N <= 1 then - return N - else - // Left and right side of '+' are computed in Parallel here - return Fib(N - 1) + Fib(N - 2) - end if -end func Fib -// '{N >= 0}' is a precondition to this function -// Preconditions are built in to the language and checked by the compiler - -// ParaSail does not have mutable global variables -// Instead, use 'var' parameters -func Increment_All(var Nums : Vector) is - for each Elem of Nums concurrent loop - Elem += 1 - end loop -end func Increment_All -// The 'concurrent' keyword in the loop header tells the compiler that -// iterations of the loop can happen in any order. -// It will choose the most optimal number of threads to use. -// Other options are 'forward' and 'reverse'. - -func Sum_Of_Squares(N : Int) -> Int is - // The type of Sum is inferred - var Sum := 0 - for I in 1 .. N forward loop - Sum += I ** 2 // ** is exponentiation - end loop -end func Sum_Of_Squares - -func Sum_Of(N : Int; Map : func (Int) -> Int) -> Int is - return (for I in 1 .. N => <0> + Map(I)) -end func Sum_Of -// It has functional aspects as well -// Here, we're taking an (Int) -> Int function as a parameter -// and using the inherently parallel map-reduce. -// Initial value is enclosed with angle brackets - -func main(Args : Basic_Array) is - Greetings() // Hello World - Println(Fib(5)) // 5 - // Container Comprehension - var Vec : Vector := [for I in 0 .. 10 {I mod 2 == 0} => I ** 2] - // Vec = [0, 4, 16, 36, 64, 100] - Increment_All(Vec) - // Vec = [1, 5, 17, 37, 65, 101] - // '|' is an overloaded operator. - // It's usually used for concatenation or adding to a container - Println("First: " | Vec[1] | ", Last: " | Vec[Length(Vec)]); - // Vectors are 1 indexed, 0 indexed ZVectors are also available - - Println(Sum_Of_Squares(3)) - - // Sum of fibs! - Println(Sum_Of(10, Fib)) -end func main - -// Preceding a type with 'optional' allows it to take the value 'null' -func Divide(A, B, C : Real) -> optional Real is - // Real is the floating point type - const Epsilon := 1.0e-6; - if B in -Epsilon .. Epsilon then - return null - elsif C in -Epsilon .. Epsilon then - return null - else - return A / B + A / C - end if -end func Divide - -// 2. Modules -// Modules are composed of an interface and a class -// ParaSail has object orientation features - -// modules can be defined as 'concurrent' -// which allows 'locked' and 'queued' parameters -concurrent interface Locked_Box> is - // Create a box with the given content - func Create(C : optional Content_Type) -> Locked_Box; - - // Put something into the box - func Put(locked var B : Locked_Box; C : Content_Type); - - // Get a copy of current content - func Content(locked B : Locked_Box) -> optional Content_Type; - - // Remove current content, leaving it null - func Remove(locked var B : Locked_Box) -> optional Content_Type; - - // Wait until content is non-null, then return it, leaving it null. - func Get(queued var B : Locked_Box) -> Content_Type; -end interface Locked_Box; - -concurrent class Locked_Box is - var Content : optional Content_Type; -exports - func Create(C : optional Content_Type) -> Locked_Box is - return (Content => C); - end func Create; - - func Put(locked var B : Locked_Box; C : Content_Type) is - B.Content := C; - end func Put; - - func Content(locked B : Locked_Box) -> optional Content_Type is - return B.Content; - end func Content; - - func Remove(locked var B : Locked_Box) -> Result : optional Content_Type is - // '<==' is the move operator - // It moves the right operand into the left operand, - // leaving the right null. - Result <== B.Content; - end func Remove; - - func Get(queued var B : Locked_Box) -> Result : Content_Type is - queued until B.Content not null then - Result <== B.Content; - end func Get; -end class Locked_Box; - -func Use_Box(Seed : Univ_Integer) is - var U_Box : Locked_Box := Create(null); - // The type of 'Ran' can be left out because - // it is inferred from the return type of Random::Start - var Ran := Random::Start(Seed); - - Println("Starting 100 pico-threads trying to put something in the box"); - Println(" or take something out."); - for I in 1..100 concurrent loop - if I < 30 then - Println("Getting out " | Get(U_Box)); - else - Println("Putting in " | I); - U_Box.Put(I); - - // The first parameter can be moved to the front with a dot - // X.Foo(Y) is equivalent to Foo(X, Y) - end if; - end loop; - - Println("And the winner is: " | Remove(U_Box)); - Println("And the box is now " | Content(U_Box)); -end func Use_Box; diff --git a/third_party/pygments/tests/examplefiles/test.pwn b/third_party/pygments/tests/examplefiles/test.pwn deleted file mode 100644 index d64686178..000000000 --- a/third_party/pygments/tests/examplefiles/test.pwn +++ /dev/null @@ -1,253 +0,0 @@ -#include - -// Single line comment -/* Multi line - comment */ - -/// documentation -/** - - documentation multi line - -**/ - -public OnGameModeInit() { - printf("Hello, World!"); -} - -enum info { - Float:ex; - exa, - exam[5], -} -new arr[5][info]; - -stock Float:test_func() -{ - new a = 5, Float:b = 10.3; - if (a == b) { - - } else { - - } - - for (new i = 0; i < 10; i++) { - continue; - } - - do { - a--; - } while (a > 0); - - while (a < 5) { - a++; - break; - } - - switch (a) { - case 0: { - } - case 0..4: { - } - case 5, 6: { - } - } - - static x; - new xx = a > 5 ? 5 : 0; - new array[sizeof arr] = {0}; - tagof a; - state a; - goto label; - new byte[2 char]; - byte{0} = 'a'; - - return (float(a) + b); -} - - -// float.inc -/* Float arithmetic - * - * (c) Copyright 1999, Artran, Inc. - * Written by Greg Garner (gmg@artran.com) - * Modified in March 2001 to include user defined - * operators for the floating point functions. - * - * This file is provided as is (no warranties). - */ -#if defined _Float_included - #endinput -#endif -#define _Float_included -#pragma library Float - -/* Different methods of rounding */ -enum floatround_method { - floatround_round, - floatround_floor, - floatround_ceil, - floatround_tozero, - floatround_unbiased -} -enum anglemode { - radian, - degrees, - grades -} - -/**************************************************/ -/* Convert an integer into a floating point value */ -native Float:float(value); - -/**************************************************/ -/* Convert a string into a floating point value */ -native Float:floatstr(const string[]); - -/**************************************************/ -/* Multiple two floats together */ -native Float:floatmul(Float:oper1, Float:oper2); - -/**************************************************/ -/* Divide the dividend float by the divisor float */ -native Float:floatdiv(Float:dividend, Float:divisor); - -/**************************************************/ -/* Add two floats together */ -native Float:floatadd(Float:oper1, Float:oper2); - -/**************************************************/ -/* Subtract oper2 float from oper1 float */ -native Float:floatsub(Float:oper1, Float:oper2); - -/**************************************************/ -/* Return the fractional part of a float */ -native Float:floatfract(Float:value); - -/**************************************************/ -/* Round a float into a integer value */ -native floatround(Float:value, floatround_method:method=floatround_round); - -/**************************************************/ -/* Compare two integers. If the two elements are equal, return 0. - If the first argument is greater than the second argument, return 1, - If the first argument is less than the second argument, return -1. */ -native floatcmp(Float:oper1, Float:oper2); - -/**************************************************/ -/* Return the square root of the input value, same as floatpower(value, 0.5) */ -native Float:floatsqroot(Float:value); - -/**************************************************/ -/* Return the value raised to the power of the exponent */ -native Float:floatpower(Float:value, Float:exponent); - -/**************************************************/ -/* Return the logarithm */ -native Float:floatlog(Float:value, Float:base=10.0); - -/**************************************************/ -/* Return the sine, cosine or tangent. The input angle may be in radian, - degrees or grades. */ -native Float:floatsin(Float:value, anglemode:mode=radian); -native Float:floatcos(Float:value, anglemode:mode=radian); -native Float:floattan(Float:value, anglemode:mode=radian); - -/**************************************************/ -/* Return the absolute value */ -native Float:floatabs(Float:value); - - -/**************************************************/ -#pragma rational Float - -/* user defined operators */ -native Float:operator*(Float:oper1, Float:oper2) = floatmul; -native Float:operator/(Float:oper1, Float:oper2) = floatdiv; -native Float:operator+(Float:oper1, Float:oper2) = floatadd; -native Float:operator-(Float:oper1, Float:oper2) = floatsub; -native Float:operator=(oper) = float; - -stock Float:operator++(Float:oper) - return oper+1.0; - -stock Float:operator--(Float:oper) - return oper-1.0; - -stock Float:operator-(Float:oper) - return oper^Float:cellmin; /* IEEE values are sign/magnitude */ - -stock Float:operator*(Float:oper1, oper2) - return floatmul(oper1, float(oper2)); /* "*" is commutative */ - -stock Float:operator/(Float:oper1, oper2) - return floatdiv(oper1, float(oper2)); - -stock Float:operator/(oper1, Float:oper2) - return floatdiv(float(oper1), oper2); - -stock Float:operator+(Float:oper1, oper2) - return floatadd(oper1, float(oper2)); /* "+" is commutative */ - -stock Float:operator-(Float:oper1, oper2) - return floatsub(oper1, float(oper2)); - -stock Float:operator-(oper1, Float:oper2) - return floatsub(float(oper1), oper2); - -stock bool:operator==(Float:oper1, Float:oper2) - return floatcmp(oper1, oper2) == 0; - -stock bool:operator==(Float:oper1, oper2) - return floatcmp(oper1, float(oper2)) == 0; /* "==" is commutative */ - -stock bool:operator!=(Float:oper1, Float:oper2) - return floatcmp(oper1, oper2) != 0; - -stock bool:operator!=(Float:oper1, oper2) - return floatcmp(oper1, float(oper2)) != 0; /* "!=" is commutative */ - -stock bool:operator>(Float:oper1, Float:oper2) - return floatcmp(oper1, oper2) > 0; - -stock bool:operator>(Float:oper1, oper2) - return floatcmp(oper1, float(oper2)) > 0; - -stock bool:operator>(oper1, Float:oper2) - return floatcmp(float(oper1), oper2) > 0; - -stock bool:operator>=(Float:oper1, Float:oper2) - return floatcmp(oper1, oper2) >= 0; - -stock bool:operator>=(Float:oper1, oper2) - return floatcmp(oper1, float(oper2)) >= 0; - -stock bool:operator>=(oper1, Float:oper2) - return floatcmp(float(oper1), oper2) >= 0; - -stock bool:operator<(Float:oper1, Float:oper2) - return floatcmp(oper1, oper2) < 0; - -stock bool:operator<(Float:oper1, oper2) - return floatcmp(oper1, float(oper2)) < 0; - -stock bool:operator<(oper1, Float:oper2) - return floatcmp(float(oper1), oper2) < 0; - -stock bool:operator<=(Float:oper1, Float:oper2) - return floatcmp(oper1, oper2) <= 0; - -stock bool:operator<=(Float:oper1, oper2) - return floatcmp(oper1, float(oper2)) <= 0; - -stock bool:operator<=(oper1, Float:oper2) - return floatcmp(float(oper1), oper2) <= 0; - -stock bool:operator!(Float:oper) - return (_:oper & cellmax) == 0; - -/* forbidden operations */ -forward operator%(Float:oper1, Float:oper2); -forward operator%(Float:oper1, oper2); -forward operator%(oper1, Float:oper2); - diff --git a/third_party/pygments/tests/examplefiles/test.pypylog b/third_party/pygments/tests/examplefiles/test.pypylog deleted file mode 100644 index 1a6aa5ed3..000000000 --- a/third_party/pygments/tests/examplefiles/test.pypylog +++ /dev/null @@ -1,1000 +0,0 @@ -[5ed621f277b8] {jit-backend-counts -[5ed621f309bc] jit-backend-counts} -[5ed622c957b0] {jit-log-opt-loop -# Loop 0 : loop with 145 ops -[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, f11, p12, p13, p14, p15, i16, f17, i18, i19, i20, i21, i22, i23, i24, i25, i26, f27, i28, f29, f30] -debug_merge_point(' #125 FOR_ITER', 0) -i32 = int_gt(i18, 0) -guard_true(i32, descr=) [p1, p0, p5, p2, p3, p4, p6, p7, p8, p9, p10, p12, p13, p14, p15, i16, f17, f11] -i33 = int_add(i19, i20) -i35 = int_sub(i18, 1) -debug_merge_point(' #128 STORE_FAST', 0) -debug_merge_point(' #131 LOAD_FAST', 0) -debug_merge_point(' #134 LOAD_FAST', 0) -debug_merge_point(' #137 LOAD_FAST', 0) -debug_merge_point(' #140 BINARY_MULTIPLY', 0) -setfield_gc(p5, i33, descr=) -setfield_gc(p5, i35, descr=) -i36 = int_mul_ovf(i21, i22) -guard_no_overflow(, descr=) [p1, p0, p12, p15, i36, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p13, i19, None, f17, f11] -debug_merge_point(' #141 LOAD_FAST', 0) -debug_merge_point(' #144 BINARY_ADD', 0) -i38 = int_add_ovf(i36, i19) -guard_no_overflow(, descr=) [p1, p0, i38, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i36, i19, None, f17, f11] -debug_merge_point(' #145 BINARY_SUBSCR', 0) -i40 = int_lt(i38, 0) -guard_false(i40, descr=) [p1, p0, p14, i38, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, i19, None, f17, f11] -i41 = int_lt(i38, i23) -guard_true(i41, descr=) [p1, p0, p14, i38, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, i19, None, f17, f11] -f42 = getarrayitem_raw(i24, i38, descr=) -debug_merge_point(' #146 STORE_FAST', 0) -debug_merge_point(' #149 LOAD_FAST', 0) -debug_merge_point(' #152 LOAD_FAST', 0) -debug_merge_point(' #155 LOAD_CONST', 0) -debug_merge_point(' #158 BINARY_SUBTRACT', 0) -debug_merge_point(' #159 LOAD_FAST', 0) -debug_merge_point(' #162 BINARY_MULTIPLY', 0) -debug_merge_point(' #163 LOAD_FAST', 0) -debug_merge_point(' #166 BINARY_ADD', 0) -i43 = int_add_ovf(i25, i19) -guard_no_overflow(, descr=) [p1, p0, i43, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f42, i25, None, i19, None, None, f11] -debug_merge_point(' #167 BINARY_SUBSCR', 0) -i45 = int_lt(i43, 0) -guard_false(i45, descr=) [p1, p0, p14, i43, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f42, None, None, i19, None, None, f11] -i46 = int_lt(i43, i23) -guard_true(i46, descr=) [p1, p0, p14, i43, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f42, None, None, i19, None, None, f11] -f47 = getarrayitem_raw(i24, i43, descr=) -debug_merge_point(' #168 LOAD_FAST', 0) -debug_merge_point(' #171 LOAD_FAST', 0) -debug_merge_point(' #174 LOAD_CONST', 0) -debug_merge_point(' #177 BINARY_ADD', 0) -debug_merge_point(' #178 LOAD_FAST', 0) -debug_merge_point(' #181 BINARY_MULTIPLY', 0) -debug_merge_point(' #182 LOAD_FAST', 0) -debug_merge_point(' #185 BINARY_ADD', 0) -i48 = int_add_ovf(i26, i19) -guard_no_overflow(, descr=) [p1, p0, i48, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i26, f47, f42, None, None, i19, None, None, f11] -debug_merge_point(' #186 BINARY_SUBSCR', 0) -i50 = int_lt(i48, 0) -guard_false(i50, descr=) [p1, p0, p14, i48, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f47, f42, None, None, i19, None, None, f11] -i51 = int_lt(i48, i23) -guard_true(i51, descr=) [p1, p0, p14, i48, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f47, f42, None, None, i19, None, None, f11] -f52 = getarrayitem_raw(i24, i48, descr=) -debug_merge_point(' #187 BINARY_ADD', 0) -f53 = float_add(f47, f52) -debug_merge_point(' #188 LOAD_FAST', 0) -debug_merge_point(' #191 BINARY_MULTIPLY', 0) -f54 = float_mul(f53, f27) -debug_merge_point(' #192 LOAD_FAST', 0) -debug_merge_point(' #195 LOAD_FAST', 0) -debug_merge_point(' #198 LOAD_FAST', 0) -debug_merge_point(' #201 BINARY_MULTIPLY', 0) -debug_merge_point(' #202 LOAD_FAST', 0) -debug_merge_point(' #205 BINARY_ADD', 0) -i55 = int_add_ovf(i28, i19) -guard_no_overflow(, descr=) [p1, p0, i55, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f54, i28, None, None, f42, None, None, i19, None, None, f11] -debug_merge_point(' #206 LOAD_CONST', 0) -debug_merge_point(' #209 BINARY_SUBTRACT', 0) -i57 = int_sub_ovf(i55, 1) -guard_no_overflow(, descr=) [p1, p0, i57, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i55, f54, None, None, None, f42, None, None, i19, None, None, f11] -debug_merge_point(' #210 BINARY_SUBSCR', 0) -i59 = int_lt(i57, 0) -guard_false(i59, descr=) [p1, p0, p14, i57, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f54, None, None, None, f42, None, None, i19, None, None, f11] -i60 = int_lt(i57, i23) -guard_true(i60, descr=) [p1, p0, p14, i57, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f54, None, None, None, f42, None, None, i19, None, None, f11] -f61 = getarrayitem_raw(i24, i57, descr=) -debug_merge_point(' #211 LOAD_FAST', 0) -debug_merge_point(' #214 LOAD_FAST', 0) -debug_merge_point(' #217 LOAD_FAST', 0) -debug_merge_point(' #220 BINARY_MULTIPLY', 0) -debug_merge_point(' #221 LOAD_FAST', 0) -debug_merge_point(' #224 BINARY_ADD', 0) -debug_merge_point(' #225 LOAD_CONST', 0) -debug_merge_point(' #228 BINARY_ADD', 0) -i63 = int_add_ovf(i55, 1) -guard_no_overflow(, descr=) [p1, p0, i63, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f61, i55, f54, None, None, None, f42, None, None, i19, None, None, f11] -debug_merge_point(' #229 BINARY_SUBSCR', 0) -i64 = int_lt(i63, i23) -guard_true(i64, descr=) [p1, p0, p14, i63, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f61, None, f54, None, None, None, f42, None, None, i19, None, None, f11] -f65 = getarrayitem_raw(i24, i63, descr=) -debug_merge_point(' #230 BINARY_ADD', 0) -f66 = float_add(f61, f65) -debug_merge_point(' #231 LOAD_FAST', 0) -debug_merge_point(' #234 BINARY_MULTIPLY', 0) -f67 = float_mul(f66, f29) -debug_merge_point(' #235 BINARY_ADD', 0) -f68 = float_add(f54, f67) -debug_merge_point(' #236 LOAD_FAST', 0) -debug_merge_point(' #239 BINARY_MULTIPLY', 0) -f69 = float_mul(f68, f30) -debug_merge_point(' #240 LOAD_FAST', 0) -debug_merge_point(' #243 LOAD_FAST', 0) -debug_merge_point(' #246 LOAD_FAST', 0) -debug_merge_point(' #249 BINARY_MULTIPLY', 0) -debug_merge_point(' #250 LOAD_FAST', 0) -debug_merge_point(' #253 BINARY_ADD', 0) -debug_merge_point(' #254 STORE_SUBSCR', 0) -i70 = int_lt(i55, i23) -guard_true(i70, descr=) [p1, p0, p14, i55, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f69, None, None, None, None, None, None, f42, None, None, i19, None, None, f11] -setarrayitem_raw(i24, i55, f69, descr=) -debug_merge_point(' #255 LOAD_FAST', 0) -debug_merge_point(' #258 LOAD_GLOBAL', 0) -debug_merge_point(' #261 LOAD_FAST', 0) -debug_merge_point(' #264 LOAD_FAST', 0) -debug_merge_point(' #267 LOAD_FAST', 0) -debug_merge_point(' #270 BINARY_MULTIPLY', 0) -debug_merge_point(' #271 LOAD_FAST', 0) -debug_merge_point(' #274 BINARY_ADD', 0) -debug_merge_point(' #275 BINARY_SUBSCR', 0) -f71 = getarrayitem_raw(i24, i55, descr=) -debug_merge_point(' #276 LOAD_FAST', 0) -debug_merge_point(' #279 BINARY_SUBTRACT', 0) -f72 = float_sub(f71, f42) -debug_merge_point(' #280 CALL_FUNCTION', 0) -i73 = force_token() -debug_merge_point(' #0 LOAD_FAST', 1) -debug_merge_point(' #3 LOAD_FAST', 1) -debug_merge_point(' #6 BINARY_MULTIPLY', 1) -f74 = float_mul(f72, f72) -debug_merge_point(' #7 RETURN_VALUE', 1) -debug_merge_point(' #283 INPLACE_ADD', 0) -f75 = float_add(f11, f74) -debug_merge_point(' #284 STORE_FAST', 0) -debug_merge_point(' #287 JUMP_ABSOLUTE', 0) -i77 = getfield_raw(38968960, descr=) -i79 = int_sub(i77, 26) -setfield_raw(38968960, i79, descr=) -i81 = int_lt(i79, 0) -guard_false(i81, descr=) [p1, p0, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p14, p15, f75, None, None, None, None, None, None, None, f42, None, None, i19, None, None, None] -debug_merge_point(' #125 FOR_ITER', 0) -jump(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, f75, p12, p13, p14, p15, i19, f42, i35, i33, i20, i21, i22, i23, i24, i25, i26, f27, i36, f29, f30, descr=) -[5ed622d5187e] jit-log-opt-loop} -[5ed622e116d0] {jit-log-opt-loop -# Loop 1 : entry bridge with 188 ops -[p0, p1, p2, p3, i4, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] -debug_merge_point(' #125 FOR_ITER', 0) -guard_value(i4, 2, descr=) [i4, p1, p0, p2, p3, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] -guard_class(p9, 19861240, descr=) [p1, p0, p9, p2, p3, p5, i6, p8, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] -i29 = getfield_gc(p9, descr=) -i31 = int_gt(i29, 0) -guard_true(i31, descr=) [p1, p0, p9, p2, p3, p5, i6, p8, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] -i32 = getfield_gc(p9, descr=) -i33 = getfield_gc(p9, descr=) -i34 = int_add(i32, i33) -i36 = int_sub(i29, 1) -setfield_gc(p9, i34, descr=) -setfield_gc(p9, i36, descr=) -guard_value(i6, 0, descr=) [i6, p1, p0, p2, p3, p5, p8, p9, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, i32] -debug_merge_point(' #128 STORE_FAST', 0) -debug_merge_point(' #131 LOAD_FAST', 0) -guard_nonnull_class(p23, 19886912, descr=) [p1, p0, p23, p2, p3, p5, p8, p9, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, i32] -debug_merge_point(' #134 LOAD_FAST', 0) -guard_nonnull_class(p24, ConstClass(W_IntObject), descr=) [p1, p0, p24, p2, p3, p5, p8, p9, p23, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p26, i32] -debug_merge_point(' #137 LOAD_FAST', 0) -guard_nonnull_class(p21, ConstClass(W_IntObject), descr=) [p1, p0, p21, p2, p3, p5, p8, p9, p23, p24, p12, p13, p14, p15, p16, p17, p18, p19, p20, p22, p26, i32] -debug_merge_point(' #140 BINARY_MULTIPLY', 0) -i41 = getfield_gc_pure(p24, descr=) -i42 = getfield_gc_pure(p21, descr=) -i43 = int_mul_ovf(i41, i42) -guard_no_overflow(, descr=) [p1, p0, p21, p24, i43, p2, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p22, p26, i32] -debug_merge_point(' #141 LOAD_FAST', 0) -debug_merge_point(' #144 BINARY_ADD', 0) -i44 = int_add_ovf(i43, i32) -guard_no_overflow(, descr=) [p1, p0, i44, p2, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, i43, i32] -debug_merge_point(' #145 BINARY_SUBSCR', 0) -i45 = getfield_gc(p23, descr=) -i47 = int_lt(i44, 0) -guard_false(i47, descr=) [p1, p0, p23, i44, i45, p2, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, None, i32] -i49 = int_lt(i44, i45) -guard_true(i49, descr=) [p1, p0, p23, i44, p2, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, None, i32] -i50 = getfield_gc(p23, descr=) -f51 = getarrayitem_raw(i50, i44, descr=) -debug_merge_point(' #146 STORE_FAST', 0) -debug_merge_point(' #149 LOAD_FAST', 0) -debug_merge_point(' #152 LOAD_FAST', 0) -debug_merge_point(' #155 LOAD_CONST', 0) -guard_value(p2, ConstPtr(ptr52), descr=) [p1, p0, p2, p3, p5, p8, p9, p23, p24, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, f51, None, i32] -debug_merge_point(' #158 BINARY_SUBTRACT', 0) -i54 = int_sub_ovf(i41, 1) -guard_no_overflow(, descr=) [p1, p0, p24, i54, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, f51, None, i32] -debug_merge_point(' #159 LOAD_FAST', 0) -debug_merge_point(' #162 BINARY_MULTIPLY', 0) -i55 = int_mul_ovf(i54, i42) -guard_no_overflow(, descr=) [p1, p0, p21, i55, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p22, p24, i54, f51, None, i32] -debug_merge_point(' #163 LOAD_FAST', 0) -debug_merge_point(' #166 BINARY_ADD', 0) -i56 = int_add_ovf(i55, i32) -guard_no_overflow(, descr=) [p1, p0, i56, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, i55, None, f51, None, i32] -debug_merge_point(' #167 BINARY_SUBSCR', 0) -i58 = int_lt(i56, 0) -guard_false(i58, descr=) [p1, p0, p23, i56, i45, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f51, None, i32] -i59 = int_lt(i56, i45) -guard_true(i59, descr=) [p1, p0, p23, i56, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f51, None, i32] -f60 = getarrayitem_raw(i50, i56, descr=) -debug_merge_point(' #168 LOAD_FAST', 0) -debug_merge_point(' #171 LOAD_FAST', 0) -debug_merge_point(' #174 LOAD_CONST', 0) -debug_merge_point(' #177 BINARY_ADD', 0) -i62 = int_add_ovf(i41, 1) -guard_no_overflow(, descr=) [p1, p0, p24, i62, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p21, p22, f60, None, None, f51, None, i32] -debug_merge_point(' #178 LOAD_FAST', 0) -debug_merge_point(' #181 BINARY_MULTIPLY', 0) -i63 = int_mul_ovf(i62, i42) -guard_no_overflow(, descr=) [p1, p0, p21, i63, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p22, p24, i62, f60, None, None, f51, None, i32] -debug_merge_point(' #182 LOAD_FAST', 0) -debug_merge_point(' #185 BINARY_ADD', 0) -i64 = int_add_ovf(i63, i32) -guard_no_overflow(, descr=) [p1, p0, i64, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, i63, None, f60, None, None, f51, None, i32] -debug_merge_point(' #186 BINARY_SUBSCR', 0) -i66 = int_lt(i64, 0) -guard_false(i66, descr=) [p1, p0, p23, i64, i45, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f60, None, None, f51, None, i32] -i67 = int_lt(i64, i45) -guard_true(i67, descr=) [p1, p0, p23, i64, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f60, None, None, f51, None, i32] -f68 = getarrayitem_raw(i50, i64, descr=) -debug_merge_point(' #187 BINARY_ADD', 0) -f69 = float_add(f60, f68) -debug_merge_point(' #188 LOAD_FAST', 0) -guard_nonnull_class(p18, 19800744, descr=) [p1, p0, p18, p3, p5, p8, p9, p14, p15, p16, p17, p19, p20, p21, p22, p23, p24, f69, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #191 BINARY_MULTIPLY', 0) -f71 = getfield_gc_pure(p18, descr=) -f72 = float_mul(f69, f71) -debug_merge_point(' #192 LOAD_FAST', 0) -debug_merge_point(' #195 LOAD_FAST', 0) -debug_merge_point(' #198 LOAD_FAST', 0) -debug_merge_point(' #201 BINARY_MULTIPLY', 0) -debug_merge_point(' #202 LOAD_FAST', 0) -debug_merge_point(' #205 BINARY_ADD', 0) -debug_merge_point(' #206 LOAD_CONST', 0) -debug_merge_point(' #209 BINARY_SUBTRACT', 0) -i74 = int_sub(i44, 1) -debug_merge_point(' #210 BINARY_SUBSCR', 0) -i76 = int_lt(i74, 0) -guard_false(i76, descr=) [p1, p0, p23, i74, i45, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, f72, None, None, None, None, None, None, f51, None, i32] -i77 = int_lt(i74, i45) -guard_true(i77, descr=) [p1, p0, p23, i74, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, f72, None, None, None, None, None, None, f51, None, i32] -f78 = getarrayitem_raw(i50, i74, descr=) -debug_merge_point(' #211 LOAD_FAST', 0) -debug_merge_point(' #214 LOAD_FAST', 0) -debug_merge_point(' #217 LOAD_FAST', 0) -debug_merge_point(' #220 BINARY_MULTIPLY', 0) -debug_merge_point(' #221 LOAD_FAST', 0) -debug_merge_point(' #224 BINARY_ADD', 0) -debug_merge_point(' #225 LOAD_CONST', 0) -debug_merge_point(' #228 BINARY_ADD', 0) -i80 = int_add(i44, 1) -debug_merge_point(' #229 BINARY_SUBSCR', 0) -i81 = int_lt(i80, i45) -guard_true(i81, descr=) [p1, p0, p23, i80, p3, p5, p8, p9, p15, p16, p17, p18, p19, p20, p21, p22, p24, f78, f72, None, None, None, None, None, None, f51, None, i32] -f82 = getarrayitem_raw(i50, i80, descr=) -debug_merge_point(' #230 BINARY_ADD', 0) -f83 = float_add(f78, f82) -debug_merge_point(' #231 LOAD_FAST', 0) -guard_nonnull_class(p17, 19800744, descr=) [p1, p0, p17, p3, p5, p8, p9, p15, p16, p18, p19, p20, p21, p22, p23, p24, f83, None, f72, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #234 BINARY_MULTIPLY', 0) -f85 = getfield_gc_pure(p17, descr=) -f86 = float_mul(f83, f85) -debug_merge_point(' #235 BINARY_ADD', 0) -f87 = float_add(f72, f86) -debug_merge_point(' #236 LOAD_FAST', 0) -guard_nonnull_class(p19, 19800744, descr=) [p1, p0, p19, p3, p5, p8, p9, p15, p16, p17, p18, p20, p21, p22, p23, p24, f87, None, None, None, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #239 BINARY_MULTIPLY', 0) -f89 = getfield_gc_pure(p19, descr=) -f90 = float_mul(f87, f89) -debug_merge_point(' #240 LOAD_FAST', 0) -debug_merge_point(' #243 LOAD_FAST', 0) -debug_merge_point(' #246 LOAD_FAST', 0) -debug_merge_point(' #249 BINARY_MULTIPLY', 0) -debug_merge_point(' #250 LOAD_FAST', 0) -debug_merge_point(' #253 BINARY_ADD', 0) -debug_merge_point(' #254 STORE_SUBSCR', 0) -setarrayitem_raw(i50, i44, f90, descr=) -debug_merge_point(' #255 LOAD_FAST', 0) -guard_nonnull_class(p20, 19800744, descr=) [p1, p0, p20, p3, p5, p8, p9, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #258 LOAD_GLOBAL', 0) -p92 = getfield_gc(p0, descr=) -guard_value(p92, ConstPtr(ptr93), descr=) [p1, p0, p92, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -p94 = getfield_gc(p92, descr=) -guard_isnull(p94, descr=) [p1, p0, p94, p92, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -p96 = getfield_gc(ConstPtr(ptr95), descr=) -guard_nonnull_class(p96, ConstClass(Function), descr=) [p1, p0, p96, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #261 LOAD_FAST', 0) -debug_merge_point(' #264 LOAD_FAST', 0) -debug_merge_point(' #267 LOAD_FAST', 0) -debug_merge_point(' #270 BINARY_MULTIPLY', 0) -debug_merge_point(' #271 LOAD_FAST', 0) -debug_merge_point(' #274 BINARY_ADD', 0) -debug_merge_point(' #275 BINARY_SUBSCR', 0) -f98 = getarrayitem_raw(i50, i44, descr=) -debug_merge_point(' #276 LOAD_FAST', 0) -debug_merge_point(' #279 BINARY_SUBTRACT', 0) -f99 = float_sub(f98, f51) -debug_merge_point(' #280 CALL_FUNCTION', 0) -p100 = getfield_gc(p96, descr=) -guard_value(p100, ConstPtr(ptr101), descr=) [p1, p0, p100, p96, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -p102 = getfield_gc(p96, descr=) -p103 = getfield_gc(p96, descr=) -p105 = call(ConstClass(getexecutioncontext), descr=) -p106 = getfield_gc(p105, descr=) -i107 = force_token() -p108 = getfield_gc(p105, descr=) -guard_isnull(p108, descr=) [p1, p0, p105, p108, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -i109 = getfield_gc(p105, descr=) -i110 = int_is_zero(i109) -guard_true(i110, descr=) [p1, p0, p105, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #0 LOAD_FAST', 1) -debug_merge_point(' #3 LOAD_FAST', 1) -debug_merge_point(' #6 BINARY_MULTIPLY', 1) -f111 = float_mul(f99, f99) -debug_merge_point(' #7 RETURN_VALUE', 1) -i112 = int_is_true(i109) -guard_false(i112, descr=) [p1, p0, p105, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, f111, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #283 INPLACE_ADD', 0) -f113 = getfield_gc_pure(p20, descr=) -f114 = float_add(f113, f111) -debug_merge_point(' #284 STORE_FAST', 0) -debug_merge_point(' #287 JUMP_ABSOLUTE', 0) -i116 = getfield_raw(38968960, descr=) -i118 = int_sub(i116, 26) -setfield_raw(38968960, i118, descr=) -i120 = int_lt(i118, 0) -guard_false(i120, descr=) [p1, p0, p3, p5, p8, p9, p15, p16, p17, p18, p19, p21, p22, p23, p24, f114, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f51, None, i32] -debug_merge_point(' #125 FOR_ITER', 0) -jump(p0, p1, p3, p5, p8, p9, p15, p16, p17, p18, p19, f114, p21, p22, p23, p24, i32, f51, i36, i34, i33, i41, i42, i45, i50, i55, i63, f71, i43, f85, f89, descr=) -[5ed622ea316e] jit-log-opt-loop} -[5ed62326a846] {jit-log-opt-bridge -# bridge out of Guard 21 with 13 ops -[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] -i18 = force_token() -setfield_gc(p1, i18, descr=) -call_may_force(ConstClass(action_dispatcher), p0, p1, descr=) -guard_not_forced(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i17, f16, f15] -guard_no_exception(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i17, f16, f15] -debug_merge_point(' #125 FOR_ITER', 0) -p21 = new_with_vtable(19800744) -setfield_gc(p21, f15, descr=) -p23 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p23, i17, descr=) -p25 = new_with_vtable(19800744) -setfield_gc(p25, f16, descr=) -jump(p1, p0, ConstPtr(ptr26), p2, 2, p3, 0, 125, p4, p5, ConstPtr(ptr30), ConstPtr(ptr31), ConstPtr(ptr32), ConstPtr(ptr33), ConstPtr(ptr34), p6, p7, p8, p9, p10, p21, p11, p12, p13, p14, p23, p25, descr=) -[5ed62327d096] jit-log-opt-bridge} -[5ed623eb929c] {jit-log-opt-bridge -# bridge out of Guard 3 with 260 ops -[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] -debug_merge_point(' #290 POP_BLOCK', 0) -p18 = getfield_gc(p3, descr=) -guard_class(p3, 19865144, descr=) [p0, p1, p3, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] -i20 = getfield_gc(p3, descr=) -guard_value(i20, 1, descr=) [p0, p1, i20, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] -debug_merge_point(' #291 JUMP_ABSOLUTE', 0) -i23 = getfield_raw(38968960, descr=) -i25 = int_sub(i23, 1) -setfield_raw(38968960, i25, descr=) -i27 = int_lt(i25, 0) -guard_false(i27, descr=) [p0, p1, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] -debug_merge_point(' #99 FOR_ITER', 0) -guard_class(p5, 19861240, descr=) [p0, p1, p5, p18, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] -i29 = getfield_gc(p5, descr=) -i31 = int_gt(i29, 0) -guard_true(i31, descr=) [p0, p1, p5, p18, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] -i32 = getfield_gc(p5, descr=) -i33 = getfield_gc(p5, descr=) -i34 = int_add(i32, i33) -i36 = int_sub(i29, 1) -debug_merge_point(' #102 STORE_FAST', 0) -debug_merge_point(' #105 SETUP_LOOP', 0) -debug_merge_point(' #108 LOAD_GLOBAL', 0) -p37 = getfield_gc(p1, descr=) -setfield_gc(p5, i34, descr=) -setfield_gc(p5, i36, descr=) -guard_value(p37, ConstPtr(ptr38), descr=) [p0, p1, p37, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] -p39 = getfield_gc(p37, descr=) -guard_isnull(p39, descr=) [p0, p1, p39, p37, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] -p41 = getfield_gc(ConstPtr(ptr40), descr=) -guard_isnull(p41, descr=) [p0, p1, p41, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] -p43 = getfield_gc(ConstPtr(ptr42), descr=) -guard_value(p43, ConstPtr(ptr44), descr=) [p0, p1, p43, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] -p45 = getfield_gc(p43, descr=) -guard_isnull(p45, descr=) [p0, p1, p45, p43, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] -p47 = getfield_gc(ConstPtr(ptr46), descr=) -guard_value(p47, ConstPtr(ptr48), descr=) [p0, p1, p47, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] -debug_merge_point(' #111 LOAD_CONST', 0) -debug_merge_point(' #114 LOAD_FAST', 0) -guard_nonnull_class(p12, ConstClass(W_IntObject), descr=) [p0, p1, p12, p4, p5, p47, p6, p7, p8, p9, p10, p11, p13, i32, p18, i15, f16, f17] -debug_merge_point(' #117 LOAD_CONST', 0) -debug_merge_point(' #120 BINARY_SUBTRACT', 0) -i50 = getfield_gc_pure(p12, descr=) -i52 = int_sub_ovf(i50, 1) -guard_no_overflow(, descr=) [p0, p1, p12, i52, p4, p5, p47, p6, p7, p8, p9, p10, p11, p13, i32, p18, i15, f16, f17] -debug_merge_point(' #121 CALL_FUNCTION', 0) -p54 = getfield_gc(ConstPtr(ptr53), descr=) -p55 = getfield_gc(ConstPtr(ptr53), descr=) -i56 = getfield_gc_pure(p55, descr=) -guard_false(i56, descr=) [p0, p1, p54, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] -p57 = getfield_gc_pure(p55, descr=) -i58 = arraylen_gc(p57, descr=) -i60 = int_sub(4, i58) -i62 = int_ge(3, i60) -guard_true(i62, descr=) [p0, p1, p54, i60, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] -i63 = int_sub(3, i60) -i64 = getfield_gc_pure(p55, descr=) -guard_false(i64, descr=) [p0, p1, p54, i63, i60, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] -p65 = getfield_gc_pure(p55, descr=) -p66 = getarrayitem_gc(p65, i63, descr=) -guard_class(p66, ConstClass(W_IntObject), descr=) [p0, p1, p66, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] -i68 = getfield_gc_pure(p66, descr=) -i69 = int_is_zero(i68) -guard_false(i69, descr=) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] -i72 = int_lt(i68, 0) -guard_false(i72, descr=) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] -i74 = int_lt(1, i52) -guard_true(i74, descr=) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] -i75 = int_sub(i52, 1) -i77 = int_sub(i75, 1) -i78 = uint_floordiv(i77, i68) -i80 = int_add(i78, 1) -i82 = int_lt(i80, 0) -guard_false(i82, descr=) [p0, p1, i68, i80, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, i52, i32, p18, i15, f16, f17] -debug_merge_point(' #124 GET_ITER', 0) -debug_merge_point(' #125 FOR_ITER', 0) -i84 = int_gt(i80, 0) -guard_true(i84, descr=) [p0, p1, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i80, i68, None, None, i32, p18, i15, f16, f17] -i85 = int_add(1, i68) -debug_merge_point(' #128 STORE_FAST', 0) -debug_merge_point(' #131 LOAD_FAST', 0) -guard_nonnull_class(p13, 19886912, descr=) [p0, p1, p13, p4, p5, p6, p7, p8, p9, p10, p11, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] -debug_merge_point(' #134 LOAD_FAST', 0) -debug_merge_point(' #137 LOAD_FAST', 0) -guard_nonnull_class(p11, ConstClass(W_IntObject), descr=) [p0, p1, p11, p4, p5, p13, p6, p7, p8, p9, p10, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] -debug_merge_point(' #140 BINARY_MULTIPLY', 0) -i88 = getfield_gc_pure(p11, descr=) -i89 = int_mul_ovf(i32, i88) -guard_no_overflow(, descr=) [p0, p1, p11, i89, p4, p5, p13, p6, p7, p8, p9, p10, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] -debug_merge_point(' #141 LOAD_FAST', 0) -debug_merge_point(' #144 BINARY_ADD', 0) -i90 = int_add_ovf(i89, 1) -guard_no_overflow(, descr=) [p0, p1, i90, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i89, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] -debug_merge_point(' #145 BINARY_SUBSCR', 0) -i91 = getfield_gc(p13, descr=) -i93 = int_lt(i90, 0) -guard_false(i93, descr=) [p0, p1, p13, i90, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] -i94 = int_lt(i90, i91) -guard_true(i94, descr=) [p0, p1, p13, i90, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] -i95 = getfield_gc(p13, descr=) -f96 = getarrayitem_raw(i95, i90, descr=) -debug_merge_point(' #146 STORE_FAST', 0) -debug_merge_point(' #149 LOAD_FAST', 0) -debug_merge_point(' #152 LOAD_FAST', 0) -debug_merge_point(' #155 LOAD_CONST', 0) -debug_merge_point(' #158 BINARY_SUBTRACT', 0) -i98 = int_sub_ovf(i32, 1) -guard_no_overflow(, descr=) [p0, p1, i98, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #159 LOAD_FAST', 0) -debug_merge_point(' #162 BINARY_MULTIPLY', 0) -i99 = int_mul_ovf(i98, i88) -guard_no_overflow(, descr=) [p0, p1, p11, i99, p4, p5, p13, p6, p7, p8, p9, p10, p12, i98, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #163 LOAD_FAST', 0) -debug_merge_point(' #166 BINARY_ADD', 0) -i100 = int_add_ovf(i99, 1) -guard_no_overflow(, descr=) [p0, p1, i100, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i99, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #167 BINARY_SUBSCR', 0) -i102 = int_lt(i100, 0) -guard_false(i102, descr=) [p0, p1, p13, i100, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -i103 = int_lt(i100, i91) -guard_true(i103, descr=) [p0, p1, p13, i100, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -f104 = getarrayitem_raw(i95, i100, descr=) -debug_merge_point(' #168 LOAD_FAST', 0) -debug_merge_point(' #171 LOAD_FAST', 0) -debug_merge_point(' #174 LOAD_CONST', 0) -debug_merge_point(' #177 BINARY_ADD', 0) -i106 = int_add_ovf(i32, 1) -guard_no_overflow(, descr=) [p0, p1, i106, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #178 LOAD_FAST', 0) -debug_merge_point(' #181 BINARY_MULTIPLY', 0) -i107 = int_mul_ovf(i106, i88) -guard_no_overflow(, descr=) [p0, p1, p11, i107, p4, p5, p13, p6, p7, p8, p9, p10, p12, i106, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #182 LOAD_FAST', 0) -debug_merge_point(' #185 BINARY_ADD', 0) -i108 = int_add_ovf(i107, 1) -guard_no_overflow(, descr=) [p0, p1, i108, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i107, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #186 BINARY_SUBSCR', 0) -i110 = int_lt(i108, 0) -guard_false(i110, descr=) [p0, p1, p13, i108, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -i111 = int_lt(i108, i91) -guard_true(i111, descr=) [p0, p1, p13, i108, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -f112 = getarrayitem_raw(i95, i108, descr=) -debug_merge_point(' #187 BINARY_ADD', 0) -f113 = float_add(f104, f112) -debug_merge_point(' #188 LOAD_FAST', 0) -guard_nonnull_class(p9, 19800744, descr=) [p0, p1, p9, p4, p5, p6, p7, p8, p10, p11, p12, p13, f113, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #191 BINARY_MULTIPLY', 0) -f115 = getfield_gc_pure(p9, descr=) -f116 = float_mul(f113, f115) -debug_merge_point(' #192 LOAD_FAST', 0) -debug_merge_point(' #195 LOAD_FAST', 0) -debug_merge_point(' #198 LOAD_FAST', 0) -debug_merge_point(' #201 BINARY_MULTIPLY', 0) -debug_merge_point(' #202 LOAD_FAST', 0) -debug_merge_point(' #205 BINARY_ADD', 0) -debug_merge_point(' #206 LOAD_CONST', 0) -debug_merge_point(' #209 BINARY_SUBTRACT', 0) -debug_merge_point(' #210 BINARY_SUBSCR', 0) -i118 = int_lt(i89, 0) -guard_false(i118, descr=) [p0, p1, p13, i89, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -i119 = int_lt(i89, i91) -guard_true(i119, descr=) [p0, p1, p13, i89, p4, p5, p6, p7, p8, p9, p10, p11, p12, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -f120 = getarrayitem_raw(i95, i89, descr=) -debug_merge_point(' #211 LOAD_FAST', 0) -debug_merge_point(' #214 LOAD_FAST', 0) -debug_merge_point(' #217 LOAD_FAST', 0) -debug_merge_point(' #220 BINARY_MULTIPLY', 0) -debug_merge_point(' #221 LOAD_FAST', 0) -debug_merge_point(' #224 BINARY_ADD', 0) -debug_merge_point(' #225 LOAD_CONST', 0) -debug_merge_point(' #228 BINARY_ADD', 0) -i122 = int_add(i90, 1) -debug_merge_point(' #229 BINARY_SUBSCR', 0) -i123 = int_lt(i122, i91) -guard_true(i123, descr=) [p0, p1, p13, i122, p4, p5, p6, p7, p8, p9, p10, p11, p12, f120, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -f124 = getarrayitem_raw(i95, i122, descr=) -debug_merge_point(' #230 BINARY_ADD', 0) -f125 = float_add(f120, f124) -debug_merge_point(' #231 LOAD_FAST', 0) -guard_nonnull_class(p8, 19800744, descr=) [p0, p1, p8, p4, p5, p6, p7, p9, p10, p11, p12, p13, f125, None, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #234 BINARY_MULTIPLY', 0) -f127 = getfield_gc_pure(p8, descr=) -f128 = float_mul(f125, f127) -debug_merge_point(' #235 BINARY_ADD', 0) -f129 = float_add(f116, f128) -debug_merge_point(' #236 LOAD_FAST', 0) -guard_nonnull_class(p10, 19800744, descr=) [p0, p1, p10, p4, p5, p6, p7, p8, p9, p11, p12, p13, f129, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #239 BINARY_MULTIPLY', 0) -f131 = getfield_gc_pure(p10, descr=) -f132 = float_mul(f129, f131) -debug_merge_point(' #240 LOAD_FAST', 0) -debug_merge_point(' #243 LOAD_FAST', 0) -debug_merge_point(' #246 LOAD_FAST', 0) -debug_merge_point(' #249 BINARY_MULTIPLY', 0) -debug_merge_point(' #250 LOAD_FAST', 0) -debug_merge_point(' #253 BINARY_ADD', 0) -debug_merge_point(' #254 STORE_SUBSCR', 0) -setarrayitem_raw(i95, i90, f132, descr=) -debug_merge_point(' #255 LOAD_FAST', 0) -debug_merge_point(' #258 LOAD_GLOBAL', 0) -p134 = getfield_gc(ConstPtr(ptr133), descr=) -guard_nonnull_class(p134, ConstClass(Function), descr=) [p0, p1, p134, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #261 LOAD_FAST', 0) -debug_merge_point(' #264 LOAD_FAST', 0) -debug_merge_point(' #267 LOAD_FAST', 0) -debug_merge_point(' #270 BINARY_MULTIPLY', 0) -debug_merge_point(' #271 LOAD_FAST', 0) -debug_merge_point(' #274 BINARY_ADD', 0) -debug_merge_point(' #275 BINARY_SUBSCR', 0) -f136 = getarrayitem_raw(i95, i90, descr=) -debug_merge_point(' #276 LOAD_FAST', 0) -debug_merge_point(' #279 BINARY_SUBTRACT', 0) -f137 = float_sub(f136, f96) -debug_merge_point(' #280 CALL_FUNCTION', 0) -p138 = getfield_gc(p134, descr=) -guard_value(p138, ConstPtr(ptr139), descr=) [p0, p1, p138, p134, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -p140 = getfield_gc(p134, descr=) -p141 = getfield_gc(p134, descr=) -p143 = call(ConstClass(getexecutioncontext), descr=) -p144 = getfield_gc(p143, descr=) -i145 = force_token() -p146 = getfield_gc(p143, descr=) -guard_isnull(p146, descr=) [p0, p1, p143, p146, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -i147 = getfield_gc(p143, descr=) -i148 = int_is_zero(i147) -guard_true(i148, descr=) [p0, p1, p143, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #0 LOAD_FAST', 1) -debug_merge_point(' #3 LOAD_FAST', 1) -debug_merge_point(' #6 BINARY_MULTIPLY', 1) -f149 = float_mul(f137, f137) -debug_merge_point(' #7 RETURN_VALUE', 1) -i150 = int_is_true(i147) -guard_false(i150, descr=) [p0, p1, p143, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, f149, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] -debug_merge_point(' #283 INPLACE_ADD', 0) -f151 = float_add(f17, f149) -debug_merge_point(' #284 STORE_FAST', 0) -debug_merge_point(' #287 JUMP_ABSOLUTE', 0) -i153 = getfield_raw(38968960, descr=) -i155 = int_sub(i153, 35) -setfield_raw(38968960, i155, descr=) -i157 = int_lt(i155, 0) -guard_false(i157, descr=) [p0, p1, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f151, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, None] -debug_merge_point(' #125 FOR_ITER', 0) -p159 = new_with_vtable(19865144) -setfield_gc(p159, 291, descr=) -setfield_gc(p159, 1, descr=) -setfield_gc(p159, p18, descr=) -p163 = new_with_vtable(19861240) -setfield_gc(p163, i85, descr=) -setfield_gc(p163, i78, descr=) -setfield_gc(p163, i68, descr=) -p165 = new_with_vtable(19800744) -setfield_gc(p165, f151, descr=) -p167 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p167, i32, descr=) -p169 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p169, 1, descr=) -p171 = new_with_vtable(19800744) -setfield_gc(p171, f96, descr=) -jump(p1, p0, ConstPtr(ptr172), p159, 2, p4, 0, 125, p5, p163, ConstPtr(ptr176), ConstPtr(ptr177), ConstPtr(ptr178), ConstPtr(ptr179), ConstPtr(ptr180), p6, p7, p8, p9, p10, p165, p11, p12, p13, p167, p169, p171, descr=) -[5ed623fc609b] jit-log-opt-bridge} -[5ed63ea5fa94] {jit-log-opt-bridge -# bridge out of Guard 110 with 23 ops -[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, f12, f13, i14, i15, i16, i17, p18] -i19 = force_token() -setfield_gc(p1, i19, descr=) -call_may_force(ConstClass(action_dispatcher), p0, p1, descr=) -guard_not_forced(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, i14, i17, i16, i15, f12, f13, p18] -guard_no_exception(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, i14, i17, i16, i15, f12, f13, p18] -debug_merge_point(' #125 FOR_ITER', 0) -p22 = new_with_vtable(19865144) -setfield_gc(p22, 291, descr=) -setfield_gc(p22, p18, descr=) -setfield_gc(p22, 1, descr=) -p26 = new_with_vtable(19861240) -setfield_gc(p26, i15, descr=) -setfield_gc(p26, i14, descr=) -setfield_gc(p26, i16, descr=) -p28 = new_with_vtable(19800744) -setfield_gc(p28, f12, descr=) -p30 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p30, i17, descr=) -p32 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p32, 1, descr=) -p35 = new_with_vtable(19800744) -setfield_gc(p35, f13, descr=) -jump(p1, p0, ConstPtr(ptr36), p22, 2, p2, 0, 125, p3, p26, ConstPtr(ptr40), ConstPtr(ptr41), ConstPtr(ptr42), ConstPtr(ptr43), ConstPtr(ptr44), p4, p5, p6, p7, p8, p28, p9, p10, p11, p30, p32, p35, descr=) -[5ed63ea8ea04] jit-log-opt-bridge} -[5ed640a0a34c] {jit-log-opt-bridge -# bridge out of Guard 58 with 13 ops -[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] -i18 = force_token() -setfield_gc(p1, i18, descr=) -call_may_force(ConstClass(action_dispatcher), p0, p1, descr=) -guard_not_forced(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] -guard_no_exception(, descr=) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] -debug_merge_point(' #125 FOR_ITER', 0) -p21 = new_with_vtable(19800744) -setfield_gc(p21, f15, descr=) -p23 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p23, i17, descr=) -p25 = new_with_vtable(19800744) -setfield_gc(p25, f16, descr=) -jump(p1, p0, ConstPtr(ptr26), p2, 2, p3, 0, 125, p4, p5, ConstPtr(ptr30), ConstPtr(ptr31), ConstPtr(ptr32), ConstPtr(ptr33), ConstPtr(ptr34), p6, p7, p8, p9, p10, p21, p11, p12, p13, p14, p23, p25, descr=) -[5ed640a1e8c2] jit-log-opt-bridge} -[5ed6431fc824] {jit-log-opt-bridge -# bridge out of Guard 24 with 264 ops -[p0, p1, p2, p3, p4, p5, i6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -guard_value(i6, 0, descr=) [i6, p0, p1, p3, p4, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -debug_merge_point(' #290 POP_BLOCK', 0) -p26 = getfield_gc(p4, descr=) -guard_class(p4, 19865144, descr=) [p0, p1, p4, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -i28 = getfield_gc(p4, descr=) -guard_value(i28, 1, descr=) [p0, p1, i28, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -debug_merge_point(' #291 JUMP_ABSOLUTE', 0) -i31 = getfield_raw(38968960, descr=) -i33 = int_sub(i31, 1) -setfield_raw(38968960, i33, descr=) -i35 = int_lt(i33, 0) -guard_false(i35, descr=) [p0, p1, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -guard_value(p3, ConstPtr(ptr36), descr=) [p0, p1, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -debug_merge_point(' #99 FOR_ITER', 0) -guard_class(p7, 19861240, descr=) [p0, p1, p7, p26, p5, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -i38 = getfield_gc(p7, descr=) -i40 = int_gt(i38, 0) -guard_true(i40, descr=) [p0, p1, p7, p26, p5, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] -i41 = getfield_gc(p7, descr=) -i42 = getfield_gc(p7, descr=) -i43 = int_add(i41, i42) -i45 = int_sub(i38, 1) -debug_merge_point(' #102 STORE_FAST', 0) -debug_merge_point(' #105 SETUP_LOOP', 0) -debug_merge_point(' #108 LOAD_GLOBAL', 0) -p46 = getfield_gc(p1, descr=) -setfield_gc(p7, i43, descr=) -setfield_gc(p7, i45, descr=) -guard_value(p46, ConstPtr(ptr47), descr=) [p0, p1, p46, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] -p48 = getfield_gc(p46, descr=) -guard_isnull(p48, descr=) [p0, p1, p48, p46, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] -p50 = getfield_gc(ConstPtr(ptr49), descr=) -guard_isnull(p50, descr=) [p0, p1, p50, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] -p52 = getfield_gc(ConstPtr(ptr51), descr=) -guard_value(p52, ConstPtr(ptr53), descr=) [p0, p1, p52, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] -p54 = getfield_gc(p52, descr=) -guard_isnull(p54, descr=) [p0, p1, p54, p52, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] -p56 = getfield_gc(ConstPtr(ptr55), descr=) -guard_value(p56, ConstPtr(ptr57), descr=) [p0, p1, p56, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] -debug_merge_point(' #111 LOAD_CONST', 0) -debug_merge_point(' #114 LOAD_FAST', 0) -guard_nonnull_class(p20, ConstClass(W_IntObject), descr=) [p0, p1, p20, p5, p7, p56, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p21, p23, p24, p26, i41] -debug_merge_point(' #117 LOAD_CONST', 0) -debug_merge_point(' #120 BINARY_SUBTRACT', 0) -i59 = getfield_gc_pure(p20, descr=) -i61 = int_sub_ovf(i59, 1) -guard_no_overflow(, descr=) [p0, p1, p20, i61, p5, p7, p56, p11, p12, p13, p14, p15, p16, p17, p18, p19, p21, p23, p24, p26, i41] -debug_merge_point(' #121 CALL_FUNCTION', 0) -p63 = getfield_gc(ConstPtr(ptr62), descr=) -p64 = getfield_gc(ConstPtr(ptr62), descr=) -i65 = getfield_gc_pure(p64, descr=) -guard_false(i65, descr=) [p0, p1, p63, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] -p66 = getfield_gc_pure(p64, descr=) -i67 = arraylen_gc(p66, descr=) -i69 = int_sub(4, i67) -i71 = int_ge(3, i69) -guard_true(i71, descr=) [p0, p1, p63, i69, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] -i72 = int_sub(3, i69) -i73 = getfield_gc_pure(p64, descr=) -guard_false(i73, descr=) [p0, p1, p63, i72, i69, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] -p74 = getfield_gc_pure(p64, descr=) -p75 = getarrayitem_gc(p74, i72, descr=) -guard_class(p75, ConstClass(W_IntObject), descr=) [p0, p1, p75, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] -i77 = getfield_gc_pure(p75, descr=) -i78 = int_is_zero(i77) -guard_false(i78, descr=) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] -i81 = int_lt(i77, 0) -guard_false(i81, descr=) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] -i83 = int_lt(1, i61) -guard_true(i83, descr=) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] -i84 = int_sub(i61, 1) -i86 = int_sub(i84, 1) -i87 = uint_floordiv(i86, i77) -i89 = int_add(i87, 1) -i91 = int_lt(i89, 0) -guard_false(i91, descr=) [p0, p1, i77, i89, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, i61, p26, i41] -debug_merge_point(' #124 GET_ITER', 0) -debug_merge_point(' #125 FOR_ITER', 0) -i93 = int_gt(i89, 0) -guard_true(i93, descr=) [p0, p1, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i89, i77, None, None, p26, i41] -i94 = int_add(1, i77) -debug_merge_point(' #128 STORE_FAST', 0) -debug_merge_point(' #131 LOAD_FAST', 0) -guard_nonnull_class(p21, 19886912, descr=) [p0, p1, p21, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #134 LOAD_FAST', 0) -debug_merge_point(' #137 LOAD_FAST', 0) -guard_nonnull_class(p19, ConstClass(W_IntObject), descr=) [p0, p1, p19, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, p24, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #140 BINARY_MULTIPLY', 0) -i97 = getfield_gc_pure(p19, descr=) -i98 = int_mul_ovf(i41, i97) -guard_no_overflow(, descr=) [p0, p1, p19, i98, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, p24, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #141 LOAD_FAST', 0) -debug_merge_point(' #144 BINARY_ADD', 0) -i99 = int_add_ovf(i98, 1) -guard_no_overflow(, descr=) [p0, p1, i99, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, i98, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #145 BINARY_SUBSCR', 0) -i100 = getfield_gc(p21, descr=) -i102 = int_lt(i99, 0) -guard_false(i102, descr=) [p0, p1, p21, i99, i100, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, None, i87, i94, None, i77, None, None, p26, i41] -i103 = int_lt(i99, i100) -guard_true(i103, descr=) [p0, p1, p21, i99, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, None, i87, i94, None, i77, None, None, p26, i41] -i104 = getfield_gc(p21, descr=) -f105 = getarrayitem_raw(i104, i99, descr=) -debug_merge_point(' #146 STORE_FAST', 0) -debug_merge_point(' #149 LOAD_FAST', 0) -debug_merge_point(' #152 LOAD_FAST', 0) -debug_merge_point(' #155 LOAD_CONST', 0) -debug_merge_point(' #158 BINARY_SUBTRACT', 0) -i107 = int_sub_ovf(i41, 1) -guard_no_overflow(, descr=) [p0, p1, i107, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #159 LOAD_FAST', 0) -debug_merge_point(' #162 BINARY_MULTIPLY', 0) -i108 = int_mul_ovf(i107, i97) -guard_no_overflow(, descr=) [p0, p1, p19, i108, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, i107, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #163 LOAD_FAST', 0) -debug_merge_point(' #166 BINARY_ADD', 0) -i109 = int_add_ovf(i108, 1) -guard_no_overflow(, descr=) [p0, p1, i109, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, i108, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #167 BINARY_SUBSCR', 0) -i111 = int_lt(i109, 0) -guard_false(i111, descr=) [p0, p1, p21, i109, i100, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -i112 = int_lt(i109, i100) -guard_true(i112, descr=) [p0, p1, p21, i109, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -f113 = getarrayitem_raw(i104, i109, descr=) -debug_merge_point(' #168 LOAD_FAST', 0) -debug_merge_point(' #171 LOAD_FAST', 0) -debug_merge_point(' #174 LOAD_CONST', 0) -debug_merge_point(' #177 BINARY_ADD', 0) -i115 = int_add_ovf(i41, 1) -guard_no_overflow(, descr=) [p0, p1, i115, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p19, p20, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #178 LOAD_FAST', 0) -debug_merge_point(' #181 BINARY_MULTIPLY', 0) -i116 = int_mul_ovf(i115, i97) -guard_no_overflow(, descr=) [p0, p1, p19, i116, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p20, i115, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #182 LOAD_FAST', 0) -debug_merge_point(' #185 BINARY_ADD', 0) -i117 = int_add_ovf(i116, 1) -guard_no_overflow(, descr=) [p0, p1, i117, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p19, p20, i116, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #186 BINARY_SUBSCR', 0) -i119 = int_lt(i117, 0) -guard_false(i119, descr=) [p0, p1, p21, i117, i100, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -i120 = int_lt(i117, i100) -guard_true(i120, descr=) [p0, p1, p21, i117, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -f121 = getarrayitem_raw(i104, i117, descr=) -debug_merge_point(' #187 BINARY_ADD', 0) -f122 = float_add(f113, f121) -debug_merge_point(' #188 LOAD_FAST', 0) -guard_nonnull_class(p16, 19800744, descr=) [p0, p1, p16, p5, p7, p12, p13, p14, p15, p17, p18, p19, p20, p21, f122, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #191 BINARY_MULTIPLY', 0) -f124 = getfield_gc_pure(p16, descr=) -f125 = float_mul(f122, f124) -debug_merge_point(' #192 LOAD_FAST', 0) -debug_merge_point(' #195 LOAD_FAST', 0) -debug_merge_point(' #198 LOAD_FAST', 0) -debug_merge_point(' #201 BINARY_MULTIPLY', 0) -debug_merge_point(' #202 LOAD_FAST', 0) -debug_merge_point(' #205 BINARY_ADD', 0) -debug_merge_point(' #206 LOAD_CONST', 0) -debug_merge_point(' #209 BINARY_SUBTRACT', 0) -debug_merge_point(' #210 BINARY_SUBSCR', 0) -i127 = int_lt(i98, 0) -guard_false(i127, descr=) [p0, p1, p21, i98, i100, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -i128 = int_lt(i98, i100) -guard_true(i128, descr=) [p0, p1, p21, i98, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -f129 = getarrayitem_raw(i104, i98, descr=) -debug_merge_point(' #211 LOAD_FAST', 0) -debug_merge_point(' #214 LOAD_FAST', 0) -debug_merge_point(' #217 LOAD_FAST', 0) -debug_merge_point(' #220 BINARY_MULTIPLY', 0) -debug_merge_point(' #221 LOAD_FAST', 0) -debug_merge_point(' #224 BINARY_ADD', 0) -debug_merge_point(' #225 LOAD_CONST', 0) -debug_merge_point(' #228 BINARY_ADD', 0) -i131 = int_add(i99, 1) -debug_merge_point(' #229 BINARY_SUBSCR', 0) -i132 = int_lt(i131, i100) -guard_true(i132, descr=) [p0, p1, p21, i131, p5, p7, p13, p14, p15, p16, p17, p18, p19, p20, f129, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -f133 = getarrayitem_raw(i104, i131, descr=) -debug_merge_point(' #230 BINARY_ADD', 0) -f134 = float_add(f129, f133) -debug_merge_point(' #231 LOAD_FAST', 0) -guard_nonnull_class(p15, 19800744, descr=) [p0, p1, p15, p5, p7, p13, p14, p16, p17, p18, p19, p20, p21, f134, None, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #234 BINARY_MULTIPLY', 0) -f136 = getfield_gc_pure(p15, descr=) -f137 = float_mul(f134, f136) -debug_merge_point(' #235 BINARY_ADD', 0) -f138 = float_add(f125, f137) -debug_merge_point(' #236 LOAD_FAST', 0) -guard_nonnull_class(p17, 19800744, descr=) [p0, p1, p17, p5, p7, p13, p14, p15, p16, p18, p19, p20, p21, f138, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #239 BINARY_MULTIPLY', 0) -f140 = getfield_gc_pure(p17, descr=) -f141 = float_mul(f138, f140) -debug_merge_point(' #240 LOAD_FAST', 0) -debug_merge_point(' #243 LOAD_FAST', 0) -debug_merge_point(' #246 LOAD_FAST', 0) -debug_merge_point(' #249 BINARY_MULTIPLY', 0) -debug_merge_point(' #250 LOAD_FAST', 0) -debug_merge_point(' #253 BINARY_ADD', 0) -debug_merge_point(' #254 STORE_SUBSCR', 0) -setarrayitem_raw(i104, i99, f141, descr=) -debug_merge_point(' #255 LOAD_FAST', 0) -guard_nonnull_class(p18, 19800744, descr=) [p0, p1, p18, p5, p7, p13, p14, p15, p16, p17, p19, p20, p21, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #258 LOAD_GLOBAL', 0) -p144 = getfield_gc(ConstPtr(ptr143), descr=) -guard_nonnull_class(p144, ConstClass(Function), descr=) [p0, p1, p144, p5, p7, p18, p13, p14, p15, p16, p17, p19, p20, p21, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #261 LOAD_FAST', 0) -debug_merge_point(' #264 LOAD_FAST', 0) -debug_merge_point(' #267 LOAD_FAST', 0) -debug_merge_point(' #270 BINARY_MULTIPLY', 0) -debug_merge_point(' #271 LOAD_FAST', 0) -debug_merge_point(' #274 BINARY_ADD', 0) -debug_merge_point(' #275 BINARY_SUBSCR', 0) -f146 = getarrayitem_raw(i104, i99, descr=) -debug_merge_point(' #276 LOAD_FAST', 0) -debug_merge_point(' #279 BINARY_SUBTRACT', 0) -f147 = float_sub(f146, f105) -debug_merge_point(' #280 CALL_FUNCTION', 0) -p148 = getfield_gc(p144, descr=) -guard_value(p148, ConstPtr(ptr149), descr=) [p0, p1, p148, p144, p5, p7, p18, p13, p14, p15, p16, p17, p19, p20, p21, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -p150 = getfield_gc(p144, descr=) -p151 = getfield_gc(p144, descr=) -p153 = call(ConstClass(getexecutioncontext), descr=) -p154 = getfield_gc(p153, descr=) -i155 = force_token() -p156 = getfield_gc(p153, descr=) -guard_isnull(p156, descr=) [p0, p1, p153, p156, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -i157 = getfield_gc(p153, descr=) -i158 = int_is_zero(i157) -guard_true(i158, descr=) [p0, p1, p153, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #0 LOAD_FAST', 1) -debug_merge_point(' #3 LOAD_FAST', 1) -debug_merge_point(' #6 BINARY_MULTIPLY', 1) -f159 = float_mul(f147, f147) -debug_merge_point(' #7 RETURN_VALUE', 1) -i160 = int_is_true(i157) -guard_false(i160, descr=) [p0, p1, p153, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, f159, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #283 INPLACE_ADD', 0) -f161 = getfield_gc_pure(p18, descr=) -f162 = float_add(f161, f159) -debug_merge_point(' #284 STORE_FAST', 0) -debug_merge_point(' #287 JUMP_ABSOLUTE', 0) -i164 = getfield_raw(38968960, descr=) -i166 = int_sub(i164, 34) -setfield_raw(38968960, i166, descr=) -i168 = int_lt(i166, 0) -guard_false(i168, descr=) [p0, p1, p5, p7, p13, p14, p15, p16, p17, p19, p20, p21, f162, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] -debug_merge_point(' #125 FOR_ITER', 0) -p170 = new_with_vtable(19865144) -setfield_gc(p170, 291, descr=) -setfield_gc(p170, 1, descr=) -setfield_gc(p170, p26, descr=) -p174 = new_with_vtable(19861240) -setfield_gc(p174, i94, descr=) -setfield_gc(p174, i87, descr=) -setfield_gc(p174, i77, descr=) -p176 = new_with_vtable(19800744) -setfield_gc(p176, f162, descr=) -p178 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p178, i41, descr=) -p180 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p180, 1, descr=) -p182 = new_with_vtable(19800744) -setfield_gc(p182, f105, descr=) -jump(p1, p0, ConstPtr(ptr183), p170, 2, p5, 0, 125, p7, p174, ConstPtr(ptr187), ConstPtr(ptr188), ConstPtr(ptr189), ConstPtr(ptr190), ConstPtr(ptr191), p13, p14, p15, p16, p17, p176, p19, p20, p21, p178, p180, p182, descr=) -[5ed6432f4a2c] jit-log-opt-bridge} -[5ed66199330c] {jit-log-opt-bridge -# bridge out of Guard 65 with 72 ops -[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i14, f15, f16] -debug_merge_point(' #294 POP_BLOCK', 0) -p17 = getfield_gc(p3, descr=) -guard_class(p3, 19865144, descr=) [p0, p1, p3, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -i19 = getfield_gc(p3, descr=) -guard_value(i19, 0, descr=) [p0, p1, i19, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -debug_merge_point(' #295 LOAD_GLOBAL', 0) -p21 = getfield_gc(p1, descr=) -guard_value(p21, ConstPtr(ptr22), descr=) [p0, p1, p21, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -p23 = getfield_gc(p21, descr=) -guard_isnull(p23, descr=) [p0, p1, p23, p21, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -p25 = getfield_gc(ConstPtr(ptr24), descr=) -guard_nonnull_class(p25, 19905496, descr=) [p0, p1, p25, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -debug_merge_point(' #298 LOOKUP_METHOD', 0) -p27 = getfield_gc(p25, descr=) -guard_value(p27, ConstPtr(ptr28), descr=) [p0, p1, p25, p27, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -p29 = getfield_gc(p27, descr=) -guard_isnull(p29, descr=) [p0, p1, p25, p29, p27, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -p31 = getfield_gc(ConstPtr(ptr30), descr=) -guard_value(p31, ConstPtr(ptr32), descr=) [p0, p1, p31, p25, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -debug_merge_point(' #301 LOAD_FAST', 0) -debug_merge_point(' #304 CALL_METHOD', 0) -call(ConstClass(set_errno), 0, descr=) -f36 = call(ConstClass(sqrt), f16, descr=) -i38 = call(ConstClass(get_errno), descr=) -i39 = float_ne(f36, f36) -guard_false(i39, descr=) [p0, p1, i38, f36, f16, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, i14, f15] -i42 = float_eq(f36, inf) -i44 = float_eq(f36, -inf) -i45 = int_or(i42, i44) -i46 = int_is_true(i45) -guard_false(i46, descr=) [p0, p1, i38, f36, f16, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, i14, f15] -i47 = int_is_true(i38) -guard_false(i47, descr=) [p0, p1, i38, f36, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] -debug_merge_point(' #307 RETURN_VALUE', 0) -guard_isnull(p17, descr=) [p0, p1, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f36, f16, i14, f15] -p48 = getfield_gc(p1, descr=) -setarrayitem_gc(p48, 0, ConstPtr(ptr50), descr=) -setarrayitem_gc(p48, 1, ConstPtr(ptr52), descr=) -setarrayitem_gc(p48, 2, ConstPtr(ptr52), descr=) -setarrayitem_gc(p48, 3, ConstPtr(ptr55), descr=) -setarrayitem_gc(p48, 4, ConstPtr(ptr55), descr=) -setarrayitem_gc(p48, 5, ConstPtr(ptr55), descr=) -setarrayitem_gc(p48, 6, ConstPtr(ptr55), descr=) -setarrayitem_gc(p48, 7, p5, descr=) -p60 = getfield_gc(p1, descr=) -setarrayitem_gc(p60, 0, p6, descr=) -setarrayitem_gc(p60, 1, p7, descr=) -setarrayitem_gc(p60, 2, p8, descr=) -setarrayitem_gc(p60, 3, p9, descr=) -p66 = new_with_vtable(19800744) -setfield_gc(p66, f16, descr=) -setarrayitem_gc(p60, 4, p66, descr=) -setarrayitem_gc(p60, 5, p10, descr=) -setarrayitem_gc(p60, 6, p11, descr=) -setarrayitem_gc(p60, 7, p12, descr=) -setarrayitem_gc(p60, 8, p13, descr=) -p73 = new_with_vtable(ConstClass(W_IntObject)) -setfield_gc(p73, i14, descr=) -setarrayitem_gc(p60, 9, p73, descr=) -p76 = new_with_vtable(19800744) -setfield_gc(p76, f15, descr=) diff --git a/third_party/pygments/tests/examplefiles/test.r3 b/third_party/pygments/tests/examplefiles/test.r3 deleted file mode 100644 index 707102dbd..000000000 --- a/third_party/pygments/tests/examplefiles/test.r3 +++ /dev/null @@ -1,114 +0,0 @@ -preface.... everything what is before header is not evaluated -so this should not be colorized: -1 + 2 - -REBOL [] ;<- this is minimal header, everything behind it must be colorized - -;## String tests ## -print "Hello ^"World" ;<- with escaped char -multiline-string: { - bla bla "bla" {bla} -} -char-a: #"a" -escaped-a: #"^(61)" -new-line: #"^/" - -;## Binaries ## -print decompress 64#{eJzLSM3JyQcABiwCFQUAAAA=} -;2#{0000 00000} ;<- this one is invalid! -2#{} -#{FF00} - -;##Date + time ## -1-Feb-2009 -1-Feb-2009/2:24:46+1:0 -1:0 1:1:1 -0:1.1 - -;## Tuple ## -red: 255.0.0 -red-with-alpha: 255.0.0.100 - -;## url!, file! and email! ## -aaa@bbb.cz -http:// -dns:// -tcp://127.0.0.1 -%/c/rebol/ -%"c:\Program Files\" -%/c/Program%20Files/ -to-rebol-file "c:\Program Files\" -suffix? %bla.swf - -;## Money ## -$1 --$1.2 -USA$100 - -;## Tag! ## - - - -;## Pair! ## -10x200 - -;## Issue! ## -type? #ff0000 ;== issue! - -;## some numbers ## -to integer! (1 + (x / 4.5) * 1E-4) - -;## some spec comments -1 + 1 -comment "aa" -2 + 2 -comment {aa} -3 + 3 -comment {a^{} -4 + 4 -comment {{}} -5 + 5 -comment { - foo: 6 -} -6 + 6 -comment [foo: 6] -7 + 7 -comment [foo: "[" ] -8 + 8 -comment [foo: {^{} ] -9 + 9 -comment [foo: {boo} ] -10 + 10 -comment 5-May-2014/11:17:34+2:00 -5-May-2014/11:17:34+2:00 11 + 11 - -;## other tests ## ----: 1 -x/(1 + n)/y -b/:1 - -;## and... -REBOL [ - purpose: { - reads css file and creates html from it - so one can see how the styles looks like - } -] -style: %default -out: rejoin [{ - - - Pygments style: } style {.css - - - -
    -}]
    -css: read/lines join style %.css
    -foreach line css [
    -    parse line [".syntax ." copy c to " " thru "/*" copy t to "*/" to end (
    -        append out rejoin ["" t "^/"])
    -    ]
    -]
    -write join style %.html join out "
    " -halt diff --git a/third_party/pygments/tests/examplefiles/test.rb b/third_party/pygments/tests/examplefiles/test.rb deleted file mode 100644 index 8ac102e63..000000000 --- a/third_party/pygments/tests/examplefiles/test.rb +++ /dev/null @@ -1,177 +0,0 @@ -a.each{|el|anz[el]=anz[el]?anz[el]+1:1} -while x<10000 -#a bis f dienen dazu die Nachbarschaft festzulegen. Man stelle sich die #Zahl von 1 bis 64 im Binärcode vor 1 bedeutet an 0 aus - b=(p[x]%32)/16<1 ? 0 : 1 - - (x-102>=0? n[x-102].to_i : 0)*a+(x-101>=0?n[x-101].to_i : 0)*e+n[x-100].to_i+(x-99>=0? n[x-99].to_i : 0)*f+(x-98>=0? n[x-98].to_i : 0)*a+ - n[x+199].to_i*b+n[x+200].to_i*d+n[x+201].to_i*b - -#und die Ausgabe folgt -g=%w{} -x=0 - -#leere regex -test //, 123 - -while x<100 - puts"#{g[x]}" - x+=1 -end - -puts"" -sleep(10) - -1E1E1 -puts 30.send(:/, 5) # prints 6 - -# fun with class attributes -class Foo - def self.blub x - if not x.nil? - self.new - end - end - def another_way_to_get_class - self.class - end -end - -# ruby 1.9 "call operator" -a = Proc.new { 42 } -a.() - -"instance variables can be #@included, #@@class_variables\n and #$globals as well." -`instance variables can be #@included, #@@class_variables\n and #$globals as well.` -'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -/instance variables can be #@included, #@@class_variables\n and #$globals as well./mousenix -:"instance variables can be #@included, #@@class_variables\n and #$globals as well." -:'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%q'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%Q'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%w'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%W'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%s'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%r'instance variables can be #@included, #@@class_variables\n and #$globals as well.' -%x'instance variables can be #@included, #@@class_variables\n and #$globals as well.' - -#%W[ but #@0illegal_values look strange.] - -%s#ruby allows strange#{constructs} -%s#ruby allows strange#$constructs -%s#ruby allows strange#@@constructs - -################################################################## -# HEREDOCS -foo(<<-A, <<-B) -this is the text of a -A -and this is the text of b -B - -a = <<"EOF" -This is a multiline #$here document -terminated by EOF on a line by itself -EOF - -a = <<'EOF' -This is a multiline #$here document -terminated by EOF on a line by itself -EOF - -b=(p[x] %32)/16<1 ? 0 : 1 - -<<"" -#{test} -#@bla -#die suppe!!! -\xfffff - - -super <<-EOE % [ - foo -EOE - -< [1, 2, 3, 4, 5, 6] -p [1,2,3].`(:concat, [4,5,6]) # => [1, 2, 3, 4, 5, 6] -p "Hurra! ".`(:*, 3) # => "Hurra! Hurra! Hurra! " -p "Hurra! ".`('*', 3) # => "Hurra! Hurra! Hurra! " -# Leider geht nicht die Wunschform -# [1,2,3] `concat` [4,5,6] - -class Object - @@infixops = [] - alias :xeq :` - def addinfix(operator) - @@infixops << operator - end - def `(expression) - @@infixops.each{|op|break if expression.match(/^(.*?) (#{op}) (.*)$/)} - raise "unknown infix operator in expression: #{expression}" if $2 == nil - eval($1).method($2.to_sym).call(eval($3)) - end -end -addinfix("concat") -p `[1,2,3] concat [4,5,6]` # => [1, 2, 3, 4, 5, 6] - - -# HEREDOC FUN!!!!!!!1111 -foo(< - <% rows.each do |row| %> - -
    <%= item.title %> - <%= item.description %> - - <% end %> - - - -

    Pages

    - - - - - - - - - - -<% if @homepage -%> -<%= render_node @homepage -%> -<% else -%> - - - -<% end -%> - -
    PageStatusModify
    No Pages
    - -
    -

    -<% unless @homepage -%> - <%= link_to image_tag('new-homepage', :alt => 'New Homepage'), homepage_new_url %> -<% end -%> - <%= image_submit_tag 'clear-page-cache' %> -

    -
    diff --git a/third_party/pygments/tests/examplefiles/test.rsl b/third_party/pygments/tests/examplefiles/test.rsl deleted file mode 100644 index d6c9fc9a3..000000000 --- a/third_party/pygments/tests/examplefiles/test.rsl +++ /dev/null @@ -1,111 +0,0 @@ -scheme COMPILER = -class - type - Prog == mk_Prog(stmt : Stmt), - - Stmt == - mk_Asgn(ide : Identifier, expr : Expr) | - mk_If(cond : Expr, s1 : Stmt, s2 : Stmt) | - mk_Seq(head : Stmt, last : Stmt), - - Expr == - mk_Const(const : Int) | - mk_Plus(fst : Expr, snd : Expr) | - mk_Id(ide : Identifier), - Identifier = Text - -type /* storage for program variables */ - `Sigma = Identifier -m-> Int - -value - m : Prog -> `Sigma -> `Sigma - m(p)(`sigma) is m(stmt(p))(`sigma), - - m : Stmt -> `Sigma -> `Sigma - m(s)(`sigma) is - case s of - mk_Asgn(i, e) -> `sigma !! [i +> m(e)(`sigma)], - mk_Seq(s1, s2) -> m(s2)(m(s1)(`sigma)), - mk_If(c, s1, s2) -> - if m(c)(`sigma) ~= 0 then m(s1)(`sigma) else m(s2)(`sigma) end - end, - - m : Expr -> `Sigma -> Int - m(e)(`sigma) is - case e of - mk_Const(n) -> n, - mk_Plus(e1, e2) -> m(e1)(`sigma) + m(e2)(`sigma), - mk_Id(id) -> if id isin dom `sigma then `sigma(id) else 0 end - end - -type - MProg = Inst-list, - Inst == - mk_Push(ide1 : Identifier) | - mk_Pop(Unit) | - mk_Add(Unit) | - mk_Cnst(val : Int) | - mk_Store(ide2 : Identifier) | - mk_Jumpfalse(off1 : Int) | - mk_Jump(off2 : Int) - - -/* An interpreter for SMALL instructions */ - -type Stack = Int-list -value - I : MProg >< Int >< Stack -> (`Sigma ->`Sigma) - I(mp, pc, s)(`sigma) is - if pc <= 0 \/ pc > len mp then `sigma else - case mp(pc) of - mk_Push(x) -> if x isin dom `sigma - then I(mp, pc + 1, <.`sigma(x).> ^ s)(`sigma) - else I(mp, pc + 1, <.0.> ^ s)(`sigma) end, - mk_Pop(()) -> if len s = 0 then `sigma - else I(mp, pc + 1, tl s)(`sigma) end, - mk_Cnst(n) -> I(mp, pc + 1, <.n.> ^ s)(`sigma), - mk_Add(()) -> if len s < 2 then `sigma - else I(mp, pc + 1,<.s(1) + s(2).> ^ tl tl s)(`sigma) end, - mk_Store(x) -> if len s = 0 then `sigma - else I(mp, pc + 1, s)(`sigma !! [x +> s(1)]) end, - mk_Jumpfalse(n) -> if len s = 0 then `sigma - elsif hd s ~= 0 then I(mp, pc + 1, s)(`sigma) - else I(mp, pc + n, s)(`sigma) end, - mk_Jump(n) -> I(mp, pc + n, s)(`sigma) - end - end - -value - comp_Prog : Prog -> MProg - comp_Prog(p) is comp_Stmt(stmt(p)), - - comp_Stmt : Stmt -> MProg - comp_Stmt(s) is - case s of - mk_Asgn(id, e) -> comp_Expr(e) ^ <. mk_Store(id), mk_Pop() .>, - mk_Seq(s1, s2) -> comp_Stmt(s1) ^ comp_Stmt(s2), - mk_If(e, s1, s2) -> - let - ce = comp_Expr(e), - cs1 = comp_Stmt(s1), cs2 = comp_Stmt(s2) - in - ce ^ - <. mk_Jumpfalse(len cs1 + 3) .> ^ - <. mk_Pop() .> ^ - cs1 ^ - <. mk_Jump(len cs2 + 2) .> ^ - <. mk_Pop() .> ^ - cs2 - end - end, - - comp_Expr : Expr -> MProg - comp_Expr(e) is - case e of - mk_Const(n) -> <. mk_Cnst(n) .>, - mk_Plus(e1, e2) -> - comp_Expr(e1) ^ comp_Expr(e2) ^ <. mk_Add() .>, - mk_Id(id) -> <. mk_Push(id) .> - end - -end diff --git a/third_party/pygments/tests/examplefiles/test.scaml b/third_party/pygments/tests/examplefiles/test.scaml deleted file mode 100644 index 8872a83de..000000000 --- a/third_party/pygments/tests/examplefiles/test.scaml +++ /dev/null @@ -1,8 +0,0 @@ --@ import val city:String = "Tampa" -- val name:String = "Hiram" -%html - %body - %p Hello #{name} from #{city} - %ul - - for ( i <- 1 to 10 ) - %li Item #{i} \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/test.sco b/third_party/pygments/tests/examplefiles/test.sco deleted file mode 100644 index a0b392518..000000000 --- a/third_party/pygments/tests/examplefiles/test.sco +++ /dev/null @@ -1,10 +0,0 @@ -f 1 0 16384 10 1 -i "N_a_M_e_" 0 2 -i "TestOscillator" 2 2 -i "TestBitwiseNOT" 0 1 -i "TestBitwiseXOR" 0 1 -i "TestGoto" 0 1 -i "TestMacroPeriodSuffix" 4 1 -i "TestAt" 0 1 -i "MacroAbuse" 0 1 -e diff --git a/third_party/pygments/tests/examplefiles/test.shen b/third_party/pygments/tests/examplefiles/test.shen deleted file mode 100644 index 7a2543343..000000000 --- a/third_party/pygments/tests/examplefiles/test.shen +++ /dev/null @@ -1,137 +0,0 @@ -(package pygments-test [some symbols] - -\* multiline - comment -*\ - -\\ With vars as functions - -(define super - [Value Succ End] Action Combine Zero -> - (if (End Value) - Zero - (Combine (Action Value) - (super [(Succ Value) Succ End] - Action Combine Zero)))) - -(define for - Stream Action -> (super Stream Action (function do) 0)) - -(define filter - Stream Condition -> - (super Stream - (/. Val (if (Condition Val) [Val] [])) - (function append) - [])) - -(for [0 (+ 1) (= 10)] (function print)) - -(filter [0 (+ 1) (= 100)] - (/. X (integer? (/ X 3)))) - - -\\ Typed functions - -(define typed-map - { (A --> B) --> (list A) --> (list B) } - F X -> (typed-map-h F X [])) - -(define typed-map-h - { (A --> B) --> (list A) --> (list B) \\ comment - --> (list B) } - _ [] X -> (reverse X) - F [X | Y] Z -> (typed-map-h F Y [(F X) | Z])) - -(define append-string - { string --> string \* comment *\ --> string } - S1 S2 -> (cn S1 S2)) - -(let X 1 - Y 2 - (+ (type X number) (type Y number))) - -\\ Yacc - -(defcc - - := (package-macro (macroexpand ) ); - := [{ | ]; - := [} | ]; - := [bar! | ]; - := [; | ]; - := [:= | ]; - := [:- | ]; - := [: | ]; - := [(intern ",") | ]; - := [];) - -(defcc - 91 := skip;) - -\\ Pattern matching - -(define matches - 1 X 3 -> X - X Y Z -> Y where (and (= X 1) (= Z 3)) - true false _ -> true - (@p a X c) (@s X "abc") (@v 1 2 3 <>) -> true - [X | Rest] [] [a b c] -> true - [(@p a b)] [[[1] 2] X] "string" -> true - _ _ _ -> false) - - -\\ Prolog - -(defprolog th* - X A Hyps <-- (show [X : A] Hyps) (when false); - X A _ <-- (fwhen (typedf? X)) (bind F (sigf X)) (call [F A]); - (mode [F] -) A Hyp <-- (th* F [--> A] Hyp); - (mode [cons X Y] -) [list A] Hyp <-- (th* X A Hyp) (th* Y [list A] Hyp); - (mode [@s X Y] -) string Hyp <-- (th* X string Hyp) (th* Y string Hyp); - (mode [lambda X Y] -) [A --> B] Hyp <-- ! - (bind X&& (placeholder)) - (bind Z (ebr X&& X Y)) - (th* Z B [[X&& : A] | Hyp]); - (mode [type X A] -) B Hyp <-- ! (unify A B) (th* X A Hyp);) - -\\ Macros - -(defmacro log-macro - [log N] -> [log N 10]) - -\\ Sequent calculus - -(datatype rank - - if (element? X [ace 2 3 4 5 6 7 8 9 10 jack queen king]) - ________ - X : rank;) - -(datatype suit - - if (element? Suit [spades hearts diamonds clubs]) - _________ - Suit : suit;) - -(datatype card - - Rank : rank; Suit : suit; - _________________ - [Rank Suit] : card; - - Rank : rank, Suit : suit >> P; - _____________________ - [Rank Suit] : card >> P;) - -(datatype card - - Rank : rank; Suit : suit; - ================== - [Rank Suit] : card;) - -\\ String interpolation and escape sequences - -"abc~A ~S~R ~% blah - c#30;c#31;blah" - -) diff --git a/third_party/pygments/tests/examplefiles/test.ssp b/third_party/pygments/tests/examplefiles/test.ssp deleted file mode 100644 index 96d26d553..000000000 --- a/third_party/pygments/tests/examplefiles/test.ssp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ val someName: String = "someDefaultValue" %> -<% import com.acme.MySnippets._ %> - - -

    Hello ${someName}%

    - -
      -<%= for (person <- people) { %> -
    • ${person.name}
    • -<% } %> -
    - diff --git a/third_party/pygments/tests/examplefiles/test.swift b/third_party/pygments/tests/examplefiles/test.swift deleted file mode 100644 index 8ef197634..000000000 --- a/third_party/pygments/tests/examplefiles/test.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// test.swift -// from https://github.com/fullstackio/FlappySwift -// -// Created by Nate Murray on 6/2/14. -// Copyright (c) 2014 Fullstack.io. All rights reserved. -// - -import UIKit -import SpriteKit - -extension SKNode { - class func unarchiveFromFile(file : NSString) -> SKNode? { - - let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") - - var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil) - var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) - - archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") - let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene - archiver.finishDecoding() - return scene - } -} - -class GameViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - - if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { - // Configure the view. - let skView = self.view as SKView - skView.showsFPS = true - skView.showsNodeCount = true - - /* Sprite Kit applies additional optimizations to improve rendering performance */ - skView.ignoresSiblingOrder = true - - /* Set the scale mode to scale to fit the window */ - scene.scaleMode = .AspectFill - - skView.presentScene(scene) - } - } - - override func shouldAutorotate() -> Bool { - return true - } - - override func supportedInterfaceOrientations() -> Int { - if UIDevice.currentDevice().userInterfaceIdiom == .Phone { - return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw()) - } else { - return Int(UIInterfaceOrientationMask.All.toRaw()) - } - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Release any cached data, images, etc that aren't in use. - } - -} diff --git a/third_party/pygments/tests/examplefiles/test.tcsh b/third_party/pygments/tests/examplefiles/test.tcsh deleted file mode 100644 index e215ed04f..000000000 --- a/third_party/pygments/tests/examplefiles/test.tcsh +++ /dev/null @@ -1,830 +0,0 @@ -# -# $Id: complete.tcsh,v 1.2 1998/05/11 10:40:54 luisgh Exp $ -# example file using the new completion code -# - -# Debian GNU/Linux -# file: /usr/share/doc/examples/tcsh/complete.tcsh -# -# This file may be read from user's .cshrc file by decompressing it into -# the home directory as ~/.complete and then adding the line -# "source ${HOME}/.complete" and maybe defining some of -# the shell variables described below. -# -# Debian enhancements by Vadim Vygonets : -# -# Added two Debian-specific completions: dpkg and dpkg-deb (who wrote -# them?). To turn it off, define no_debian_complete before loading -# this file. -# -# Added some new completions. To turn them off, define -# no_new_complete before loading this file. -# -# Changed completions of several commands. The ones are evaluated if -# the following shell variables are defined: -# -# traditional_cp_mv_complete -# for traditional completion of cp and mv commands -# traditional_zcat_complete -# for traditional completion of zcat command -# traditional_nm_complete -# for traditional completion of nm command -# traditilnal_tex_complete -# for traditional completion of tex command -# traditional_find_complete -# for traditional completion of find command -# traditional_configure_complete -# for traditional completion of ./configure command -# foolproof_rm_complete or traditional_rm_complete -# for traditional completion of rm command -# traditional_complete -# all of the above - -if ($?traditional_complete) then - set traditional_cp_mv_complete - set traditional_zcat_complete - set traditional_nm_complete - set traditilnal_tex_complete - set traditional_find_complete - set traditional_configure_complete - set foolproof_rm_complete -endif - -if ($?traditional_rm_complete) then - set foolproof_rm_complete -endif - -onintr - -if (! $?prompt) goto end - -if ($?tcsh) then - if ($tcsh != 1) then - set rev=$tcsh:r - set rel=$rev:e - set pat=$tcsh:e - set rev=$rev:r - endif - if ($rev > 5 && $rel > 1) then - set complete=1 - endif - unset rev rel pat -endif - -if ($?complete) then - set noglob - set hosts - foreach f ($HOME/.hosts /usr/local/etc/csh.hosts $HOME/.rhosts /etc/hosts.equiv) - if ( -r $f ) then - set hosts=($hosts `cut -d " " -f 1 $f | grep -v +`) - endif - end - if ( -r $HOME/.netrc ) then - set f=`awk '/machine/ { print $2 }' < $HOME/.netrc` >& /dev/null - set hosts=($hosts $f) - endif - unset f - if ( ! $?hosts ) then - set hosts=(hyperion.ee.cornell.edu phaeton.ee.cornell.edu \ - guillemin.ee.cornell.edu vangogh.cs.berkeley.edu \ - ftp.uu.net prep.ai.mit.edu export.lcs.mit.edu \ - labrea.stanford.edu sumex-aim.stanford.edu \ - tut.cis.ohio-state.edu) - endif - - complete ywho n/*/\$hosts/ # argument from list in $hosts - complete rsh p/1/\$hosts/ c/-/"(l n)"/ n/-l/u/ N/-l/c/ n/-/c/ p/2/c/ p/*/f/ - complete xrsh p/1/\$hosts/ c/-/"(l 8 e)"/ n/-l/u/ N/-l/c/ n/-/c/ p/2/c/ p/*/f/ - complete rlogin p/1/\$hosts/ c/-/"(l 8 e)"/ n/-l/u/ - complete telnet p/1/\$hosts/ p/2/x:''/ n/*/n/ - - complete cd p/1/d/ # Directories only - complete chdir p/1/d/ - complete pushd p/1/d/ - complete popd p/1/d/ - complete pu p/1/d/ - complete po p/1/d/ - complete complete p/1/X/ # Completions only - complete uncomplete n/*/X/ - complete exec p/1/c/ # Commands only - complete trace p/1/c/ - complete strace p/1/c/ - complete which n/*/c/ - complete where n/*/c/ - complete skill p/1/c/ - complete dde p/1/c/ - complete adb c/-I/d/ n/-/c/ N/-/"(core)"/ p/1/c/ p/2/"(core)"/ - complete sdb p/1/c/ - complete dbx c/-I/d/ n/-/c/ N/-/"(core)"/ p/1/c/ p/2/"(core)"/ - complete xdb p/1/c/ - complete gdb n/-d/d/ n/*/c/ - complete ups p/1/c/ - complete set 'c/*=/f/' 'p/1/s/=' 'n/=/f/' - complete unset n/*/s/ - complete alias p/1/a/ # only aliases are valid - complete unalias n/*/a/ - complete xdvi n/*/f:*.dvi/ # Only files that match *.dvi - complete dvips n/*/f:*.dvi/ -if ($?traditilnal_tex_complete) then - complete tex n/*/f:*.tex/ # Only files that match *.tex -else - complete tex n/*/f:*.{tex,texi}/ # Files that match *.tex and *.texi -endif - complete latex n/*/f:*.{tex,ltx}/ - complete su c/--/"(login fast preserve-environment command shell \ - help version)"/ c/-/"(f l m p c s -)"/ \ - n/{-c,--command}/c/ \ - n@{-s,--shell}@'`cat /etc/shells`'@ n/*/u/ - complete cc c/-[IL]/d/ \ - c@-l@'`\ls -1 /usr/lib/lib*.a | sed s%^.\*/lib%%\;s%\\.a\$%%`'@ \ - c/-/"(o l c g L I D U)"/ n/*/f:*.[coasi]/ - complete acc c/-[IL]/d/ \ - c@-l@'`\ls -1 /usr/lang/SC1.0/lib*.a | sed s%^.\*/lib%%\;s%\\.a\$%%`'@ \ - c/-/"(o l c g L I D U)"/ n/*/f:*.[coasi]/ - complete gcc c/-[IL]/d/ \ - c/-f/"(caller-saves cse-follow-jumps delayed-branch \ - elide-constructors expensive-optimizations \ - float-store force-addr force-mem inline \ - inline-functions keep-inline-functions \ - memoize-lookups no-default-inline \ - no-defer-pop no-function-cse omit-frame-pointer \ - rerun-cse-after-loop schedule-insns \ - schedule-insns2 strength-reduce \ - thread-jumps unroll-all-loops \ - unroll-loops syntax-only all-virtual \ - cond-mismatch dollars-in-identifiers \ - enum-int-equiv no-asm no-builtin \ - no-strict-prototype signed-bitfields \ - signed-char this-is-variable unsigned-bitfields \ - unsigned-char writable-strings call-saved-reg \ - call-used-reg fixed-reg no-common \ - no-gnu-binutils nonnull-objects \ - pcc-struct-return pic PIC shared-data \ - short-enums short-double volatile)"/ \ - c/-W/"(all aggregate-return cast-align cast-qual \ - comment conversion enum-clash error format \ - id-clash-len implicit missing-prototypes \ - no-parentheses pointer-arith return-type shadow \ - strict-prototypes switch uninitialized unused \ - write-strings)"/ \ - c/-m/"(68000 68020 68881 bitfield fpa nobitfield rtd \ - short c68000 c68020 soft-float g gnu unix fpu \ - no-epilogue)"/ \ - c/-d/"(D M N)"/ \ - c/-/"(f W vspec v vpath ansi traditional \ - traditional-cpp trigraphs pedantic x o l c g L \ - I D U O O2 C E H B b V M MD MM i dynamic \ - nodtdlib static nostdinc undef)"/ \ - c/-l/f:*.a/ \ - n/*/f:*.{c,C,cc,o,a,s,i}/ - complete g++ n/*/f:*.{C,cc,o,s,i}/ - complete CC n/*/f:*.{C,cc,o,s,i}/ -if ($?foolproof_rm_complete) then - complete rm c/--/"(directory force interactive verbose \ - recursive help version)"/ c/-/"(d f i v r R -)"/ \ - n/*/f:^*.{c,cc,C,h,in}/ # Protect precious files -else - complete rm c/--/"(directory force interactive verbose \ - recursive help version)"/ c/-/"(d f i v r R -)"/ -endif - complete vi n/*/f:^*.[oa]/ - complete bindkey N/-a/b/ N/-c/c/ n/-[ascr]/'x:'/ \ - n/-[svedlr]/n/ c/-[vedl]/n/ c/-/"(a s k c v e d l r)"/\ - n/-k/"(left right up down)"/ p/2-/b/ \ - p/1/'x:'/ - -if ($?traditional_find_complete) then - complete find n/-fstype/"(nfs 4.2)"/ n/-name/f/ \ - n/-type/"(c b d f p l s)"/ n/-user/u/ n/-group/g/ \ - n/-exec/c/ n/-ok/c/ n/-cpio/f/ n/-ncpio/f/ n/-newer/f/ \ - c/-/"(fstype name perm prune type user nouser \ - group nogroup size inum atime mtime ctime exec \ - ok print ls cpio ncpio newer xdev depth \ - daystart follow maxdepth mindepth noleaf version \ - anewer cnewer amin cmin mmin true false uid gid \ - ilname iname ipath iregex links lname empty path \ - regex used xtype fprint fprint0 fprintf \ - print0 printf not a and o or)"/ \ - n/*/d/ -else - complete find n/-fstype/"(ufs nfs tmp mfs minix ext2 msdos umsdos vfat proc iso9660 4.2 4.3 local)"/ \ - n/-name/f/ \ - n/-type/"(c b d f p l s)"/ n/-user/u/ n/-group/g/ \ - n/-exec/c/ n/-ok/c/ n/-cpio/f/ n/-ncpio/f/ n/-newer/f/ \ - c/-/"(fstype name perm prune type user nouser \ - group nogroup size inum atime mtime ctime exec \ - ok print ls cpio ncpio newer xdev depth \ - daystart follow maxdepth mindepth noleaf version \ - anewer cnewer amin cmin mmin true false uid gid \ - ilname iname ipath iregex links lname empty path \ - regex used xtype fprint fprint0 fprintf \ - print0 printf not a and o or)"/ \ - n/*/d/ -endif - complete -%* c/%/j/ # fill in the jobs builtin - complete {fg,bg,stop} c/%/j/ p/1/"(%)"// - - complete limit c/-/"(h)"/ n/*/l/ - complete unlimit c/-/"(h)"/ n/*/l/ - - complete -co* p/0/"(compress)"/ # make compress completion - # not ambiguous -if ($?traditional_zcat_complete) then - complete zcat n/*/f:*.Z/ -else - complete zcat c/--/"(force help license quiet version)"/ \ - c/-/"(f h L q V -)"/ n/*/f:*.{gz,Z,z,zip}/ -endif -if ($?traditional_nm_complete) then - complete nm n/*/f:^*.{h,C,c,cc}/ -else -complete nm 'c/--radix=/x:/' \ - 'c/--target=/x:/' \ - 'c/--format=/(bsd sysv posix)/n/' \ - 'c/--/(debugsyms extern-only demangle dynamic print-armap \ - print-file-name numeric-sort no-sort reverse-sort \ - size-sort undefined-only portability target= radix= \ - format= defined-only\ line-numbers no-demangle version \ - help)//' \ - 'n/*/f:^*.{h,c,cc,s,S}/' -endif - - complete finger c/*@/\$hosts/ n/*/u/@ - complete ping p/1/\$hosts/ - complete traceroute p/1/\$hosts/ - - complete {talk,ntalk,phone} p/1/'`users | tr " " "\012" | uniq`'/ \ - n/*/\`who\ \|\ grep\ \$:1\ \|\ awk\ \'\{\ print\ \$2\ \}\'\`/ - - complete ftp c/-/"(d i g n v)"/ n/-/\$hosts/ p/1/\$hosts/ n/*/n/ - - # this one is simple... - #complete rcp c/*:/f/ C@[./\$~]*@f@ n/*/\$hosts/: - # From Michael Schroeder - # This one will rsh to the file to fetch the list of files! - complete rcp 'c%*@*:%`set q=$:-0;set q="$q:s/@/ /";set q="$q:s/:/ /";set q=($q " ");rsh $q[2] -l $q[1] ls -dp $q[3]\*`%' 'c%*:%`set q=$:-0;set q="$q:s/:/ /";set q=($q " ");rsh $q[1] ls -dp $q[2]\*`%' 'c%*@%$hosts%:' 'C@[./$~]*@f@' 'n/*/$hosts/:' - - complete dd c/--/"(help version)"/ c/[io]f=/f/ \ - c/conv=*,/"(ascii ebcdic ibm block unblock \ - lcase ucase swab noerror sync)"/,\ - c/conv=/"(ascii ebcdic ibm block unblock \ - lcase ucase swab noerror sync)"/,\ - c/*=/x:''/ \ - n/*/"(if of conv ibs obs bs cbs files skip file seek count)"/= - - complete nslookup p/1/x:''/ p/2/\$hosts/ - - complete ar c/[dmpqrtx]/"(c l o u v a b i)"/ p/1/"(d m p q r t x)"// \ - p/2/f:*.a/ p/*/f:*.o/ - - complete {refile,sprev,snext,scan,pick,rmm,inc,folder,show} \ - c@+@F:$HOME/Mail/@ - - # these and interrupt handling from Jaap Vermeulen - complete {rexec,rxexec,rxterm,rmterm} \ - 'p/1/$hosts/' 'c/-/(l L E)/' 'n/-l/u/' 'n/-L/f/' \ - 'n/-E/e/' 'n/*/c/' - complete kill 'c/-/S/' 'c/%/j/' \ - 'n/*/`ps -u $LOGNAME | awk '"'"'{print $1}'"'"'`/' - - # these from Marc Horowitz - complete attach 'n/-mountpoint/d/' 'n/-m/d/' 'n/-type/(afs nfs rvd ufs)/' \ - 'n/-t/(afs nfs rvd ufs)/' 'n/-user/u/' 'n/-U/u/' \ - 'c/-/(verbose quiet force printpath lookup debug map \ - nomap remap zephyr nozephyr readonly write \ - mountpoint noexplicit explicit type mountoptions \ - nosetuid setuid override skipfsck lock user host)/' \ - 'n/-e/f/' 'n/*/()/' - complete hesinfo 'p/1/u/' \ - 'p/2/(passwd group uid grplist pcap pobox cluster \ - filsys sloc service)/' - - # these from E. Jay Berkenbilt -if ($?traditional_configure_complete) then - complete ./configure 'c/--*=/f/' 'c/--{cache-file,prefix,srcdir}/(=)//' \ - 'c/--/(cache-file verbose prefix srcdir)//' -else -complete ./configure \ - 'c@--{prefix,exec-prefix,bindir,sbindir,libexecdir,datadir,sysconfdir,sharedstatedir,localstatedir,infodir,mandir,srcdir,x-includes,x-libraries}=*@x:'@ \ - 'c/--cachefile=*/x:/' \ - 'c/--{enable,disable,with}-*/x://' \ - 'c/--*=/x:/' \ - 'c/--/(prefix= exec-prefix= bindir= sbindir= \ - libexecdir= datadir= sysconfdir= \ - sharedstatedir= localstatedir= infodir= \ - mandir= srcdir= x-includes= x-libraries= \ - enable- disable- with- )//' \ - 'c/--(help no-create quiet silent version \ - verbose)/' -endif - complete gs 'c/-sDEVICE=/(x11 cdjmono cdj550 epson eps9high epsonc \ - dfaxhigh dfaxlow laserjet ljet4 sparc pbm \ - pbmraw pgm pgmraw ppm ppmraw bit)/' \ - 'c/-sOutputFile=/f/' 'c/-s/(DEVICE OutputFile)/=' \ - 'c/-d/(NODISPLAY NOPLATFONTS NOPAUSE)/' 'n/*/f/' - complete perl 'n/-S/c/' - complete printenv 'n/*/e/' - complete sccs p/1/"(admin cdc check clean comb deledit delget \ - delta diffs edit enter fix get help info \ - print prs prt rmdel sccsdiff tell unedit \ - unget val what)"/ - complete setenv 'p/1/e/' 'c/*:/f/' - - # these and method of setting hosts from Kimmo Suominen - if ( -f $HOME/.mh_profile && -x "`which folders`" ) then - - if ( ! $?FOLDERS ) setenv FOLDERS "`folders -fast -recurse`" - if ( ! $?MHA ) setenv MHA "`ali | sed -e '/^ /d' -e 's/:.*//'`" - - set folders = ( $FOLDERS ) - set mha = ( $MHA ) - - complete ali \ - 'c/-/(alias nolist list nonormalize normalize nouser user help)/' \ - 'n,-alias,f,' - - complete anno \ - 'c/-/(component noinplace inplace nodate date text help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete burst \ - 'c/-/(noinplace inplace noquiet quiet noverbose verbose help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete comp \ - 'c/-/(draftfolder draftmessage nodraftfolder editor noedit file form nouse use whatnowproc nowhatnowproc help)/' \ - 'c,+,$folders,' \ - 'n,-whatnowproc,c,' \ - 'n,-file,f,'\ - 'n,-form,f,'\ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete dist \ - 'c/-/(noannotate annotate draftfolder draftmessage nodraftfolder editor noedit form noinplace inplace whatnowproc nowhatnowproc help)/' \ - 'c,+,$folders,' \ - 'n,-whatnowproc,c,' \ - 'n,-form,f,'\ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete folder \ - 'c/-/(all nofast fast noheader header nopack pack noverbose verbose norecurse recurse nototal total noprint print nolist list push pop help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete folders \ - 'c/-/(all nofast fast noheader header nopack pack noverbose verbose norecurse recurse nototal total noprint print nolist list push pop help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete forw \ - 'c/-/(noannotate annotate draftfolder draftmessage nodraftfolder editor noedit filter form noformat format noinplace inplace digest issue volume whatnowproc nowhatnowproc help)/' \ - 'c,+,$folders,' \ - 'n,-whatnowproc,c,' \ - 'n,-filter,f,'\ - 'n,-form,f,'\ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete inc \ - 'c/-/(audit file noaudit nochangecur changecur file form format nosilent silent notruncate truncate width help)/' \ - 'c,+,$folders,' \ - 'n,-audit,f,'\ - 'n,-form,f,' - - complete mark \ - 'c/-/(add delete list sequence nopublic public nozero zero help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete mhmail \ - 'c/-/(body cc from subject help)/' \ - 'n,-cc,$mha,' \ - 'n,-from,$mha,' \ - 'n/*/$mha/' - - complete mhpath \ - 'c/-/(help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete msgchk \ - 'c/-/(nodate date nonotify notify help)/' - - complete msh \ - 'c/-/(prompt noscan scan notopcur topcur help)/' - - complete next \ - 'c/-/(draft form moreproc nomoreproc length width showproc noshowproc header noheader help)/' \ - 'c,+,$folders,' \ - 'n,-moreproc,c,' \ - 'n,-showproc,c,' \ - 'n,-form,f,' - - complete packf \ - 'c/-/(file help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete pick \ - 'c/-/(and or not lbrace rbrace cc date from search subject to othercomponent after before datefield sequence nopublic public nozero zero nolist list help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete prev \ - 'c/-/(draft form moreproc nomoreproc length width showproc noshowproc header noheader help)/' \ - 'c,+,$folders,' \ - 'n,-moreproc,c,' \ - 'n,-showproc,c,' \ - 'n,-form,f,' - - complete prompter \ - 'c/-/(erase kill noprepend prepend norapid rapid nodoteof doteof help)/' - - complete refile \ - 'c/-/(draft nolink link nopreserve preserve src file help)/' \ - 'c,+,$folders,' \ - 'n,-file,f,'\ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete rmf \ - 'c/-/(nointeractive interactive help)/' \ - 'c,+,$folders,' - - complete rmm \ - 'c/-/(help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete scan \ - 'c/-/(noclear clear form format noheader header width noreverse reverse file help)/' \ - 'c,+,$folders,' \ - 'n,-form,f,'\ - 'n,-file,f,'\ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete send \ - 'c/-/(alias draft draftfolder draftmessage nodraftfolder filter nofilter noformat format noforward forward nomsgid msgid nopush push noverbose verbose nowatch watch width help)/' \ - 'n,-alias,f,'\ - 'n,-filter,f,' - - complete show \ - 'c/-/(draft form moreproc nomoreproc length width showproc noshowproc header noheader help)/' \ - 'c,+,$folders,' \ - 'n,-moreproc,c,' \ - 'n,-showproc,c,' \ - 'n,-form,f,'\ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete sortm \ - 'c/-/(datefield textfield notextfield limit nolimit noverbose verbose help)/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete vmh \ - 'c/-/(prompt vmhproc novmhproc help)/' \ - 'n,-vmhproc,c,' - - complete whatnow \ - 'c/-/(draftfolder draftmessage nodraftfolder editor noedit prompt help)/' - - complete whom \ - 'c/-/(alias nocheck check draft draftfolder draftmessage nodraftfolder help)/' \ - 'n,-alias,f,' - - complete plum \ - 'c/-/()/' \ - 'c,+,$folders,' \ - 'n,*,`(mark | sed "s/:.*//";echo next cur prev first last)|tr " " "\12" | sort -u`,' - - complete mail \ - 'c/-/()/' \ - 'n/*/$mha/' - - endif - - # these from Tom Warzeka - # you may need to set the following variables for your host - set _elispdir = /usr/lib/emacs/19.34/lisp # GNU Emacs lisp directory - set _maildir = /var/spool/mail # Post Office: /var/spool/mail or /usr/mail - set _ypdir = /var/yp # directory where NIS (YP) maps are kept - set _domain = "`dnsdomainname`" - - # this one works but is slow and doesn't descend into subdirectories - # complete cd C@[./\$~]*@d@ \ - # p@1@'`\ls -1F . $cdpath | grep /\$ | sort -u`'@ n@*@n@ - - if ( -r /etc/shells ) then - complete setenv p@1@e@ n@DISPLAY@\$hosts@: n@SHELL@'`cat /etc/shells`'@ - else - complete setenv p@1@e@ n@DISPLAY@\$hosts@: - endif - complete unsetenv n/*/e/ - - if (-r $HOME/.mailrc) then - complete mail c/-/"(e i f n s u v)"/ c/*@/\$hosts/ \ - c@+@F:$HOME/Mail@ C@[./\$~]@f@ n/-s/x:''/ \ - n@-u@T:$_maildir@ n/-f/f/ \ - n@*@'`sed -n s/alias//p $HOME/.mailrc | tr -s " " " " | cut -f 2`'@ - else - complete mail c/-/"(e i f n s u v)"/ c/*@/\$hosts/ \ - c@+@F:$HOME/Mail@ C@[./\$~]@f@ n/-s/x:''/ \ - n@-u@T:$_maildir@ n/-f/f/ n/*/u/ - endif - - complete man n@1@'`\ls -1 /usr/man/man1 | sed s%\\.1.\*\$%%`'@ \ - n@2@'`\ls -1 /usr/man/man2 | sed s%\\.2.\*\$%%`'@ \ - n@3@'`\ls -1 /usr/man/man3 | sed s%\\.3.\*\$%%`'@ \ - n@4@'`\ls -1 /usr/man/man4 | sed s%\\.4.\*\$%%`'@ \ - n@5@'`\ls -1 /usr/man/man5 | sed s%\\.5.\*\$%%`'@ \ - n@6@'`\ls -1 /usr/man/man6 | sed s%\\.6.\*\$%%`'@ \ - n@7@'`\ls -1 /usr/man/man7 | sed s%\\.7.\*\$%%`'@ \ - n@8@'`\ls -1 /usr/man/man8 | sed s%\\.8.\*\$%%`'@ \ - n@9@'`[ -r /usr/man/man9 ] && \ls -1 /usr/man/man9 | sed s%\\.9.\*\$%%`'@ \ - n@0@'`[ -r /usr/man/man0 ] && \ls -1 /usr/man/man0 | sed s%\\.0.\*\$%%`'@ \ - n@new@'`[ -r /usr/man/mann ] && \ls -1 /usr/man/mann | sed s%\\.n.\*\$%%`'@ \ - n@old@'`[ -r /usr/man/mano ] && \ls -1 /usr/man/mano | sed s%\\.o.\*\$%%`'@ \ -n@local@'`[ -r /usr/man/manl ] && \ls -1 /usr/man/manl | sed s%\\.l.\*\$%%`'@ \ -n@public@'`[ -r /usr/man/manp ]&& \ls -1 /usr/man/manp | sed s%\\.p.\*\$%%`'@ \ - c/-/"(- f k P s t)"/ n/-f/c/ n/-k/x:''/ n/-P/d/ \ - N@-P@'`\ls -1 $:-1/man? | sed s%\\..\*\$%%`'@ n/*/c/ - - complete ps c/-t/x:''/ c/-/"(a c C e g k l S t u v w x)"/ \ - n/-k/x:''/ N/-k/x:''/ n/*/x:''/ - complete compress c/-/"(c f v b)"/ n/-b/x:''/ n/*/f:^*.Z/ - complete uncompress c/-/"(c f v)"/ n/*/f:*.Z/ - - complete xhost c/[+-]/\$hosts/ n/*/\$hosts/ - - # these conform to the latest GNU versions available at press time ... - - complete emacs c/-/"(batch d f funcall i insert kill l load \ - no-init-file nw q t u user)"/ c/+/x:''/ \ - n/-d/x:''/ n/-f/x:''/ n/-i/f/ \ - n@-l@F:$_elispdir@ n/-t/x:''/ \ - n/-u/u/ n/*/f:^*[\#~]/ - - complete gzcat c/--/"(force help license quiet version)"/ \ - c/-/"(f h L q V -)"/ n/*/f:*.{gz,Z,z,zip}/ - complete gzip c/--/"(stdout to-stdout decompress uncompress \ - force help list license no-name quiet recurse \ - suffix test verbose version fast best)"/ \ - c/-/"(c d f h l L n q r S t v V 1 2 3 4 5 6 7 8 9 -)"/\ - n/{-S,--suffix}/x:''/ \ - n/{-d,--{de,un}compress}/f:*.{gz,Z,z,zip,taz,tgz}/ \ - N/{-d,--{de,un}compress}/f:*.{gz,Z,z,zip,taz,tgz}/ \ - n/*/f:^*.{gz,Z,z,zip,taz,tgz}/ - complete {gunzip,ungzip} c/--/"(stdout to-stdout force help list license \ - no-name quiet recurse suffix test verbose version)"/ \ - c/-/"(c f h l L n q r S t v V -)"/ \ - n/{-S,--suffix}/x:''/ \ - n/*/f:*.{gz,Z,z,zip,taz,tgz}/ - complete zgrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ - c/-/"(A b B c C e f h i l n s v V w x)"/ \ - p/1/x:''/ \ - n/-*e/x:''/ n/-*f/f/ n/*/f/ - complete zegrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ - c/-/"(A b B c C e f h i l n s v V w x)"/ \ - p/1/x:''/ \ - n/-*e/x:''/ n/-*f/f/ n/*/f/ - complete zfgrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ - c/-/"(A b B c C e f h i l n s v V w x)"/ \ - p/1/x:''/ \ - n/-*e/x:''/ n/-*f/f/ n/*/f/ - - complete znew c/-/"(f t v 9 P K)"/ n/*/f:*.Z/ - complete zmore n/*/f:*.{gz,Z,z,zip}/ - complete zfile n/*/f:*.{gz,Z,z,zip,taz,tgz}/ - complete ztouch n/*/f:*.{gz,Z,z,zip,taz,tgz}/ - complete zforce n/*/f:^*.{gz,tgz}/ - - complete grep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ - c/-/"(A b B c C e f h i l n s v V w x)"/ \ - p/1/x:''/ \ - n/-*e/x:''/ n/-*f/f/ n/*/f/ - complete egrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ - c/-/"(A b B c C e f h i l n s v V w x)"/ \ - p/1/x:''/ \ - n/-*e/x:''/ n/-*f/f/ n/*/f/ - complete fgrep c/-*A/x:'<#_lines_after>'/ c/-*B/x:'<#_lines_before>'/\ - c/-/"(A b B c C e f h i l n s v V w x)"/ \ - p/1/x:''/ \ - n/-*e/x:''/ n/-*f/f/ n/*/f/ - - complete users c/--/"(help version)"/ p/1/x:''/ - complete who c/--/"(heading mesg idle count help message version \ - writable)"/ c/-/"(H T w i u m q s -)"/ \ - p/1/x:''/ n/am/"(i)"/ n/are/"(you)"/ - - complete chown c/--/"(changes silent quiet verbose recursive help \ - version)"/ c/-/"(c f v R -)"/ C@[./\$~]@f@ c/*[.:]/g/ \ - n/-/u/. p/1/u/. n/*/f/ - complete chgrp c/--/"(changes silent quiet verbose recursive help \ - version)"/ c/-/"(c f v R -)"/ n/-/g/ p/1/g/ n/*/f/ - - complete cat c/--/"(number-nonblank number squeeze-blank show-all \ - show-nonprinting show-ends show-tabs help version)"/ \ - c/-/"(b e n s t u v A E T -)"/ n/*/f/ -if ($?traditional_cp_mv_complete) then - complete mv c/--/"(backup force interactive update verbose suffix \ - version-control help version)"/ \ - c/-/"(b f i u v S V -)"/ \ - n/{-S,--suffix}/x:''/ \ - n/{-V,--version-control}/"(t numbered nil existing \ - never simple)"/ n/-/f/ N/-/d/ p/1/f/ p/2/d/ n/*/f/ - complete cp c/--/"(archive backup no-dereference force interactive \ - link preserve symbolic-link update verbose parents \ - one-file-system recursive suffix version-control help \ - version)"/ c/-/"(a b d f i l p r s u v x P R S V -)"/ \ - n/-*r/d/ n/{-S,--suffix}/x:''/ \ - n/{-V,--version-control}/"(t numbered nil existing \ - never simple)"/ n/-/f/ N/-/d/ p/1/f/ p/2/d/ n/*/f/ -else - complete mv c/--/"(backup force interactive update verbose suffix \ - version-control help version)"/ \ - c/-/"(b f i u v S V -)"/ \ - n/{-S,--suffix}/x:''/ \ - n/{-V,--version-control}/"(t numbered nil existing \ - never simple)"/ n/-/f/ N/-/d/ n/*/f/ - complete cp c/--/"(archive backup no-dereference force interactive \ - link preserve symbolic-link update verbose parents \ - one-file-system recursive suffix version-control help \ - version)"/ c/-/"(a b d f i l p r s u v x P R S V -)"/ \ - n/-*r/d/ n/{-S,--suffix}/x:''/ \ - n/{-V,--version-control}/"(t numbered nil existing \ - never simple)"/ n/-/f/ N/-/d/ n/*/f/ -endif - complete ln c/--/"(backup directory force interactive symbolic \ - verbose suffix version-control help version)"/ \ - c/-/"(b d F f i s v S V -)"/ \ - n/{-S,--suffix}/x:''/ \ - n/{-V,--version-control}/"(t numbered nil existing \ - never simple)"/ n/-/f/ N/-/x:''/ \ - p/1/f/ p/2/x:''/ - complete touch c/--/"(date file help time version)"/ \ - c/-/"(a c d f m r t -)"/ \ - n/{-d,--date}/x:''/ \ - c/--time/"(access atime mtime modify use)"/ \ - n/{-r,--file}/f/ n/-t/x:''/ n/*/f/ - complete mkdir c/--/"(parents help version mode)"/ c/-/"(p m -)"/ \ - n/{-m,--mode}/x:''/ n/*/d/ - complete rmdir c/--/"(parents help version)"/ c/-/"(p -)"/ n/*/d/ - - complete tar c/-[Acru]*/"(b B C f F g G h i l L M N o P \ - R S T v V w W X z Z)"/ \ - c/-[dtx]*/"( B C f F g G i k K m M O p P \ - R s S T v w x X z Z)"/ \ - p/1/"(A c d r t u x -A -c -d -r -t -u -x \ - --catenate --concatenate --create --diff --compare \ - --delete --append --list --update --extract --get)"/ \ - c/--/"(catenate concatenate create diff compare \ - delete append list update extract get atime-preserve \ - block-size read-full-blocks directory checkpoint file \ - force-local info-script new-volume-script incremental \ - listed-incremental dereference ignore-zeros \ - ignore-failed-read keep-old-files starting-file \ - one-file-system tape-length modification-time \ - multi-volume after-date newer old-archive portability \ - to-stdout same-permissions preserve-permissions \ - absolute-paths preserve record-number remove-files \ - same-order preserve-order same-owner sparse \ - files-from null totals verbose label version \ - interactive confirmation verify exclude exclude-from \ - compress uncompress gzip ungzip use-compress-program \ - block-compress)"/ \ - c/-/"(b B C f F g G h i k K l L m M N o O p P R s S \ - T v V w W X z Z 0 1 2 3 4 5 6 7 -)"/ \ - n/-c*f/x:''/ \ - n/{-[Adrtux]*f,--file}/f:*.tar/ \ - N/{-x*f,--file}/'`tar -tf $:-1`'/ \ - n/--use-compress-program/c/ \ - n/{-b,--block-size}/x:''/ \ - n/{-V,--label}/x:''/ \ - n/{-N,--{after-date,newer}}/x:''/ \ - n/{-L,--tape-length}/x:''/ \ - n/{-C,--directory}/d/ \ - N/{-C,--directory}/'`\ls $:-1`'/ \ - n/-[0-7]/"(l m h)"/ - - # BSD 4.3 filesystems - complete mount c/-/"(a h v t r)"/ n/-h/\$hosts/ n/-t/"(4.2 nfs)"/ \ - n@*@'`cut -d " " -f 2 /etc/fstab`'@ - complete umount c/-/"(a h v t)"/ n/-h/\$hosts/ n/-t/"(4.2 nfs)"/ \ - n/*/'`mount | cut -d " " -f 3`'/ - # BSD 4.2 filesystems - #complete mount c/-/"(a h v t r)"/ n/-h/\$hosts/ n/-t/"(ufs nfs)"/ \ - # n@*@'`cut -d ":" -f 2 /etc/fstab`'@ - #complete umount c/-/"(a h v t)"/ n/-h/\$hosts/ n/-t/"(ufs nfs)"/ \ - # n/*/'`mount | cut -d " " -f 3`'/ - - # these deal with NIS (formerly YP); if it's not running you don't need 'em - complete domainname p@1@D:$_ypdir@" " n@*@n@ - complete ypcat c@-@"(d k t x)"@ n@-x@n@ n@-d@D:$_ypdir@" " \ - N@-d@\`\\ls\ -1\ $_ypdir/\$:-1\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ \ - n@*@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ - complete ypmatch c@-@"(d k t x)"@ n@-x@n@ n@-d@D:$_ypdir@" " \ - N@-d@x:''@ n@-@x:''@ p@1@x:''@ \ - n@*@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ - complete ypwhich c@-@"(d m t x V1 V2)"@ n@-x@n@ n@-d@D:$_ypdir@" " \ - n@-m@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ \ - N@-m@n@ n@*@\$hosts@ - - # there's no need to clutter the user's shell with these - unset _elispdir _maildir _ypdir _domain - - complete make \ - 'n/-f/f/' \ - 'c/*=/f/' \ - 'n@*@`cat -s GNUmakefile Makefile makefile |& sed -n -e "/No such file/d" -e "/^[^ #].*:/s/:.*//p"`@' - - if ( -f /etc/printcap ) then - set printers=(`sed -n -e "/^[^ #].*:/s/:.*//p" /etc/printcap`) - - complete lpr 'c/-P/$printers/' - complete lpq 'c/-P/$printers/' - complete lprm 'c/-P/$printers/' - complete lpquota 'p/1/(-Qprlogger)/' 'c/-P/$printers/' - complete dvips 'c/-P/$printers/' 'n/-o/f:*.{ps,PS}/' 'n/*/f:*.dvi/' - endif - -# New -if (! $?no_new_complete) then - uncomplete vi - complete {vi,vim,gvim,nvi,elvis} n/*/f:^*.{o,a,so,sa,aux,dvi,log,fig,bbl,blg,bst,idx,ilg,ind,toc}/ - complete {ispell,spell,spellword} 'n@-d@`ls /usr/lib/ispell/*.aff | sed -e "s/\.aff//" `@' 'n/*/f:^*.{o,a,so,sa,aux,dvi,log,fig,bbl,blg,bst,idx,ilg,ind,toc}/' - complete mutt 'n/-[ai]/f/' 'n/-c/u/' c@=@F:$HOME/Mail/@ \ - 'n/-s/x:\/' 'n/[^-]/u/' - complete elm 'n/-[Ai]/f/' 'c@=@F:$HOME/Mail/@' 'n/-s/x:\/' - complete ncftp 'n@*@`sed -e '1,2d' $HOME/.ncftp/bookmarks | cut -f 1,2 -d "," | tr "," "\012" | sort | uniq ` '@ - complete bibtex 'n@*@`ls *.aux | sed -e "s/\.aux//"`'@ - complete dvi2tty n/*/f:*.dvi/ # Only files that match *.dvi - complete {xpdf,acroread} 'n/*/f:*.pdf/' - complete {gv,ghostview} 'n/*/f:*.{ps,eps,epsi}/' - complete enscript \ - 'c/--/(columns= pages= header= no-header truncate-lines \ - line-numbers setpagedevice= escapes font= \ - header-font= fancy-header no-job-header \ - highlight-bars indent= filter= borders page-prefeed \ - no-page-prefeed lineprinter lines-per-page= mail \ - media= copies= newline= output= missing-characters \ - printer= quiet silent landscape portrait \ - baselineskip= statusdict= title= tabsize= underlay= \ - verbose version encoding pass-through download-font= \ - filter-stdin= help highlight-bar-gray= list-media \ - list-options non-printable-format= page-label-format= \ - printer-options= ul-angle= ul-font= ul-gray= \ - ul-position= ul-style= \ - )/' -endif # ! $?no_new_complete - -# Debian specific -if (! $?no_debian_complete) then -complete dpkg 'c/--{admindir,instdir,root}=/d/' \ - 'c/--debug=/n/' \ - 'c/--{admindir,debug,instdir,root}/(=)//' \ - 'c/--/(admindir= debug= instdir= root= \ - assert-support-predepends assert-working-epoch \ - audit auto-deconfigure clear-avail \ - compare-versions configure contents control \ - extract force-bad-path field \ - force-configure-any force-conflicts \ - force-depends force-depends-version force-help \ - force-hold force-non-root \ - force-overwrite-diverted \ - force-remove-essential force-remove-reinstreq \ - forget-old-unavail fsys-tarfile get-selections \ - help ignore-depends info install largemem \ - license list listfiles merge-avail no-act \ - pending predep-package print-architecture \ - print-gnu-build-architecture \ - print-installation-architecture print-avail \ - purge record-avail recursive refuse-downgrade \ - remove search set-selections selected-only \ - skip-same-version smallmem status unpack \ - update-avail version vextract \ - )//' \ - 'n/*/f:*.deb'/ -complete dpkg-deb 'c/--{build}=/d/' \ - 'c/--/"( build contents info field control extract \ - vextract fsys-tarfile help version \ - license )"' \ - 'n/*/f:*.deb/' -endif # ! $?no_debian_complete - - unset noglob - unset complete - unset traditional_complete - unset traditional_cp_mv_complete - unset traditional_zcat_complete - unset traditional_nm_complete - unset traditilnal_tex_complete - unset traditional_find_complete - unset traditional_configure_complete - unset traditional_rm_complete - unset foolproof_rm_complete - unset no_new_complete - unset no_debian_complete -endif - -end: - onintr - diff --git a/third_party/pygments/tests/examplefiles/test.vb b/third_party/pygments/tests/examplefiles/test.vb deleted file mode 100644 index e7252e90c..000000000 --- a/third_party/pygments/tests/examplefiles/test.vb +++ /dev/null @@ -1,407 +0,0 @@ -' Copyright (c) 2008 Silken Web - Free BSD License -' 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. -' * Neither the name of Silken Web nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. -' -' 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. - -Imports System.Net.Mail -Imports SilkenWeb.Entities -Imports System.Text.RegularExpressions -Imports System.Reflection -Imports SilkenWeb.Validation -Imports System.Globalization -Imports SilkenWeb.Reflection - -Namespace SilkenWeb - - ''' - ''' Represents an Email and what you can do with it. - ''' - ''' - ''' Keith Jackson - ''' 11/04/2008 - ''' - ''' This class is intended to be inherrited for providing all manner of system generated emails, each represented by it's own class. - ''' - Public MustInherit Class EmailBase : Implements IValidatable, IDisposable - -#Region " Constants " - - Public Const LenientRegexPattern As String = "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" - Public Const StrictRegexPattern As String = "^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$" - Public Const InvalidEmailAddressError As String = "The Email address provided was invalid" - Public Const InvalidEmailAddressErrorWithAddress As String = "The Email address, {0}, provided was invalid" - Public Const NullEmailAddressError As String = "The Email address was not provided" - -#End Region - -#Region " Fields " - - Private disposedValue As Boolean - - Private _message As MailMessage = New MailMessage() - Private _mailClient As SmtpClient - - Private _useStrictValidation As Boolean - -#End Region - -#Region " Construction " - - ''' - ''' Instantiates a new Email of the derived type. - ''' - ''' The email address of the sender of the message. - ''' The email addresses of the recipients of the message. - ''' The subject of the message. - ''' The body of the message. - Protected Sub New(ByVal sender As String, ByVal subject As String, ByVal body As String, ByVal ParamArray recipients As String()) - _message.From = New MailAddress(sender) - For i As Integer = 0 To recipients.Length - 1 - _message.To.Add(recipients(i)) - Next - _message.Subject = subject - _message.Body = body - End Sub - -#End Region - -#Region " Properties " - - ''' - ''' Gets the Attachments for the message. - ''' - Protected Overridable ReadOnly Property Attachments() As AttachmentCollection - Get - Return _message.Attachments - End Get - End Property - - ''' - ''' The email addresses of the BCC recipients of the message. - ''' - Public Property BccRecipients() As String() - Get - Return _message.Bcc.ToAddressStringArray() - End Get - Set(ByVal value As String()) - _message.Bcc.Clear() - _message.Bcc.Add(value.ToDelimitedString()) - End Set - End Property - - ''' - ''' The body of the message. - ''' - Protected Overridable Property Body() As String - Get - Return _message.Body - End Get - Set(ByVal value As String) - _message.Body = value - End Set - End Property - - ''' - ''' The email addresses of the CC recipients of the message. - ''' - Public Property CCRecipients() As String() - Get - Return _message.CC.ToAddressStringArray() - End Get - Set(ByVal value As String()) - _message.CC.Clear() - _message.CC.Add(value.ToDelimitedString()) - End Set - End Property - - ''' - ''' Gets or Sets a flag to indicate if the body of the message is HTML. - ''' - Public Property IsBodyHtml() As Boolean - Get - Return _message.IsBodyHtml - End Get - Set(ByVal value As Boolean) - _message.IsBodyHtml = value - End Set - End Property - - ''' - ''' Gets the Mail message wrapped by the EmailBase class. - ''' - Protected ReadOnly Property Message() As MailMessage - Get - Return _message - End Get - End Property - - ''' - ''' Gets or Sets the Priority of the message. - ''' - Public Property Priority() As MailPriority - Get - Return _message.Priority - End Get - Set(ByVal value As MailPriority) - _message.Priority = value - End Set - End Property - - ''' - ''' The email addresses of the recipients of the message. - ''' - Public Property Recipients() As String() - Get - Return _message.To.ToAddressStringArray() - End Get - Set(ByVal value As String()) - _message.To.Clear() - _message.To.Add(value.ToDelimitedString()) - End Set - End Property - - ''' - ''' The reply email address of the sender of the message. - ''' - Public Property ReplyTo() As String - Get - If _message.ReplyTo Is Nothing Then - Return String.Empty - Else - Return _message.ReplyTo.Address - End If - End Get - Set(ByVal value As String) - If _message.ReplyTo Is Nothing Then - _message.ReplyTo = New MailAddress(value) - Else - _message.ReplyTo = New MailAddress(value, _message.ReplyTo.DisplayName) - End If - End Set - End Property - - ''' - ''' The reply display name of the sender of the message. - ''' - Public Property ReplyToDisplayName() As String - Get - If _message.ReplyTo Is Nothing Then - Return String.Empty - Else - Return _message.ReplyTo.DisplayName - End If - End Get - Set(ByVal value As String) - If _message.ReplyTo Is Nothing Then - _message.ReplyTo = New MailAddress(_message.From.Address, value) - Else - _message.ReplyTo = New MailAddress(_message.ReplyTo.Address, value) - End If - End Set - End Property - - ''' - ''' The email address of the sender of the message. - ''' - Public Overridable Property Sender() As String - Get - Return _message.From.Address - End Get - Protected Set(ByVal value As String) - _message.From = New MailAddress(value, _message.From.DisplayName) - End Set - End Property - - ''' - ''' The display name of the sender of the message. - ''' - Public Overridable Property SenderDisplayName() As String - Get - Return _message.From.DisplayName - End Get - Protected Set(ByVal value As String) - _message.From = New MailAddress(_message.From.Address, value) - End Set - End Property - - ''' - ''' The subject of the message. - ''' - Public Overridable Property Subject() As String - Get - Return _message.Subject - End Get - Protected Set(ByVal value As String) - _message.Subject = value - End Set - End Property - -#End Region - -#Region " Methods " - -#Region " Send Methods " - - ''' - ''' Sends this email - ''' - ''' The SMTP server to use to send the email. - Public Sub Send(ByVal mailServer As String) - _mailClient = New SmtpClient(mailServer) - _mailClient.Send(_message) - End Sub - - ''' - ''' Sends this email asynchronously. - ''' - ''' The SMTP server to use to send the email. - ''' A user defined token passed to the recieving method on completion of the asynchronous task. - Public Sub SendAsync(ByVal mailServer As String, ByVal userToken As Object) - _mailClient = New SmtpClient(mailServer) - _mailClient.SendAsync(_message, userToken) - End Sub - - ''' - ''' Cancels an attempt to send this email asynchronously. - ''' - Public Sub SendAsyncCancel() - _mailClient.SendAsyncCancel() - End Sub - -#End Region - -#End Region - -#Region " IValidatable Implementation " - - ''' - ''' gets and Sets a flag to indicate whether to use strict validation. - ''' - Public Property UseStrictValidation() As Boolean - Get - Return _useStrictValidation - End Get - Set(ByVal value As Boolean) - _useStrictValidation = value - End Set - End Property - - ''' - ''' Validates this email. - ''' - ''' A ValidationResponse, containing a flag to indicate if validation was passed and a collection of Property Names and validation errors. - Public Function Validate() As ValidationResponse Implements IValidatable.Validate - - Dim retVal As New ValidationResponse() - Dim mailRegEx As String = If(_useStrictValidation, StrictRegexPattern, LenientRegexPattern) - - ValidateAddress("Sender", retVal, mailRegEx, True) - ValidateAddresses("Recipients", retVal, mailRegEx, True) - ValidateAddresses("CcRecipients", retVal, mailRegEx) - ValidateAddresses("BccRecipients", retVal, mailRegEx) - ValidateAddress("ReplyTo", retVal, mailRegEx) - - Return retVal - - End Function - - ''' - ''' Validates a single Email Address property. - ''' - ''' The name of the property to validate. - ''' The validation response object. - ''' The regular expression pattern to use for validation. - Private Overloads Sub ValidateAddress(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String) - ValidateAddress(propertyName, retVal, mailRegEx, False) - End Sub - - ''' - ''' Validates a single Email Address property. - ''' - ''' The name of the property to validate. - ''' The validation response object. - ''' The regular expression pattern to use for validation. - ''' Indicates if the address is required; False if not specified. - Private Overloads Sub ValidateAddress(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String, ByVal required As Boolean) - - Dim emailAddress As String = ReflectionHelper.Properties.GetProperty(Of String)(Me, propertyName) - - If emailAddress Is Nothing OrElse emailAddress.Length = 0 Then - If required Then retVal.Add(New KeyValuePair(Of String, String)(propertyName, NullEmailAddressError)) - Else - If (Not Regex.IsMatch(emailAddress, mailRegEx)) Then - retVal.Add(New KeyValuePair(Of String, String)(propertyName, InvalidEmailAddressError)) - End If - End If - - End Sub - - ''' - ''' Validates a string array of Email Address property. - ''' - ''' The name of the property to validate. - ''' The validation response object. - ''' The regular expression pattern to use for validation. - Private Overloads Sub ValidateAddresses(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String) - ValidateAddresses(propertyName, retVal, mailRegEx, False) - End Sub - - ''' - ''' Validates a string array of Email Address property. - ''' - ''' The name of the property to validate. - ''' The validation response object. - ''' The regular expression pattern to use for validation. - ''' Indicates if the address is required; False if not specified. - Private Overloads Sub ValidateAddresses(ByVal propertyName As String, ByRef retVal As ValidationResponse, ByVal mailRegEx As String, ByVal required As Boolean) - - Dim emailAddresses() As String = ReflectionHelper.Properties.GetProperty(Of String())(Me, propertyName) - - If emailAddresses Is Nothing OrElse emailAddresses.Length = 0 Then - If required Then retVal.Add(New KeyValuePair(Of String, String)(propertyName, String.Format(CultureInfo.CurrentCulture, NullEmailAddressError))) - Else - For i As Integer = 0 To emailAddresses.Length - 1 - If (Not Regex.IsMatch(emailAddresses(i), mailRegEx)) Then - retVal.Add(New KeyValuePair(Of String, String)(propertyName, String.Format(CultureInfo.CurrentCulture, InvalidEmailAddressErrorWithAddress, emailAddresses(i)))) - End If - Next - End If - - End Sub - -#End Region - -#Region " IDisposable Implementation " - - Protected Overridable Sub Dispose(ByVal disposing As Boolean) - If Not Me.disposedValue Then - If disposing Then - _message.Dispose() - End If - _mailClient = Nothing - _message = Nothing - End If - Me.disposedValue = True - End Sub - - Public Sub Dispose() Implements IDisposable.Dispose - ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. - Dispose(True) - GC.SuppressFinalize(Me) - End Sub - -#End Region - - End Class - -End Namespace diff --git a/third_party/pygments/tests/examplefiles/test.vhdl b/third_party/pygments/tests/examplefiles/test.vhdl deleted file mode 100644 index 426f23756..000000000 --- a/third_party/pygments/tests/examplefiles/test.vhdl +++ /dev/null @@ -1,161 +0,0 @@ -library ieee; -use ieee.std_logic_unsigned.all; -use ieee.std_logic_1164.all; -use ieee.numeric_std.all; - - -entity top_testbench is --test - generic ( -- test - n : integer := 8 -- test - ); -- test -end top_testbench; -- test - - -architecture top_testbench_arch of top_testbench is - - component top is - generic ( - n : integer - ) ; - port ( - clk : in std_logic; - rst : in std_logic; - d1 : in std_logic_vector (n-1 downto 0); - d2 : in std_logic_vector (n-1 downto 0); - operation : in std_logic; - result : out std_logic_vector (2*n-1 downto 0) - ); - end component; - - signal clk : std_logic; - signal rst : std_logic; - signal operation : std_logic; - signal d1 : std_logic_vector (n-1 downto 0); - signal d2 : std_logic_vector (n-1 downto 0); - signal result : std_logic_vector (2*n-1 downto 0); - - type test_type is ( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); - attribute enum_encoding of my_state : type is "001 010 011 100 111"; -begin - - TESTUNIT : top generic map (n => n) - port map (clk => clk, - rst => rst, - d1 => d1, - d2 => d2, - operation => operation, - result => result); - - clock_process : process - begin - clk <= '0'; - wait for 5 ns; - clk <= '1'; - wait for 5 ns; - end process; - - data_process : process - begin - - -- test case #1 - operation <= '0'; - - rst <= '1'; - wait for 5 ns; - rst <= '0'; - wait for 5 ns; - - d1 <= std_logic_vector(to_unsigned(60, d1'length)); - d2 <= std_logic_vector(to_unsigned(12, d2'length)); - wait for 360 ns; - - assert (result = std_logic_vector(to_unsigned(720, result'length))) - report "Test case #1 failed" severity error; - - -- test case #2 - operation <= '0'; - - rst <= '1'; - wait for 5 ns; - rst <= '0'; - wait for 5 ns; - - d1 <= std_logic_vector(to_unsigned(55, d1'length)); - d2 <= std_logic_vector(to_unsigned(1, d2'length)); - wait for 360 ns; - - assert (result = std_logic_vector(to_unsigned(55, result'length))) - report "Test case #2 failed" severity error; - - -- etc - - end process; - -end top_testbench_arch; - - -configuration testbench_for_top of top_testbench is - for top_testbench_arch - for TESTUNIT : top - use entity work.top(top_arch); - end for; - end for; -end testbench_for_top; - - -function compare(A: std_logic, B: std_Logic) return std_logic is - constant pi : real := 3.14159; - constant half_pi : real := pi / 2.0; - constant cycle_time : time := 2 ns; - constant N, N5 : integer := 5; -begin - if (A = '0' and B = '1') then - return B; - else - return A; - end if ; -end compare; - - -procedure print(P : std_logic_vector(7 downto 0); - U : std_logic_vector(3 downto 0)) is - variable my_line : line; - alias swrite is write [line, string, side, width] ; -begin - swrite(my_line, "sqrt( "); - write(my_line, P); - swrite(my_line, " )= "); - write(my_line, U); - writeline(output, my_line); -end print; - - -entity add32csa is -- one stage of carry save adder for multiplier - port( - b : in std_logic; -- a multiplier bit - a : in std_logic_vector(31 downto 0); -- multiplicand - sum_in : in std_logic_vector(31 downto 0); -- sums from previous stage - cin : in std_logic_vector(31 downto 0); -- carrys from previous stage - sum_out : out std_logic_vector(31 downto 0); -- sums to next stage - cout : out std_logic_vector(31 downto 0)); -- carrys to next stage -end add32csa; - - -ARCHITECTURE circuits of add32csa IS - SIGNAL zero : STD_LOGIC_VECTOR(31 downto 0) := X"00000000"; - SIGNAL aa : std_logic_vector(31 downto 0) := X"00000000"; - - COMPONENT fadd -- duplicates entity port - PoRT(a : in std_logic; - b : in std_logic; - cin : in std_logic; - s : out std_logic; - cout : out std_logic); - end comPonent fadd; - -begin -- circuits of add32csa - aa <= a when b='1' else zero after 1 ns; - stage: for I in 0 to 31 generate - sta: fadd port map(aa(I), sum_in(I), cin(I) , sum_out(I), cout(I)); - end generate stage; -end architecture circuits; -- of add32csa diff --git a/third_party/pygments/tests/examplefiles/test.xqy b/third_party/pygments/tests/examplefiles/test.xqy deleted file mode 100644 index c626ea964..000000000 --- a/third_party/pygments/tests/examplefiles/test.xqy +++ /dev/null @@ -1,138 +0,0 @@ -(: made up functions, etc just to test xquery parsing (: even embedded comments -on multiple :) -lines -:) -xquery version "1.0"; - -module namespace xqueryexample "http://example.com/namespace"; -import module namespace importedns = "http://example.com/ns/imported" at "no/such/file.xqy"; - -declare namespace sess = "com.example.session"; - -declare variable $amazing := "awesome"; -declare variable $SESSIONS as element(sess:session)* := c:sessions(); - -declare option sess:clear "false"; - -define function whatsit($param as xs:string) as xs:string { - let $var1 := 1 - let $var2 := 2 - return (1 + 2 div ($var1 + $var2)) - - let $let := "test" - return (: some whitespace :) element element { - attribute attribute { 1 }, - element test { 'a' }, - attribute foo { "bar" }, - fn:doc()[ foo/@bar eq $let ], - //x/with/another/*/*:version/xpath/@attr } -}; - -let $bride := "Bride" -let $test := validate lax { html } -let $test := validate strict { html } -let $test := validate { html } -let $test := $var1/*:Article (: comment here :) [fn:not()] -let $test := $var1/@*:name/fn:string() - -let $noop := ordered { $test } -let $noop := unordered { $test } - -let $noop := - for $version at $i in $versions/version - let $row := if($i mod 2 eq 0) then "even" else "odd" - order by $version descending - return - -return - -{ - - - The Princess { fn:capitalize($bride) } - -
    - - { - (: placeholder for local sessions :) - element div { - attribute id { "sessions-local" }, - attribute class { "hidden" }, - element h1 { "Local Sessions" }, - element p { - 'These sessions use storage provided by your browser.', - 'You can also ', - element a { - attribute href { 'session-import-local.xqy' }, - 'import' }, - ' sessions from local XML files.' - } - } - } - { - for $i in $sessions - let $id := c:session-id($i) - let $uri := c:session-uri($i) - (: we only care about the lock that expires last :) - let $conflicting := c:conflicting-locks($uri, 1) - let $name as xs:string := ($i/sess:name, "(unnamed)")[1] - return element tr { - element td { $name }, - element td { string($i/sec:user) }, - element td { data($i/sess:created) }, - element td { data($i/sess:last-modified) }, - element td { - if (empty($conflicting)) then () else - text { - "by", $conflicting/lock:owner, - "until", adjust-dateTime-to-timezone( - x:epoch-seconds-to-dateTime( - $conflicting/lock:timestamp + $conflicting/lock:timeout - ) - ) - }, - (: only show resume button if there are no conflicting locks :) - element input { - attribute type { "button" }, - attribute title { - data($i/sess:query-buffers/sess:query[1]) }, - attribute onclick { - concat("list.resumeSession('", $id, "')") }, - attribute value { - "Resume", (' ', $id)[ $d:DEBUG ] } - }[ not($conflicting) ], - $x:NBSP, - (: clone button :) - element input { - attribute type { "button" }, - attribute title { "clone this session" }, - attribute onclick { - concat("list.cloneSession('", $id, "', this)") }, - attribute value { "Clone", (' ', $id)[ $d:DEBUG ] } - }, - $x:NBSP, - (: export button :) - element input { - attribute type { "button" }, - attribute title { "export this session" }, - attribute onclick { - concat("list.exportServerSession('", $id, "', this)") }, - attribute value { "Export", (' ', $id)[ $d:DEBUG ] } - }, - $x:NBSP, - (: only show delete button if there are no conflicting locks :) - element input { - attribute type { "button" }, - attribute title { "permanently delete this session" }, - attribute onclick { - concat("list.deleteSession('", $id, "', this)") }, - attribute value { "Delete", (' ', $id)[ $d:DEBUG ] } - }[ not($conflicting) ] - } - } - } -
    -
    -} -   - diff --git a/third_party/pygments/tests/examplefiles/test.xsl b/third_party/pygments/tests/examplefiles/test.xsl deleted file mode 100644 index 590bb043c..000000000 --- a/third_party/pygments/tests/examplefiles/test.xsl +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/third_party/pygments/tests/examplefiles/test.zep b/third_party/pygments/tests/examplefiles/test.zep deleted file mode 100644 index 4724d4c48..000000000 --- a/third_party/pygments/tests/examplefiles/test.zep +++ /dev/null @@ -1,33 +0,0 @@ -namespace Test; - -use Test\Foo; - -class Bar -{ - protected a; - private b; - public c {set, get}; - - public function __construct(string str, boolean bool) - { - let this->c = str; - this->setC(bool); - let this->b = []; - } - - public function sayHello(string name) - { - echo "Hello " . name; - } - - protected function loops() - { - for a in b { - echo a; - } - loop { - return "boo!"; - } - } - -} \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/test2.odin b/third_party/pygments/tests/examplefiles/test2.odin deleted file mode 100644 index 2a6b4517e..000000000 --- a/third_party/pygments/tests/examplefiles/test2.odin +++ /dev/null @@ -1,30 +0,0 @@ -school_schedule = < - lesson_times = <08:30:00, 09:30:00, 10:30:00, ...> - - locations = < - [1] = <"under the big plane tree"> - [2] = <"under the north arch"> - [3] = <"in a garden"> - > - - subjects = < - ["philosophy:plato"] = < -- note construction of key - name = <"philosophy"> - teacher = <"plato"> - topics = <"meta-physics", "natural science"> - weighting = <76%> - > - ["philosophy:kant"] = < - name = <"philosophy"> - teacher = <"kant"> - topics = <"meaning and reason", "meta-physics", "ethics"> - weighting = <80%> - > - ["art"] = < - name = <"art"> - teacher = <"goya"> - topics = <"technique", "portraiture", "satire"> - weighting = <78%> - > - > -> diff --git a/third_party/pygments/tests/examplefiles/test2.pypylog b/third_party/pygments/tests/examplefiles/test2.pypylog deleted file mode 100644 index 543e21ddf..000000000 --- a/third_party/pygments/tests/examplefiles/test2.pypylog +++ /dev/null @@ -1,120 +0,0 @@ -[2f1dd6c3b8b7] {jit-log-opt-loop -# Loop 0 ( ds1dr4 dsdr3 ds1dr4) : loop with 115 ops -[p0, p1] -+33: label(p0, p1, descr=TargetToken(-1223434224)) -debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') -+33: guard_nonnull_class(p1, 138371488, descr=) [p1, p0] -+54: p3 = getfield_gc_pure(p1, descr=) -+57: guard_value(p3, ConstPtr(ptr4), descr=) [p1, p0, p3] -+69: p5 = getfield_gc_pure(p1, descr=) -+72: p7 = getarrayitem_gc(p5, 0, descr=) -+75: guard_class(p7, 138371552, descr=) [p0, p5, p7] -+88: p9 = getfield_gc(p7, descr=) -+91: guard_nonnull_class(p9, 138373024, descr=) [p0, p5, p7, p9] -+109: p12 = getarrayitem_gc(p5, 1, descr=) -+112: guard_class(p12, 138371552, descr=) [p0, p5, p12, p7] -+125: p14 = getfield_gc(p12, descr=) -+128: guard_nonnull_class(p14, 138373024, descr=) [p0, p5, p12, p14, p7] -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -+146: p16 = getfield_gc_pure(p9, descr=) -+149: guard_value(p16, ConstPtr(ptr17), descr=) [p16, p9, p0, p12, p7] -+161: p18 = getfield_gc_pure(p9, descr=) -+164: guard_class(p18, 138371648, descr=) [p18, p9, p0, p12, p7] -+177: p20 = getfield_gc_pure(p9, descr=) -+180: guard_class(p20, 138371648, descr=) [p20, p9, p18, p0, p12, p7] -+193: p22 = getfield_gc_pure(p9, descr=) -+196: guard_class(p22, 138371936, descr=) [p22, p9, p20, p18, p0, p12, p7] -debug_merge_point(0, 0, 'None') -+209: p24 = getfield_gc_pure(p22, descr=) -+215: guard_value(p24, ConstPtr(ptr25), descr=) [p24, p22, p9, None, None, p0, p12, p7] -+227: p27 = getfield_gc_pure(p22, descr=) -+230: guard_class(p27, 138371648, descr=) [p22, p27, p9, None, None, p0, p12, p7] -debug_merge_point(0, 0, '_') -debug_merge_point(0, 0, 'None') -+243: p30 = getfield_gc(ConstPtr(ptr29), descr=) -+249: i34 = call(ConstClass(ll_dict_lookup_trampoline__v64___simple_call__function_ll), p30, ConstPtr(ptr32), 360200661, descr=) -+281: guard_no_exception(, descr=) [p27, p20, p18, i34, p30, None, None, None, p0, p12, p7] -+294: i36 = int_and(i34, -2147483648) -+302: i37 = int_is_true(i36) -guard_false(i37, descr=) [p27, p20, p18, i34, p30, None, None, None, p0, p12, p7] -+311: p38 = getfield_gc(p30, descr=) -+314: p39 = getinteriorfield_gc(p38, i34, descr=>) -+318: i40 = instance_ptr_eq(p18, p39) -guard_true(i40, descr=) [p27, p20, None, None, None, p0, p12, p7] -debug_merge_point(0, 0, 'None') -+327: i41 = getfield_gc_pure(p20, descr=) -+330: i42 = getfield_gc_pure(p27, descr=) -+333: i43 = int_sub(i41, i42) -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -+335: i45 = int_eq(0, i43) -guard_false(i45, descr=) [p0, i43, None, None, None, None, p12, p7] -p47 = new_with_vtable(138371648) -+393: setfield_gc(p47, i43, descr=) -setfield_gc(p7, p47, descr=) -+414: p48 = getfield_gc(p12, descr=) -+420: guard_nonnull_class(p48, 138371648, descr=) [p0, p48, p12, p47, p7] -debug_merge_point(0, 0, ' 1 1 1 dsdr3 1') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, '_') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, ' dsdr3 dsdr3') -debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') -+438: label(p0, p48, p30, p38, descr=TargetToken(-1223434176)) -debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, '_') -debug_merge_point(0, 0, 'None') -+438: i50 = call(ConstClass(ll_dict_lookup_trampoline__v64___simple_call__function_ll), p30, ConstPtr(ptr32), 360200661, descr=) -+464: guard_no_exception(, descr=) [p48, i50, p30, p0] -+477: i51 = int_and(i50, -2147483648) -+485: i52 = int_is_true(i51) -guard_false(i52, descr=) [p48, i50, p30, p0] -+494: p53 = getinteriorfield_gc(p38, i50, descr=>) -+501: i55 = instance_ptr_eq(ConstPtr(ptr54), p53) -guard_true(i55, descr=) [p48, p0] -debug_merge_point(0, 0, 'None') -+513: i56 = getfield_gc_pure(p48, descr=) -+516: i58 = int_sub(i56, 1) -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -+519: i59 = int_eq(0, i58) -guard_false(i59, descr=) [i58, p48, p0] -debug_merge_point(0, 0, ' 1 1 1 dsdr3 1') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, '_') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, 'None') -debug_merge_point(0, 0, ' dsdr3 dsdr3') -debug_merge_point(0, 0, ' ds1dr4 dsdr3 ds1dr4') -p61 = new_with_vtable(138371700) -p63 = new_with_vtable(138373024) -p65 = new_with_vtable(138371936) -+606: setfield_gc(p63, ConstPtr(ptr66), descr=) -p68 = new_with_vtable(138373024) -+632: setfield_gc(p65, ConstPtr(ptr69), descr=) -p71 = new_with_vtable(138371936) -+658: setfield_gc(p68, ConstPtr(ptr17), descr=) -+665: setfield_gc(p71, ConstPtr(ptr72), descr=) -+672: setfield_gc(p68, p71, descr=) -+675: setfield_gc(p68, p48, descr=) -+678: setfield_gc(p68, ConstPtr(ptr54), descr=) -p73 = new_with_vtable(138371648) -+701: setfield_gc(p61, p0, descr=) -+716: setfield_gc(p61, 2, descr=) -+723: setfield_gc(p71, ConstPtr(ptr25), descr=) -+730: setfield_gc(p65, p68, descr=) -+733: setfield_gc(p63, p65, descr=) -+736: setfield_gc(p63, ConstPtr(ptr75), descr=) -+743: setfield_gc(p63, ConstPtr(ptr54), descr=) -+750: setfield_gc(p61, p63, descr=) -+753: setfield_gc(p73, i58, descr=) -+762: jump(p61, p73, p30, p38, descr=TargetToken(-1223434176)) -+775: --end of the loop-- -[2f1dd6da3b99] jit-log-opt-loop} diff --git a/third_party/pygments/tests/examplefiles/test_basic.adls b/third_party/pygments/tests/examplefiles/test_basic.adls deleted file mode 100644 index df5aa7431..000000000 --- a/third_party/pygments/tests/examplefiles/test_basic.adls +++ /dev/null @@ -1,28 +0,0 @@ --- --- Example of an openEHR Archetype, written in the Archetype Definition Language (ADL) --- Definition available here: http://www.openehr.org/releases/trunk/architecture/am/adl2.pdf --- Author: derived from the openEHR-EHR-EVALUATION.adverse_reaction.v1 archetype at http://www.openEHR.org/ckm --- - -archetype (adl_version=2.0.5; rm_release=1.0.2; generated) - openEHR-EHR-EVALUATION.adverse_reaction.v1.0.0 - -language - original_language = <[ISO_639-1::en]> - -description - lifecycle_state = <"unmanaged"> - -definition - EVALUATION[id1] - -terminology - term_definitions = < - ["en"] = < - ["id1"] = < - text = <"Adverse Reaction"> - description = <"xxx"> - > - > - > - diff --git a/third_party/pygments/tests/examplefiles/truncated.pytb b/third_party/pygments/tests/examplefiles/truncated.pytb deleted file mode 100644 index ad5b6d492..000000000 --- a/third_party/pygments/tests/examplefiles/truncated.pytb +++ /dev/null @@ -1,15 +0,0 @@ - File "/usr/lib/python2.3/site-packages/trac/web/main.py", line 314, in dispatch_request - dispatcher.dispatch(req) - File "/usr/lib/python2.3/site-packages/trac/web/main.py", line 186, in dispatch - req.session = Session(self.env, req) - File "/usr/lib/python2.3/site-packages/trac/web/session.py", line 52, in __init__ - self.promote_session(sid) - File "/usr/lib/python2.3/site-packages/trac/web/session.py", line 125, in promote_session - "AND authenticated=0", (sid,)) - File "/usr/lib/python2.3/site-packages/trac/db/util.py", line 47, in execute - return self.cursor.execute(sql_escape_percent(sql), args) - File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 44, in execute - args or []) - File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 36, in _rollback_on_error - return function(self, *args, **kwargs) -OperationalError: database is locked diff --git a/third_party/pygments/tests/examplefiles/twig_test b/third_party/pygments/tests/examplefiles/twig_test deleted file mode 100644 index 0932fe908..000000000 --- a/third_party/pygments/tests/examplefiles/twig_test +++ /dev/null @@ -1,4612 +0,0 @@ -From the Twig test suite, https://github.com/fabpot/Twig, available under BSD license. - ---TEST-- -Exception for an unclosed tag ---TEMPLATE-- -{% block foo %} - {% if foo %} - - - - - {% for i in fo %} - - - - {% endfor %} - - - -{% endblock %} ---EXCEPTION-- -Twig_Error_Syntax: Unexpected tag name "endblock" (expecting closing tag for the "if" tag defined near line 4) in "index.twig" at line 16 ---TEST-- -Exception for an undefined trait ---TEMPLATE-- -{% use 'foo' with foobar as bar %} ---TEMPLATE(foo)-- -{% block bar %} -{% endblock %} ---EXCEPTION-- -Twig_Error_Runtime: Block "foobar" is not defined in trait "foo" in "index.twig". ---TEST-- -Twig supports method calls ---TEMPLATE-- -{{ items.foo }} -{{ items['foo'] }} -{{ items[foo] }} -{{ items[items[foo]] }} ---DATA-- -return array('foo' => 'bar', 'items' => array('foo' => 'bar', 'bar' => 'foo')) ---EXPECT-- -bar -bar -foo -bar ---TEST-- -Twig supports array notation ---TEMPLATE-- -{# empty array #} -{{ []|join(',') }} - -{{ [1, 2]|join(',') }} -{{ ['foo', "bar"]|join(',') }} -{{ {0: 1, 'foo': 'bar'}|join(',') }} -{{ {0: 1, 'foo': 'bar'}|keys|join(',') }} - -{{ {0: 1, foo: 'bar'}|join(',') }} -{{ {0: 1, foo: 'bar'}|keys|join(',') }} - -{# nested arrays #} -{% set a = [1, 2, [1, 2], {'foo': {'foo': 'bar'}}] %} -{{ a[2]|join(',') }} -{{ a[3]["foo"]|join(',') }} - -{# works even if [] is used inside the array #} -{{ [foo[bar]]|join(',') }} - -{# elements can be any expression #} -{{ ['foo'|upper, bar|upper, bar == foo]|join(',') }} - -{# arrays can have a trailing , like in PHP #} -{{ - [ - 1, - 2, - ]|join(',') -}} - -{# keys can be any expression #} -{% set a = 1 %} -{% set b = "foo" %} -{% set ary = { (a): 'a', (b): 'b', 'c': 'c', (a ~ b): 'd' } %} -{{ ary|keys|join(',') }} -{{ ary|join(',') }} ---DATA-- -return array('bar' => 'bar', 'foo' => array('bar' => 'bar')) ---EXPECT-- -1,2 -foo,bar -1,bar -0,foo - -1,bar -0,foo - -1,2 -bar - -bar - -FOO,BAR, - -1,2 - -1,foo,c,1foo -a,b,c,d ---TEST-- -Twig supports binary operations (+, -, *, /, ~, %, and, or) ---TEMPLATE-- -{{ 1 + 1 }} -{{ 2 - 1 }} -{{ 2 * 2 }} -{{ 2 / 2 }} -{{ 3 % 2 }} -{{ 1 and 1 }} -{{ 1 and 0 }} -{{ 0 and 1 }} -{{ 0 and 0 }} -{{ 1 or 1 }} -{{ 1 or 0 }} -{{ 0 or 1 }} -{{ 0 or 0 }} -{{ 0 or 1 and 0 }} -{{ 1 or 0 and 1 }} -{{ "foo" ~ "bar" }} -{{ foo ~ "bar" }} -{{ "foo" ~ bar }} -{{ foo ~ bar }} -{{ 20 // 7 }} ---DATA-- -return array('foo' => 'bar', 'bar' => 'foo') ---EXPECT-- -2 -1 -4 -1 -1 -1 - - - -1 -1 -1 - - -1 -foobar -barbar -foofoo -barfoo -2 ---TEST-- -Twig supports bitwise operations ---TEMPLATE-- -{{ 1 b-and 5 }} -{{ 1 b-or 5 }} -{{ 1 b-xor 5 }} -{{ (1 and 0 b-or 0) is same as(1 and (0 b-or 0)) ? 'ok' : 'ko' }} ---DATA-- -return array() ---EXPECT-- -1 -5 -4 -ok ---TEST-- -Twig supports comparison operators (==, !=, <, >, >=, <=) ---TEMPLATE-- -{{ 1 > 2 }}/{{ 1 > 1 }}/{{ 1 >= 2 }}/{{ 1 >= 1 }} -{{ 1 < 2 }}/{{ 1 < 1 }}/{{ 1 <= 2 }}/{{ 1 <= 1 }} -{{ 1 == 1 }}/{{ 1 == 2 }} -{{ 1 != 1 }}/{{ 1 != 2 }} ---DATA-- -return array() ---EXPECT-- -///1 -1//1/1 -1/ -/1 ---TEST-- -Twig supports the "divisible by" operator ---TEMPLATE-- -{{ 8 is divisible by(2) ? 'OK' }} -{{ 8 is not divisible by(3) ? 'OK' }} -{{ 8 is divisible by (2) ? 'OK' }} -{{ 8 is not - divisible - by - (3) ? 'OK' }} ---DATA-- -return array() ---EXPECT-- -OK -OK -OK -OK ---TEST-- -Twig supports the .. operator ---TEMPLATE-- -{% for i in 0..10 %}{{ i }} {% endfor %} - -{% for letter in 'a'..'z' %}{{ letter }} {% endfor %} - -{% for letter in 'a'|upper..'z'|upper %}{{ letter }} {% endfor %} - -{% for i in foo[0]..foo[1] %}{{ i }} {% endfor %} - -{% for i in 0 + 1 .. 10 - 1 %}{{ i }} {% endfor %} ---DATA-- -return array('foo' => array(1, 10)) ---EXPECT-- -0 1 2 3 4 5 6 7 8 9 10 -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 -1 2 3 4 5 6 7 8 9 10 -1 2 3 4 5 6 7 8 9 ---TEST-- -Twig supports the "ends with" operator ---TEMPLATE-- -{{ 'foo' ends with 'o' ? 'OK' : 'KO' }} -{{ not ('foo' ends with 'f') ? 'OK' : 'KO' }} -{{ not ('foo' ends with 'foowaytoolong') ? 'OK' : 'KO' }} -{{ 'foo' ends with '' ? 'OK' : 'KO' }} -{{ '1' ends with true ? 'OK' : 'KO' }} -{{ 1 ends with true ? 'OK' : 'KO' }} -{{ 0 ends with false ? 'OK' : 'KO' }} -{{ '' ends with false ? 'OK' : 'KO' }} -{{ false ends with false ? 'OK' : 'KO' }} -{{ false ends with '' ? 'OK' : 'KO' }} ---DATA-- -return array() ---EXPECT-- -OK -OK -OK -OK -KO -KO -KO -KO -KO -KO ---TEST-- -Twig supports grouping of expressions ---TEMPLATE-- -{{ (2 + 2) / 2 }} ---DATA-- -return array() ---EXPECT-- -2 ---TEST-- -Twig supports literals ---TEMPLATE-- -1 {{ true }} -2 {{ TRUE }} -3 {{ false }} -4 {{ FALSE }} -5 {{ none }} -6 {{ NONE }} -7 {{ null }} -8 {{ NULL }} ---DATA-- -return array() ---EXPECT-- -1 1 -2 1 -3 -4 -5 -6 -7 -8 ---TEST-- -Twig supports __call() for attributes ---TEMPLATE-- -{{ foo.foo }} -{{ foo.bar }} ---EXPECT-- -foo_from_call -bar_from_getbar ---TEST-- -Twig supports the "matches" operator ---TEMPLATE-- -{{ 'foo' matches '/o/' ? 'OK' : 'KO' }} -{{ 'foo' matches '/^fo/' ? 'OK' : 'KO' }} -{{ 'foo' matches '/O/i' ? 'OK' : 'KO' }} ---DATA-- -return array() ---EXPECT-- -OK -OK -OK ---TEST-- -Twig supports method calls ---TEMPLATE-- -{{ items.foo.foo }} -{{ items.foo.getFoo() }} -{{ items.foo.bar }} -{{ items.foo['bar'] }} -{{ items.foo.bar('a', 43) }} -{{ items.foo.bar(foo) }} -{{ items.foo.self.foo() }} -{{ items.foo.is }} -{{ items.foo.in }} -{{ items.foo.not }} ---DATA-- -return array('foo' => 'bar', 'items' => array('foo' => new TwigTestFoo(), 'bar' => 'foo')) ---CONFIG-- -return array('strict_variables' => false) ---EXPECT-- -foo -foo -bar - -bar_a-43 -bar_bar -foo -is -in -not ---TEST-- -Twig allows to use named operators as variable names ---TEMPLATE-- -{% for match in matches %} - {{- match }} -{% endfor %} -{{ in }} -{{ is }} ---DATA-- -return array('matches' => array(1, 2, 3), 'in' => 'in', 'is' => 'is') ---EXPECT-- -1 -2 -3 -in -is ---TEST-- -Twig parses postfix expressions ---TEMPLATE-- -{% import _self as macros %} - -{% macro foo() %}foo{% endmacro %} - -{{ 'a' }} -{{ 'a'|upper }} -{{ ('a')|upper }} -{{ -1|upper }} -{{ macros.foo() }} -{{ (macros).foo() }} ---DATA-- -return array(); ---EXPECT-- -a -A -A --1 -foo -foo ---TEST-- -Twig supports the "same as" operator ---TEMPLATE-- -{{ 1 is same as(1) ? 'OK' }} -{{ 1 is not same as(true) ? 'OK' }} -{{ 1 is same as(1) ? 'OK' }} -{{ 1 is not same as(true) ? 'OK' }} -{{ 1 is same as (1) ? 'OK' }} -{{ 1 is not - same - as - (true) ? 'OK' }} ---DATA-- -return array() ---EXPECT-- -OK -OK -OK -OK -OK -OK ---TEST-- -Twig supports the "starts with" operator ---TEMPLATE-- -{{ 'foo' starts with 'f' ? 'OK' : 'KO' }} -{{ not ('foo' starts with 'oo') ? 'OK' : 'KO' }} -{{ not ('foo' starts with 'foowaytoolong') ? 'OK' : 'KO' }} -{{ 'foo' starts with 'f' ? 'OK' : 'KO' }} -{{ 'foo' starts -with 'f' ? 'OK' : 'KO' }} -{{ 'foo' starts with '' ? 'OK' : 'KO' }} -{{ '1' starts with true ? 'OK' : 'KO' }} -{{ '' starts with false ? 'OK' : 'KO' }} -{{ 'a' starts with false ? 'OK' : 'KO' }} -{{ false starts with '' ? 'OK' : 'KO' }} ---DATA-- -return array() ---EXPECT-- -OK -OK -OK -OK -OK -OK -KO -KO -KO -KO ---TEST-- -Twig supports string interpolation ---TEMPLATE-- -{# "foo #{"foo #{bar} baz"} baz" #} -{# "foo #{bar}#{bar} baz" #} ---DATA-- -return array('bar' => 'BAR'); ---EXPECT-- -foo foo BAR baz baz -foo BARBAR baz ---TEST-- -Twig supports the ternary operator ---TEMPLATE-- -{{ 1 ? 'YES' }} -{{ 0 ? 'YES' }} ---DATA-- -return array() ---EXPECT-- -YES - ---TEST-- -Twig supports the ternary operator ---TEMPLATE-- -{{ 'YES' ?: 'NO' }} -{{ 0 ?: 'NO' }} ---DATA-- -return array() ---EXPECT-- -YES -NO ---TEST-- -Twig supports the ternary operator ---TEMPLATE-- -{{ 1 ? 'YES' : 'NO' }} -{{ 0 ? 'YES' : 'NO' }} -{{ 0 ? 'YES' : (1 ? 'YES1' : 'NO1') }} -{{ 0 ? 'YES' : (0 ? 'YES1' : 'NO1') }} -{{ 1 == 1 ? 'foo
    ':'' }} -{{ foo ~ (bar ? ('-' ~ bar) : '') }} ---DATA-- -return array('foo' => 'foo', 'bar' => 'bar') ---EXPECT-- -YES -NO -YES1 -NO1 -foo
    -foo-bar ---TEST-- -Twig does not allow to use two-word named operators as variable names ---TEMPLATE-- -{{ starts with }} ---DATA-- -return array() ---EXCEPTION-- -Twig_Error_Syntax: Unexpected token "operator" of value "starts with" in "index.twig" at line 2 ---TEST-- -Twig unary operators precedence ---TEMPLATE-- -{{ -1 - 1 }} -{{ -1 - -1 }} -{{ -1 * -1 }} -{{ 4 / -1 * 5 }} ---DATA-- -return array() ---EXPECT-- --2 -0 -1 --20 ---TEST-- -Twig supports unary operators (not, -, +) ---TEMPLATE-- -{{ not 1 }}/{{ not 0 }} -{{ +1 + 1 }}/{{ -1 - 1 }} -{{ not (false or true) }} ---DATA-- -return array() ---EXPECT-- -/1 -2/-2 - ---TEST-- -"abs" filter ---TEMPLATE-- -{{ (-5.5)|abs }} -{{ (-5)|abs }} -{{ (-0)|abs }} -{{ 0|abs }} -{{ 5|abs }} -{{ 5.5|abs }} -{{ number1|abs }} -{{ number2|abs }} -{{ number3|abs }} -{{ number4|abs }} -{{ number5|abs }} -{{ number6|abs }} ---DATA-- -return array('number1' => -5.5, 'number2' => -5, 'number3' => -0, 'number4' => 0, 'number5' => 5, 'number6' => 5.5) ---EXPECT-- -5.5 -5 -0 -0 -5 -5.5 -5.5 -5 -0 -0 -5 -5.5 ---TEST-- -"batch" filter ---TEMPLATE-- -{% for row in items|batch(3.1) %} -
    - {% for column in row %} -
    {{ column }}
    - {% endfor %} -
    -{% endfor %} ---DATA-- -return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) ---EXPECT-- -
    -
    a
    -
    b
    -
    c
    -
    d
    -
    -
    -
    e
    -
    f
    -
    g
    -
    h
    -
    -
    -
    i
    -
    j
    -
    ---TEST-- -"batch" filter ---TEMPLATE-- -{% for row in items|batch(3) %} -
    - {% for column in row %} -
    {{ column }}
    - {% endfor %} -
    -{% endfor %} ---DATA-- -return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) ---EXPECT-- -
    -
    a
    -
    b
    -
    c
    -
    -
    -
    d
    -
    e
    -
    f
    -
    -
    -
    g
    -
    h
    -
    i
    -
    -
    -
    j
    -
    ---TEST-- -"batch" filter ---TEMPLATE-- - -{% for row in items|batch(3, '') %} - - {% for column in row %} - - {% endfor %} - -{% endfor %} -
    {{ column }}
    ---DATA-- -return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) ---EXPECT-- - - - - - - - - - - - - - - - - - - - - - -
    abc
    def
    ghi
    j
    ---TEST-- -"batch" filter ---TEMPLATE-- -{% for row in items|batch(3, 'fill') %} -
    - {% for column in row %} -
    {{ column }}
    - {% endfor %} -
    -{% endfor %} ---DATA-- -return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l')) ---EXPECT-- -
    -
    a
    -
    b
    -
    c
    -
    -
    -
    d
    -
    e
    -
    f
    -
    -
    -
    g
    -
    h
    -
    i
    -
    -
    -
    j
    -
    k
    -
    l
    -
    ---TEST-- -"batch" filter ---TEMPLATE-- - -{% for row in items|batch(3, 'fill') %} - - {% for column in row %} - - {% endfor %} - -{% endfor %} -
    {{ column }}
    ---DATA-- -return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) ---EXPECT-- - - - - - - - - - - - - - - - - - - - - - -
    abc
    def
    ghi
    jfillfill
    ---TEST-- -"convert_encoding" filter ---CONDITION-- -function_exists('iconv') || function_exists('mb_convert_encoding') ---TEMPLATE-- -{{ "愛していますか?"|convert_encoding('ISO-2022-JP', 'UTF-8')|convert_encoding('UTF-8', 'ISO-2022-JP') }} ---DATA-- -return array() ---EXPECT-- -愛していますか? ---TEST-- -"date" filter (interval support as of PHP 5.3) ---CONDITION-- -version_compare(phpversion(), '5.3.0', '>=') ---TEMPLATE-- -{{ date2|date }} -{{ date2|date('%d days') }} ---DATA-- -date_default_timezone_set('UTC'); -$twig->getExtension('core')->setDateFormat('Y-m-d', '%d days %h hours'); -return array( - 'date2' => new DateInterval('P2D'), -) ---EXPECT-- -2 days 0 hours -2 days ---TEST-- -"date" filter ---TEMPLATE-- -{{ date1|date }} -{{ date1|date('d/m/Y') }} ---DATA-- -date_default_timezone_set('UTC'); -$twig->getExtension('core')->setDateFormat('Y-m-d', '%d days %h hours'); -return array( - 'date1' => mktime(13, 45, 0, 10, 4, 2010), -) ---EXPECT-- -2010-10-04 -04/10/2010 ---TEST-- -"date" filter ---CONDITION-- -version_compare(phpversion(), '5.5.0', '>=') ---TEMPLATE-- -{{ date1|date }} -{{ date1|date('d/m/Y') }} -{{ date1|date('d/m/Y H:i:s', 'Asia/Hong_Kong') }} -{{ date1|date('d/m/Y H:i:s', timezone1) }} -{{ date1|date('d/m/Y H:i:s') }} - -{{ date2|date('d/m/Y H:i:s P', 'Europe/Paris') }} -{{ date2|date('d/m/Y H:i:s P', 'Asia/Hong_Kong') }} -{{ date2|date('d/m/Y H:i:s P', false) }} -{{ date2|date('e', 'Europe/Paris') }} -{{ date2|date('e', false) }} ---DATA-- -date_default_timezone_set('Europe/Paris'); -return array( - 'date1' => new DateTimeImmutable('2010-10-04 13:45'), - 'date2' => new DateTimeImmutable('2010-10-04 13:45', new DateTimeZone('America/New_York')), - 'timezone1' => new DateTimeZone('America/New_York'), -) ---EXPECT-- -October 4, 2010 13:45 -04/10/2010 -04/10/2010 19:45:00 -04/10/2010 07:45:00 -04/10/2010 13:45:00 - -04/10/2010 19:45:00 +02:00 -05/10/2010 01:45:00 +08:00 -04/10/2010 13:45:00 -04:00 -Europe/Paris -America/New_York ---TEST-- -"date" filter (interval support as of PHP 5.3) ---CONDITION-- -version_compare(phpversion(), '5.3.0', '>=') ---TEMPLATE-- -{{ date1|date }} -{{ date1|date('%d days %h hours') }} -{{ date1|date('%d days %h hours', timezone1) }} ---DATA-- -date_default_timezone_set('UTC'); -return array( - 'date1' => new DateInterval('P2D'), - // This should have no effect on DateInterval formatting - 'timezone1' => new DateTimeZone('America/New_York'), -) ---EXPECT-- -2 days -2 days 0 hours -2 days 0 hours ---TEST-- -"date_modify" filter ---TEMPLATE-- -{{ date1|date_modify('-1day')|date('Y-m-d H:i:s') }} -{{ date2|date_modify('-1day')|date('Y-m-d H:i:s') }} ---DATA-- -date_default_timezone_set('UTC'); -return array( - 'date1' => '2010-10-04 13:45', - 'date2' => new DateTime('2010-10-04 13:45'), -) ---EXPECT-- -2010-10-03 13:45:00 -2010-10-03 13:45:00 ---TEST-- -"date" filter ---TEMPLATE-- -{{ date|date(format='d/m/Y H:i:s P', timezone='America/Chicago') }} -{{ date|date(timezone='America/Chicago', format='d/m/Y H:i:s P') }} -{{ date|date('d/m/Y H:i:s P', timezone='America/Chicago') }} ---DATA-- -date_default_timezone_set('UTC'); -return array('date' => mktime(13, 45, 0, 10, 4, 2010)) ---EXPECT-- -04/10/2010 08:45:00 -05:00 -04/10/2010 08:45:00 -05:00 -04/10/2010 08:45:00 -05:00 ---TEST-- -"date" filter ---TEMPLATE-- -{{ date1|date }} -{{ date1|date('d/m/Y') }} -{{ date1|date('d/m/Y H:i:s', 'Asia/Hong_Kong') }} -{{ date1|date('d/m/Y H:i:s P', 'Asia/Hong_Kong') }} -{{ date1|date('d/m/Y H:i:s P', 'America/Chicago') }} -{{ date1|date('e') }} -{{ date1|date('d/m/Y H:i:s') }} - -{{ date2|date }} -{{ date2|date('d/m/Y') }} -{{ date2|date('d/m/Y H:i:s', 'Asia/Hong_Kong') }} -{{ date2|date('d/m/Y H:i:s', timezone1) }} -{{ date2|date('d/m/Y H:i:s') }} - -{{ date3|date }} -{{ date3|date('d/m/Y') }} - -{{ date4|date }} -{{ date4|date('d/m/Y') }} - -{{ date5|date }} -{{ date5|date('d/m/Y') }} - -{{ date6|date('d/m/Y H:i:s P', 'Europe/Paris') }} -{{ date6|date('d/m/Y H:i:s P', 'Asia/Hong_Kong') }} -{{ date6|date('d/m/Y H:i:s P', false) }} -{{ date6|date('e', 'Europe/Paris') }} -{{ date6|date('e', false) }} - -{{ date7|date }} ---DATA-- -date_default_timezone_set('Europe/Paris'); -return array( - 'date1' => mktime(13, 45, 0, 10, 4, 2010), - 'date2' => new DateTime('2010-10-04 13:45'), - 'date3' => '2010-10-04 13:45', - 'date4' => 1286199900, // DateTime::createFromFormat('Y-m-d H:i', '2010-10-04 13:45', new DateTimeZone('UTC'))->getTimestamp() -- A unixtimestamp is always GMT - 'date5' => -189291360, // DateTime::createFromFormat('Y-m-d H:i', '1964-01-02 03:04', new DateTimeZone('UTC'))->getTimestamp(), - 'date6' => new DateTime('2010-10-04 13:45', new DateTimeZone('America/New_York')), - 'date7' => '2010-01-28T15:00:00+05:00', - 'timezone1' => new DateTimeZone('America/New_York'), -) ---EXPECT-- -October 4, 2010 13:45 -04/10/2010 -04/10/2010 19:45:00 -04/10/2010 19:45:00 +08:00 -04/10/2010 06:45:00 -05:00 -Europe/Paris -04/10/2010 13:45:00 - -October 4, 2010 13:45 -04/10/2010 -04/10/2010 19:45:00 -04/10/2010 07:45:00 -04/10/2010 13:45:00 - -October 4, 2010 13:45 -04/10/2010 - -October 4, 2010 15:45 -04/10/2010 - -January 2, 1964 04:04 -02/01/1964 - -04/10/2010 19:45:00 +02:00 -05/10/2010 01:45:00 +08:00 -04/10/2010 13:45:00 -04:00 -Europe/Paris -America/New_York - -January 28, 2010 11:00 ---TEST-- -"default" filter ---TEMPLATE-- -Variable: -{{ definedVar |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ zeroVar |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ emptyVar |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ nullVar |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ undefinedVar |default('default') is same as('default') ? 'ok' : 'ko' }} -Array access: -{{ nested.definedVar |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ nested['definedVar'] |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ nested.zeroVar |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ nested.emptyVar |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ nested.nullVar |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ nested.undefinedVar |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ nested['undefinedVar'] |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ undefinedVar.foo |default('default') is same as('default') ? 'ok' : 'ko' }} -Plain values: -{{ 'defined' |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ 0 |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ '' |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ null |default('default') is same as('default') ? 'ok' : 'ko' }} -Precedence: -{{ 'o' ~ nullVar |default('k') }} -{{ 'o' ~ nested.nullVar |default('k') }} -Object methods: -{{ object.foo |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ object.undefinedMethod |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ object.getFoo() |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ object.getFoo('a') |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ object.undefinedMethod() |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ object.undefinedMethod('a') |default('default') is same as('default') ? 'ok' : 'ko' }} -Deep nested: -{{ nested.undefinedVar.foo.bar |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ nested.definedArray.0 |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ nested['definedArray'][0] |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ object.self.foo |default('default') is same as('default') ? 'ko' : 'ok' }} -{{ object.self.undefinedMethod |default('default') is same as('default') ? 'ok' : 'ko' }} -{{ object.undefinedMethod.self |default('default') is same as('default') ? 'ok' : 'ko' }} ---DATA-- -return array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'emptyVar' => '', - 'nullVar' => null, - 'nested' => array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'emptyVar' => '', - 'nullVar' => null, - 'definedArray' => array(0), - ), - 'object' => new TwigTestFoo(), -) ---CONFIG-- -return array('strict_variables' => false) ---EXPECT-- -Variable: -ok -ok -ok -ok -ok -Array access: -ok -ok -ok -ok -ok -ok -ok -ok -Plain values: -ok -ok -ok -ok -Precedence: -ok -ok -Object methods: -ok -ok -ok -ok -ok -ok -Deep nested: -ok -ok -ok -ok -ok -ok ---DATA-- -return array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'emptyVar' => '', - 'nullVar' => null, - 'nested' => array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'emptyVar' => '', - 'nullVar' => null, - 'definedArray' => array(0), - ), - 'object' => new TwigTestFoo(), -) ---CONFIG-- -return array('strict_variables' => true) ---EXPECT-- -Variable: -ok -ok -ok -ok -ok -Array access: -ok -ok -ok -ok -ok -ok -ok -ok -Plain values: -ok -ok -ok -ok -Precedence: -ok -ok -Object methods: -ok -ok -ok -ok -ok -ok -Deep nested: -ok -ok -ok -ok -ok -ok ---TEST-- -dynamic filter ---TEMPLATE-- -{{ 'bar'|foo_path }} -{{ 'bar'|a_foo_b_bar }} ---DATA-- -return array() ---EXPECT-- -foo/bar -a/b/bar ---TEST-- -"escape" filter does not escape with the html strategy when using the html_attr strategy ---TEMPLATE-- -{{ '
    '|escape('html_attr') }} ---DATA-- -return array() ---EXPECT-- -<br /> ---TEST-- -"escape" filter ---TEMPLATE-- -{{ "愛していますか?
    "|e }} ---DATA-- -return array() ---EXPECT-- -愛していますか? <br /> ---TEST-- -"escape" filter ---TEMPLATE-- -{{ "foo
    "|e }} ---DATA-- -return array() ---EXPECT-- -foo <br /> ---TEST-- -"first" filter ---TEMPLATE-- -{{ [1, 2, 3, 4]|first }} -{{ {a: 1, b: 2, c: 3, d: 4}|first }} -{{ '1234'|first }} -{{ arr|first }} -{{ 'Ä€é'|first }} -{{ ''|first }} ---DATA-- -return array('arr' => new ArrayObject(array(1, 2, 3, 4))) ---EXPECT-- -1 -1 -1 -1 -Ä ---TEST-- -"escape" filter ---TEMPLATE-- -{% set foo %} - foo
    -{% endset %} - -{{ foo|e('html') -}} -{{ foo|e('js') }} -{% autoescape true %} - {{ foo }} -{% endautoescape %} ---DATA-- -return array() ---EXPECT-- - foo<br /> -\x20\x20\x20\x20foo\x3Cbr\x20\x2F\x3E\x0A - foo
    ---TEST-- -"format" filter ---TEMPLATE-- -{{ string|format(foo, 3) }} ---DATA-- -return array('string' => '%s/%d', 'foo' => 'bar') ---EXPECT-- -bar/3 ---TEST-- -"join" filter ---TEMPLATE-- -{{ ["foo", "bar"]|join(', ') }} -{{ foo|join(', ') }} -{{ bar|join(', ') }} ---DATA-- -return array('foo' => new TwigTestFoo(), 'bar' => new ArrayObject(array(3, 4))) ---EXPECT-- -foo, bar -1, 2 -3, 4 ---TEST-- -"json_encode" filter ---TEMPLATE-- -{{ "foo"|json_encode|raw }} -{{ foo|json_encode|raw }} -{{ [foo, "foo"]|json_encode|raw }} ---DATA-- -return array('foo' => new Twig_Markup('foo', 'UTF-8')) ---EXPECT-- -"foo" -"foo" -["foo","foo"] ---TEST-- -"last" filter ---TEMPLATE-- -{{ [1, 2, 3, 4]|last }} -{{ {a: 1, b: 2, c: 3, d: 4}|last }} -{{ '1234'|last }} -{{ arr|last }} -{{ 'Ä€é'|last }} -{{ ''|last }} ---DATA-- -return array('arr' => new ArrayObject(array(1, 2, 3, 4))) ---EXPECT-- -4 -4 -4 -4 -é ---TEST-- -"length" filter ---TEMPLATE-- -{{ array|length }} -{{ string|length }} -{{ number|length }} -{{ markup|length }} ---DATA-- -return array('array' => array(1, 4), 'string' => 'foo', 'number' => 1000, 'markup' => new Twig_Markup('foo', 'UTF-8')) ---EXPECT-- -2 -3 -4 -3 ---TEST-- -"length" filter ---CONDITION-- -function_exists('mb_get_info') ---TEMPLATE-- -{{ string|length }} -{{ markup|length }} ---DATA-- -return array('string' => 'été', 'markup' => new Twig_Markup('foo', 'UTF-8')) ---EXPECT-- -3 -3 ---TEST-- -"merge" filter ---TEMPLATE-- -{{ items|merge({'bar': 'foo'})|join }} -{{ items|merge({'bar': 'foo'})|keys|join }} -{{ {'bar': 'foo'}|merge(items)|join }} -{{ {'bar': 'foo'}|merge(items)|keys|join }} -{{ numerics|merge([4, 5, 6])|join }} ---DATA-- -return array('items' => array('foo' => 'bar'), 'numerics' => array(1, 2, 3)) ---EXPECT-- -barfoo -foobar -foobar -barfoo -123456 ---TEST-- -"nl2br" filter ---TEMPLATE-- -{{ "I like Twig.\nYou will like it too.\n\nEverybody like it!"|nl2br }} -{{ text|nl2br }} ---DATA-- -return array('text' => "If you have some HTML\nit will be escaped.") ---EXPECT-- -I like Twig.
    -You will like it too.
    -
    -Everybody like it! -If you have some <strong>HTML</strong>
    -it will be escaped. ---TEST-- -"number_format" filter with defaults. ---TEMPLATE-- -{{ 20|number_format }} -{{ 20.25|number_format }} -{{ 20.25|number_format(1) }} -{{ 20.25|number_format(2, ',') }} -{{ 1020.25|number_format }} -{{ 1020.25|number_format(2, ',') }} -{{ 1020.25|number_format(2, ',', '.') }} ---DATA-- -$twig->getExtension('core')->setNumberFormat(2, '!', '='); -return array(); ---EXPECT-- -20!00 -20!25 -20!3 -20,25 -1=020!25 -1=020,25 -1.020,25 ---TEST-- -"number_format" filter ---TEMPLATE-- -{{ 20|number_format }} -{{ 20.25|number_format }} -{{ 20.25|number_format(2) }} -{{ 20.25|number_format(2, ',') }} -{{ 1020.25|number_format(2, ',') }} -{{ 1020.25|number_format(2, ',', '.') }} ---DATA-- -return array(); ---EXPECT-- -20 -20 -20.25 -20,25 -1,020,25 -1.020,25 ---TEST-- -"replace" filter ---TEMPLATE-- -{{ "I like %this% and %that%."|replace({'%this%': "foo", '%that%': "bar"}) }} ---DATA-- -return array() ---EXPECT-- -I like foo and bar. ---TEST-- -"reverse" filter ---TEMPLATE-- -{{ [1, 2, 3, 4]|reverse|join('') }} -{{ '1234évènement'|reverse }} -{{ arr|reverse|join('') }} -{{ {'a': 'c', 'b': 'a'}|reverse()|join(',') }} -{{ {'a': 'c', 'b': 'a'}|reverse(preserveKeys=true)|join(glue=',') }} -{{ {'a': 'c', 'b': 'a'}|reverse(preserve_keys=true)|join(glue=',') }} ---DATA-- -return array('arr' => new ArrayObject(array(1, 2, 3, 4))) ---EXPECT-- -4321 -tnemenèvé4321 -4321 -a,c -a,c -a,c ---TEST-- -"round" filter ---TEMPLATE-- -{{ 2.7|round }} -{{ 2.1|round }} -{{ 2.1234|round(3, 'floor') }} -{{ 2.1|round(0, 'ceil') }} - -{{ 21.3|round(-1)}} -{{ 21.3|round(-1, 'ceil')}} -{{ 21.3|round(-1, 'floor')}} ---DATA-- -return array() ---EXPECT-- -3 -2 -2.123 -3 - -20 -30 -20 ---TEST-- -"slice" filter ---TEMPLATE-- -{{ [1, 2, 3, 4][1:2]|join('') }} -{{ {a: 1, b: 2, c: 3, d: 4}[1:2]|join('') }} -{{ [1, 2, 3, 4][start:length]|join('') }} -{{ [1, 2, 3, 4]|slice(1, 2)|join('') }} -{{ [1, 2, 3, 4]|slice(1, 2)|keys|join('') }} -{{ [1, 2, 3, 4]|slice(1, 2, true)|keys|join('') }} -{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|join('') }} -{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|keys|join('') }} -{{ '1234'|slice(1, 2) }} -{{ '1234'[1:2] }} -{{ arr|slice(1, 2)|join('') }} -{{ arr[1:2]|join('') }} - -{{ [1, 2, 3, 4]|slice(1)|join('') }} -{{ [1, 2, 3, 4][1:]|join('') }} -{{ '1234'|slice(1) }} -{{ '1234'[1:] }} -{{ '1234'[:1] }} ---DATA-- -return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3, 4))) ---EXPECT-- -23 -23 -23 -23 -01 -12 -23 -bc -23 -23 -23 -23 - -234 -234 -234 -234 -1 ---TEST-- -"sort" filter ---TEMPLATE-- -{{ array1|sort|join }} -{{ array2|sort|join }} ---DATA-- -return array('array1' => array(4, 1), 'array2' => array('foo', 'bar')) ---EXPECT-- -14 -barfoo ---TEST-- -"split" filter ---TEMPLATE-- -{{ "one,two,three,four,five"|split(',')|join('-') }} -{{ foo|split(',')|join('-') }} -{{ foo|split(',', 3)|join('-') }} -{{ baz|split('')|join('-') }} -{{ baz|split('', 2)|join('-') }} -{{ foo|split(',', -2)|join('-') }} ---DATA-- -return array('foo' => "one,two,three,four,five", 'baz' => '12345',) ---EXPECT-- -one-two-three-four-five -one-two-three-four-five -one-two-three,four,five -1-2-3-4-5 -12-34-5 -one-two-three--TEST-- -"trim" filter ---TEMPLATE-- -{{ " I like Twig. "|trim }} -{{ text|trim }} -{{ " foo/"|trim("/") }} ---DATA-- -return array('text' => " If you have some HTML it will be escaped. ") ---EXPECT-- -I like Twig. -If you have some <strong>HTML</strong> it will be escaped. - foo ---TEST-- -"url_encode" filter for PHP < 5.4 and HHVM ---CONDITION-- -defined('PHP_QUERY_RFC3986') ---TEMPLATE-- -{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode }} -{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode|raw }} -{{ {}|url_encode|default("default") }} -{{ 'spéßi%le%c0d@dspa ce'|url_encode }} ---DATA-- -return array() ---EXPECT-- -foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= -foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= -default -sp%C3%A9%C3%9Fi%25le%25c0d%40dspa%20ce ---TEST-- -"url_encode" filter ---CONDITION-- -defined('PHP_QUERY_RFC3986') ---TEMPLATE-- -{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode }} -{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode|raw }} -{{ {}|url_encode|default("default") }} -{{ 'spéßi%le%c0d@dspa ce'|url_encode }} ---DATA-- -return array() ---EXPECT-- -foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= -foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= -default -sp%C3%A9%C3%9Fi%25le%25c0d%40dspa%20ce ---TEST-- -"attribute" function ---TEMPLATE-- -{{ attribute(obj, method) }} -{{ attribute(array, item) }} -{{ attribute(obj, "bar", ["a", "b"]) }} -{{ attribute(obj, "bar", arguments) }} -{{ attribute(obj, method) is defined ? 'ok' : 'ko' }} -{{ attribute(obj, nonmethod) is defined ? 'ok' : 'ko' }} ---DATA-- -return array('obj' => new TwigTestFoo(), 'method' => 'foo', 'array' => array('foo' => 'bar'), 'item' => 'foo', 'nonmethod' => 'xxx', 'arguments' => array('a', 'b')) ---EXPECT-- -foo -bar -bar_a-b -bar_a-b -ok -ko ---TEST-- -"block" function ---TEMPLATE-- -{% extends 'base.twig' %} -{% block bar %}BAR{% endblock %} ---TEMPLATE(base.twig)-- -{% block foo %}{{ block('bar') }}{% endblock %} -{% block bar %}BAR_BASE{% endblock %} ---DATA-- -return array() ---EXPECT-- -BARBAR ---TEST-- -"constant" function ---TEMPLATE-- -{{ constant('DATE_W3C') == expect ? 'true' : 'false' }} -{{ constant('ARRAY_AS_PROPS', object) }} ---DATA-- -return array('expect' => DATE_W3C, 'object' => new ArrayObject(array('hi'))); ---EXPECT-- -true -2 ---TEST-- -"cycle" function ---TEMPLATE-- -{% for i in 0..6 %} -{{ cycle(array1, i) }}-{{ cycle(array2, i) }} -{% endfor %} ---DATA-- -return array('array1' => array('odd', 'even'), 'array2' => array('apple', 'orange', 'citrus')) ---EXPECT-- -odd-apple -even-orange -odd-citrus -even-apple -odd-orange -even-citrus -odd-apple ---TEST-- -"date" function ---TEMPLATE-- -{{ date(date, "America/New_York")|date('d/m/Y H:i:s P', false) }} -{{ date(timezone="America/New_York", date=date)|date('d/m/Y H:i:s P', false) }} ---DATA-- -date_default_timezone_set('UTC'); -return array('date' => mktime(13, 45, 0, 10, 4, 2010)) ---EXPECT-- -04/10/2010 09:45:00 -04:00 -04/10/2010 09:45:00 -04:00 ---TEST-- -"date" function ---TEMPLATE-- -{{ date() == date('now') ? 'OK' : 'KO' }} -{{ date(date1) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} -{{ date(date2) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} -{{ date(date3) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} -{{ date(date4) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} -{{ date(date5) == date('1964-01-02 03:04') ? 'OK' : 'KO' }} ---DATA-- -date_default_timezone_set('UTC'); -return array( - 'date1' => mktime(13, 45, 0, 10, 4, 2010), - 'date2' => new DateTime('2010-10-04 13:45'), - 'date3' => '2010-10-04 13:45', - 'date4' => 1286199900, // DateTime::createFromFormat('Y-m-d H:i', '2010-10-04 13:45', new DateTimeZone('UTC'))->getTimestamp() -- A unixtimestamp is always GMT - 'date5' => -189291360, // DateTime::createFromFormat('Y-m-d H:i', '1964-01-02 03:04', new DateTimeZone('UTC'))->getTimestamp(), -) ---EXPECT-- -OK -OK -OK -OK -OK -OK ---TEST-- -"dump" function, xdebug is not loaded or xdebug <2.2-dev is loaded ---CONDITION-- -!extension_loaded('xdebug') || (($r = new ReflectionExtension('xdebug')) && version_compare($r->getVersion(), '2.2-dev', '<')) ---TEMPLATE-- -{{ dump() }} ---DATA-- -return array('foo' => 'foo', 'bar' => 'bar') ---CONFIG-- -return array('debug' => true, 'autoescape' => false); ---TEST-- -"dump" function ---CONDITION-- -!extension_loaded('xdebug') ---TEMPLATE-- -{{ dump('foo') }} -{{ dump('foo', 'bar') }} ---DATA-- -return array('foo' => 'foo', 'bar' => 'bar') ---CONFIG-- -return array('debug' => true, 'autoescape' => false); ---EXPECT-- -string(3) "foo" - -string(3) "foo" -string(3) "bar" ---TEST-- -dynamic function ---TEMPLATE-- -{{ foo_path('bar') }} -{{ a_foo_b_bar('bar') }} ---DATA-- -return array() ---EXPECT-- -foo/bar -a/b/bar ---TEST-- -"include" function ---TEMPLATE-- -{% set tmp = include("foo.twig") %} - -FOO{{ tmp }}BAR ---TEMPLATE(foo.twig)-- -FOOBAR ---DATA-- -return array() ---EXPECT-- -FOO -FOOBARBAR ---TEST-- -"include" function is safe for auto-escaping ---TEMPLATE-- -{{ include("foo.twig") }} ---TEMPLATE(foo.twig)-- -

    Test

    ---DATA-- -return array() ---EXPECT-- -

    Test

    ---TEST-- -"include" function ---TEMPLATE-- -FOO -{{ include("foo.twig") }} - -BAR ---TEMPLATE(foo.twig)-- -FOOBAR ---DATA-- -return array() ---EXPECT-- -FOO - -FOOBAR - -BAR ---TEST-- -"include" function allows expressions for the template to include ---TEMPLATE-- -FOO -{{ include(foo) }} - -BAR ---TEMPLATE(foo.twig)-- -FOOBAR ---DATA-- -return array('foo' => 'foo.twig') ---EXPECT-- -FOO - -FOOBAR - -BAR ---TEST-- -"include" function ---TEMPLATE-- -{{ include(["foo.twig", "bar.twig"], ignore_missing = true) }} -{{ include("foo.twig", ignore_missing = true) }} -{{ include("foo.twig", ignore_missing = true, variables = {}) }} -{{ include("foo.twig", ignore_missing = true, variables = {}, with_context = true) }} ---DATA-- -return array() ---EXPECT-- ---TEST-- -"include" function ---TEMPLATE-- -{% extends "base.twig" %} - -{% block content %} - {{ parent() }} -{% endblock %} ---TEMPLATE(base.twig)-- -{% block content %} - {{ include("foo.twig") }} -{% endblock %} ---DATA-- -return array(); ---EXCEPTION-- -Twig_Error_Loader: Template "foo.twig" is not defined in "base.twig" at line 3. ---TEST-- -"include" function ---TEMPLATE-- -{{ include("foo.twig") }} ---DATA-- -return array(); ---EXCEPTION-- -Twig_Error_Loader: Template "foo.twig" is not defined in "index.twig" at line 2. ---TEST-- -"include" tag sandboxed ---TEMPLATE-- -{{ include("foo.twig", sandboxed = true) }} ---TEMPLATE(foo.twig)-- -{{ foo|e }} ---DATA-- -return array() ---EXCEPTION-- -Twig_Sandbox_SecurityError: Filter "e" is not allowed in "index.twig" at line 2. ---TEST-- -"include" function accepts Twig_Template instance ---TEMPLATE-- -{{ include(foo) }} FOO ---TEMPLATE(foo.twig)-- -BAR ---DATA-- -return array('foo' => $twig->loadTemplate('foo.twig')) ---EXPECT-- -BAR FOO ---TEST-- -"include" function ---TEMPLATE-- -{{ include(["foo.twig", "bar.twig"]) }} -{{- include(["bar.twig", "foo.twig"]) }} ---TEMPLATE(foo.twig)-- -foo ---DATA-- -return array() ---EXPECT-- -foo -foo ---TEST-- -"include" function accept variables and with_context ---TEMPLATE-- -{{ include("foo.twig") }} -{{- include("foo.twig", with_context = false) }} -{{- include("foo.twig", {'foo1': 'bar'}) }} -{{- include("foo.twig", {'foo1': 'bar'}, with_context = false) }} ---TEMPLATE(foo.twig)-- -{% for k, v in _context %}{{ k }},{% endfor %} ---DATA-- -return array('foo' => 'bar') ---EXPECT-- -foo,global,_parent, -global,_parent, -foo,global,foo1,_parent, -foo1,global,_parent, ---TEST-- -"include" function accept variables ---TEMPLATE-- -{{ include("foo.twig", {'foo': 'bar'}) }} -{{- include("foo.twig", vars) }} ---TEMPLATE(foo.twig)-- -{{ foo }} ---DATA-- -return array('vars' => array('foo' => 'bar')) ---EXPECT-- -bar -bar ---TEST-- -"max" function ---TEMPLATE-- -{{ max([2, 1, 3, 5, 4]) }} -{{ max(2, 1, 3, 5, 4) }} -{{ max({2:"two", 1:"one", 3:"three", 5:"five", 4:"for"}) }} ---DATA-- -return array() ---EXPECT-- -5 -5 -two ---TEST-- -"min" function ---TEMPLATE-- -{{ min(2, 1, 3, 5, 4) }} -{{ min([2, 1, 3, 5, 4]) }} -{{ min({2:"two", 1:"one", 3:"three", 5:"five", 4:"for"}) }} ---DATA-- -return array() ---EXPECT-- -1 -1 -five ---TEST-- -"range" function ---TEMPLATE-- -{{ range(low=0+1, high=10+0, step=2)|join(',') }} ---DATA-- -return array() ---EXPECT-- -1,3,5,7,9 ---TEST-- -"block" function recursively called in a parent template ---TEMPLATE-- -{% extends "ordered_menu.twig" %} -{% block label %}"{{ parent() }}"{% endblock %} -{% block list %}{% set class = 'b' %}{{ parent() }}{% endblock %} ---TEMPLATE(ordered_menu.twig)-- -{% extends "menu.twig" %} -{% block list %}{% set class = class|default('a') %}
      {{ block('children') }}
    {% endblock %} ---TEMPLATE(menu.twig)-- -{% extends "base.twig" %} -{% block list %}
      {{ block('children') }}
    {% endblock %} -{% block children %}{% set currentItem = item %}{% for item in currentItem %}{{ block('item') }}{% endfor %}{% set item = currentItem %}{% endblock %} -{% block item %}
  • {% if item is not iterable %}{{ block('label') }}{% else %}{{ block('list') }}{% endif %}
  • {% endblock %} -{% block label %}{{ item }}{{ block('unknown') }}{% endblock %} ---TEMPLATE(base.twig)-- -{{ block('list') }} ---DATA-- -return array('item' => array('1', '2', array('3.1', array('3.2.1', '3.2.2'), '3.4'))) ---EXPECT-- -
    1. "1"
    2. "2"
      1. "3.1"
        1. "3.2.1"
        2. "3.2.2"
      2. "3.4"
    ---TEST-- -"source" function ---TEMPLATE-- -FOO -{{ source("foo.twig") }} - -BAR ---TEMPLATE(foo.twig)-- -{{ foo }}
    ---DATA-- -return array() ---EXPECT-- -FOO - -{{ foo }}
    - -BAR ---TEST-- -"template_from_string" function ---TEMPLATE-- -{% include template_from_string(template) %} - -{% include template_from_string("Hello {{ name }}") %} -{% include template_from_string('{% extends "parent.twig" %}{% block content %}Hello {{ name }}{% endblock %}') %} ---TEMPLATE(parent.twig)-- -{% block content %}{% endblock %} ---DATA-- -return array('name' => 'Fabien', 'template' => "Hello {{ name }}") ---EXPECT-- -Hello Fabien -Hello Fabien -Hello Fabien ---TEST-- -macro ---TEMPLATE-- -{% from _self import test %} - -{% macro test(a, b = 'bar') -%} -{{ a }}{{ b }} -{%- endmacro %} - -{{ test('foo') }} -{{ test('bar', 'foo') }} ---DATA-- -return array(); ---EXPECT-- -foobar -barfoo ---TEST-- -macro ---TEMPLATE-- -{% import _self as macros %} - -{% macro foo(data) %} - {{ data }} -{% endmacro %} - -{% macro bar() %} -
    -{% endmacro %} - -{{ macros.foo(macros.bar()) }} ---DATA-- -return array(); ---EXPECT-- -
    ---TEST-- -macro ---TEMPLATE-- -{% from _self import test %} - -{% macro test(this) -%} - {{ this }} -{%- endmacro %} - -{{ test(this) }} ---DATA-- -return array('this' => 'foo'); ---EXPECT-- -foo ---TEST-- -macro ---TEMPLATE-- -{% import _self as test %} -{% from _self import test %} - -{% macro test(a, b) -%} - {{ a|default('a') }}
    - {{- b|default('b') }}
    -{%- endmacro %} - -{{ test.test() }} -{{ test() }} -{{ test.test(1, "c") }} -{{ test(1, "c") }} ---DATA-- -return array(); ---EXPECT-- -a
    b
    -a
    b
    -1
    c
    -1
    c
    ---TEST-- -macro with a filter ---TEMPLATE-- -{% import _self as test %} - -{% macro test() %} - {% filter escape %}foo
    {% endfilter %} -{% endmacro %} - -{{ test.test() }} ---DATA-- -return array(); ---EXPECT-- -foo<br /> ---TEST-- -Twig outputs 0 nodes correctly ---TEMPLATE-- -{{ foo }}0{{ foo }} ---DATA-- -return array('foo' => 'foo') ---EXPECT-- -foo0foo ---TEST-- -error in twig extension ---TEMPLATE-- -{{ object.region is not null ? object.regionChoices[object.region] }} ---EXPECT-- -house.region.s ---TEST-- -Twig is able to deal with SimpleXMLElement instances as variables ---CONDITION-- -version_compare(phpversion(), '5.3.0', '>=') ---TEMPLATE-- -Hello '{{ images.image.0.group }}'! -{{ images.image.0.group.attributes.myattr }} -{{ images.children().image.count() }} -{% for image in images %} - - {{ image.group }} -{% endfor %} ---DATA-- -return array('images' => new SimpleXMLElement('foobar')) ---EXPECT-- -Hello 'foo'! -example -2 - - foo - - bar ---TEST-- -Twig does not confuse strings with integers in getAttribute() ---TEMPLATE-- -{{ hash['2e2'] }} ---DATA-- -return array('hash' => array('2e2' => 'works')) ---EXPECT-- -works ---TEST-- -"autoescape" tag applies escaping on its children ---TEMPLATE-- -{% autoescape %} -{{ var }}
    -{% endautoescape %} -{% autoescape 'html' %} -{{ var }}
    -{% endautoescape %} -{% autoescape false %} -{{ var }}
    -{% endautoescape %} -{% autoescape true %} -{{ var }}
    -{% endautoescape %} -{% autoescape false %} -{{ var }}
    -{% endautoescape %} ---DATA-- -return array('var' => '
    ') ---EXPECT-- -<br />
    -<br />
    -

    -<br />
    -

    ---TEST-- -"autoescape" tag applies escaping on embedded blocks ---TEMPLATE-- -{% autoescape 'html' %} - {% block foo %} - {{ var }} - {% endblock %} -{% endautoescape %} ---DATA-- -return array('var' => '
    ') ---EXPECT-- -<br /> ---TEST-- -"autoescape" tag does not double-escape ---TEMPLATE-- -{% autoescape 'html' %} -{{ var|escape }} -{% endautoescape %} ---DATA-- -return array('var' => '
    ') ---EXPECT-- -<br /> ---TEST-- -"autoescape" tag applies escaping after calling functions ---TEMPLATE-- - -autoescape false -{% autoescape false %} - -safe_br -{{ safe_br() }} - -unsafe_br -{{ unsafe_br() }} - -{% endautoescape %} - -autoescape 'html' -{% autoescape 'html' %} - -safe_br -{{ safe_br() }} - -unsafe_br -{{ unsafe_br() }} - -unsafe_br()|raw -{{ (unsafe_br())|raw }} - -safe_br()|escape -{{ (safe_br())|escape }} - -safe_br()|raw -{{ (safe_br())|raw }} - -unsafe_br()|escape -{{ (unsafe_br())|escape }} - -{% endautoescape %} - -autoescape js -{% autoescape 'js' %} - -safe_br -{{ safe_br() }} - -{% endautoescape %} ---DATA-- -return array() ---EXPECT-- - -autoescape false - -safe_br -
    - -unsafe_br -
    - - -autoescape 'html' - -safe_br -
    - -unsafe_br -<br /> - -unsafe_br()|raw -
    - -safe_br()|escape -<br /> - -safe_br()|raw -
    - -unsafe_br()|escape -<br /> - - -autoescape js - -safe_br -\x3Cbr\x20\x2F\x3E ---TEST-- -"autoescape" tag does not apply escaping on literals ---TEMPLATE-- -{% autoescape 'html' %} - -1. Simple literal -{{ "
    " }} - -2. Conditional expression with only literals -{{ true ? "
    " : "
    " }} - -3. Conditional expression with a variable -{{ true ? "
    " : someVar }} - -4. Nested conditionals with only literals -{{ true ? (true ? "
    " : "
    ") : "\n" }} - -5. Nested conditionals with a variable -{{ true ? (true ? "
    " : someVar) : "\n" }} - -6. Nested conditionals with a variable marked safe -{{ true ? (true ? "
    " : someVar|raw) : "\n" }} - -{% endautoescape %} ---DATA-- -return array() ---EXPECT-- - -1. Simple literal -
    - -2. Conditional expression with only literals -
    - -3. Conditional expression with a variable -<br /> - -4. Nested conditionals with only literals -
    - -5. Nested conditionals with a variable -<br /> - -6. Nested conditionals with a variable marked safe -
    ---TEST-- -"autoescape" tags can be nested at will ---TEMPLATE-- -{{ var }} -{% autoescape 'html' %} - {{ var }} - {% autoescape false %} - {{ var }} - {% autoescape 'html' %} - {{ var }} - {% endautoescape %} - {{ var }} - {% endautoescape %} - {{ var }} -{% endautoescape %} -{{ var }} ---DATA-- -return array('var' => '
    ') ---EXPECT-- -<br /> - <br /> -
    - <br /> -
    - <br /> -<br /> ---TEST-- -"autoescape" tag applies escaping to object method calls ---TEMPLATE-- -{% autoescape 'html' %} -{{ user.name }} -{{ user.name|lower }} -{{ user }} -{% endautoescape %} ---EXPECT-- -Fabien<br /> -fabien<br /> -Fabien<br /> ---TEST-- -"autoescape" tag does not escape when raw is used as a filter ---TEMPLATE-- -{% autoescape 'html' %} -{{ var|raw }} -{% endautoescape %} ---DATA-- -return array('var' => '
    ') ---EXPECT-- -
    ---TEST-- -"autoescape" tag accepts an escaping strategy ---TEMPLATE-- -{% autoescape true js %}{{ var }}{% endautoescape %} - -{% autoescape true html %}{{ var }}{% endautoescape %} - -{% autoescape 'js' %}{{ var }}{% endautoescape %} - -{% autoescape 'html' %}{{ var }}{% endautoescape %} ---DATA-- -return array('var' => '
    "') ---EXPECT-- -\x3Cbr\x20\x2F\x3E\x22 -<br />" -\x3Cbr\x20\x2F\x3E\x22 -<br />" ---TEST-- -escape types ---TEMPLATE-- - -1. autoescape 'html' |escape('js') - -{% autoescape 'html' %} - -{% endautoescape %} - -2. autoescape 'html' |escape('js') - -{% autoescape 'html' %} - -{% endautoescape %} - -3. autoescape 'js' |escape('js') - -{% autoescape 'js' %} - -{% endautoescape %} - -4. no escape - -{% autoescape false %} - -{% endautoescape %} - -5. |escape('js')|escape('html') - -{% autoescape false %} - -{% endautoescape %} - -6. autoescape 'html' |escape('js')|escape('html') - -{% autoescape 'html' %} - -{% endautoescape %} - ---DATA-- -return array('msg' => "<>\n'\"") ---EXPECT-- - -1. autoescape 'html' |escape('js') - - - -2. autoescape 'html' |escape('js') - - - -3. autoescape 'js' |escape('js') - - - -4. no escape - - - -5. |escape('js')|escape('html') - - - -6. autoescape 'html' |escape('js')|escape('html') - - - ---TEST-- -"autoescape" tag do not applies escaping on filter arguments ---TEMPLATE-- -{% autoescape 'html' %} -{{ var|nl2br("
    ") }} -{{ var|nl2br("
    "|escape) }} -{{ var|nl2br(sep) }} -{{ var|nl2br(sep|raw) }} -{{ var|nl2br(sep|escape) }} -{% endautoescape %} ---DATA-- -return array('var' => "\nTwig", 'sep' => '
    ') ---EXPECT-- -<Fabien>
    -Twig -<Fabien><br /> -Twig -<Fabien>
    -Twig -<Fabien>
    -Twig -<Fabien><br /> -Twig ---TEST-- -"autoescape" tag applies escaping after calling filters ---TEMPLATE-- -{% autoescape 'html' %} - -(escape_and_nl2br is an escaper filter) - -1. Don't escape escaper filter output -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is not escaped ) -{{ var|escape_and_nl2br }} - -2. Don't escape escaper filter output -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is not escaped, |raw is redundant ) -{{ var|escape_and_nl2br|raw }} - -3. Explicit escape -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is explicitly escaped by |escape ) -{{ var|escape_and_nl2br|escape }} - -4. Escape non-escaper filter output -( var is upper-cased by |upper, - the output is auto-escaped ) -{{ var|upper }} - -5. Escape if last filter is not an escaper -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is upper-cased by |upper, - the output is auto-escaped as |upper is not an escaper ) -{{ var|escape_and_nl2br|upper }} - -6. Don't escape escaper filter output -( var is upper cased by upper, - the output is escaped by |escape_and_nl2br, line-breaks are added, - the output is not escaped as |escape_and_nl2br is an escaper ) -{{ var|upper|escape_and_nl2br }} - -7. Escape if last filter is not an escaper -( the output of |format is "" ~ var ~ "", - the output is auto-escaped ) -{{ "%s"|format(var) }} - -8. Escape if last filter is not an escaper -( the output of |format is "" ~ var ~ "", - |raw is redundant, - the output is auto-escaped ) -{{ "%s"|raw|format(var) }} - -9. Don't escape escaper filter output -( the output of |format is "" ~ var ~ "", - the output is not escaped due to |raw filter at the end ) -{{ "%s"|format(var)|raw }} - -10. Don't escape escaper filter output -( the output of |format is "" ~ var ~ "", - the output is not escaped due to |raw filter at the end, - the |raw filter on var is redundant ) -{{ "%s"|format(var|raw)|raw }} - -{% endautoescape %} ---DATA-- -return array('var' => "\nTwig") ---EXPECT-- - -(escape_and_nl2br is an escaper filter) - -1. Don't escape escaper filter output -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is not escaped ) -<Fabien>
    -Twig - -2. Don't escape escaper filter output -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is not escaped, |raw is redundant ) -<Fabien>
    -Twig - -3. Explicit escape -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is explicitly escaped by |escape ) -&lt;Fabien&gt;<br /> -Twig - -4. Escape non-escaper filter output -( var is upper-cased by |upper, - the output is auto-escaped ) -<FABIEN> -TWIG - -5. Escape if last filter is not an escaper -( var is escaped by |escape_and_nl2br, line-breaks are added, - the output is upper-cased by |upper, - the output is auto-escaped as |upper is not an escaper ) -&LT;FABIEN&GT;<BR /> -TWIG - -6. Don't escape escaper filter output -( var is upper cased by upper, - the output is escaped by |escape_and_nl2br, line-breaks are added, - the output is not escaped as |escape_and_nl2br is an escaper ) -<FABIEN>
    -TWIG - -7. Escape if last filter is not an escaper -( the output of |format is "" ~ var ~ "", - the output is auto-escaped ) -<b><Fabien> -Twig</b> - -8. Escape if last filter is not an escaper -( the output of |format is "" ~ var ~ "", - |raw is redundant, - the output is auto-escaped ) -<b><Fabien> -Twig</b> - -9. Don't escape escaper filter output -( the output of |format is "" ~ var ~ "", - the output is not escaped due to |raw filter at the end ) - -Twig - -10. Don't escape escaper filter output -( the output of |format is "" ~ var ~ "", - the output is not escaped due to |raw filter at the end, - the |raw filter on var is redundant ) - -Twig ---TEST-- -"autoescape" tag applies escaping after calling filters, and before calling pre_escape filters ---TEMPLATE-- -{% autoescape 'html' %} - -(nl2br is pre_escaped for "html" and declared safe for "html") - -1. Pre-escape and don't post-escape -( var|escape|nl2br ) -{{ var|nl2br }} - -2. Don't double-pre-escape -( var|escape|nl2br ) -{{ var|escape|nl2br }} - -3. Don't escape safe values -( var|raw|nl2br ) -{{ var|raw|nl2br }} - -4. Don't escape safe values -( var|escape|nl2br|nl2br ) -{{ var|nl2br|nl2br }} - -5. Re-escape values that are escaped for an other contexts -( var|escape_something|escape|nl2br ) -{{ var|escape_something|nl2br }} - -6. Still escape when using filters not declared safe -( var|escape|nl2br|upper|escape ) -{{ var|nl2br|upper }} - -{% endautoescape %} ---DATA-- -return array('var' => "\nTwig") ---EXPECT-- - -(nl2br is pre_escaped for "html" and declared safe for "html") - -1. Pre-escape and don't post-escape -( var|escape|nl2br ) -<Fabien>
    -Twig - -2. Don't double-pre-escape -( var|escape|nl2br ) -<Fabien>
    -Twig - -3. Don't escape safe values -( var|raw|nl2br ) -
    -Twig - -4. Don't escape safe values -( var|escape|nl2br|nl2br ) -<Fabien>

    -Twig - -5. Re-escape values that are escaped for an other contexts -( var|escape_something|escape|nl2br ) -<FABIEN>
    -TWIG - -6. Still escape when using filters not declared safe -( var|escape|nl2br|upper|escape ) -&LT;FABIEN&GT;<BR /> -TWIG - ---TEST-- -"autoescape" tag handles filters preserving the safety ---TEMPLATE-- -{% autoescape 'html' %} - -(preserves_safety is preserving safety for "html") - -1. Unsafe values are still unsafe -( var|preserves_safety|escape ) -{{ var|preserves_safety }} - -2. Safe values are still safe -( var|escape|preserves_safety ) -{{ var|escape|preserves_safety }} - -3. Re-escape values that are escaped for an other contexts -( var|escape_something|preserves_safety|escape ) -{{ var|escape_something|preserves_safety }} - -4. Still escape when using filters not declared safe -( var|escape|preserves_safety|replace({'FABIEN': 'FABPOT'})|escape ) -{{ var|escape|preserves_safety|replace({'FABIEN': 'FABPOT'}) }} - -{% endautoescape %} ---DATA-- -return array('var' => "\nTwig") ---EXPECT-- - -(preserves_safety is preserving safety for "html") - -1. Unsafe values are still unsafe -( var|preserves_safety|escape ) -<FABIEN> -TWIG - -2. Safe values are still safe -( var|escape|preserves_safety ) -<FABIEN> -TWIG - -3. Re-escape values that are escaped for an other contexts -( var|escape_something|preserves_safety|escape ) -<FABIEN> -TWIG - -4. Still escape when using filters not declared safe -( var|escape|preserves_safety|replace({'FABIEN': 'FABPOT'})|escape ) -&LT;FABPOT&GT; -TWIG - ---TEST-- -"block" tag ---TEMPLATE-- -{% block title1 %}FOO{% endblock %} -{% block title2 foo|lower %} ---TEMPLATE(foo.twig)-- -{% block content %}{% endblock %} ---DATA-- -return array('foo' => 'bar') ---EXPECT-- -FOObar ---TEST-- -"block" tag ---TEMPLATE-- -{% block content %} - {% block content %} - {% endblock %} -{% endblock %} ---DATA-- -return array() ---EXCEPTION-- -Twig_Error_Syntax: The block 'content' has already been defined line 2 in "index.twig" at line 3 ---TEST-- -"§" special chars in a block name ---TEMPLATE-- -{% block § %} -§ -{% endblock § %} ---DATA-- -return array() ---EXPECT-- -§ ---TEST-- -"embed" tag ---TEMPLATE-- -FOO -{% embed "foo.twig" %} - {% block c1 %} - {{ parent() }} - block1extended - {% endblock %} -{% endembed %} - -BAR ---TEMPLATE(foo.twig)-- -A -{% block c1 %} - block1 -{% endblock %} -B -{% block c2 %} - block2 -{% endblock %} -C ---DATA-- -return array() ---EXPECT-- -FOO - -A - block1 - - block1extended - B - block2 -C -BAR ---TEST-- -"embed" tag ---TEMPLATE(index.twig)-- -FOO -{% embed "foo.twig" %} - {% block c1 %} - {{ nothing }} - {% endblock %} -{% endembed %} -BAR ---TEMPLATE(foo.twig)-- -{% block c1 %}{% endblock %} ---DATA-- -return array() ---EXCEPTION-- -Twig_Error_Runtime: Variable "nothing" does not exist in "index.twig" at line 5 ---TEST-- -"embed" tag ---TEMPLATE-- -FOO -{% embed "foo.twig" %} - {% block c1 %} - {{ parent() }} - block1extended - {% endblock %} -{% endembed %} - -{% embed "foo.twig" %} - {% block c1 %} - {{ parent() }} - block1extended - {% endblock %} -{% endembed %} - -BAR ---TEMPLATE(foo.twig)-- -A -{% block c1 %} - block1 -{% endblock %} -B -{% block c2 %} - block2 -{% endblock %} -C ---DATA-- -return array() ---EXPECT-- -FOO - -A - block1 - - block1extended - B - block2 -C - -A - block1 - - block1extended - B - block2 -C -BAR ---TEST-- -"embed" tag ---TEMPLATE-- -{% embed "foo.twig" %} - {% block c1 %} - {{ parent() }} - {% embed "foo.twig" %} - {% block c1 %} - {{ parent() }} - block1extended - {% endblock %} - {% endembed %} - - {% endblock %} -{% endembed %} ---TEMPLATE(foo.twig)-- -A -{% block c1 %} - block1 -{% endblock %} -B -{% block c2 %} - block2 -{% endblock %} -C ---DATA-- -return array() ---EXPECT-- -A - block1 - - -A - block1 - - block1extended - B - block2 -C - B - block2 -C ---TEST-- -"embed" tag ---TEMPLATE-- -{% extends "base.twig" %} - -{% block c1 %} - {{ parent() }} - blockc1baseextended -{% endblock %} - -{% block c2 %} - {{ parent() }} - - {% embed "foo.twig" %} - {% block c1 %} - {{ parent() }} - block1extended - {% endblock %} - {% endembed %} -{% endblock %} ---TEMPLATE(base.twig)-- -A -{% block c1 %} - blockc1base -{% endblock %} -{% block c2 %} - blockc2base -{% endblock %} -B ---TEMPLATE(foo.twig)-- -A -{% block c1 %} - block1 -{% endblock %} -B -{% block c2 %} - block2 -{% endblock %} -C ---DATA-- -return array() ---EXPECT-- -A - blockc1base - - blockc1baseextended - blockc2base - - - -A - block1 - - block1extended - B - block2 -CB--TEST-- -"filter" tag applies a filter on its children ---TEMPLATE-- -{% filter upper %} -Some text with a {{ var }} -{% endfilter %} ---DATA-- -return array('var' => 'var') ---EXPECT-- -SOME TEXT WITH A VAR ---TEST-- -"filter" tag applies a filter on its children ---TEMPLATE-- -{% filter json_encode|raw %}test{% endfilter %} ---DATA-- -return array() ---EXPECT-- -"test" ---TEST-- -"filter" tags accept multiple chained filters ---TEMPLATE-- -{% filter lower|title %} - {{ var }} -{% endfilter %} ---DATA-- -return array('var' => 'VAR') ---EXPECT-- - Var ---TEST-- -"filter" tags can be nested at will ---TEMPLATE-- -{% filter lower|title %} - {{ var }} - {% filter upper %} - {{ var }} - {% endfilter %} - {{ var }} -{% endfilter %} ---DATA-- -return array('var' => 'var') ---EXPECT-- - Var - Var - Var ---TEST-- -"filter" tag applies the filter on "for" tags ---TEMPLATE-- -{% filter upper %} -{% for item in items %} -{{ item }} -{% endfor %} -{% endfilter %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- -A -B ---TEST-- -"filter" tag applies the filter on "if" tags ---TEMPLATE-- -{% filter upper %} -{% if items %} -{{ items|join(', ') }} -{% endif %} - -{% if items.3 is defined %} -FOO -{% else %} -{{ items.1 }} -{% endif %} - -{% if items.3 is defined %} -FOO -{% elseif items.1 %} -{{ items.0 }} -{% endif %} - -{% endfilter %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- -A, B - -B - -A ---TEST-- -"for" tag takes a condition ---TEMPLATE-- -{% for i in 1..5 if i is odd -%} - {{ loop.index }}.{{ i }}{{ foo.bar }} -{% endfor %} ---DATA-- -return array('foo' => array('bar' => 'X')) ---CONFIG-- -return array('strict_variables' => false) ---EXPECT-- -1.1X -2.3X -3.5X ---TEST-- -"for" tag keeps the context safe ---TEMPLATE-- -{% for item in items %} - {% for item in items %} - * {{ item }} - {% endfor %} - * {{ item }} -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- - * a - * b - * a - * a - * b - * b ---TEST-- -"for" tag can use an "else" clause ---TEMPLATE-- -{% for item in items %} - * {{ item }} -{% else %} - no item -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- - * a - * b ---DATA-- -return array('items' => array()) ---EXPECT-- - no item ---DATA-- -return array() ---CONFIG-- -return array('strict_variables' => false) ---EXPECT-- - no item ---TEST-- -"for" tag does not reset inner variables ---TEMPLATE-- -{% for i in 1..2 %} - {% for j in 0..2 %} - {{k}}{% set k = k+1 %} {{ loop.parent.loop.index }} - {% endfor %} -{% endfor %} ---DATA-- -return array('k' => 0) ---EXPECT-- - 0 1 - 1 1 - 2 1 - 3 2 - 4 2 - 5 2 ---TEST-- -"for" tag can iterate over keys and values ---TEMPLATE-- -{% for key, item in items %} - * {{ key }}/{{ item }} -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- - * 0/a - * 1/b ---TEST-- -"for" tag can iterate over keys ---TEMPLATE-- -{% for key in items|keys %} - * {{ key }} -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- - * 0 - * 1 ---TEST-- -"for" tag adds a loop variable to the context locally ---TEMPLATE-- -{% for item in items %} -{% endfor %} -{% if loop is not defined %}WORKS{% endif %} ---DATA-- -return array('items' => array()) ---EXPECT-- -WORKS ---TEST-- -"for" tag adds a loop variable to the context ---TEMPLATE-- -{% for item in items %} - * {{ loop.index }}/{{ loop.index0 }} - * {{ loop.revindex }}/{{ loop.revindex0 }} - * {{ loop.first }}/{{ loop.last }}/{{ loop.length }} - -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- - * 1/0 - * 2/1 - * 1//2 - - * 2/1 - * 1/0 - * /1/2 ---TEST-- -"for" tag ---TEMPLATE-- -{% for i, item in items if loop.last > 0 %} -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXCEPTION-- -Twig_Error_Syntax: The "loop" variable cannot be used in a looping condition in "index.twig" at line 2 ---TEST-- -"for" tag ---TEMPLATE-- -{% for i, item in items if i > 0 %} - {{ loop.last }} -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXCEPTION-- -Twig_Error_Syntax: The "loop.last" variable is not defined when looping with a condition in "index.twig" at line 3 ---TEST-- -"for" tag can use an "else" clause ---TEMPLATE-- -{% for item in items %} - {% for item in items1 %} - * {{ item }} - {% else %} - no {{ item }} - {% endfor %} -{% else %} - no item1 -{% endfor %} ---DATA-- -return array('items' => array('a', 'b'), 'items1' => array()) ---EXPECT-- -no a - no b ---TEST-- -"for" tag iterates over iterable and countable objects ---TEMPLATE-- -{% for item in items %} - * {{ item }} - * {{ loop.index }}/{{ loop.index0 }} - * {{ loop.revindex }}/{{ loop.revindex0 }} - * {{ loop.first }}/{{ loop.last }}/{{ loop.length }} - -{% endfor %} - -{% for key, value in items %} - * {{ key }}/{{ value }} -{% endfor %} - -{% for key in items|keys %} - * {{ key }} -{% endfor %} ---DATA-- -class ItemsIteratorCountable implements Iterator, Countable -{ - protected $values = array('foo' => 'bar', 'bar' => 'foo'); - public function current() { return current($this->values); } - public function key() { return key($this->values); } - public function next() { return next($this->values); } - public function rewind() { return reset($this->values); } - public function valid() { return false !== current($this->values); } - public function count() { return count($this->values); } -} -return array('items' => new ItemsIteratorCountable()) ---EXPECT-- - * bar - * 1/0 - * 2/1 - * 1//2 - - * foo - * 2/1 - * 1/0 - * /1/2 - - - * foo/bar - * bar/foo - - * foo - * bar ---TEST-- -"for" tag iterates over iterable objects ---TEMPLATE-- -{% for item in items %} - * {{ item }} - * {{ loop.index }}/{{ loop.index0 }} - * {{ loop.first }} - -{% endfor %} - -{% for key, value in items %} - * {{ key }}/{{ value }} -{% endfor %} - -{% for key in items|keys %} - * {{ key }} -{% endfor %} ---DATA-- -class ItemsIterator implements Iterator -{ - protected $values = array('foo' => 'bar', 'bar' => 'foo'); - public function current() { return current($this->values); } - public function key() { return key($this->values); } - public function next() { return next($this->values); } - public function rewind() { return reset($this->values); } - public function valid() { return false !== current($this->values); } -} -return array('items' => new ItemsIterator()) ---EXPECT-- - * bar - * 1/0 - * 1 - - * foo - * 2/1 - * - - - * foo/bar - * bar/foo - - * foo - * bar ---TEST-- -"for" tags can be nested ---TEMPLATE-- -{% for key, item in items %} -* {{ key }} ({{ loop.length }}): -{% for value in item %} - * {{ value }} ({{ loop.length }}) -{% endfor %} -{% endfor %} ---DATA-- -return array('items' => array('a' => array('a1', 'a2', 'a3'), 'b' => array('b1'))) ---EXPECT-- -* a (2): - * a1 (3) - * a2 (3) - * a3 (3) -* b (2): - * b1 (1) ---TEST-- -"for" tag iterates over item values ---TEMPLATE-- -{% for item in items %} - * {{ item }} -{% endfor %} ---DATA-- -return array('items' => array('a', 'b')) ---EXPECT-- - * a - * b ---TEST-- -global variables ---TEMPLATE-- -{% include "included.twig" %} -{% from "included.twig" import foobar %} -{{ foobar() }} ---TEMPLATE(included.twig)-- -{% macro foobar() %} -called foobar -{% endmacro %} ---DATA-- -return array(); ---EXPECT-- -called foobar ---TEST-- -"if" creates a condition ---TEMPLATE-- -{% if a is defined %} - {{ a }} -{% elseif b is defined %} - {{ b }} -{% else %} - NOTHING -{% endif %} ---DATA-- -return array('a' => 'a') ---EXPECT-- - a ---DATA-- -return array('b' => 'b') ---EXPECT-- - b ---DATA-- -return array() ---EXPECT-- - NOTHING ---TEST-- -"if" takes an expression as a test ---TEMPLATE-- -{% if a < 2 %} - A1 -{% elseif a > 10 %} - A2 -{% else %} - A3 -{% endif %} ---DATA-- -return array('a' => 1) ---EXPECT-- - A1 ---DATA-- -return array('a' => 12) ---EXPECT-- - A2 ---DATA-- -return array('a' => 7) ---EXPECT-- - A3 ---TEST-- -"include" tag ---TEMPLATE-- -FOO -{% include "foo.twig" %} - -BAR ---TEMPLATE(foo.twig)-- -FOOBAR ---DATA-- -return array() ---EXPECT-- -FOO - -FOOBAR -BAR ---TEST-- -"include" tag allows expressions for the template to include ---TEMPLATE-- -FOO -{% include foo %} - -BAR ---TEMPLATE(foo.twig)-- -FOOBAR ---DATA-- -return array('foo' => 'foo.twig') ---EXPECT-- -FOO - -FOOBAR -BAR ---TEST-- -"include" tag ---TEMPLATE-- -{% include ["foo.twig", "bar.twig"] ignore missing %} -{% include "foo.twig" ignore missing %} -{% include "foo.twig" ignore missing with {} %} -{% include "foo.twig" ignore missing with {} only %} ---DATA-- -return array() ---EXPECT-- ---TEST-- -"include" tag ---TEMPLATE-- -{% extends "base.twig" %} - -{% block content %} - {{ parent() }} -{% endblock %} ---TEMPLATE(base.twig)-- -{% block content %} - {% include "foo.twig" %} -{% endblock %} ---DATA-- -return array(); ---EXCEPTION-- -Twig_Error_Loader: Template "foo.twig" is not defined in "base.twig" at line 3. ---TEST-- -"include" tag ---TEMPLATE-- -{% include "foo.twig" %} ---DATA-- -return array(); ---EXCEPTION-- -Twig_Error_Loader: Template "foo.twig" is not defined in "index.twig" at line 2. ---TEST-- -"include" tag accept variables and only ---TEMPLATE-- -{% include "foo.twig" %} -{% include "foo.twig" only %} -{% include "foo.twig" with {'foo1': 'bar'} %} -{% include "foo.twig" with {'foo1': 'bar'} only %} ---TEMPLATE(foo.twig)-- -{% for k, v in _context %}{{ k }},{% endfor %} ---DATA-- -return array('foo' => 'bar') ---EXPECT-- -foo,global,_parent, -global,_parent, -foo,global,foo1,_parent, -foo1,global,_parent, ---TEST-- -"include" tag accepts Twig_Template instance ---TEMPLATE-- -{% include foo %} FOO ---TEMPLATE(foo.twig)-- -BAR ---DATA-- -return array('foo' => $twig->loadTemplate('foo.twig')) ---EXPECT-- -BAR FOO ---TEST-- -"include" tag ---TEMPLATE-- -{% include ["foo.twig", "bar.twig"] %} -{% include ["bar.twig", "foo.twig"] %} ---TEMPLATE(foo.twig)-- -foo ---DATA-- -return array() ---EXPECT-- -foo -foo ---TEST-- -"include" tag accept variables ---TEMPLATE-- -{% include "foo.twig" with {'foo': 'bar'} %} -{% include "foo.twig" with vars %} ---TEMPLATE(foo.twig)-- -{{ foo }} ---DATA-- -return array('vars' => array('foo' => 'bar')) ---EXPECT-- -bar -bar ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "foo.twig" %} - -{% block content %} -FOO -{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %}{% endblock %} ---DATA-- -return array() ---EXPECT-- -FOO ---TEST-- -block_expr2 ---TEMPLATE-- -{% extends "base2.twig" %} - -{% block element -%} - Element: - {{- parent() -}} -{% endblock %} ---TEMPLATE(base2.twig)-- -{% extends "base.twig" %} ---TEMPLATE(base.twig)-- -{% spaceless %} -{% block element -%} -
    - {%- if item.children is defined %} - {%- for item in item.children %} - {{- block('element') -}} - {% endfor %} - {%- endif -%} -
    -{%- endblock %} -{% endspaceless %} ---DATA-- -return array( - 'item' => array( - 'children' => array( - null, - null, - ) - ) -) ---EXPECT-- -Element:
    Element:
    Element:
    ---TEST-- -block_expr ---TEMPLATE-- -{% extends "base.twig" %} - -{% block element -%} - Element: - {{- parent() -}} -{% endblock %} ---TEMPLATE(base.twig)-- -{% spaceless %} -{% block element -%} -
    - {%- if item.children is defined %} - {%- for item in item.children %} - {{- block('element') -}} - {% endfor %} - {%- endif -%} -
    -{%- endblock %} -{% endspaceless %} ---DATA-- -return array( - 'item' => array( - 'children' => array( - null, - null, - ) - ) -) ---EXPECT-- -Element:
    Element:
    Element:
    ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends standalone ? foo : 'bar.twig' %} - -{% block content %}{{ parent() }}FOO{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %}FOO{% endblock %} ---TEMPLATE(bar.twig)-- -{% block content %}BAR{% endblock %} ---DATA-- -return array('foo' => 'foo.twig', 'standalone' => true) ---EXPECT-- -FOOFOO ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends foo %} - -{% block content %} -FOO -{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %}{% endblock %} ---DATA-- -return array('foo' => 'foo.twig') ---EXPECT-- -FOO ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "foo.twig" %} ---TEMPLATE(foo.twig)-- -{% block content %}FOO{% endblock %} ---DATA-- -return array() ---EXPECT-- -FOO ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends ["foo.twig", "bar.twig"] %} ---TEMPLATE(bar.twig)-- -{% block content %} -foo -{% endblock %} ---DATA-- -return array() ---EXPECT-- -foo ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "layout.twig" %}{% block content %}{{ parent() }}index {% endblock %} ---TEMPLATE(layout.twig)-- -{% extends "base.twig" %}{% block content %}{{ parent() }}layout {% endblock %} ---TEMPLATE(base.twig)-- -{% block content %}base {% endblock %} ---DATA-- -return array() ---EXPECT-- -base layout index ---TEST-- -"block" tag ---TEMPLATE-- -{% block content %} - CONTENT - {%- block subcontent -%} - SUBCONTENT - {%- endblock -%} - ENDCONTENT -{% endblock %} ---TEMPLATE(foo.twig)-- ---DATA-- -return array() ---EXPECT-- -CONTENTSUBCONTENTENDCONTENT ---TEST-- -"block" tag ---TEMPLATE-- -{% extends "foo.twig" %} - -{% block content %} - {% block subcontent %} - {% block subsubcontent %} - SUBSUBCONTENT - {% endblock %} - {% endblock %} -{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %} - {% block subcontent %} - SUBCONTENT - {% endblock %} -{% endblock %} ---DATA-- -return array() ---EXPECT-- -SUBSUBCONTENT ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "layout.twig" %} -{% block inside %}INSIDE{% endblock inside %} ---TEMPLATE(layout.twig)-- -{% extends "base.twig" %} -{% block body %} - {% block inside '' %} -{% endblock body %} ---TEMPLATE(base.twig)-- -{% block body '' %} ---DATA-- -return array() ---EXPECT-- -INSIDE ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends foo ? 'foo.twig' : 'bar.twig' %} ---TEMPLATE(foo.twig)-- -FOO ---TEMPLATE(bar.twig)-- -BAR ---DATA-- -return array('foo' => true) ---EXPECT-- -FOO ---DATA-- -return array('foo' => false) ---EXPECT-- -BAR ---TEST-- -"extends" tag ---TEMPLATE-- -{% block content %} - {% extends "foo.twig" %} -{% endblock %} ---EXCEPTION-- -Twig_Error_Syntax: Cannot extend from a block in "index.twig" at line 3 ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "base.twig" %} -{% block content %}{% include "included.twig" %}{% endblock %} - -{% block footer %}Footer{% endblock %} ---TEMPLATE(included.twig)-- -{% extends "base.twig" %} -{% block content %}Included Content{% endblock %} ---TEMPLATE(base.twig)-- -{% block content %}Default Content{% endblock %} - -{% block footer %}Default Footer{% endblock %} ---DATA-- -return array() ---EXPECT-- -Included Content -Default Footer -Footer ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "foo.twig" %} - -{% block content %} - {% block inside %} - INSIDE OVERRIDDEN - {% endblock %} - - BEFORE - {{ parent() }} - AFTER -{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %} - BAR -{% endblock %} ---DATA-- -return array() ---EXPECT-- - -INSIDE OVERRIDDEN - - BEFORE - BAR - - AFTER ---TEST-- -"extends" tag ---TEMPLATE-- -{% extends "foo.twig" %} - -{% block content %}{{ parent() }}FOO{{ parent() }}{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %}BAR{% endblock %} ---DATA-- -return array() ---EXPECT-- -BARFOOBAR ---TEST-- -"parent" tag ---TEMPLATE-- -{% use 'foo.twig' %} - -{% block content %} - {{ parent() }} -{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %}BAR{% endblock %} ---DATA-- -return array() ---EXPECT-- -BAR ---TEST-- -"parent" tag ---TEMPLATE-- -{% block content %} - {{ parent() }} -{% endblock %} ---EXCEPTION-- -Twig_Error_Syntax: Calling "parent" on a template that does not extend nor "use" another template is forbidden in "index.twig" at line 3 ---TEST-- -"extends" tag accepts Twig_Template instance ---TEMPLATE-- -{% extends foo %} - -{% block content %} -{{ parent() }}FOO -{% endblock %} ---TEMPLATE(foo.twig)-- -{% block content %}BAR{% endblock %} ---DATA-- -return array('foo' => $twig->loadTemplate('foo.twig')) ---EXPECT-- -BARFOO ---TEST-- -"parent" function ---TEMPLATE-- -{% extends "parent.twig" %} - -{% use "use1.twig" %} -{% use "use2.twig" %} - -{% block content_parent %} - {{ parent() }} -{% endblock %} - -{% block content_use1 %} - {{ parent() }} -{% endblock %} - -{% block content_use2 %} - {{ parent() }} -{% endblock %} - -{% block content %} - {{ block('content_use1_only') }} - {{ block('content_use2_only') }} -{% endblock %} ---TEMPLATE(parent.twig)-- -{% block content_parent 'content_parent' %} -{% block content_use1 'content_parent' %} -{% block content_use2 'content_parent' %} -{% block content '' %} ---TEMPLATE(use1.twig)-- -{% block content_use1 'content_use1' %} -{% block content_use2 'content_use1' %} -{% block content_use1_only 'content_use1_only' %} ---TEMPLATE(use2.twig)-- -{% block content_use2 'content_use2' %} -{% block content_use2_only 'content_use2_only' %} ---DATA-- -return array() ---EXPECT-- - content_parent - content_use1 - content_use2 - content_use1_only - content_use2_only ---TEST-- -"macro" tag ---TEMPLATE-- -{% import _self as macros %} - -{{ macros.input('username') }} -{{ macros.input('password', null, 'password', 1) }} - -{% macro input(name, value, type, size) %} - -{% endmacro %} ---DATA-- -return array() ---EXPECT-- - - - ---TEST-- -"macro" tag supports name for endmacro ---TEMPLATE-- -{% import _self as macros %} - -{{ macros.foo() }} -{{ macros.bar() }} - -{% macro foo() %}foo{% endmacro %} -{% macro bar() %}bar{% endmacro bar %} ---DATA-- -return array() ---EXPECT-- -foo -bar - ---TEST-- -"macro" tag ---TEMPLATE-- -{% import 'forms.twig' as forms %} - -{{ forms.input('username') }} -{{ forms.input('password', null, 'password', 1) }} ---TEMPLATE(forms.twig)-- -{% macro input(name, value, type, size) %} - -{% endmacro %} ---DATA-- -return array() ---EXPECT-- - - - ---TEST-- -"macro" tag ---TEMPLATE-- -{% from 'forms.twig' import foo %} -{% from 'forms.twig' import foo as foobar, bar %} - -{{ foo('foo') }} -{{ foobar('foo') }} -{{ bar('foo') }} ---TEMPLATE(forms.twig)-- -{% macro foo(name) %}foo{{ name }}{% endmacro %} -{% macro bar(name) %}bar{{ name }}{% endmacro %} ---DATA-- -return array() ---EXPECT-- -foofoo -foofoo -barfoo ---TEST-- -"macro" tag ---TEMPLATE-- -{% from 'forms.twig' import foo %} - -{{ foo('foo') }} -{{ foo() }} ---TEMPLATE(forms.twig)-- -{% macro foo(name) %}{{ name|default('foo') }}{{ global }}{% endmacro %} ---DATA-- -return array() ---EXPECT-- -fooglobal -fooglobal ---TEST-- -"macro" tag ---TEMPLATE-- -{% import _self as forms %} - -{{ forms.input('username') }} -{{ forms.input('password', null, 'password', 1) }} - -{% macro input(name, value, type, size) %} - -{% endmacro %} ---DATA-- -return array() ---EXPECT-- - - - ---TEST-- -"raw" tag ---TEMPLATE-- -{% raw %} -{{ foo }} -{% endraw %} ---DATA-- -return array() ---EXPECT-- -{{ foo }} ---TEST-- -"raw" tag ---TEMPLATE-- -{% raw %} -{{ foo }} -{% endverbatim %} ---DATA-- -return array() ---EXCEPTION-- -Twig_Error_Syntax: Unexpected end of file: Unclosed "raw" block in "index.twig" at line 2 ---TEST-- -"raw" tag ---TEMPLATE-- -1*** - -{%- raw %} - {{ 'bla' }} -{% endraw %} - -1*** -2*** - -{%- raw -%} - {{ 'bla' }} -{% endraw %} - -2*** -3*** - -{%- raw -%} - {{ 'bla' }} -{% endraw -%} - -3*** -4*** - -{%- raw -%} - {{ 'bla' }} -{%- endraw %} - -4*** -5*** - -{%- raw -%} - {{ 'bla' }} -{%- endraw -%} - -5*** ---DATA-- -return array() ---EXPECT-- -1*** - {{ 'bla' }} - - -1*** -2***{{ 'bla' }} - - -2*** -3***{{ 'bla' }} -3*** -4***{{ 'bla' }} - -4*** -5***{{ 'bla' }}5*** ---TEST-- -sandbox tag ---TEMPLATE-- -{%- sandbox %} - {%- include "foo.twig" %} - a -{%- endsandbox %} ---TEMPLATE(foo.twig)-- -foo ---EXCEPTION-- -Twig_Error_Syntax: Only "include" tags are allowed within a "sandbox" section in "index.twig" at line 4 ---TEST-- -sandbox tag ---TEMPLATE-- -{%- sandbox %} - {%- include "foo.twig" %} - - {% if 1 %} - {%- include "foo.twig" %} - {% endif %} -{%- endsandbox %} ---TEMPLATE(foo.twig)-- -foo ---EXCEPTION-- -Twig_Error_Syntax: Only "include" tags are allowed within a "sandbox" section in "index.twig" at line 5 ---TEST-- -sandbox tag ---TEMPLATE-- -{%- sandbox %} - {%- include "foo.twig" %} -{%- endsandbox %} - -{%- sandbox %} - {%- include "foo.twig" %} - {%- include "foo.twig" %} -{%- endsandbox %} - -{%- sandbox %}{% include "foo.twig" %}{% endsandbox %} ---TEMPLATE(foo.twig)-- -foo ---DATA-- -return array() ---EXPECT-- -foo -foo -foo -foo ---TEST-- -"set" tag ---TEMPLATE-- -{% set foo = 'foo' %} -{% set bar = 'foo
    ' %} - -{{ foo }} -{{ bar }} - -{% set foo, bar = 'foo', 'bar' %} - -{{ foo }}{{ bar }} ---DATA-- -return array() ---EXPECT-- -foo -foo<br /> - - -foobar ---TEST-- -"set" tag block empty capture ---TEMPLATE-- -{% set foo %}{% endset %} - -{% if foo %}FAIL{% endif %} ---DATA-- -return array() ---EXPECT-- ---TEST-- -"set" tag block capture ---TEMPLATE-- -{% set foo %}f
    o
    o{% endset %} - -{{ foo }} ---DATA-- -return array() ---EXPECT-- -f
    o
    o ---TEST-- -"set" tag ---TEMPLATE-- -{% set foo, bar = 'foo' ~ 'bar', 'bar' ~ 'foo' %} - -{{ foo }} -{{ bar }} ---DATA-- -return array() ---EXPECT-- -foobar -barfoo ---TEST-- -"spaceless" tag removes whites between HTML tags ---TEMPLATE-- -{% spaceless %} - -
    foo
    - -{% endspaceless %} ---DATA-- -return array() ---EXPECT-- -
    foo
    ---TEST-- -"§" custom tag ---TEMPLATE-- -{% § %} ---DATA-- -return array() ---EXPECT-- -§ ---TEST-- -Whitespace trimming on tags. ---TEMPLATE-- -{{ 5 * '{#-'|length }} -{{ '{{-'|length * 5 + '{%-'|length }} - -Trim on control tag: -{% for i in range(1, 9) -%} - {{ i }} -{%- endfor %} - - -Trim on output tag: -{% for i in range(1, 9) %} - {{- i -}} -{% endfor %} - - -Trim comments: - -{#- Invisible -#} - -After the comment. - -Trim leading space: -{% if leading %} - - {{- leading }} -{% endif %} - -{%- if leading %} - {{- leading }} - -{%- endif %} - - -Trim trailing space: -{% if trailing -%} - {{ trailing -}} - -{% endif -%} - -Combined: - -{%- if both -%} -
      -
    • {{- both -}}
    • -
    - -{%- endif -%} - -end ---DATA-- -return array('leading' => 'leading space', 'trailing' => 'trailing space', 'both' => 'both') ---EXPECT-- -15 -18 - -Trim on control tag: -123456789 - -Trim on output tag: -123456789 - -Trim comments:After the comment. - -Trim leading space: -leading space -leading space - -Trim trailing space: -trailing spaceCombined:
      -
    • both
    • -
    end ---TEST-- -"use" tag ---TEMPLATE-- -{% use "blocks.twig" with content as foo %} - -{{ block('foo') }} ---TEMPLATE(blocks.twig)-- -{% block content 'foo' %} ---DATA-- -return array() ---EXPECT-- -foo ---TEST-- -"use" tag ---TEMPLATE-- -{% use "blocks.twig" %} - -{{ block('content') }} ---TEMPLATE(blocks.twig)-- -{% block content 'foo' %} ---DATA-- -return array() ---EXPECT-- -foo ---TEST-- -"use" tag ---TEMPLATE-- -{% use "foo.twig" %} ---TEMPLATE(foo.twig)-- -{% use "bar.twig" %} ---TEMPLATE(bar.twig)-- ---DATA-- -return array() ---EXPECT-- ---TEST-- -"use" tag ---TEMPLATE-- -{% use "foo.twig" %} - -{{ block('content') }} -{{ block('foo') }} -{{ block('bar') }} ---TEMPLATE(foo.twig)-- -{% use "bar.twig" %} - -{% block content 'foo' %} -{% block foo 'foo' %} ---TEMPLATE(bar.twig)-- -{% block content 'bar' %} -{% block bar 'bar' %} ---DATA-- -return array() ---EXPECT-- -foo -foo -bar ---TEST-- -"use" tag ---TEMPLATE-- -{% use "ancestor.twig" %} -{% use "parent.twig" %} - -{{ block('container') }} ---TEMPLATE(parent.twig)-- -{% block sub_container %} -
    overriden sub_container
    -{% endblock %} ---TEMPLATE(ancestor.twig)-- -{% block container %} -
    {{ block('sub_container') }}
    -{% endblock %} - -{% block sub_container %} -
    sub_container
    -{% endblock %} ---DATA-- -return array() ---EXPECT-- -
    overriden sub_container
    -
    ---TEST-- -"use" tag ---TEMPLATE-- -{% use "parent.twig" %} - -{{ block('container') }} ---TEMPLATE(parent.twig)-- -{% use "ancestor.twig" %} - -{% block sub_container %} -
    overriden sub_container
    -{% endblock %} ---TEMPLATE(ancestor.twig)-- -{% block container %} -
    {{ block('sub_container') }}
    -{% endblock %} - -{% block sub_container %} -
    sub_container
    -{% endblock %} ---DATA-- -return array() ---EXPECT-- -
    overriden sub_container
    -
    ---TEST-- -"use" tag ---TEMPLATE-- -{% use "foo.twig" with content as foo_content %} -{% use "bar.twig" %} - -{{ block('content') }} -{{ block('foo') }} -{{ block('bar') }} -{{ block('foo_content') }} ---TEMPLATE(foo.twig)-- -{% block content 'foo' %} -{% block foo 'foo' %} ---TEMPLATE(bar.twig)-- -{% block content 'bar' %} -{% block bar 'bar' %} ---DATA-- -return array() ---EXPECT-- -bar -foo -bar -foo ---TEST-- -"use" tag ---TEMPLATE-- -{% use "foo.twig" %} -{% use "bar.twig" %} - -{{ block('content') }} -{{ block('foo') }} -{{ block('bar') }} ---TEMPLATE(foo.twig)-- -{% block content 'foo' %} -{% block foo 'foo' %} ---TEMPLATE(bar.twig)-- -{% block content 'bar' %} -{% block bar 'bar' %} ---DATA-- -return array() ---EXPECT-- -bar -foo -bar ---TEST-- -"use" tag ---TEMPLATE-- -{% use 'file2.html.twig'%} -{% block foobar %} - {{- parent() -}} - Content of block (second override) -{% endblock foobar %} ---TEMPLATE(file2.html.twig)-- -{% use 'file1.html.twig' %} -{% block foobar %} - {{- parent() -}} - Content of block (first override) -{% endblock foobar %} ---TEMPLATE(file1.html.twig)-- -{% block foobar -%} - Content of block -{% endblock foobar %} ---DATA-- -return array() ---EXPECT-- -Content of block -Content of block (first override) -Content of block (second override) ---TEST-- -"use" tag ---TEMPLATE-- -{% use 'file2.html.twig' %} -{% use 'file1.html.twig' with foo %} -{% block foo %} - {{- parent() -}} - Content of foo (second override) -{% endblock foo %} -{% block bar %} - {{- parent() -}} - Content of bar (second override) -{% endblock bar %} ---TEMPLATE(file2.html.twig)-- -{% use 'file1.html.twig' %} -{% block foo %} - {{- parent() -}} - Content of foo (first override) -{% endblock foo %} -{% block bar %} - {{- parent() -}} - Content of bar (first override) -{% endblock bar %} ---TEMPLATE(file1.html.twig)-- -{% block foo -%} - Content of foo -{% endblock foo %} -{% block bar -%} - Content of bar -{% endblock bar %} ---DATA-- -return array() ---EXPECT-- -Content of foo -Content of foo (first override) -Content of foo (second override) -Content of bar -Content of bar (second override) ---TEST-- -"use" tag ---TEMPLATE-- -{% use 'file2.html.twig' with foobar as base_base_foobar %} -{% block foobar %} - {{- block('base_base_foobar') -}} - Content of block (second override) -{% endblock foobar %} ---TEMPLATE(file2.html.twig)-- -{% use 'file1.html.twig' with foobar as base_foobar %} -{% block foobar %} - {{- block('base_foobar') -}} - Content of block (first override) -{% endblock foobar %} ---TEMPLATE(file1.html.twig)-- -{% block foobar -%} - Content of block -{% endblock foobar %} ---DATA-- -return array() ---EXPECT-- -Content of block -Content of block (first override) -Content of block (second override) ---TEST-- -"verbatim" tag ---TEMPLATE-- -{% verbatim %} -{{ foo }} -{% endverbatim %} ---DATA-- -return array() ---EXPECT-- -{{ foo }} ---TEST-- -"verbatim" tag ---TEMPLATE-- -{% verbatim %} -{{ foo }} -{% endraw %} ---DATA-- -return array() ---EXCEPTION-- -Twig_Error_Syntax: Unexpected end of file: Unclosed "verbatim" block in "index.twig" at line 2 ---TEST-- -"verbatim" tag ---TEMPLATE-- -1*** - -{%- verbatim %} - {{ 'bla' }} -{% endverbatim %} - -1*** -2*** - -{%- verbatim -%} - {{ 'bla' }} -{% endverbatim %} - -2*** -3*** - -{%- verbatim -%} - {{ 'bla' }} -{% endverbatim -%} - -3*** -4*** - -{%- verbatim -%} - {{ 'bla' }} -{%- endverbatim %} - -4*** -5*** - -{%- verbatim -%} - {{ 'bla' }} -{%- endverbatim -%} - -5*** ---DATA-- -return array() ---EXPECT-- -1*** - {{ 'bla' }} - - -1*** -2***{{ 'bla' }} - - -2*** -3***{{ 'bla' }} -3*** -4***{{ 'bla' }} - -4*** -5***{{ 'bla' }}5*** ---TEST-- -array index test ---TEMPLATE-- -{% for key, value in days %} -{{ key }} -{% endfor %} ---DATA-- -return array('days' => array( - 1 => array('money' => 9), - 2 => array('money' => 21), - 3 => array('money' => 38), - 4 => array('money' => 6), - 18 => array('money' => 6), - 19 => array('money' => 3), - 31 => array('money' => 11), -)); ---EXPECT-- -1 -2 -3 -4 -18 -19 -31 ---TEST-- -"const" test ---TEMPLATE-- -{{ 8 is constant('E_NOTICE') ? 'ok' : 'no' }} -{{ 'bar' is constant('TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} -{{ value is constant('TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} -{{ 2 is constant('ARRAY_AS_PROPS', object) ? 'ok' : 'no' }} ---DATA-- -return array('value' => 'bar', 'object' => new ArrayObject(array('hi'))); ---EXPECT-- -ok -ok -ok -ok--TEST-- -"defined" test ---TEMPLATE-- -{{ definedVar is defined ? 'ok' : 'ko' }} -{{ definedVar is not defined ? 'ko' : 'ok' }} -{{ undefinedVar is defined ? 'ko' : 'ok' }} -{{ undefinedVar is not defined ? 'ok' : 'ko' }} -{{ zeroVar is defined ? 'ok' : 'ko' }} -{{ nullVar is defined ? 'ok' : 'ko' }} -{{ nested.definedVar is defined ? 'ok' : 'ko' }} -{{ nested['definedVar'] is defined ? 'ok' : 'ko' }} -{{ nested.definedVar is not defined ? 'ko' : 'ok' }} -{{ nested.undefinedVar is defined ? 'ko' : 'ok' }} -{{ nested['undefinedVar'] is defined ? 'ko' : 'ok' }} -{{ nested.undefinedVar is not defined ? 'ok' : 'ko' }} -{{ nested.zeroVar is defined ? 'ok' : 'ko' }} -{{ nested.nullVar is defined ? 'ok' : 'ko' }} -{{ nested.definedArray.0 is defined ? 'ok' : 'ko' }} -{{ nested['definedArray'][0] is defined ? 'ok' : 'ko' }} -{{ object.foo is defined ? 'ok' : 'ko' }} -{{ object.undefinedMethod is defined ? 'ko' : 'ok' }} -{{ object.getFoo() is defined ? 'ok' : 'ko' }} -{{ object.getFoo('a') is defined ? 'ok' : 'ko' }} -{{ object.undefinedMethod() is defined ? 'ko' : 'ok' }} -{{ object.undefinedMethod('a') is defined ? 'ko' : 'ok' }} -{{ object.self.foo is defined ? 'ok' : 'ko' }} -{{ object.self.undefinedMethod is defined ? 'ko' : 'ok' }} -{{ object.undefinedMethod.self is defined ? 'ko' : 'ok' }} ---DATA-- -return array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'nullVar' => null, - 'nested' => array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'nullVar' => null, - 'definedArray' => array(0), - ), - 'object' => new TwigTestFoo(), -); ---EXPECT-- -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok ---DATA-- -return array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'nullVar' => null, - 'nested' => array( - 'definedVar' => 'defined', - 'zeroVar' => 0, - 'nullVar' => null, - 'definedArray' => array(0), - ), - 'object' => new TwigTestFoo(), -); ---CONFIG-- -return array('strict_variables' => false) ---EXPECT-- -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok -ok ---TEST-- -"empty" test ---TEMPLATE-- -{{ foo is empty ? 'ok' : 'ko' }} -{{ bar is empty ? 'ok' : 'ko' }} -{{ foobar is empty ? 'ok' : 'ko' }} -{{ array is empty ? 'ok' : 'ko' }} -{{ zero is empty ? 'ok' : 'ko' }} -{{ string is empty ? 'ok' : 'ko' }} -{{ countable_empty is empty ? 'ok' : 'ko' }} -{{ countable_not_empty is empty ? 'ok' : 'ko' }} -{{ markup_empty is empty ? 'ok' : 'ko' }} -{{ markup_not_empty is empty ? 'ok' : 'ko' }} ---DATA-- - -class CountableStub implements Countable -{ - private $items; - - public function __construct(array $items) - { - $this->items = $items; - } - - public function count() - { - return count($this->items); - } -} -return array( - 'foo' => '', 'bar' => null, 'foobar' => false, 'array' => array(), 'zero' => 0, 'string' => '0', - 'countable_empty' => new CountableStub(array()), 'countable_not_empty' => new CountableStub(array(1, 2)), - 'markup_empty' => new Twig_Markup('', 'UTF-8'), 'markup_not_empty' => new Twig_Markup('test', 'UTF-8'), -); ---EXPECT-- -ok -ok -ok -ok -ko -ko -ok -ko -ok -ko ---TEST-- -"even" test ---TEMPLATE-- -{{ 1 is even ? 'ko' : 'ok' }} -{{ 2 is even ? 'ok' : 'ko' }} -{{ 1 is not even ? 'ok' : 'ko' }} -{{ 2 is not even ? 'ko' : 'ok' }} ---DATA-- -return array() ---EXPECT-- -ok -ok -ok -ok ---TEST-- -Twig supports the in operator ---TEMPLATE-- -{% if bar in foo %} -TRUE -{% endif %} -{% if not (bar in foo) %} -{% else %} -TRUE -{% endif %} -{% if bar not in foo %} -{% else %} -TRUE -{% endif %} -{% if 'a' in bar %} -TRUE -{% endif %} -{% if 'c' not in bar %} -TRUE -{% endif %} -{% if '' not in bar %} -TRUE -{% endif %} -{% if '' in '' %} -TRUE -{% endif %} -{% if '0' not in '' %} -TRUE -{% endif %} -{% if 'a' not in '0' %} -TRUE -{% endif %} -{% if '0' in '0' %} -TRUE -{% endif %} -{{ false in [0, 1] ? 'TRUE' : 'FALSE' }} -{{ true in [0, 1] ? 'TRUE' : 'FALSE' }} -{{ '0' in [0, 1] ? 'TRUE' : 'FALSE' }} -{{ '' in [0, 1] ? 'TRUE' : 'FALSE' }} -{{ 0 in ['', 1] ? 'TRUE' : 'FALSE' }} -{{ '' in 'foo' ? 'TRUE' : 'FALSE' }} -{{ 0 in 'foo' ? 'TRUE' : 'FALSE' }} -{{ false in 'foo' ? 'TRUE' : 'FALSE' }} -{{ true in '100' ? 'TRUE' : 'FALSE' }} -{{ [] in 'Array' ? 'TRUE' : 'FALSE' }} -{{ [] in [true, false] ? 'TRUE' : 'FALSE' }} -{{ [] in [true, ''] ? 'TRUE' : 'FALSE' }} -{{ [] in [true, []] ? 'TRUE' : 'FALSE' }} -{{ dir_object in 'foo'~dir_name ? 'TRUE' : 'FALSE' }} -{{ 5 in 125 ? 'TRUE' : 'FALSE' }} ---DATA-- -return array('bar' => 'bar', 'foo' => array('bar' => 'bar'), 'dir_name' => dirname(__FILE__), 'dir_object' => new SplFileInfo(dirname(__FILE__))) ---EXPECT-- -TRUE -TRUE -TRUE -TRUE -TRUE -TRUE -TRUE -TRUE -TRUE -FALSE -FALSE -FALSE -FALSE -FALSE -TRUE -FALSE -FALSE -FALSE -FALSE -FALSE -FALSE -TRUE -FALSE -FALSE ---TEST-- -Twig supports the in operator when using objects ---TEMPLATE-- -{% if object in object_list %} -TRUE -{% endif %} ---DATA-- -$foo = new TwigTestFoo(); -$foo1 = new TwigTestFoo(); - -$foo->position = $foo1; -$foo1->position = $foo; - -return array( - 'object' => $foo, - 'object_list' => array($foo1, $foo), -); ---EXPECT-- -TRUE ---TEST-- -"iterable" test ---TEMPLATE-- -{{ foo is iterable ? 'ok' : 'ko' }} -{{ traversable is iterable ? 'ok' : 'ko' }} -{{ obj is iterable ? 'ok' : 'ko' }} -{{ val is iterable ? 'ok' : 'ko' }} ---DATA-- -return array( - 'foo' => array(), - 'traversable' => new ArrayIterator(array()), - 'obj' => new stdClass(), - 'val' => 'test', -); ---EXPECT-- -ok -ok -ko -ko--TEST-- -"odd" test ---TEMPLATE-- -{{ 1 is odd ? 'ok' : 'ko' }} -{{ 2 is odd ? 'ko' : 'ok' }} ---DATA-- -return array() ---EXPECT-- -ok -ok diff --git a/third_party/pygments/tests/examplefiles/type.lisp b/third_party/pygments/tests/examplefiles/type.lisp deleted file mode 100644 index c02c29df2..000000000 --- a/third_party/pygments/tests/examplefiles/type.lisp +++ /dev/null @@ -1,1218 +0,0 @@ -;;;; TYPEP und Verwandtes -;;;; Michael Stoll, 21. 10. 1988 -;;;; Bruno Haible, 10.6.1989 -;;;; Sam Steingold 2000-2005 - -;;; Datenstrukturen für TYPEP: -;;; - Ein Type-Specifier-Symbol hat auf seiner Propertyliste unter dem -;;; Indikator SYS::TYPE-SYMBOL eine Funktion von einem Argument, die -;;; testet, ob ein Objekt vom richtigen Typ ist. -;;; - Ein Symbol, das eine Type-Specifier-Liste beginnen kann, hat auf seiner -;;; Propertyliste unter dem Indikator SYS::TYPE-LIST eine Funktion von -;;; einem Argument für das zu testende Objekt und zusätzlichen Argumenten -;;; für die Listenelemente. -;;; - Ein Symbol, das als Typmacro definiert wurde, hat auf seiner Property- -;;; liste unter dem Indikator SYSTEM::DEFTYPE-EXPANDER den zugehörigen -;;; Expander: eine Funktion, die den zu expandierenden Type-Specifier (eine -;;; mindestens einelementige Liste) als Argument bekommt. - -(in-package "EXT") -(export '(type-expand)) -(in-package "SYSTEM") - -; vorläufig, solange bis clos.lisp geladen wird: -(eval-when (eval) - (predefun clos::built-in-class-p (object) (declare (ignore object)) nil)) -(unless (fboundp 'clos::class-name) - (defun clos::class-name (c) (declare (ignore c)) nil) -) - -(defun typespec-error (fun type) - (error-of-type 'error - (TEXT "~S: invalid type specification ~S") - fun type -) ) - -;; ============================================================================ - -;; return the CLOS class named by TYPESPEC or NIL -(defun clos-class (typespec) - (let ((cc (get typespec 'CLOS::CLOSCLASS))) - (when (and cc (clos::defined-class-p cc) (eq (clos:class-name cc) typespec)) - cc))) - -;;; TYPEP, CLTL S. 72, S. 42-51 -(defun typep (x y &optional env &aux f) ; x = Objekt, y = Typ - (declare (ignore env)) - (setq y (expand-deftype y)) - (cond - ((symbolp y) - (cond ((setq f (get y 'TYPE-SYMBOL)) (funcall f x)) - ((setq f (get y 'TYPE-LIST)) (funcall f x)) - ((setq f (get y 'DEFSTRUCT-DESCRIPTION)) (ds-typep x y f)) - ((setq f (clos-class y)) - ; It's not worth handling structure classes specially here. - (clos::typep-class x f)) - (t (typespec-error 'typep y)) - ) ) - ((and (consp y) (symbolp (first y))) - (cond - ((and (eq (first y) 'SATISFIES) (eql (length y) 2)) - (unless (symbolp (second y)) - (error-of-type 'error - (TEXT "~S: argument to SATISFIES must be a symbol: ~S") - 'typep (second y) - ) ) - (if (funcall (symbol-function (second y)) x) t nil) - ) - ((eq (first y) 'MEMBER) - (if (member x (rest y)) t nil) - ) - ((and (eq (first y) 'EQL) (eql (length y) 2)) - (eql x (second y)) - ) - ((and (eq (first y) 'NOT) (eql (length y) 2)) - (not (typep x (second y))) - ) - ((eq (first y) 'AND) - (dolist (type (rest y) t) - (unless (typep x type) (return nil)) - ) ) - ((eq (first y) 'OR) - (dolist (type (rest y) nil) - (when (typep x type) (return t)) - ) ) - ((setq f (get (first y) 'TYPE-LIST)) (apply f x (rest y))) - (t (typespec-error 'typep y)) - ) ) - ((clos::defined-class-p y) (clos::typep-class x y)) - ((clos::eql-specializer-p y) (eql x (clos::eql-specializer-singleton y))) - ((encodingp y) (charset-typep x y)) - (t (typespec-error 'typep y)) -) ) - -;; ---------------------------------------------------------------------------- - -;; UPGRADED-ARRAY-ELEMENT-TYPE is a lattice homomorphism, see -;; ANSI CL 15.1.2.1. -(defun upgraded-array-element-type (type &optional environment) - (declare (ignore environment)) - ;; see array.d - (case type - ((BIT) 'BIT) - ((CHARACTER) 'CHARACTER) - ((T) 'T) - ((NIL) 'NIL) - (t (if (subtypep type 'NIL) - 'NIL - (multiple-value-bind (low high) (sys::subtype-integer type) - ; Es gilt (or (null low) (subtypep type `(INTEGER ,low ,high))) - (if (and (integerp low) (not (minusp low)) (integerp high)) - (let ((l (integer-length high))) - ; Es gilt (subtypep type `(UNSIGNED-BYTE ,l)) - (cond ((<= l 1) 'BIT) - ((<= l 2) '(UNSIGNED-BYTE 2)) - ((<= l 4) '(UNSIGNED-BYTE 4)) - ((<= l 8) '(UNSIGNED-BYTE 8)) - ((<= l 16) '(UNSIGNED-BYTE 16)) - ((<= l 32) '(UNSIGNED-BYTE 32)) - (t 'T))) - (if (subtypep type 'CHARACTER) - 'CHARACTER - 'T))))))) - -;; ---------------------------------------------------------------------------- - -;; UPGRADED-COMPLEX-PART-TYPE is a lattice homomorphism, see -;; HyperSpec/Body/fun_complex.html and HyperSpec/Body/syscla_complex.html, -;; and an idempotent. Therefore -;; (subtypep (upgraded-complex-part-type T1) (upgraded-complex-part-type T2)) -;; is equivalent to -;; (subtypep T1 (upgraded-complex-part-type T2)) -;; (Proof: Let U T be an abbreviation for (upgraded-complex-part-type T). -;; If U T1 <= U T2, then T1 <= U T1 <= U T2. -;; If T1 <= U T2, then by homomorphism U T1 <= U U T2 = U T2.) -;; -;; For _any_ CL implementation, you could define -;; (defun upgraded-complex-part-type (type) 'REAL) -;; Likewise for _any_ CL implementation, you could define -;; (defun upgraded-complex-part-type (type) type) -;; or - again for _any_ CL implementation: -;; (defun upgraded-complex-part-type (type) -;; (cond ((subtypep type 'NIL) 'NIL) -;; ((subtypep type 'SHORT-FLOAT) 'SHORT-FLOAT) -;; ((subtypep type 'SINGLE-FLOAT) 'SINGLE-FLOAT) -;; ((subtypep type 'DOUBLE-FLOAT) 'DOUBLE-FLOAT) -;; ((subtypep type 'LONG-FLOAT) 'LONG-FLOAT) -;; ((subtypep type 'RATIONAL) 'RATIONAL) -;; ((subtypep type 'REAL) 'REAL) -;; (t (error ...)))) -;; The reason is that a complex number is immutable: no setters for the -;; realpart and imagpart exist. -;; -;; We choose the second implementation because it allows the most precise -;; type inference. -(defun upgraded-complex-part-type (type &optional environment) - (declare (ignore environment)) - (if (subtypep type 'REAL) - type - (error-of-type 'error - (TEXT "~S: type ~S is not a subtype of ~S") - 'upgraded-complex-part-type type 'real))) - -;; ---------------------------------------------------------------------------- - -;; Macros for defining the various built-in "atomic type specifier"s and -;; "compound type specifier"s. The following macros add information for both -;; the TYPEP function above and the c-TYPEP in the compiler. - -; Alist symbol -> funname, used by the compiler. -(defparameter c-typep-alist1 '()) -; Alist symbol -> lambdabody, used by the compiler. -(defparameter c-typep-alist2 '()) -; Alist symbol -> expander function, used by the compiler. -(defparameter c-typep-alist3 '()) - -; (def-atomic-type symbol function-name) -; defines an atomic type. The function-name designates a function taking one -; argument and returning a generalized boolean value. It can be either a -; symbol or a lambda expression. -(defmacro def-atomic-type (symbol funname) - (let ((lambdap (and (consp funname) (eq (car funname) 'LAMBDA)))) - `(PROGN - (SETF (GET ',symbol 'TYPE-SYMBOL) - ,(if lambdap - `(FUNCTION ,(concat-pnames "TYPE-SYMBOL-" symbol) ,funname) - `(FUNCTION ,funname) - ) - ) - ,(if lambdap - `(SETQ C-TYPEP-ALIST2 - (NCONC C-TYPEP-ALIST2 (LIST (CONS ',symbol ',(cdr funname)))) - ) - `(SETQ C-TYPEP-ALIST1 - (NCONC C-TYPEP-ALIST1 (LIST (CONS ',symbol ',funname))) - ) - ) - ',symbol - ) -) ) - -; (def-compound-type symbol lambda-list (x) check-form typep-form c-typep-form) -; defines a compound type. The lambda-list is of the form (&optional ...) -; where the arguments come from the CDR of the type specifier. -; For typep-form, x is an object. -; For c-typep-form, x is a multiply evaluatable form (actually a gensym). -; check-form is a form performing error checking, may call `error'. -; typep-form should return a generalized boolean value. -; c-typep-form should produce a form returning a generalized boolean value. -(defmacro def-compound-type (symbol lambdalist (var) check-form typep-form c-typep-form) - `(PROGN - (SETF (GET ',symbol 'TYPE-LIST) - (FUNCTION ,(concat-pnames "TYPE-LIST-" symbol) - (LAMBDA (,var ,@lambdalist) - ,@(if check-form - `((MACROLET ((ERROR (&REST ERROR-ARGS) - (LIST* 'ERROR-OF-TYPE ''ERROR ERROR-ARGS) - )) - ,check-form - )) - ) - ,typep-form - ) ) ) - (SETQ C-TYPEP-ALIST3 - (NCONC C-TYPEP-ALIST3 - (LIST (CONS ',symbol - #'(LAMBDA (,var ,@lambdalist &REST ILLEGAL-ARGS) - (DECLARE (IGNORE ILLEGAL-ARGS)) - ,@(if check-form - `((MACROLET ((ERROR (&REST ERROR-ARGS) - (LIST 'PROGN - (LIST* 'C-WARN ERROR-ARGS) - '(THROW 'C-TYPEP NIL) - )) ) - ,check-form - )) - ) - ,c-typep-form - ) - ) ) ) ) - ',symbol - ) -) - -; CLtL1 p. 43 -(def-atomic-type ARRAY arrayp) -(def-atomic-type ATOM atom) -(def-atomic-type BASE-CHAR - #+BASE-CHAR=CHARACTER - characterp - #-BASE-CHAR=CHARACTER - (lambda (x) (and (characterp x) (base-char-p x))) -) -(def-atomic-type BASE-STRING - (lambda (x) - (and (stringp x) - (eq (array-element-type x) - #+BASE-CHAR=CHARACTER 'CHARACTER #-BASE-CHAR=CHARACTER 'BASE-CHAR -) ) ) ) -(def-atomic-type BIGNUM - (lambda (x) (and (integerp x) (not (fixnump x)))) -) -(def-atomic-type BIT - (lambda (x) (or (eql x 0) (eql x 1))) -) -(def-atomic-type BIT-VECTOR bit-vector-p) -(def-atomic-type BOOLEAN - (lambda (x) (or (eq x 'nil) (eq x 't))) -) -(def-atomic-type CHARACTER characterp) -(def-atomic-type COMPILED-FUNCTION compiled-function-p) -(def-atomic-type COMPLEX complexp) -(def-atomic-type CONS consp) -(def-atomic-type DOUBLE-FLOAT double-float-p) -(def-atomic-type ENCODING encodingp) -(def-atomic-type EXTENDED-CHAR - #+BASE-CHAR=CHARACTER - (lambda (x) (declare (ignore x)) nil) - #-BASE-CHAR=CHARACTER - (lambda (x) (and (characterp x) (not (base-char-p x)))) -) -(def-atomic-type FIXNUM fixnump) -(def-atomic-type FLOAT floatp) -(def-atomic-type FUNCTION functionp) -(def-atomic-type HASH-TABLE hash-table-p) -(def-atomic-type INTEGER integerp) -(def-atomic-type KEYWORD keywordp) -(def-atomic-type LIST listp) -#+LOGICAL-PATHNAMES -(def-atomic-type LOGICAL-PATHNAME logical-pathname-p) -(def-atomic-type LONG-FLOAT long-float-p) -(def-atomic-type NIL - (lambda (x) (declare (ignore x)) nil) -) -(def-atomic-type NULL null) -(def-atomic-type NUMBER numberp) -(def-atomic-type PACKAGE packagep) -(def-atomic-type PATHNAME pathnamep) -(def-atomic-type RANDOM-STATE random-state-p) -(def-atomic-type RATIO - (lambda (x) (and (rationalp x) (not (integerp x)))) -) -(def-atomic-type RATIONAL rationalp) -(def-atomic-type READTABLE readtablep) -(def-atomic-type REAL realp) -(def-atomic-type SEQUENCE sequencep) -(def-atomic-type SHORT-FLOAT short-float-p) -(def-atomic-type SIMPLE-ARRAY simple-array-p) -(def-atomic-type SIMPLE-BASE-STRING - (lambda (x) - (and (simple-string-p x) - (eq (array-element-type x) - #+BASE-CHAR=CHARACTER 'CHARACTER #-BASE-CHAR=CHARACTER 'BASE-CHAR -) ) ) ) -(def-atomic-type SIMPLE-BIT-VECTOR simple-bit-vector-p) -(def-atomic-type SIMPLE-STRING simple-string-p) -(def-atomic-type SIMPLE-VECTOR simple-vector-p) -(def-atomic-type SINGLE-FLOAT single-float-p) -(defun %standard-char-p (x) (and (characterp x) (standard-char-p x))) ; ABI -(def-atomic-type STANDARD-CHAR %standard-char-p) -(def-atomic-type CLOS:STANDARD-OBJECT clos::std-instance-p) -(def-atomic-type STREAM streamp) -(def-atomic-type FILE-STREAM file-stream-p) -(def-atomic-type SYNONYM-STREAM synonym-stream-p) -(def-atomic-type BROADCAST-STREAM broadcast-stream-p) -(def-atomic-type CONCATENATED-STREAM concatenated-stream-p) -(def-atomic-type TWO-WAY-STREAM two-way-stream-p) -(def-atomic-type ECHO-STREAM echo-stream-p) -(def-atomic-type STRING-STREAM string-stream-p) -(def-atomic-type STRING stringp) -(def-atomic-type STRING-CHAR characterp) -(def-atomic-type CLOS:STRUCTURE-OBJECT clos::structure-object-p) -(def-atomic-type SYMBOL symbolp) -(def-atomic-type T (lambda (x) (declare (ignore x)) t)) -;; foreign1.lisp is loaded after this file, -;; so these symbols are not external yet -#+ffi -(def-atomic-type ffi::foreign-function - (lambda (x) (eq 'ffi::foreign-function (type-of x)))) -#+ffi -(def-atomic-type ffi::foreign-variable - (lambda (x) (eq 'ffi::foreign-variable (type-of x)))) -#+ffi -(def-atomic-type ffi::foreign-address - (lambda (x) (eq 'ffi::foreign-address (type-of x)))) -;; see lispbibl.d (#define FOREIGN) and predtype.d (TYPE-OF): -#+(or unix ffi affi win32) -(def-atomic-type foreign-pointer - (lambda (x) (eq 'foreign-pointer (type-of x)))) -(def-atomic-type VECTOR vectorp) -(def-atomic-type PLIST - (lambda (x) (multiple-value-bind (length tail) (list-length-dotted x) - (and (null tail) (evenp length))))) - -(defmacro ensure-dim (type dim) - ;; make sure DIM is a valid dimension - `(unless (or (eq ,dim '*) (typep ,dim `(INTEGER 0 (,ARRAY-DIMENSION-LIMIT)))) - (error (TEXT "~S: dimension ~S is invalid") ',type ,dim))) - -(defmacro ensure-rank (type rank) - ;; make sure RANK is a valid rank - `(unless (typep ,rank `(INTEGER 0 (,ARRAY-RANK-LIMIT))) - (error (TEXT "~S: rank ~S is invalid") ',type ,rank))) - -; CLtL1 p. 46-50 -(defun c-typep-array (tester el-type dims x) - `(AND (,tester ,x) - ,@(if (eq el-type '*) - '() - `((EQUAL (ARRAY-ELEMENT-TYPE ,x) ',(upgraded-array-element-type el-type))) - ) - ,@(if (eq dims '*) - '() - (if (numberp dims) - `((EQL ,dims (ARRAY-RANK ,x))) - `((EQL ,(length dims) (ARRAY-RANK ,x)) - ,@(let ((i 0)) - (mapcap #'(lambda (dim) - (prog1 - (if (eq dim '*) - '() - `((EQL ',dim (ARRAY-DIMENSION ,x ,i))) - ) - (incf i) - ) ) - dims - ) ) - ) - ) ) - ) -) -(defun c-typep-vector (tester size x) - `(AND (,tester ,x) - ,@(if (eq size '*) - '() - `((EQL ',size (ARRAY-DIMENSION ,x 0))) - ) - ) -) -(defun typep-number-test (x low high test type) - (and (funcall test x) - (cond ((eq low '*)) - ((funcall test low) (<= low x)) - ((and (consp low) (null (rest low)) (funcall test (first low))) - (< (first low) x) - ) - (t (error-of-type 'error - #1=(TEXT "~S: argument to ~S must be *, ~S or a list of ~S: ~S") - 'typep type type type low - ) ) ) - (cond ((eq high '*)) - ((funcall test high) (>= high x)) - ((and (consp high) (null (rest high)) (funcall test (first high))) - (> (first high) x) - ) - (t (error-of-type 'error - #1# 'typep type type type high -) ) ) ) ) -(defun c-typep-number (caller tester low high x) - `(AND (,tester ,x) - ,@(cond ((eq low '*) '()) - ((funcall tester low) `((<= ,low ,x))) - ((and (consp low) (null (rest low)) (funcall tester (first low))) - `((< ,(first low) ,x)) - ) - (t (c-warn #1=(TEXT "~S: argument to ~S must be *, ~S or a list of ~S: ~S") - 'typep caller caller caller low - ) - (throw 'c-TYPEP nil) - ) ) - ,@(cond ((eq high '*) '()) - ((funcall tester high) `((>= ,high ,x))) - ((and (consp high) (null (rest high)) (funcall tester (first high))) - `((> ,(first high) ,x)) - ) - (t (c-warn #1# 'typep caller caller caller high) - (throw 'c-TYPEP nil) - ) ) - ) -) -(def-compound-type ARRAY (&optional (el-type '*) (dims '*)) (x) - (unless (eq dims '*) - (if (numberp dims) - (ensure-rank ARRAY dims) - (dolist (dim dims) (ensure-dim ARRAY dim)))) - (and (arrayp x) - (or (eq el-type '*) - (equal (array-element-type x) (upgraded-array-element-type el-type)) - ) - (or (eq dims '*) - (if (numberp dims) - (eql dims (array-rank x)) - (and (eql (length dims) (array-rank x)) - (every #'(lambda (a b) (or (eq a '*) (eql a b))) - dims (array-dimensions x) - ) ) ) ) ) - (c-typep-array 'ARRAYP el-type dims x) -) -(def-compound-type SIMPLE-ARRAY (&optional (el-type '*) (dims '*)) (x) - (unless (eq dims '*) - (if (numberp dims) - (ensure-rank SIMPLE-ARRAY dims) - (dolist (dim dims) (ensure-dim SIMPLE-ARRAY dim)))) - (and (simple-array-p x) - (or (eq el-type '*) - (equal (array-element-type x) (upgraded-array-element-type el-type)) - ) - (or (eq dims '*) - (if (numberp dims) - (eql dims (array-rank x)) - (and (eql (length dims) (array-rank x)) - (every #'(lambda (a b) (or (eq a '*) (eql a b))) - dims (array-dimensions x) - ) ) ) ) ) - (c-typep-array 'SIMPLE-ARRAY-P el-type dims x) -) -(def-compound-type VECTOR (&optional (el-type '*) (size '*)) (x) - (ensure-dim VECTOR size) - (and (vectorp x) - (or (eq el-type '*) - (equal (array-element-type x) (upgraded-array-element-type el-type)) - ) - (or (eq size '*) (eql (array-dimension x 0) size)) - ) - `(AND (VECTORP ,x) - ,@(if (eq el-type '*) - '() - `((EQUAL (ARRAY-ELEMENT-TYPE ,x) ',(upgraded-array-element-type el-type))) - ) - ,@(if (eq size '*) - '() - `((EQL (ARRAY-DIMENSION ,x 0) ',size)) - ) - ) -) -(def-compound-type SIMPLE-VECTOR (&optional (size '*)) (x) - (ensure-dim SIMLPE-VECTOR size) - (and (simple-vector-p x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'SIMPLE-VECTOR-P size x) -) -(def-compound-type COMPLEX (&optional (rtype '*) (itype rtype)) (x) - nil - (and (complexp x) - (or (eq rtype '*) - (typep (realpart x) (upgraded-complex-part-type rtype))) - (or (eq itype '*) - (typep (imagpart x) (upgraded-complex-part-type itype)))) - `(AND (COMPLEXP ,x) - ,@(if (eq rtype '*) - '() - `((TYPEP (REALPART ,x) ',(upgraded-complex-part-type rtype)))) - ,@(if (eq itype '*) - '() - `((TYPEP (IMAGPART ,x) ',(upgraded-complex-part-type itype)))))) -(def-compound-type INTEGER (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'integerp 'INTEGER) - (c-typep-number 'INTEGER 'INTEGERP low high x) -) -(def-compound-type MOD (n) (x) - (unless (integerp n) - (error (TEXT "~S: argument to MOD must be an integer: ~S") - 'typep n - ) ) - (and (integerp x) (<= 0 x) (< x n)) - `(AND (INTEGERP ,x) (NOT (MINUSP ,x)) (< ,x ,n)) -) -(def-compound-type SIGNED-BYTE (&optional (n '*)) (x) - (unless (or (eq n '*) (integerp n)) - (error (TEXT "~S: argument to SIGNED-BYTE must be an integer or * : ~S") - 'typep n - ) ) - (and (integerp x) (or (eq n '*) (< (integer-length x) n))) - `(AND (INTEGERP ,x) - ,@(if (eq n '*) '() `((< (INTEGER-LENGTH ,x) ,n))) - ) -) -(def-compound-type UNSIGNED-BYTE (&optional (n '*)) (x) - (unless (or (eq n '*) (integerp n)) - (error (TEXT "~S: argument to UNSIGNED-BYTE must be an integer or * : ~S") - 'typep n - ) ) - (and (integerp x) - (not (minusp x)) - (or (eq n '*) (<= (integer-length x) n)) - ) - `(AND (INTEGERP ,x) (NOT (MINUSP ,x)) - ,@(if (eq n '*) '() `((<= (INTEGER-LENGTH ,x) ,n))) - ) -) -(def-compound-type REAL (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'realp 'REAL) - (c-typep-number 'REAL 'REALP low high x) -) -(def-compound-type RATIONAL (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'rationalp 'RATIONAL) - (c-typep-number 'RATIONAL 'RATIONALP low high x) -) -(def-compound-type FLOAT (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'floatp 'FLOAT) - (c-typep-number 'FLOAT 'FLOATP low high x) -) -(def-compound-type SHORT-FLOAT (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'short-float-p 'SHORT-FLOAT) - (c-typep-number 'SHORT-FLOAT 'SHORT-FLOAT-P low high x) -) -(def-compound-type SINGLE-FLOAT (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'single-float-p 'SINGLE-FLOAT) - (c-typep-number 'SINGLE-FLOAT 'SINGLE-FLOAT-P low high x) -) -(def-compound-type DOUBLE-FLOAT (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'double-float-p 'DOUBLE-FLOAT) - (c-typep-number 'DOUBLE-FLOAT 'DOUBLE-FLOAT-P low high x) -) -(def-compound-type LONG-FLOAT (&optional (low '*) (high '*)) (x) - nil - (typep-number-test x low high #'long-float-p 'LONG-FLOAT) - (c-typep-number 'LONG-FLOAT 'LONG-FLOAT-P low high x) -) -(def-compound-type STRING (&optional (size '*)) (x) - (ensure-dim STRING size) - (and (stringp x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'STRINGP size x) -) -(def-compound-type SIMPLE-STRING (&optional (size '*)) (x) - (ensure-dim SIMPLE-STRING size) - (and (simple-string-p x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'SIMPLE-STRING-P size x) -) -(def-compound-type BASE-STRING (&optional (size '*)) (x) - (ensure-dim BASE-STRING size) - (and (stringp x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'STRINGP size x) -) -(def-compound-type SIMPLE-BASE-STRING (&optional (size '*)) (x) - (ensure-dim SIMPLE-BASE-STRING size) - (and (simple-string-p x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'SIMPLE-STRING-P size x) -) -(def-compound-type BIT-VECTOR (&optional (size '*)) (x) - (ensure-dim BIT-VECTOR size) - (and (bit-vector-p x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'BIT-VECTOR-P size x) -) -(def-compound-type SIMPLE-BIT-VECTOR (&optional (size '*)) (x) - (ensure-dim SIMPLE-BIT-VECTOR size) - (and (simple-bit-vector-p x) - (or (eq size '*) (eql size (array-dimension x 0))) - ) - (c-typep-vector 'SIMPLE-BIT-VECTOR-P size x) -) -(def-compound-type CONS (&optional (car-type '*) (cdr-type '*)) (x) - nil - (and (consp x) - (or (eq car-type '*) (typep (car x) car-type)) - (or (eq cdr-type '*) (typep (cdr x) cdr-type)) - ) - `(AND (CONSP ,x) - ,@(if (eq car-type '*) '() `((TYPEP (CAR ,x) ',car-type))) - ,@(if (eq cdr-type '*) '() `((TYPEP (CDR ,x) ',cdr-type))) - ) -) - -(fmakunbound 'def-compound-type) - -;; ---------------------------------------------------------------------------- - -; Typtest ohne Gefahr einer Fehlermeldung. Für SIGNAL und HANDLER-BIND. -(defun safe-typep (x y &optional env) - (let ((*error-handler* - #'(lambda (&rest error-args) - (declare (ignore error-args)) - (return-from safe-typep (values nil nil)) - )) ) - (values (typep x y env) t) -) ) - -; Umwandlung eines "type for declaration" in einen "type for discrimination". -(defun type-for-discrimination (y &optional (notp nil) &aux f) - (cond ((symbolp y) - (cond ((get y 'TYPE-SYMBOL) y) - ((get y 'TYPE-LIST) y) - ((setq f (get y 'DEFTYPE-EXPANDER)) - (let* ((z (funcall f (list y))) - (zx (type-for-discrimination z notp))) - (if (eql zx z) y zx) - )) - (t y) - ) ) - ((and (consp y) (symbolp (first y))) - (case (first y) - ((SATISFIES MEMBER EQL) y) - (NOT - (let* ((z (second y)) - (zx (type-for-discrimination z (not notp)))) - (if (eql zx z) y `(NOT ,zx)) - )) - ((AND OR COMPLEX VALUES) - (let* ((z (rest y)) - (zx (mapcar #'(lambda (x) (type-for-discrimination x notp)) z))) - (if (every #'eql z zx) y (cons (first y) zx)) - )) - (FUNCTION - ;; (FUNCTION arg-types res-type) is somewhere between - ;; NIL and FUNCTION, but undecidable. - (if notp 'NIL 'FUNCTION) - ) - (t (cond ((get (first y) 'TYPE-LIST) y) - ((setq f (get (first y) 'DEFTYPE-EXPANDER)) - (let* ((z (funcall f y)) - (zx (type-for-discrimination z notp))) - (if (eql zx z) y zx) - )) - (t y) - ) ) ) ) - (t y) -) ) - -; Testet eine Liste von Werten auf Erfüllen eines Type-Specifiers. Für THE. -(defun %the (values type) ; ABI - (macrolet ((near-typep (objform typform) - ;; near-typep ist wie typep, nur dass das Objekt auch ein - ;; Read-Label sein darf. Das tritt z.B. auf bei - ;; (read-from-string "#1=#S(FOO :X #1#)") - ;; im Konstruktor MAKE-FOO. Die Implementation ist aber - ;; nicht gezwungen, bei fehlerhaftem THE zwingend einen - ;; Fehler zu melden, darum ist ein lascherer Typcheck hier - ;; erlaubt. - (let ((g (gensym))) - `(let ((,g ,objform)) - (or (typep ,g ,typform) (eq (type-of ,g) 'READ-LABEL)))))) - (if (and (consp type) (eq (car type) 'VALUES)) - ;; The VALUES type specifier is ill-defined in ANSI CL. - ;; - ;; There are two possibilities to define a VALUES type specifier in a - ;; sane way: - ;; - (EXACT-VALUES type1 ... [&optional ...]) describes the exact shape - ;; of the values list, as received by MULTIPLE-VALUE-LIST. - ;; For example, (EXACT-VALUES SYMBOL) is matched by (values 'a) but not - ;; by (values 'a 'b) or (values). - ;; - (ASSIGNABLE-VALUES type1 ... [&optional ...]) describes the values - ;; as received by a set of variables through MULTIPLE-VALUE-BIND or - ;; MULTIPLE-VALUE-SETQ. For example, (ASSIGNABLE-VALUES SYMBOL) is - ;; defined by whether - ;; (MULTIPLE-VALUE-BIND (var1) values (DECLARE (TYPE SYMBOL var1)) ...) - ;; is valid or not; therefore (ASSIGNABLE-VALUES SYMBOL) is matched by - ;; (values 'a) and (values 'a 'b) and (values). - ;; Note that &OPTIONAL is actually redundant here: - ;; (ASSIGNABLE-VALUES type1 ... &optional otype1 ...) - ;; is equivalent to - ;; (ASSIGNABLE-VALUES type1 ... (OR NULL otype1) ...) - ;; HyperSpec/Body/typspe_values.html indicates that VALUES means - ;; EXACT-VALUES; however, HyperSpec/Body/speope_the.html indicates that - ;; VALUES means ASSIGNABLE-VALUES. - ;; - ;; SBCL interprets the VALUES type specifier to mean EXACT-VALUES when - ;; it contains &OPTIONAL or &REST, but ASSIGNABLE-VALUES when it has - ;; only a tuple of type specifiers. This is utter nonsense, in particular - ;; because it makes (VALUES type1 ... typek &OPTIONAL) - ;; different from (VALUES type1 ... typek). - ;; - ;; Here we use the ASSIGNABLE-VALUES interpretation. - ;; In SUBTYPEP we just punt and don't assume any interpretation. - (let ((vals values) (types (cdr type))) - ;; required: - (loop - (when (or (atom types) (atom vals)) (return-from %the t)) - (when (memq (car types) lambda-list-keywords) (return)) - (unless (near-typep (pop vals) (pop types)) - (return-from %the nil))) - ;; &optional: - (when (and (consp types) (eq (car types) '&optional)) - (setq types (cdr types)) - (loop - (when (or (atom types) (atom vals)) (return-from %the t)) - (when (memq (car types) lambda-list-keywords) (return)) - (unless (near-typep (pop vals) (pop types)) - (return-from %the nil)))) - ;; &rest &key: - (case (car types) - (&rest - (setq types (cdr types)) - (when (atom types) (typespec-error 'the type)) - (unless (near-typep (pop vals) (pop types)) - (return-from %the nil))) - (&key) - (t (typespec-error 'the type))) - (if (eq (car types) '&key) - (progn - (setq types (cdr types)) - (when (oddp (length vals)) (return-from %the nil)) - (let ((keywords nil)) - (loop - (when (or (atom types) (atom vals)) (return-from %the t)) - (when (memq (car types) lambda-list-keywords) (return)) - (let ((item (pop types))) - (unless (and (listp item) (eql (length item) 2) - (symbolp (first item))) - (typespec-error 'the type)) - (let ((kw (symbol-to-keyword (first item)))) - (unless (near-typep (getf vals kw) (second item)) - (return-from %the nil)) - (push kw keywords)))) - (if (and (consp types) (eq (car types) '&allow-other-keys)) - (setq types (cdr types)) - (unless (getf vals ':allow-other-keys) - (do ((L vals (cddr L))) - ((atom L)) - (unless (memq (car L) keywords) - (return-from %the nil))))))) - (when (consp types) (typespec-error 'the type))) - t) - (near-typep (if (consp values) (car values) nil) type)))) - -;;; =========================================================================== - -;; SUBTYPEP -(load "subtypep") - - -;; Returns the number of bytes that are needed to represent #\Null in a -;; given encoding. -(defun encoding-zeroes (encoding) - #+UNICODE - ;; this should use min_bytes_per_char for cache, not the hash table - (let ((name (ext:encoding-charset encoding)) - (table #.(make-hash-table :key-type '(or string symbol) :value-type 'fixnum - :test 'stablehash-equal :warn-if-needs-rehash-after-gc t - :initial-contents '(("UTF-7" . 1)))) - (tester #.(make-string 2 :initial-element (code-char 0)))) - (or (gethash name table) - (setf (gethash name table) - (- (length (ext:convert-string-to-bytes tester encoding)) - (length (ext:convert-string-to-bytes tester encoding - :end 1)))))) - #-UNICODE 1) - -;; Determines two values low,high such that -;; (subtypep type `(INTEGER ,low ,high)) -;; holds and low is as large as possible and high is as small as possible. -;; low = * means -infinity, high = * means infinity. -;; When (subtypep type 'INTEGER) is false, the values NIL,NIL are returned. -;; We need this function only for MAKE-ARRAY, UPGRADED-ARRAY-ELEMENT-TYPE and -;; OPEN and can therefore w.l.o.g. replace -;; type with `(OR ,type (MEMBER 0)) -#| ;; The original implementation calls canonicalize-type and then applies - ;; a particular SUBTYPE variant: - (defun subtype-integer (type) - (macrolet ((yes () '(return-from subtype-integer (values low high))) - (no () '(return-from subtype-integer nil)) - (unknown () '(return-from subtype-integer nil))) - (setq type (canonicalize-type type)) - (if (consp type) - (case (first type) - (MEMBER ; (MEMBER &rest objects) - ;; All elements must be of type INTEGER. - (let ((low 0) (high 0)) ; wlog! - (dolist (x (rest type) (yes)) - (unless (typep x 'INTEGER) (return (no))) - (setq low (min low x) high (max high x))))) - (OR ; (OR type*) - ;; Every type must be subtype of INTEGER. - (let ((low 0) (high 0)) ; wlog! - (dolist (type1 (rest type) (yes)) - (multiple-value-bind (low1 high1) (subtype-integer type1) - (unless low1 (return (no))) - (setq low (if (or (eq low '*) (eq low1 '*)) '* (min low low1)) - high (if (or (eq high '*) (eq high1 '*)) - '* (max high high1))))))) - (AND ; (AND type*) - ;; If one of the types is subtype of INTEGER, then yes, - ;; otherwise unknown. - (let ((low nil) (high nil)) - (dolist (type1 (rest type)) - (multiple-value-bind (low1 high1) (subtype-integer type1) - (when low1 - (if low - (setq low (if (eq low '*) low1 (if (eq low1 '*) low (max low low1))) - high (if (eq high '*) high1 (if (eq high1 '*) high (min high high1)))) - (setq low low1 high high1))))) - (if low - (progn - (when (and (numberp low) (numberp high) (not (<= low high))) - (setq low 0 high 0) ; type equivalent to NIL) - (yes)) - (unknown))))) - (setq type (list type))) - (if (eq (first type) 'INTEGER) - (let ((low (if (rest type) (second type) '*)) - (high (if (cddr type) (third type) '*))) - (when (consp low) - (setq low (first low)) - (when (numberp low) (incf low))) - (when (consp high) - (setq high (first high)) - (when (numberp high) (decf high))) - (when (and (numberp low) (numberp high) (not (<= low high))) ; type leer? - (setq low 0 high 0)) - (yes)) - (if (and (eq (first type) 'INTERVALS) (eq (second type) 'INTEGER)) - (let ((low (third type)) - (high (car (last type)))) - (when (consp low) - (setq low (first low)) - (when (numberp low) (incf low))) - (when (consp high) - (setq high (first high)) - (when (numberp high) (decf high))) - (yes)) - (unknown))))) -|# ;; This implementation inlines the (tail-recursive) canonicalize-type - ;; function. Its advantage is that it doesn't cons as much. - ;; (For example, (subtype-integer '(UNSIGNED-BYTE 8)) doesn't cons.) -(defun subtype-integer (type) - (macrolet ((yes () '(return-from subtype-integer (values low high))) - (no () '(return-from subtype-integer nil)) - (unknown () '(return-from subtype-integer nil))) - (setq type (expand-deftype type)) - (cond ((symbolp type) - (case type - (BIT (let ((low 0) (high 1)) (yes))) - (FIXNUM - (let ((low '#,most-negative-fixnum) - (high '#,most-positive-fixnum)) - (yes))) - ((INTEGER BIGNUM SIGNED-BYTE) - (let ((low '*) (high '*)) (yes))) - (UNSIGNED-BYTE - (let ((low 0) (high '*)) (yes))) - ((NIL) - (let ((low 0) (high 0)) (yes))) ; wlog! - (t (no)))) - ((and (consp type) (symbolp (first type))) - (unless (and (list-length type) (null (cdr (last type)))) - (typespec-error 'subtypep type)) - (case (first type) - (MEMBER ; (MEMBER &rest objects) - ;; All elements must be of type INTEGER. - (let ((low 0) (high 0)) ; wlog! - (dolist (x (rest type) (yes)) - (unless (typep x 'INTEGER) (return (no))) - (setq low (min low x) high (max high x))))) - (EQL ; (EQL object) - (let ((x (second type))) - (if (typep x 'INTEGER) - (let ((low (min 0 x)) (high (max 0 x))) (yes)) - (no)))) - (OR ; (OR type*) - ;; Every type must be subtype of INTEGER. - (let ((low 0) (high 0)) ; wlog! - (dolist (type1 (rest type) (yes)) - (multiple-value-bind (low1 high1) (subtype-integer type1) - (unless low1 (return (no))) - (setq low (if (or (eq low '*) (eq low1 '*)) - '* (min low low1)) - high (if (or (eq high '*) (eq high1 '*)) - '* (max high high1))))))) - (AND ; (AND type*) - ;; If one of the types is subtype of INTEGER, then yes, - ;; otherwise unknown. - (let ((low nil) (high nil)) - (dolist (type1 (rest type)) - (multiple-value-bind (low1 high1) (subtype-integer type1) - (when low1 - (if low - (setq low (if (eq low '*) low1 - (if (eq low1 '*) low - (max low low1))) - high (if (eq high '*) high1 - (if (eq high1 '*) high - (min high high1)))) - (setq low low1 - high high1))))) - (if low - (progn - (when (and (numberp low) (numberp high) - (not (<= low high))) - (setq low 0 high 0)) ; type equivalent to NIL - (yes)) - (unknown)))) - (INTEGER - (let ((low (if (rest type) (second type) '*)) - (high (if (cddr type) (third type) '*))) - (when (consp low) - (setq low (first low)) - (when (numberp low) (incf low))) - (when (consp high) - (setq high (first high)) - (when (numberp high) (decf high))) - (when (and (numberp low) (numberp high) (not (<= low high))) - (setq low 0 high 0)) ; type equivalent to NIL - (yes))) - (INTERVALS - (if (eq (second type) 'INTEGER) - (let ((low (third type)) - (high (car (last type)))) - (when (consp low) - (setq low (first low)) - (when (numberp low) (incf low))) - (when (consp high) - (setq high (first high)) - (when (numberp high) (decf high))) - (yes)) - (unknown))) - (MOD ; (MOD n) - (let ((n (second type))) - (unless (and (integerp n) (>= n 0)) - (typespec-error 'subtypep type)) - (if (eql n 0) - (no) - (let ((low 0) (high (1- n))) - (yes))))) - (SIGNED-BYTE ; (SIGNED-BYTE &optional s) - (let ((s (if (cdr type) (second type) '*))) - (if (eq s '*) - (let ((low '*) (high '*)) (yes)) - (progn - (unless (and (integerp s) (plusp s)) - (typespec-error 'subtypep type)) - (let ((n (ash 1 (1- s)))) ; (ash 1 *) == (expt 2 *) - (let ((low (- n)) (high (1- n))) - (yes))))))) - (UNSIGNED-BYTE ; (UNSIGNED-BYTE &optional s) - (let ((s (if (cdr type) (second type) '*))) - (if (eq s '*) - (let ((low 0) (high '*)) (yes)) - (progn - (unless (and (integerp s) (>= s 0)) - (typespec-error 'subtypep type)) - (let ((n (ash 1 s))) ; (ash 1 *) == (expt 2 *) - (let ((low 0) (high (1- n))) - (yes))))))) - (t (no)))) - ((clos::defined-class-p type) - (if (and (clos::built-in-class-p type) - (eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type)) - (return-from subtype-integer - (subtype-integer (clos:class-name type))) - (no))) - ((clos::eql-specializer-p type) - (let ((x (clos::eql-specializer-singleton type))) - (if (typep x 'INTEGER) - (let ((low (min 0 x)) (high (max 0 x))) (yes)) - (no)))) - ((encodingp type) (no)) - (t (typespec-error 'subtypep type))))) - -#| TODO: Fix subtype-integer such that this works. -Henry Baker: - (defun type-null (x) - (values (and (eq 'bit (upgraded-array-element-type `(or bit ,x))) - (not (typep 0 x)) - (not (typep 1 x))) - t)) - (type-null '(and symbol number)) - (type-null '(and integer symbol)) - (type-null '(and integer character)) -|# - -;; Determines a sequence kind (an atom, as defined in defseq.lisp: one of -;; LIST - stands for LIST -;; VECTOR - stands for (VECTOR T) -;; STRING - stands for (VECTOR CHARACTER) -;; 1, 2, 4, 8, 16, 32 - stands for (VECTOR (UNSIGNED-BYTE n)) -;; 0 - stands for (VECTOR NIL)) -;; that indicates the sequence type meant by the given type. Other possible -;; return values are -;; SEQUENCE - denoting a type whose intersection with (OR LIST VECTOR) is not -;; subtype of LIST or VECTOR, or -;; NIL - indicating a type whose intersection with (OR LIST VECTOR) is empty. -;; When the type is (OR (VECTOR eltype1) ... (VECTOR eltypeN)), the chosen -;; element type is the smallest element type that contains all of eltype1 ... -;; eltypeN. -;; -;; User-defined sequence types are not supported here. -;; -;; This implementation inlines the (tail-recursive) canonicalize-type -;; function. Its advantage is that it doesn't cons as much. Also it employs -;; some heuristics and does not have the full power of SUBTYPEP. -(defun subtype-sequence (type) - (setq type (expand-deftype type)) - (cond ((symbolp type) - (case type - ((LIST CONS NULL) 'LIST) - ((NIL) 'NIL) - ((BIT-VECTOR SIMPLE-BIT-VECTOR) '1) - ((STRING SIMPLE-STRING BASE-STRING SIMPLE-BASE-STRING) 'STRING) - ((VECTOR SIMPLE-VECTOR ARRAY SIMPLE-ARRAY) 'VECTOR) - ((SEQUENCE) 'SEQUENCE) - (t 'NIL))) - ((and (consp type) (symbolp (first type))) - (unless (and (list-length type) (null (cdr (last type)))) - (typespec-error 'subtypep type)) - (case (first type) - (MEMBER ; (MEMBER &rest objects) - (let ((kind 'NIL)) - (dolist (x (rest type)) - (setq kind (sequence-type-union kind (type-of-sequence x)))) - kind)) - (EQL ; (EQL object) - (unless (eql (length type) 2) - (typespec-error 'subtypep type)) - (type-of-sequence (second type))) - (OR ; (OR type*) - (let ((kind 'NIL)) - (dolist (x (rest type)) - (setq kind (sequence-type-union kind (subtype-sequence x)))) - kind)) - (AND ; (AND type*) - (let ((kind 'SEQUENCE)) - (dolist (x (rest type)) - (setq kind (sequence-type-intersection kind (subtype-sequence x)))) - kind)) - ((SIMPLE-BIT-VECTOR BIT-VECTOR) ; (SIMPLE-BIT-VECTOR &optional size) - (when (cddr type) - (typespec-error 'subtypep type)) - '1) - ((SIMPLE-STRING STRING SIMPLE-BASE-STRING BASE-STRING) ; (SIMPLE-STRING &optional size) - (when (cddr type) - (typespec-error 'subtypep type)) - 'STRING) - (SIMPLE-VECTOR ; (SIMPLE-VECTOR &optional size) - (when (cddr type) - (typespec-error 'subtypep type)) - 'VECTOR) - ((VECTOR ARRAY SIMPLE-ARRAY) ; (VECTOR &optional el-type size), (ARRAY &optional el-type dimensions) - (when (cdddr type) - (typespec-error 'subtypep type)) - (let ((el-type (if (cdr type) (second type) '*))) - (if (eq el-type '*) - 'VECTOR - (let ((eltype (upgraded-array-element-type el-type))) - (cond ((eq eltype 'T) 'VECTOR) - ((eq eltype 'CHARACTER) 'STRING) - ((eq eltype 'BIT) '1) - ((and (consp eltype) (eq (first eltype) 'UNSIGNED-BYTE)) (second eltype)) - ((eq eltype 'NIL) '0) - (t (error (TEXT "~S is not up-to-date with ~S for element type ~S") - 'subtypep-sequence 'upgraded-array-element-type eltype))))))) - ((CONS) ; (CONS &optional cartype cdrtype) - (when (cdddr type) - (typespec-error 'subtypep type)) - 'LIST) - (t 'NIL))) - ((clos::defined-class-p type) - (if (and (clos::built-in-class-p type) - (eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type)) - (subtype-sequence (clos:class-name type)) - 'NIL)) - ((clos::eql-specializer-p type) - (type-of-sequence (clos::eql-specializer-singleton type))) - (t 'NIL))) -(defun type-of-sequence (x) - (cond ((listp x) 'LIST) - ((vectorp x) - (let ((eltype (array-element-type x))) - (cond ((eq eltype 'T) 'VECTOR) - ((eq eltype 'CHARACTER) 'STRING) - ((eq eltype 'BIT) '1) - ((and (consp eltype) (eq (first eltype) 'UNSIGNED-BYTE)) (second eltype)) - ((eq eltype 'NIL) '0) - (t (error (TEXT "~S is not up-to-date with ~S for element type ~S") - 'type-of-sequence 'array-element-type eltype))))) - (t 'NIL))) -(defun sequence-type-union (t1 t2) - (cond ; Simple general rules. - ((eql t1 t2) t1) - ((eq t1 'NIL) t2) - ((eq t2 'NIL) t1) - ; Now the union of two different types. - ((or (eq t1 'SEQUENCE) (eq t2 'SEQUENCE)) 'SEQUENCE) - ((or (eq t1 'LIST) (eq t2 'LIST)) - ; union of LIST and a vector type - 'SEQUENCE) - ((or (eq t1 'VECTOR) (eq t2 'VECTOR)) 'VECTOR) - ((eql t1 0) t2) - ((eql t2 0) t1) - ((or (eq t1 'STRING) (eq t2 'STRING)) - ; union of STRING and an integer-vector type - 'VECTOR) - (t (max t1 t2)))) -(defun sequence-type-intersection (t1 t2) - (cond ; Simple general rules. - ((eql t1 t2) t1) - ((or (eq t1 'NIL) (eq t2 'NIL)) 'NIL) - ; Now the intersection of two different types. - ((eq t1 'SEQUENCE) t2) - ((eq t2 'SEQUENCE) t1) - ((or (eq t1 'LIST) (eq t2 'LIST)) - ; intersection of LIST and a vector type - 'NIL) - ((eq t1 'VECTOR) t2) - ((eq t2 'VECTOR) t1) - ((or (eql t1 0) (eql t2 0)) '0) - ((or (eq t1 'STRING) (eq t2 'STRING)) - ; intersection of STRING and an integer-vector type - '0) - (t (min t1 t2)))) - -;; ============================================================================ - -(defun type-expand (typespec &optional once-p) - (multiple-value-bind (expanded user-defined-p) - (expand-deftype typespec once-p) - (if user-defined-p (values expanded user-defined-p) - (cond ((symbolp typespec) - (cond ((or (get typespec 'TYPE-SYMBOL) (get typespec 'TYPE-LIST)) - (values typespec nil)) - ((or (get typespec 'DEFSTRUCT-DESCRIPTION) - (clos-class typespec)) - (values typespec nil)) - (t (typespec-error 'type-expand typespec)))) - ((and (consp typespec) (symbolp (first typespec))) - (case (first typespec) - ((SATISFIES MEMBER EQL NOT AND OR) (values typespec nil)) - (t (cond ((get (first typespec) 'TYPE-LIST) - (values typespec nil)) - (t (typespec-error 'type-expand typespec)))))) - ((clos::defined-class-p typespec) (values typespec nil)) - (t (typespec-error 'type-expand typespec)))))) - -;; ============================================================================ - -(unless (clos::funcallable-instance-p #'clos::class-name) - (fmakunbound 'clos::class-name)) - - -(keywordp :junk) - T - -(keywordp ::junk) - T - -(symbol-name ::junk) - "JUNK" - -(symbol-name :#junk) - "#JUNK" - -(symbol-name :#.junk) - "#.JUNK" diff --git a/third_party/pygments/tests/examplefiles/underscore.coffee b/third_party/pygments/tests/examplefiles/underscore.coffee deleted file mode 100644 index a34a1ce86..000000000 --- a/third_party/pygments/tests/examplefiles/underscore.coffee +++ /dev/null @@ -1,603 +0,0 @@ - - # Underscore.coffee - # (c) 2010 Jeremy Ashkenas, DocumentCloud Inc. - # Underscore is freely distributable under the terms of the MIT license. - # Portions of Underscore are inspired by or borrowed from Prototype.js, - # Oliver Steele's Functional, and John Resig's Micro-Templating. - # For all details and documentation: - # http://documentcloud.github.com/underscore/ - - - # ------------------------- Baseline setup --------------------------------- - - # Establish the root object, "window" in the browser, or "global" on the server. - root: this - - - # Save the previous value of the "_" variable. - previousUnderscore: root._ - - - # If Underscore is called as a function, it returns a wrapped object that - # can be used OO-style. This wrapper holds altered versions of all the - # underscore functions. Wrapped objects may be chained. - wrapper: (obj) -> - this._wrapped: obj - this - - - # Establish the object that gets thrown to break out of a loop iteration. - breaker: if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration - - - # Create a safe reference to the Underscore object forreference below. - _: root._: (obj) -> new wrapper(obj) - - - # Export the Underscore object for CommonJS. - if typeof(exports) != 'undefined' then exports._: _ - - - # Create quick reference variables for speed access to core prototypes. - slice: Array::slice - unshift: Array::unshift - toString: Object::toString - hasOwnProperty: Object::hasOwnProperty - propertyIsEnumerable: Object::propertyIsEnumerable - - - # Current version. - _.VERSION: '0.5.7' - - - # ------------------------ Collection Functions: --------------------------- - - # The cornerstone, an each implementation. - # Handles objects implementing forEach, arrays, and raw objects. - _.each: (obj, iterator, context) -> - index: 0 - try - return obj.forEach(iterator, context) if obj.forEach - if _.isArray(obj) or _.isArguments(obj) - return iterator.call(context, obj[i], i, obj) for i in [0...obj.length] - iterator.call(context, val, key, obj) for key, val of obj - catch e - throw e if e isnt breaker - obj - - - # Return the results of applying the iterator to each element. Use JavaScript - # 1.6's version of map, if possible. - _.map: (obj, iterator, context) -> - return obj.map(iterator, context) if (obj and _.isFunction(obj.map)) - results: [] - _.each obj, (value, index, list) -> - results.push(iterator.call(context, value, index, list)) - results - - - # Reduce builds up a single result from a list of values. Also known as - # inject, or foldl. Uses JavaScript 1.8's version of reduce, if possible. - _.reduce: (obj, memo, iterator, context) -> - return obj.reduce(_.bind(iterator, context), memo) if (obj and _.isFunction(obj.reduce)) - _.each obj, (value, index, list) -> - memo: iterator.call(context, memo, value, index, list) - memo - - - # The right-associative version of reduce, also known as foldr. Uses - # JavaScript 1.8's version of reduceRight, if available. - _.reduceRight: (obj, memo, iterator, context) -> - return obj.reduceRight(_.bind(iterator, context), memo) if (obj and _.isFunction(obj.reduceRight)) - _.each _.clone(_.toArray(obj)).reverse(), (value, index) -> - memo: iterator.call(context, memo, value, index, obj) - memo - - - # Return the first value which passes a truth test. - _.detect: (obj, iterator, context) -> - result: null - _.each obj, (value, index, list) -> - if iterator.call(context, value, index, list) - result: value - _.breakLoop() - result - - - # Return all the elements that pass a truth test. Use JavaScript 1.6's - # filter(), if it exists. - _.select: (obj, iterator, context) -> - if obj and _.isFunction(obj.filter) then return obj.filter(iterator, context) - results: [] - _.each obj, (value, index, list) -> - results.push(value) if iterator.call(context, value, index, list) - results - - - # Return all the elements for which a truth test fails. - _.reject: (obj, iterator, context) -> - results: [] - _.each obj, (value, index, list) -> - results.push(value) if not iterator.call(context, value, index, list) - results - - - # Determine whether all of the elements match a truth test. Delegate to - # JavaScript 1.6's every(), if it is present. - _.all: (obj, iterator, context) -> - iterator ||= _.identity - return obj.every(iterator, context) if obj and _.isFunction(obj.every) - result: true - _.each obj, (value, index, list) -> - _.breakLoop() unless (result: result and iterator.call(context, value, index, list)) - result - - - # Determine if at least one element in the object matches a truth test. Use - # JavaScript 1.6's some(), if it exists. - _.any: (obj, iterator, context) -> - iterator ||= _.identity - return obj.some(iterator, context) if obj and _.isFunction(obj.some) - result: false - _.each obj, (value, index, list) -> - _.breakLoop() if (result: iterator.call(context, value, index, list)) - result - - - # Determine if a given value is included in the array or object, - # based on '==='. - _.include: (obj, target) -> - return _.indexOf(obj, target) isnt -1 if _.isArray(obj) - for key, val of obj - return true if val is target - false - - - # Invoke a method with arguments on every item in a collection. - _.invoke: (obj, method) -> - args: _.rest(arguments, 2) - (if method then val[method] else val).apply(val, args) for val in obj - - - # Convenience version of a common use case of map: fetching a property. - _.pluck: (obj, key) -> - _.map(obj, ((val) -> val[key])) - - - # Return the maximum item or (item-based computation). - _.max: (obj, iterator, context) -> - return Math.max.apply(Math, obj) if not iterator and _.isArray(obj) - result: {computed: -Infinity} - _.each obj, (value, index, list) -> - computed: if iterator then iterator.call(context, value, index, list) else value - computed >= result.computed and (result: {value: value, computed: computed}) - result.value - - - # Return the minimum element (or element-based computation). - _.min: (obj, iterator, context) -> - return Math.min.apply(Math, obj) if not iterator and _.isArray(obj) - result: {computed: Infinity} - _.each obj, (value, index, list) -> - computed: if iterator then iterator.call(context, value, index, list) else value - computed < result.computed and (result: {value: value, computed: computed}) - result.value - - - # Sort the object's values by a criteria produced by an iterator. - _.sortBy: (obj, iterator, context) -> - _.pluck(((_.map obj, (value, index, list) -> - {value: value, criteria: iterator.call(context, value, index, list)} - ).sort((left, right) -> - a: left.criteria; b: right.criteria - if a < b then -1 else if a > b then 1 else 0 - )), 'value') - - - # Use a comparator function to figure out at what index an object should - # be inserted so as to maintain order. Uses binary search. - _.sortedIndex: (array, obj, iterator) -> - iterator ||= _.identity - low: 0; high: array.length - while low < high - mid: (low + high) >> 1 - if iterator(array[mid]) < iterator(obj) then low: mid + 1 else high: mid - low - - - # Convert anything iterable into a real, live array. - _.toArray: (iterable) -> - return [] if (!iterable) - return iterable.toArray() if (iterable.toArray) - return iterable if (_.isArray(iterable)) - return slice.call(iterable) if (_.isArguments(iterable)) - _.values(iterable) - - - # Return the number of elements in an object. - _.size: (obj) -> _.toArray(obj).length - - - # -------------------------- Array Functions: ------------------------------ - - # Get the first element of an array. Passing "n" will return the first N - # values in the array. Aliased as "head". The "guard" check allows it to work - # with _.map. - _.first: (array, n, guard) -> - if n and not guard then slice.call(array, 0, n) else array[0] - - - # Returns everything but the first entry of the array. Aliased as "tail". - # Especially useful on the arguments object. Passing an "index" will return - # the rest of the values in the array from that index onward. The "guard" - # check allows it to work with _.map. - _.rest: (array, index, guard) -> - slice.call(array, if _.isUndefined(index) or guard then 1 else index) - - - # Get the last element of an array. - _.last: (array) -> array[array.length - 1] - - - # Trim out all falsy values from an array. - _.compact: (array) -> array[i] for i in [0...array.length] when array[i] - - - # Return a completely flattened version of an array. - _.flatten: (array) -> - _.reduce array, [], (memo, value) -> - return memo.concat(_.flatten(value)) if _.isArray(value) - memo.push(value) - memo - - - # Return a version of the array that does not contain the specified value(s). - _.without: (array) -> - values: _.rest(arguments) - val for val in _.toArray(array) when not _.include(values, val) - - - # Produce a duplicate-free version of the array. If the array has already - # been sorted, you have the option of using a faster algorithm. - _.uniq: (array, isSorted) -> - memo: [] - for el, i in _.toArray(array) - memo.push(el) if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el)) - memo - - - # Produce an array that contains every item shared between all the - # passed-in arrays. - _.intersect: (array) -> - rest: _.rest(arguments) - _.select _.uniq(array), (item) -> - _.all rest, (other) -> - _.indexOf(other, item) >= 0 - - - # Zip together multiple lists into a single array -- elements that share - # an index go together. - _.zip: -> - length: _.max(_.pluck(arguments, 'length')) - results: new Array(length) - for i in [0...length] - results[i]: _.pluck(arguments, String(i)) - results - - - # If the browser doesn't supply us with indexOf (I'm looking at you, MSIE), - # we need this function. Return the position of the first occurence of an - # item in an array, or -1 if the item is not included in the array. - _.indexOf: (array, item) -> - return array.indexOf(item) if array.indexOf - i: 0; l: array.length - while l - i - if array[i] is item then return i else i++ - -1 - - - # Provide JavaScript 1.6's lastIndexOf, delegating to the native function, - # if possible. - _.lastIndexOf: (array, item) -> - return array.lastIndexOf(item) if array.lastIndexOf - i: array.length - while i - if array[i] is item then return i else i-- - -1 - - - # Generate an integer Array containing an arithmetic progression. A port of - # the native Python range() function. See: - # http://docs.python.org/library/functions.html#range - _.range: (start, stop, step) -> - a: arguments - solo: a.length <= 1 - i: start: if solo then 0 else a[0]; - stop: if solo then a[0] else a[1]; - step: a[2] or 1 - len: Math.ceil((stop - start) / step) - return [] if len <= 0 - range: new Array(len) - idx: 0 - while true - return range if (if step > 0 then i - stop else stop - i) >= 0 - range[idx]: i - idx++ - i+= step - - - # ----------------------- Function Functions: ----------------------------- - - # Create a function bound to a given object (assigning 'this', and arguments, - # optionally). Binding with arguments is also known as 'curry'. - _.bind: (func, obj) -> - args: _.rest(arguments, 2) - -> func.apply(obj or root, args.concat(arguments)) - - - # Bind all of an object's methods to that object. Useful for ensuring that - # all callbacks defined on an object belong to it. - _.bindAll: (obj) -> - funcs: if arguments.length > 1 then _.rest(arguments) else _.functions(obj) - _.each(funcs, (f) -> obj[f]: _.bind(obj[f], obj)) - obj - - - # Delays a function for the given number of milliseconds, and then calls - # it with the arguments supplied. - _.delay: (func, wait) -> - args: _.rest(arguments, 2) - setTimeout((-> func.apply(func, args)), wait) - - - # Defers a function, scheduling it to run after the current call stack has - # cleared. - _.defer: (func) -> - _.delay.apply(_, [func, 1].concat(_.rest(arguments))) - - - # Returns the first function passed as an argument to the second, - # allowing you to adjust arguments, run code before and after, and - # conditionally execute the original function. - _.wrap: (func, wrapper) -> - -> wrapper.apply(wrapper, [func].concat(arguments)) - - - # Returns a function that is the composition of a list of functions, each - # consuming the return value of the function that follows. - _.compose: -> - funcs: arguments - -> - args: arguments - for i in [(funcs.length - 1)..0] - args: [funcs[i].apply(this, args)] - args[0] - - - # ------------------------- Object Functions: ---------------------------- - - # Retrieve the names of an object's properties. - _.keys: (obj) -> - return _.range(0, obj.length) if _.isArray(obj) - key for key, val of obj - - - # Retrieve the values of an object's properties. - _.values: (obj) -> - _.map(obj, _.identity) - - - # Return a sorted list of the function names available in Underscore. - _.functions: (obj) -> - _.select(_.keys(obj), (key) -> _.isFunction(obj[key])).sort() - - - # Extend a given object with all of the properties in a source object. - _.extend: (destination, source) -> - for key, val of source - destination[key]: val - destination - - - # Create a (shallow-cloned) duplicate of an object. - _.clone: (obj) -> - return obj.slice(0) if _.isArray(obj) - _.extend({}, obj) - - - # Invokes interceptor with the obj, and then returns obj. - # The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. - _.tap: (obj, interceptor) -> - interceptor(obj) - obj - - - # Perform a deep comparison to check if two objects are equal. - _.isEqual: (a, b) -> - # Check object identity. - return true if a is b - # Different types? - atype: typeof(a); btype: typeof(b) - return false if atype isnt btype - # Basic equality test (watch out for coercions). - return true if `a == b` - # One is falsy and the other truthy. - return false if (!a and b) or (a and !b) - # One of them implements an isEqual()? - return a.isEqual(b) if a.isEqual - # Check dates' integer values. - return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b) - # Both are NaN? - return true if _.isNaN(a) and _.isNaN(b) - # Compare regular expressions. - if _.isRegExp(a) and _.isRegExp(b) - return a.source is b.source and - a.global is b.global and - a.ignoreCase is b.ignoreCase and - a.multiline is b.multiline - # If a is not an object by this point, we can't handle it. - return false if atype isnt 'object' - # Check for different array lengths before comparing contents. - return false if a.length and (a.length isnt b.length) - # Nothing else worked, deep compare the contents. - aKeys: _.keys(a); bKeys: _.keys(b) - # Different object sizes? - return false if aKeys.length isnt bKeys.length - # Recursive comparison of contents. - # for (var key in a) if (!_.isEqual(a[key], b[key])) return false; - return true - - - # Is a given array or object empty? - _.isEmpty: (obj) -> _.keys(obj).length is 0 - - - # Is a given value a DOM element? - _.isElement: (obj) -> obj and obj.nodeType is 1 - - - # Is a given value an array? - _.isArray: (obj) -> !!(obj and obj.concat and obj.unshift) - - - # Is a given variable an arguments object? - _.isArguments: (obj) -> obj and _.isNumber(obj.length) and not obj.concat and - not obj.substr and not obj.apply and not propertyIsEnumerable.call(obj, 'length') - - - # Is the given value a function? - _.isFunction: (obj) -> !!(obj and obj.constructor and obj.call and obj.apply) - - - # Is the given value a string? - _.isString: (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr)) - - - # Is a given value a number? - _.isNumber: (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]' - - - # Is a given value a Date? - _.isDate: (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear) - - - # Is the given value a regular expression? - _.isRegExp: (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false)) - - - # Is the given value NaN -- this one is interesting. NaN != NaN, and - # isNaN(undefined) == true, so we make sure it's a number first. - _.isNaN: (obj) -> _.isNumber(obj) and window.isNaN(obj) - - - # Is a given value equal to null? - _.isNull: (obj) -> obj is null - - - # Is a given variable undefined? - _.isUndefined: (obj) -> typeof obj is 'undefined' - - - # -------------------------- Utility Functions: -------------------------- - - # Run Underscore.js in noConflict mode, returning the '_' variable to its - # previous owner. Returns a reference to the Underscore object. - _.noConflict: -> - root._: previousUnderscore - this - - - # Keep the identity function around for default iterators. - _.identity: (value) -> value - - - # Break out of the middle of an iteration. - _.breakLoop: -> throw breaker - - - # Generate a unique integer id (unique within the entire client session). - # Useful for temporary DOM ids. - idCounter: 0 - _.uniqueId: (prefix) -> - (prefix or '') + idCounter++ - - - # By default, Underscore uses ERB-style template delimiters, change the - # following template settings to use alternative delimiters. - _.templateSettings: { - start: '<%' - end: '%>' - interpolate: /<%=(.+?)%>/g - } - - - # JavaScript templating a-la ERB, pilfered from John Resig's - # "Secrets of the JavaScript Ninja", page 83. - # Single-quotea fix from Rick Strahl's version. - _.template: (str, data) -> - c: _.templateSettings - fn: new Function 'obj', - 'var p=[],print=function(){p.push.apply(p,arguments);};' + - 'with(obj){p.push(\'' + - str.replace(/[\r\t\n]/g, " ") - .replace(new RegExp("'(?=[^"+c.end[0]+"]*"+c.end+")","g"),"\t") - .split("'").join("\\'") - .split("\t").join("'") - .replace(c.interpolate, "',$1,'") - .split(c.start).join("');") - .split(c.end).join("p.push('") + - "');}return p.join('');" - if data then fn(data) else fn - - - # ------------------------------- Aliases ---------------------------------- - - _.forEach: _.each - _.foldl: _.inject: _.reduce - _.foldr: _.reduceRight - _.filter: _.select - _.every: _.all - _.some: _.any - _.head: _.first - _.tail: _.rest - _.methods: _.functions - - - # /*------------------------ Setup the OOP Wrapper: --------------------------*/ - - # Helper function to continue chaining intermediate results. - result: (obj, chain) -> - if chain then _(obj).chain() else obj - - - # Add all of the Underscore functions to the wrapper object. - _.each _.functions(_), (name) -> - method: _[name] - wrapper.prototype[name]: -> - unshift.call(arguments, this._wrapped) - result(method.apply(_, arguments), this._chain) - - - # Add all mutator Array functions to the wrapper. - _.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) -> - method: Array.prototype[name] - wrapper.prototype[name]: -> - method.apply(this._wrapped, arguments) - result(this._wrapped, this._chain) - - - # Add all accessor Array functions to the wrapper. - _.each ['concat', 'join', 'slice'], (name) -> - method: Array.prototype[name] - wrapper.prototype[name]: -> - result(method.apply(this._wrapped, arguments), this._chain) - - - # Start chaining a wrapped Underscore object. - wrapper::chain: -> - this._chain: true - this - - - # Extracts the result from a wrapped and chained object. - wrapper::value: -> this._wrapped diff --git a/third_party/pygments/tests/examplefiles/unicode.applescript b/third_party/pygments/tests/examplefiles/unicode.applescript deleted file mode 100644 index 8cc6c6fb9..000000000 --- a/third_party/pygments/tests/examplefiles/unicode.applescript +++ /dev/null @@ -1,5 +0,0 @@ -set jp to "日本語" - -set ru to "Русский" - -jp & " and " & ru -- returns "日本語 and Русский" diff --git a/third_party/pygments/tests/examplefiles/unicode.go b/third_party/pygments/tests/examplefiles/unicode.go deleted file mode 100644 index d4bef4d18..000000000 --- a/third_party/pygments/tests/examplefiles/unicode.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import "fmt" - -func main() { - 世界 := "Hello, world!" - さようなら := "Goodbye, world!" - fmt.Println(世界) - fmt.Println(さようなら) -} diff --git a/third_party/pygments/tests/examplefiles/unicode.js b/third_party/pygments/tests/examplefiles/unicode.js deleted file mode 100644 index 8f553f6f8..000000000 --- a/third_party/pygments/tests/examplefiles/unicode.js +++ /dev/null @@ -1,6 +0,0 @@ -var école; -var sinθ; -var เมือง; -var a\u1234b; - -var nbsp; diff --git a/third_party/pygments/tests/examplefiles/unicodedoc.py b/third_party/pygments/tests/examplefiles/unicodedoc.py deleted file mode 100644 index 9d3db0c86..000000000 --- a/third_party/pygments/tests/examplefiles/unicodedoc.py +++ /dev/null @@ -1,11 +0,0 @@ -def foo(): - ur"""unicode-raw""" - -def bar(): - u"""unicode""" - -def baz(): - r'raw' - -def zap(): - """docstring""" diff --git a/third_party/pygments/tests/examplefiles/unix-io.lid b/third_party/pygments/tests/examplefiles/unix-io.lid deleted file mode 100644 index 617fcaa44..000000000 --- a/third_party/pygments/tests/examplefiles/unix-io.lid +++ /dev/null @@ -1,37 +0,0 @@ -Library: io -Synopsis: A portable IO library -Author: Gail Zacharias -Files: library - streams/defs - streams/stream - streams/sequence-stream - streams/native-buffer - streams/buffer - streams/typed-stream - streams/external-stream - streams/buffered-stream - streams/convenience - streams/wrapper-stream - streams/cleanup-streams - streams/native-speed - streams/async-writes - streams/file-stream - streams/multi-buffered-streams - pprint - print - print-double-integer-kludge - format - buffered-format - format-condition - unix-file-accessor - unix-standard-io - unix-interface - format-out -C-Source-Files: unix-portability.c -Major-Version: 2 -Minor-Version: 1 -Target-Type: dll -Copyright: Original Code is Copyright (c) 1995-2004 Functional Objects, Inc. - All rights reserved. -License: See License.txt in this distribution for details. -Warranty: Distributed WITHOUT WARRANTY OF ANY KIND diff --git a/third_party/pygments/tests/examplefiles/vbnet_test.bas b/third_party/pygments/tests/examplefiles/vbnet_test.bas deleted file mode 100644 index af5f25740..000000000 --- a/third_party/pygments/tests/examplefiles/vbnet_test.bas +++ /dev/null @@ -1,29 +0,0 @@ -Public Class Form1 - Inherits System.Windows.Forms.Form - - Private t As New System.Timers.Timer(2000) - - Private Sub Form1_Load(ByVal sender As Object, _ - ByVal e As System.EventArgs) Handles MyBase.Load - - AddHandler t.Elapsed, AddressOf TimerFired - End Sub - - Private Sub btnStart_Click(ByVal sender As System.Object, _ - ByVal e As System.EventArgs) Handles btnStart.Click - - t.Enabled = True - End Sub - - Private Sub btnStop_Click(ByVal sender As System.Object, _ - ByVal e As System.EventArgs) Handles btnStop.Click - - t.Enabled = False - End Sub - - Public Sub TimerFired(ByVal sender As Object, _ - ByVal e As System.Timers.ElapsedEventArgs) - - Label1.Text = "Signal Time = " & e.SignalTime.ToString - End Sub -End Class diff --git a/third_party/pygments/tests/examplefiles/vctreestatus_hg b/third_party/pygments/tests/examplefiles/vctreestatus_hg deleted file mode 100644 index 193ed8038..000000000 --- a/third_party/pygments/tests/examplefiles/vctreestatus_hg +++ /dev/null @@ -1,4 +0,0 @@ -M LICENSE -M setup.py -! setup.cfg -? vctreestatus_hg diff --git a/third_party/pygments/tests/examplefiles/vimrc b/third_party/pygments/tests/examplefiles/vimrc deleted file mode 100644 index d2f9cd1ba..000000000 --- a/third_party/pygments/tests/examplefiles/vimrc +++ /dev/null @@ -1,21 +0,0 @@ -" A comment - -:py print "py" -::pyt print 'pyt' - pyth print '''pyth''' - : pytho print "pytho" -python print """python""" - - : : python<, .5 } - - #declare Index2 = Index2 + 1; - #end - - #declare Index1 = Index1 + 1; -#end diff --git a/third_party/pygments/tests/examplefiles/wiki.factor b/third_party/pygments/tests/examplefiles/wiki.factor deleted file mode 100644 index d046e91cc..000000000 --- a/third_party/pygments/tests/examplefiles/wiki.factor +++ /dev/null @@ -1,384 +0,0 @@ -! Copyright (C) 2008 Slava Pestov -! See http://factorcode.org/license.txt for BSD license. -USING: accessors kernel hashtables calendar random assocs -namespaces make splitting sequences sorting math.order present -io.files io.directories io.encodings.ascii -syndication farkup -html.components html.forms -http.server -http.server.dispatchers -furnace.actions -furnace.utilities -furnace.redirection -furnace.auth -furnace.auth.login -furnace.boilerplate -furnace.syndication -validators -db.types db.tuples lcs urls ; -IN: webapps.wiki - -: wiki-url ( rest path -- url ) - [ "$wiki/" % % "/" % present % ] "" make - swap >>path ; - -: view-url ( title -- url ) "view" wiki-url ; - -: edit-url ( title -- url ) "edit" wiki-url ; - -: revisions-url ( title -- url ) "revisions" wiki-url ; - -: revision-url ( id -- url ) "revision" wiki-url ; - -: user-edits-url ( author -- url ) "user-edits" wiki-url ; - -TUPLE: wiki < dispatcher ; - -SYMBOL: can-delete-wiki-articles? - -can-delete-wiki-articles? define-capability - -TUPLE: article title revision ; - -article "ARTICLES" { - { "title" "TITLE" { VARCHAR 256 } +not-null+ +user-assigned-id+ } - { "revision" "REVISION" INTEGER +not-null+ } ! revision id -} define-persistent - -:
    ( title -- article ) article new swap >>title ; - -TUPLE: revision id title author date content description ; - -revision "REVISIONS" { - { "id" "ID" INTEGER +db-assigned-id+ } - { "title" "TITLE" { VARCHAR 256 } +not-null+ } ! article id - { "author" "AUTHOR" { VARCHAR 256 } +not-null+ } ! uid - { "date" "DATE" TIMESTAMP +not-null+ } - { "content" "CONTENT" TEXT +not-null+ } - { "description" "DESCRIPTION" TEXT } -} define-persistent - -M: revision feed-entry-title - [ title>> ] [ drop " by " ] [ author>> ] tri 3append ; - -M: revision feed-entry-date date>> ; - -M: revision feed-entry-url id>> revision-url ; - -: reverse-chronological-order ( seq -- sorted ) - [ date>> ] inv-sort-with ; - -: ( id -- revision ) - revision new swap >>id ; - -: validate-title ( -- ) - { { "title" [ v-one-line ] } } validate-params ; - -: validate-author ( -- ) - { { "author" [ v-username ] } } validate-params ; - -: ( responder -- responder' ) - - { wiki "page-common" } >>template ; - -: ( -- action ) - - [ "Front Page" view-url ] >>display ; - -: latest-revision ( title -- revision/f ) -
    select-tuple - dup [ revision>> select-tuple ] when ; - -: ( -- action ) - - - "title" >>rest - - [ validate-title ] >>init - - [ - "title" value dup latest-revision [ - from-object - { wiki "view" } - ] [ - edit-url - ] ?if - ] >>display - - ; - -: ( -- action ) - - - "id" >>rest - - [ - validate-integer-id - "id" value - select-tuple from-object - ] >>init - - { wiki "view" } >>template - - ; - -: ( -- action ) - - [ - article new select-tuples random - [ title>> ] [ "Front Page" ] if* - view-url - ] >>display ; - -: amend-article ( revision article -- ) - swap id>> >>revision update-tuple ; - -: add-article ( revision -- ) - [ title>> ] [ id>> ] bi article boa insert-tuple ; - -: add-revision ( revision -- ) - [ insert-tuple ] - [ - dup title>>
    select-tuple - [ amend-article ] [ add-article ] if* - ] - bi ; - -: ( -- action ) - - - "title" >>rest - - [ - validate-title - - "title" value
    select-tuple - [ revision>> select-tuple ] - [ f "title" value >>title ] - if* - - [ title>> "title" set-value ] - [ content>> "content" set-value ] - bi - ] >>init - - { wiki "edit" } >>template - - ; - -: ( -- action ) - - [ - validate-title - - { - { "content" [ v-required ] } - { "description" [ [ v-one-line ] v-optional ] } - } validate-params - - f - "title" value >>title - now >>date - username >>author - "content" value >>content - "description" value >>description - [ add-revision ] [ title>> view-url ] bi - ] >>submit - - - "edit wiki articles" >>description ; - -: ( responder -- responder ) - - { wiki "revisions-common" } >>template ; - -: list-revisions ( -- seq ) - f "title" value >>title select-tuples - reverse-chronological-order ; - -: ( -- action ) - - - "title" >>rest - - [ - validate-title - list-revisions "revisions" set-value - ] >>init - - { wiki "revisions" } >>template - - - ; - -: ( -- action ) - - - "title" >>rest - - [ validate-title ] >>init - - [ "Revisions of " "title" value append ] >>title - - [ "title" value revisions-url ] >>url - - [ list-revisions ] >>entries ; - -: rollback-description ( description -- description' ) - [ "Rollback of '" "'" surround ] [ "Rollback" ] if* ; - -: ( -- action ) - - - [ validate-integer-id ] >>validate - - [ - "id" value select-tuple - f >>id - now >>date - username >>author - [ rollback-description ] change-description - [ add-revision ] - [ title>> revisions-url ] bi - ] >>submit - - - "rollback wiki articles" >>description ; - -: list-changes ( -- seq ) - f select-tuples - reverse-chronological-order ; - -: ( -- action ) - - [ list-changes "revisions" set-value ] >>init - { wiki "changes" } >>template - - ; - -: ( -- action ) - - [ URL" $wiki/changes" ] >>url - [ "All changes" ] >>title - [ list-changes ] >>entries ; - -: ( -- action ) - - - [ validate-title ] >>validate - - [ - "title" value
    delete-tuples - f "title" value >>title delete-tuples - URL" $wiki" - ] >>submit - - - "delete wiki articles" >>description - { can-delete-wiki-articles? } >>capabilities ; - -: ( -- action ) - - - [ - { - { "old-id" [ v-integer ] } - { "new-id" [ v-integer ] } - } validate-params - - "old-id" "new-id" - [ value select-tuple ] bi@ - [ - over title>> "title" set-value - [ "old" [ from-object ] nest-form ] - [ "new" [ from-object ] nest-form ] - bi* - ] - [ [ content>> string-lines ] bi@ diff "diff" set-value ] - 2bi - ] >>init - - { wiki "diff" } >>template - - ; - -: ( -- action ) - - - [ - f
    select-tuples - [ title>> ] sort-with - "articles" set-value - ] >>init - - { wiki "articles" } >>template ; - -: list-user-edits ( -- seq ) - f "author" value >>author select-tuples - reverse-chronological-order ; - -: ( -- action ) - - - "author" >>rest - - [ - validate-author - list-user-edits "revisions" set-value - ] >>init - - { wiki "user-edits" } >>template - - ; - -: ( -- action ) - - "author" >>rest - [ validate-author ] >>init - [ "Edits by " "author" value append ] >>title - [ "author" value user-edits-url ] >>url - [ list-user-edits ] >>entries ; - -: init-sidebars ( -- ) - "Contents" latest-revision [ "contents" [ from-object ] nest-form ] when* - "Footer" latest-revision [ "footer" [ from-object ] nest-form ] when* ; - -: init-relative-link-prefix ( -- ) - URL" $wiki/view/" adjust-url present relative-link-prefix set ; - -: ( -- dispatcher ) - wiki new-dispatcher - "" add-responder - "view" add-responder - "revision" add-responder - "random" add-responder - "revisions" add-responder - "revisions.atom" add-responder - "diff" add-responder - "edit" add-responder - "submit" add-responder - "rollback" add-responder - "user-edits" add-responder - "articles" add-responder - "changes" add-responder - "user-edits.atom" add-responder - "changes.atom" add-responder - "delete" add-responder - - [ init-sidebars init-relative-link-prefix ] >>init - { wiki "wiki-common" } >>template ; - -: init-wiki ( -- ) - "resource:extra/webapps/wiki/initial-content" [ - [ - dup ".txt" ?tail [ - swap ascii file-contents - f - swap >>content - swap >>title - "slava" >>author - now >>date - add-revision - ] [ 2drop ] if - ] each - ] with-directory-files ; \ No newline at end of file diff --git a/third_party/pygments/tests/examplefiles/xml_example b/third_party/pygments/tests/examplefiles/xml_example deleted file mode 100644 index e657e5649..000000000 --- a/third_party/pygments/tests/examplefiles/xml_example +++ /dev/null @@ -1,1897 +0,0 @@ - - - - - - abort - abs - abstract - accept - access - aliased - all - and - array - at - begin - body - constant - declare - delay - delta - digits - do - else - elsif - end - entry - exception - exit - for - function - generic - goto - in - is - limited - mod - new - not - null - of - or - others - out - package - pragma - private - procedure - protected - raise - range - rem - record - renames - requeue - return - reverse - separate - subtype - tagged - task - terminate - then - type - until - use - when - while - with - xor - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BEGIN - END - if - else - while - do - for - in - continue - break - print - printf - getline - function - return - next - exit - - - ARGC - ARGV - CONVFMT - ENVIRON - FILENAME - FNR - FS - NF - NR - OFMT - OFS - ORS - RS - RSTART - RLENGTH - SUBSEP - - - gsub - index - length - match - split - sprintf - sub - substr - tolower - toupper - atan2 - cos - exp - int - log - rand - sin - sqrt - srand - close - fflush - system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - break - case - else - esac - exit - export - for - function - in - return - select - then - until - while - . - done - do - elif - fi - if - - - - cp - date - echo - eval - dcop - dcopstart - dcopfind - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - break - case - continue - default - do - else - enum - extern - for - goto - if - inline - return - sizeof - struct - switch - typedef - union - while - - - auto - char - const - double - float - int - long - register - restrict - short - signed - static - unsigned - void - volatile - _Imaginary - _Complex - _Bool - - - FIXME - TODO - ### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - aaa - access-list - address - alias - arp - async-bootp - banner - boot - bridge - buffers - busy-message - call-history-mib - cdp - chat-script - class-map - clock - cns - config-register - controller - crypto - default - default-value - dialer - dialer-list - dnsix-dmdp - dnsix-nat - downward-compatible-config - enable - end - exception - exit - file - frame-relay - help - hostname - interface - ip - isdn - isdn-mib - kerberos - key - line - logging - login-string - map-class - map-list - memory-size - menu - modemcap - multilink - netbios - no - ntp - partition - policy-map - priority-list - privilege - process-max-time - prompt - queue-list - resume-string - rlogin - rmon - route-map - router - rtr - scheduler - service - snmp-server - sntp - stackmaker - state-machine - subscriber-policy - tacacs-server - template - terminal-queue - tftp-server - time-range - username - virtual-profile - virtual-template - vpdn - vpdn-group - x25 - x29 - - - accounting - accounting-list - accounting-threshold - accounting-transits - address-pool - as-path - audit - auth-proxy - authentication - authorization - bgp-community - bootp - cef - classless - community-list - default-gateway - default-network - dhcp - dhcp-server - domain-list - domain-lookup - domain-name - dvmrp - exec-callback - extcommunity-list - finger - flow-aggregation - flow-cache - flow-export - forward-protocol - ftp - gratuitous-arps - host - host-routing - hp-host - http - icmp - inspect - local - mrm - mroute - msdp - multicast - multicast-routing - name-server - nat - new-model - ospf - password - password-encryption - pgm - pim - port-map - prefix-list - radius - rcmd - reflexive-list - route - routing - rsvp - rtcp - sap - sdr - security - source-route - subnet-zero - tacacs - tcp - tcp-small-servers - telnet - tftp - timestamps - udp-small-servers - vrf - wccp - - - accounting - accounting-list - accounting-threshold - accounting-transits - address-pool - as-path - audit - auth-proxy - authentication - authorization - bgp-community - bootp - cef - classless - community-list - default-gateway - default-network - dhcp - dhcp-server - domain-list - domain-lookup - domain-name - dvmrp - exec-callback - extcommunity-list - finger - flow-aggregation - flow-cache - flow-export - forward-protocol - ftp - gratuitous-arps - host - host-routing - hp-host - http - icmp - inspect - local - mrm - mroute - msdp - multicast - multicast-routing - name-server - nat - new-model - ospf - password - password-encryption - pgm - pim - port-map - prefix-list - radius - rcmd - reflexive-list - route - routing - rsvp - rtcp - sap - sdr - security - source-route - subnet-zero - tacacs - tcp - tcp-small-servers - telnet - tftp - timestamps - udp-small-servers - vrf - wccp - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if - else - for - in - while - do - continue - break - with - try - catch - switch - case - new - var - function - return - this - delete - true - false - void - throw - typeof - const - default - - - - - - Anchor - Applet - Area - Array - Boolean - Button - Checkbox - Date - Document - Event - FileUpload - Form - Frame - Function - Hidden - History - Image - Layer - Linke - Location - Math - Navigator - Number - Object - Option - Password - Radio - RegExp - Reset - Screen - Select - String - Submit - Text - Textarea - Window - - - - - - abs - acos - alert - anchor - apply - asin - atan - atan2 - back - blur - call - captureEvents - ceil - charAt - charCodeAt - clearInterval - clearTimeout - click - close - compile - concat - confirm - cos - disableExternalCapture - enableExternalCapture - eval - exec - exp - find - floor - focus - forward - fromCharCode - getDate - getDay - getFullYear - getHours - getMilliseconds - getMinutes - getMonth - getSeconds - getSelection - getTime - getTimezoneOffset - getUTCDate - getUTCDay - getUTCFullYear - getUTCHours - getUTCMilliseconds - getUTCMinutes - getUTCMonth - getUTCSeconds - go - handleEvent - home - indexOf - javaEnabled - join - lastIndexOf - link - load - log - match - max - min - moveAbove - moveBelow - moveBy - moveTo - moveToAbsolute - open - parse - plugins.refresh - pop - pow - preference - print - prompt - push - random - releaseEvents - reload - replace - reset - resizeBy - resizeTo - reverse - round - routeEvent - scrollBy - scrollTo - search - select - setDate - setFullYear - setHours - setInterval - setMilliseconds - setMinutes - setMonth - setSeconds - setTime - setTimeout - setUTCDate - setUTCFullYear - setUTCHours - setUTCMilliseconds - setUTCMinutes - setUTCMonth - setUTCSeconds - shift - sin - slice - sort - splice - split - sqrt - stop - String formatting - submit - substr - substring - taintEnabled - tan - test - toLocaleString - toLowerCase - toSource - toString - toUpperCase - toUTCString - unshift - unwatch - UTC - valueOf - watch - write - writeln - - - - - - break - case - catch - continue - default - do - else - for - function - if - in - return - switch - try - var - while - - - - - - Abs - ACos - ArrayAppend - ArrayAvg - ArrayClear - ArrayDeleteAt - ArrayInsertAt - ArrayIsEmpty - ArrayLen - ArrayMax - ArrayMin - ArrayNew - ArrayPrepend - ArrayResize - ArraySet - ArraySort - ArraySum - ArraySwap - ArrayToList - Asc - ASin - Atn - BitAnd - BitMaskClear - BitMaskRead - BitMaskSet - BitNot - BitOr - BitSHLN - BitSHRN - BitXor - Ceiling - Chr - CJustify - Compare - CompareNoCase - Cos - CreateDate - CreateDateTime - CreateObject - CreateODBCDate - CreateODBCDateTime - CreateODBCTime - CreateTime - CreateTimeSpan - CreateUUID - DateAdd - DateCompare - DateConvert - DateDiff - DateFormat - DatePart - Day - DayOfWeek - DayOfWeekAsString - DayOfYear - DaysInMonth - DaysInYear - DE - DecimalFormat - DecrementValue - Decrypt - DeleteClientVariable - DirectoryExists - DollarFormat - Duplicate - Encrypt - Evaluate - Exp - ExpandPath - FileExists - Find - FindNoCase - FindOneOf - FirstDayOfMonth - Fix - FormatBaseN - GetAuthUser - GetBaseTagData - GetBaseTagList - GetBaseTemplatePath - GetClientVariablesList - GetCurrentTemplatePath - GetDirectoryFromPath - GetException - GetFileFromPath - GetFunctionList - GetHttpRequestData - GetHttpTimeString - GetK2ServerDocCount - GetK2ServerDocCountLimit - GetLocale - GetMetaData - GetMetricData - GetPageContext - GetProfileSections - GetProfileString - GetServiceSettings - GetTempDirectory - GetTempFile - GetTemplatePath - GetTickCount - GetTimeZoneInfo - GetToken - Hash - Hour - HTMLCodeFormat - HTMLEditFormat - IIf - IncrementValue - InputBaseN - Insert - Int - IsArray - IsBinary - IsBoolean - IsCustomFunction - IsDate - IsDebugMode - IsDefined - IsK2ServerABroker - IsK2ServerDocCountExceeded - IsK2ServerOnline - IsLeapYear - IsNumeric - IsNumericDate - IsObject - IsQuery - IsSimpleValue - IsStruct - IsUserInRole - IsWDDX - IsXmlDoc - IsXmlElement - IsXmlRoot - JavaCast - JSStringFormat - LCase - Left - Len - ListAppend - ListChangeDelims - ListContains - ListContainsNoCase - ListDeleteAt - ListFind - ListFindNoCase - ListFirst - ListGetAt - ListInsertAt - ListLast - ListLen - ListPrepend - ListQualify - ListRest - ListSetAt - ListSort - ListToArray - ListValueCount - ListValueCountNoCase - LJustify - Log - Log10 - LSCurrencyFormat - LSDateFormat - LSEuroCurrencyFormat - LSIsCurrency - LSIsDate - LSIsNumeric - LSNumberFormat - LSParseCurrency - LSParseDateTime - LSParseEuroCurrency - LSParseNumber - LSTimeFormat - LTrim - Max - Mid - Min - Minute - Month - MonthAsString - Now - NumberFormat - ParagraphFormat - ParameterExists - ParseDateTime - Pi - PreserveSingleQuotes - Quarter - QueryAddColumn - QueryAddRow - QueryNew - QuerySetCell - QuotedValueList - Rand - Randomize - RandRange - REFind - REFindNoCase - RemoveChars - RepeatString - Replace - ReplaceList - ReplaceNoCase - REReplace - REReplaceNoCase - Reverse - Right - RJustify - Round - RTrim - Second - SetEncoding - SetLocale - SetProfileString - SetVariable - Sgn - Sin - SpanExcluding - SpanIncluding - Sqr - StripCR - StructAppend - StructClear - StructCopy - StructCount - StructDelete - StructFind - StructFindKey - StructFindValue - StructGet - StructInsert - StructIsEmpty - StructKeyArray - StructKeyExists - StructKeyList - StructNew - StructSort - StructUpdate - Tan - TimeFormat - ToBase64 - ToBinary - ToString - Trim - UCase - URLDecode - URLEncodedFormat - URLSessionFormat - Val - ValueList - Week - WriteOutput - XmlChildPos - XmlElemNew - XmlFormat - XmlNew - XmlParse - XmlSearch - XmlTransform - Year - YesNoFormat - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BEGIN - BY - CASE - CLOSE - CONST - DO - ELSE - ELSIF - END - FOR - IF - IMPORT - LOOP - MODULE - NEW - OF - OUT - PROCEDURE - REPEAT - THEN - TO - TYPE - UNTIL - VAR - WHILE - WITH - - - ASSERT - EXIT - HALT - RETURN - - - ANYPTR - ANYREC - ARRAY - BOOLEAN - SHORTCHAR - CHAR - BYTE - SHORTINT - INTEGER - LONGINT - POINTER - RECORD - SHORTREAL - REAL - SET - - - ABSTRACT - EMPTY - EXTENSIBLE - LIMITED - - - ABS - ASH - BITS - CAP - CHR - DEC - ENTIER - EXCL - INC - INCL - LEN - LONG - MAX - MIN - ODD - ORD - SHORT - SIZE - - - FALSE - INF - NIL - TRUE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/third_party/pygments/tests/examplefiles/yahalom.cpsa b/third_party/pygments/tests/examplefiles/yahalom.cpsa deleted file mode 100644 index 3bc918d43..000000000 --- a/third_party/pygments/tests/examplefiles/yahalom.cpsa +++ /dev/null @@ -1,34 +0,0 @@ -(herald "Yahalom Protocol with Forwarding Removed") - -(defprotocol yahalom basic - (defrole init - (vars (a b c name) (n-a n-b text) (k skey)) - (trace (send (cat a n-a)) - (recv (enc b k n-a n-b (ltk a c))) - (send (enc n-b k)))) - (defrole resp - (vars (b a c name) (n-a n-b text) (k skey)) - (trace (recv (cat a n-a)) - (send (cat b (enc a n-a n-b (ltk b c)))) - (recv (enc a k (ltk b c))) - (recv (enc n-b k)))) - (defrole serv - (vars (c a b name) (n-a n-b text) (k skey)) - (trace (recv (cat b (enc a n-a n-b (ltk b c)))) - (send (enc b k n-a n-b (ltk a c))) - (send (enc a k (ltk b c)))) - (uniq-orig k))) - -(defskeleton yahalom - (vars (a b c name) (n-b text)) - (defstrand resp 4 (a a) (b b) (c c) (n-b n-b)) - (non-orig (ltk b c) (ltk a c)) - (uniq-orig n-b)) - -;;; Ensure encryption key remains secret. -(defskeleton yahalom - (vars (a b c name) (n-b text) (k skey)) - (defstrand resp 4 (a a) (b b) (c c) (n-b n-b) (k k)) - (deflistener k) - (non-orig (ltk b c) (ltk a c)) - (uniq-orig n-b)) diff --git a/third_party/pygments/tests/examplefiles/zmlrpc.f90 b/third_party/pygments/tests/examplefiles/zmlrpc.f90 deleted file mode 100644 index 441497b30..000000000 --- a/third_party/pygments/tests/examplefiles/zmlrpc.f90 +++ /dev/null @@ -1,798 +0,0 @@ -!!$ -!!$ -!!$ MD2P4 -!!$ Multilevel Domain Decomposition Parallel Preconditioner Package for PSBLAS -!!$ for -!!$ Parallel Sparse BLAS v2.0 -!!$ (C) Copyright 2006 Salvatore Filippone University of Rome Tor Vergata -!!$ Alfredo Buttari University of Rome Tor Vergata -!!$ Daniela Di Serafino II University of Naples -!!$ Pasqua D'Ambra ICAR-CNR -!!$ -!!$ 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. -!!$ 3. The name of the MD2P4 group or the names of its contributors may -!!$ not be used to endorse or promote products derived from this -!!$ software without specific written permission. -!!$ -!!$ 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 MD2P4 GROUP OR ITS 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. -!!$ -!!$ -subroutine psb_zmlprc_aply(alpha,baseprecv,x,beta,y,desc_data,trans,work,info) - ! - ! Compute Y <- beta*Y + alpha*K^-1 X - ! where K is a multilevel preconditioner stored in baseprecv - ! - ! cfr.: Smith, Biorstad & Gropp - ! Domain Decomposition - ! Cambridge Univ. Press - ! - ! To each level I there corresponds a matrix A(I) and a preconditioner K(I) - ! - ! A notational difference: in the DD reference above the preconditioner for - ! a given level K(I) is written out as a sum over the subdomains - ! - ! SUM_k(R_k^T A_k R_k) - ! - ! whereas in this code the sum is implicit in the parallelization, - ! i.e. each process takes care of one subdomain, and for each level we have - ! as many subdomains as there are processes (except for the coarsest level where - ! we might have a replicated index space). Thus the sum apparently disappears - ! from our code, but only apparently, because it is implicit in the call - ! to psb_baseprc_aply. - ! - ! A bit of description of the baseprecv(:) data structure: - ! 1. Number of levels = NLEV = size(baseprecv(:)) - ! 2. baseprecv(ilev)%av(:) sparse matrices needed for the current level. - ! Includes: - ! 2.1.: baseprecv(ilev)%av(l_pr_) L factor of ILU preconditioners - ! 2.2.: baseprecv(ilev)%av(u_pr_) U factor of ILU preconditioners - ! 2.3.: baseprecv(ilev)%av(ap_nd_) Off-diagonal part of A for Jacobi sweeps - ! 2.4.: baseprecv(ilev)%av(ac_) Aggregated matrix of level ILEV - ! 2.5.: baseprecv(ilev)%av(sm_pr_t_) Smoother prolongator transpose; maps vectors - ! (ilev-1) ---> (ilev) - ! 2.6.: baseprecv(ilev)%av(sm_pr_) Smoother prolongator; maps vectors - ! (ilev) ---> (ilev-1) - ! Shouldn't we keep just one of them and handle transpose in the sparse BLAS? maybe - ! - ! 3. baseprecv(ilev)%desc_data comm descriptor for level ILEV - ! 4. baseprecv(ilev)%base_a Pointer (really a pointer!) to the base matrix - ! of the current level, i.e.: if ILEV=1 then A - ! else the aggregated matrix av(ac_); so we have - ! a unified treatment of residuals. Need this to - ! avoid passing explicitly matrix A to the - ! outer prec. routine - ! 5. baseprecv(ilev)%mlia The aggregation map from (ilev-1)-->(ilev) - ! if no smoother, it is used instead of sm_pr_ - ! 6. baseprecv(ilev)%nlaggr Number of aggregates on the various procs. - ! - - use psb_serial_mod - use psb_descriptor_type - use psb_prec_type - use psb_psblas_mod - use psb_penv_mod - use psb_const_mod - use psb_error_mod - use psb_penv_mod - implicit none - - type(psb_desc_type),intent(in) :: desc_data - type(psb_zbaseprc_type), intent(in) :: baseprecv(:) - complex(kind(1.d0)),intent(in) :: alpha,beta - complex(kind(1.d0)),intent(inout) :: x(:), y(:) - character :: trans - complex(kind(1.d0)),target :: work(:) - integer, intent(out) :: info - - - ! Local variables - integer :: n_row,n_col - complex(kind(1.d0)), allocatable :: tx(:),ty(:),t2l(:),w2l(:),& - & x2l(:),b2l(:),tz(:),tty(:) - character ::diagl, diagu - integer :: ictxt,np,me,i, isz, nrg,nr2l,err_act, iptype, int_err(5) - real(kind(1.d0)) :: omega - real(kind(1.d0)) :: t1, t2, t3, t4, t5, t6, t7, mpi_wtime - logical, parameter :: debug=.false., debugprt=.false. - integer :: ismth, nlev, ilev - external mpi_wtime - character(len=20) :: name, ch_err - - type psb_mlprec_wrk_type - complex(kind(1.d0)), pointer :: tx(:)=>null(),ty(:)=>null(),& - & x2l(:)=>null(),y2l(:)=>null(),& - & b2l(:)=>null(),tty(:)=>null() - end type psb_mlprec_wrk_type - type(psb_mlprec_wrk_type), pointer :: mlprec_wrk(:) - - interface psb_baseprc_aply - subroutine psb_zbaseprc_aply(alpha,prec,x,beta,y,desc_data,trans,work,info) - use psb_descriptor_type - use psb_prec_type - type(psb_desc_type),intent(in) :: desc_data - type(psb_zbaseprc_type), intent(in) :: prec - complex(kind(1.d0)),intent(inout) :: x(:), y(:) - complex(kind(1.d0)),intent(in) :: alpha,beta - character(len=1) :: trans - complex(kind(1.d0)),target :: work(:) - integer, intent(out) :: info - end subroutine psb_zbaseprc_aply - end interface - - name='psb_mlprc_aply' - info = 0 - call psb_erractionsave(err_act) - - - ictxt=desc_data%matrix_data(psb_ctxt_) - call psb_info(ictxt, me, np) - - nlev = size(baseprecv) - allocate(mlprec_wrk(nlev),stat=info) - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - - select case(baseprecv(2)%iprcparm(ml_type_)) - - case(no_ml_) - ! Should not really get here. - call psb_errpush(4010,name,a_err='no_ml_ in mlprc_aply?') - goto 9999 - - - case(add_ml_prec_) - - - ! - ! Additive is very simple. - ! 1. X(1) = Xext - ! 2. DO ILEV=2,NLEV - ! X(ILEV) = AV(PR_SM_T_)*X(ILEV-1) - ! 3. Y(ILEV) = (K(ILEV)**(-1))*X(ILEV) - ! 4. DO ILEV=NLEV-1,1,-1 - ! Y(ILEV) = AV(PR_SM_)*Y(ILEV+1) - ! 5. Yext = beta*Yext + Y(1) - ! - ! Note: level numbering reversed wrt ref. DD, i.e. - ! 1..NLEV <=> (j) <-> 0 - - - call psb_baseprc_aply(alpha,baseprecv(1),x,beta,y,& - & baseprecv(1)%base_desc,trans,work,info) - if(info /=0) goto 9999 - allocate(mlprec_wrk(1)%x2l(size(x)),mlprec_wrk(1)%y2l(size(y))) - mlprec_wrk(1)%x2l(:) = x(:) - - - do ilev = 2, nlev - n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) - n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) - nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) - allocate(mlprec_wrk(ilev)%x2l(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& - & mlprec_wrk(ilev)%tx(max(n_row,n_col)),& - & mlprec_wrk(ilev)%ty(max(n_row,n_col)), stat=info) - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - mlprec_wrk(ilev)%x2l(:) = zzero - mlprec_wrk(ilev)%y2l(:) = zzero - mlprec_wrk(ilev)%tx(1:n_row) = mlprec_wrk(ilev-1)%x2l(1:n_row) - mlprec_wrk(ilev)%tx(n_row+1:max(n_row,n_col)) = zzero - mlprec_wrk(ilev)%ty(:) = zzero - - ismth=baseprecv(ilev)%iprcparm(smth_kind_) - - if (ismth /= no_smth_) then - ! - ! Smoothed aggregation - ! - - - if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then - call psb_halo(mlprec_wrk(ilev-1)%x2l,baseprecv(ilev-1)%base_desc,& - & info,work=work) - if(info /=0) goto 9999 - else - mlprec_wrk(ilev-1)%x2l(n_row+1:max(n_row,n_col)) = zzero - end if - - call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%x2l,& - & zzero,mlprec_wrk(ilev)%x2l,info) - if(info /=0) goto 9999 - - else - ! - ! Raw aggregation, may take shortcut - ! - do i=1,n_row - mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & - & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & - & mlprec_wrk(ilev-1)%x2l(i) - end do - - end if - - if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) Then - call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) - else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) Then - write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& - & baseprecv(ilev)%iprcparm(coarse_mat_) - endif - - call psb_baseprc_aply(zone,baseprecv(ilev),& - & mlprec_wrk(ilev)%x2l,zzero,mlprec_wrk(ilev)%y2l,& - & baseprecv(ilev)%desc_data, 'N',work,info) - - enddo - - do ilev =nlev,2,-1 - - ismth=baseprecv(ilev)%iprcparm(smth_kind_) - n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) - n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) - nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) - - if (ismth /= no_smth_) then - - call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_),mlprec_wrk(ilev)%y2l,& - & zone,mlprec_wrk(ilev-1)%y2l,info) - if(info /=0) goto 9999 - - else - - do i=1, n_row - mlprec_wrk(ilev-1)%y2l(i) = mlprec_wrk(ilev-1)%y2l(i) + & - & mlprec_wrk(ilev)%y2l(baseprecv(ilev)%mlia(i)) - enddo - - end if - end do - - call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,zone,y,baseprecv(1)%base_desc,info) - if(info /=0) goto 9999 - - - case(mult_ml_prec_) - - ! - ! Multiplicative multilevel - ! Pre/post smoothing versions. - ! - - select case(baseprecv(2)%iprcparm(smth_pos_)) - - case(post_smooth_) - - - ! - ! Post smoothing. - ! 1. X(1) = Xext - ! 2. DO ILEV=2, NLEV :: X(ILEV) = AV(PR_SM_T_,ILEV)*X(ILEV-1) - ! 3. Y(NLEV) = (K(NLEV)**(-1))*X(NLEV) - ! 4. DO ILEV=NLEV-1,1,-1 - ! Y(ILEV) = AV(PR_SM_,ILEV+1)*Y(ILEV+1) - ! Y(ILEV) = Y(ILEV) + (K(ILEV)**(-1))*(X(ILEV)-A(ILEV)*Y(ILEV)) - ! - ! 5. Yext = beta*Yext + Y(1) - ! - ! Note: level numbering reversed wrt ref. DD, i.e. - ! 1..NLEV <=> (j) <-> 0 - ! - ! Also: post smoothing is not spelled out in detail in DD. - ! - ! - - - n_col = desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(1)%desc_data%matrix_data(psb_n_col_) - - allocate(mlprec_wrk(1)%x2l(nr2l),mlprec_wrk(1)%y2l(nr2l), & - & mlprec_wrk(1)%tx(nr2l), stat=info) - mlprec_wrk(1)%x2l(:) = zzero - mlprec_wrk(1)%y2l(:) = zzero - mlprec_wrk(1)%tx(:) = zzero - - call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%tx,& - & baseprecv(1)%base_desc,info) - call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%x2l,& - & baseprecv(1)%base_desc,info) - - do ilev=2, nlev - n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) - n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) - nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) - ismth = baseprecv(ilev)%iprcparm(smth_kind_) - - allocate(mlprec_wrk(ilev)%tx(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& - & mlprec_wrk(ilev)%x2l(nr2l), stat=info) - - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - mlprec_wrk(ilev)%x2l(:) = zzero - mlprec_wrk(ilev)%y2l(:) = zzero - mlprec_wrk(ilev)%tx(:) = zzero - if (ismth /= no_smth_) then - ! - ! Smoothed aggregation - ! - if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then - call psb_halo(mlprec_wrk(ilev-1)%x2l,& - & baseprecv(ilev-1)%base_desc,info,work=work) - if(info /=0) goto 9999 - else - mlprec_wrk(ilev-1)%x2l(n_row+1:max(n_row,n_col)) = zzero - end if - - call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%x2l, & - & zzero,mlprec_wrk(ilev)%x2l,info) - if(info /=0) goto 9999 - - else - ! - ! Raw aggregation, may take shortcut - ! - do i=1,n_row - mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & - & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & - & mlprec_wrk(ilev-1)%x2l(i) - end do - end if - - if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) Then - call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) - else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) Then - write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& - & baseprecv(ilev)%iprcparm(coarse_mat_) - endif - call psb_geaxpby(zone,mlprec_wrk(ilev)%x2l,zzero,mlprec_wrk(ilev)%tx,& - & baseprecv(ilev)%base_desc,info) - if(info /=0) goto 9999 - - enddo - - - call psb_baseprc_aply(zone,baseprecv(nlev),mlprec_wrk(nlev)%x2l, & - & zzero, mlprec_wrk(nlev)%y2l,baseprecv(nlev)%desc_data,'N',work,info) - - if(info /=0) goto 9999 - - - do ilev=nlev-1, 1, -1 - ismth = baseprecv(ilev+1)%iprcparm(smth_kind_) - if (ismth /= no_smth_) then - if (ismth == smth_omg_) & - & call psb_halo(mlprec_wrk(ilev+1)%y2l,baseprecv(ilev+1)%desc_data,& - & info,work=work) - call psb_csmm(zone,baseprecv(ilev+1)%av(sm_pr_),mlprec_wrk(ilev+1)%y2l,& - & zzero,mlprec_wrk(ilev)%y2l,info) - if(info /=0) goto 9999 - - else - n_row = baseprecv(ilev)%base_desc%matrix_data(psb_n_row_) - mlprec_wrk(ilev)%y2l(:) = zzero - do i=1, n_row - mlprec_wrk(ilev)%y2l(i) = mlprec_wrk(ilev)%y2l(i) + & - & mlprec_wrk(ilev+1)%y2l(baseprecv(ilev+1)%mlia(i)) - enddo - - end if - - call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& - & zone,mlprec_wrk(ilev)%tx,baseprecv(ilev)%base_desc,info,work=work) - - if(info /=0) goto 9999 - - call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%tx,& - & zone,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%base_desc, trans, work,info) - - if(info /=0) goto 9999 - - enddo - - call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,beta,y,baseprecv(1)%base_desc,info) - - if(info /=0) goto 9999 - - - case(pre_smooth_) - - - ! - ! Pre smoothing. - ! 1. X(1) = Xext - ! 2. Y(1) = (K(1)**(-1))*X(1) - ! 3. TX(1) = X(1) - A(1)*Y(1) - ! 4. DO ILEV=2, NLEV - ! X(ILEV) = AV(PR_SM_T_,ILEV)*TX(ILEV-1) - ! Y(ILEV) = (K(ILEV)**(-1))*X(ILEV) - ! TX(ILEV) = (X(ILEV)-A(ILEV)*Y(ILEV)) - ! 5. DO ILEV=NLEV-1,1,-1 - ! Y(ILEV) = Y(ILEV) + AV(PR_SM_,ILEV+1)*Y(ILEV+1) - ! 6. Yext = beta*Yext + Y(1) - ! - ! Note: level numbering reversed wrt ref. DD, i.e. - ! 1..NLEV <=> (j) <-> 0 - ! - ! - - n_col = desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(1)%desc_data%matrix_data(psb_n_col_) - - allocate(mlprec_wrk(1)%x2l(nr2l),mlprec_wrk(1)%y2l(nr2l), & - & mlprec_wrk(1)%tx(nr2l), stat=info) - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - mlprec_wrk(1)%y2l(:) = zzero - - - mlprec_wrk(1)%x2l(:) = x - - call psb_baseprc_aply(zone,baseprecv(1),mlprec_wrk(1)%x2l,& - & zzero,mlprec_wrk(1)%y2l,& - & baseprecv(1)%base_desc,& - & trans,work,info) - - if(info /=0) goto 9999 - - mlprec_wrk(1)%tx = mlprec_wrk(1)%x2l - - call psb_spmm(-zone,baseprecv(1)%base_a,mlprec_wrk(1)%y2l,& - & zone,mlprec_wrk(1)%tx,baseprecv(1)%base_desc,info,work=work) - if(info /=0) goto 9999 - - do ilev = 2, nlev - n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) - n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) - nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) - ismth = baseprecv(ilev)%iprcparm(smth_kind_) - allocate(mlprec_wrk(ilev)%tx(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& - & mlprec_wrk(ilev)%x2l(nr2l), stat=info) - - - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - mlprec_wrk(ilev)%x2l(:) = zzero - mlprec_wrk(ilev)%y2l(:) = zzero - mlprec_wrk(ilev)%tx(:) = zzero - - - if (ismth /= no_smth_) then - ! - !Smoothed Aggregation - ! - if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then - - call psb_halo(mlprec_wrk(ilev-1)%tx,baseprecv(ilev-1)%base_desc,& - & info,work=work) - if(info /=0) goto 9999 - else - mlprec_wrk(ilev-1)%tx(n_row+1:max(n_row,n_col)) = zzero - end if - - call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%tx,zzero,& - & mlprec_wrk(ilev)%x2l,info) - if(info /=0) goto 9999 - - else - ! - ! Raw aggregation, may take shortcuts - ! - mlprec_wrk(ilev)%x2l = zzero - do i=1,n_row - mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & - & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & - & mlprec_wrk(ilev-1)%tx(i) - end do - end if - - if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) then - call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) - else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) then - write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& - & baseprecv(ilev)%iprcparm(coarse_mat_) - endif - - - call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%x2l,& - & zzero,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%desc_data, 'N',work,info) - - if(info /=0) goto 9999 - - if(ilev < nlev) then - mlprec_wrk(ilev)%tx = mlprec_wrk(ilev)%x2l - call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& - & zone,mlprec_wrk(ilev)%tx,baseprecv(ilev)%base_desc,info,work=work) - if(info /=0) goto 9999 - endif - - enddo - - do ilev = nlev-1, 1, -1 - - ismth=baseprecv(ilev+1)%iprcparm(smth_kind_) - - if (ismth /= no_smth_) then - - if (ismth == smth_omg_) & - & call psb_halo(mlprec_wrk(ilev+1)%y2l,& - & baseprecv(ilev+1)%desc_data,info,work=work) - call psb_csmm(zone,baseprecv(ilev+1)%av(sm_pr_),mlprec_wrk(ilev+1)%y2l,& - & zone,mlprec_wrk(ilev)%y2l,info) - - if(info /=0) goto 9999 - - else - - n_row = baseprecv(ilev+1)%base_desc%matrix_data(psb_n_row_) - do i=1, n_row - mlprec_wrk(ilev)%y2l(i) = mlprec_wrk(ilev)%y2l(i) + & - & mlprec_wrk(ilev+1)%y2l(baseprecv(ilev+1)%mlia(i)) - enddo - - end if - - enddo - - call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,beta,y,& - & baseprecv(1)%base_desc,info) - - if(info /=0) goto 9999 - - - - case(smooth_both_) - - ! - ! Symmetrized smoothing. - ! 1. X(1) = Xext - ! 2. Y(1) = (K(1)**(-1))*X(1) - ! 3. TX(1) = X(1) - A(1)*Y(1) - ! 4. DO ILEV=2, NLEV - ! X(ILEV) = AV(PR_SM_T_,ILEV)*TX(ILEV-1) - ! Y(ILEV) = (K(ILEV)**(-1))*X(ILEV) - ! TX(ILEV) = (X(ILEV)-A(ILEV)*Y(ILEV)) - ! 5. DO ILEV=NLEV-1,1,-1 - ! Y(ILEV) = Y(ILEV) + AV(PR_SM_,ILEV+1)*Y(ILEV+1) - ! Y(ILEV) = Y(ILEV) + (K(ILEV)**(-1))*(X(ILEV)-A(ILEV)*Y(ILEV)) - ! 6. Yext = beta*Yext + Y(1) - ! - ! Note: level numbering reversed wrt ref. DD, i.e. - ! 1..NLEV <=> (j) <-> 0 - ! - ! - n_col = desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(1)%desc_data%matrix_data(psb_n_col_) - - allocate(mlprec_wrk(1)%x2l(nr2l),mlprec_wrk(1)%y2l(nr2l), & - & mlprec_wrk(1)%ty(nr2l), mlprec_wrk(1)%tx(nr2l), stat=info) - - mlprec_wrk(1)%x2l(:) = zzero - mlprec_wrk(1)%y2l(:) = zzero - mlprec_wrk(1)%tx(:) = zzero - mlprec_wrk(1)%ty(:) = zzero - - - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%x2l,& - & baseprecv(1)%base_desc,info) - call psb_geaxpby(zone,x,zzero,mlprec_wrk(1)%tx,& - & baseprecv(1)%base_desc,info) - - call psb_baseprc_aply(zone,baseprecv(1),mlprec_wrk(1)%x2l,& - & zzero,mlprec_wrk(1)%y2l,& - & baseprecv(1)%base_desc,& - & trans,work,info) - - if(info /=0) goto 9999 - - mlprec_wrk(1)%ty = mlprec_wrk(1)%x2l - - call psb_spmm(-zone,baseprecv(1)%base_a,mlprec_wrk(1)%y2l,& - & zone,mlprec_wrk(1)%ty,baseprecv(1)%base_desc,info,work=work) - if(info /=0) goto 9999 - - do ilev = 2, nlev - n_row = baseprecv(ilev-1)%base_desc%matrix_data(psb_n_row_) - n_col = baseprecv(ilev-1)%desc_data%matrix_data(psb_n_col_) - nr2l = baseprecv(ilev)%desc_data%matrix_data(psb_n_col_) - nrg = baseprecv(ilev)%desc_data%matrix_data(psb_n_row_) - ismth=baseprecv(ilev)%iprcparm(smth_kind_) - allocate(mlprec_wrk(ilev)%ty(nr2l),mlprec_wrk(ilev)%y2l(nr2l),& - & mlprec_wrk(ilev)%x2l(nr2l), stat=info) - - mlprec_wrk(ilev)%x2l(:) = zzero - mlprec_wrk(ilev)%y2l(:) = zzero - mlprec_wrk(ilev)%tx(:) = zzero - mlprec_wrk(ilev)%ty(:) = zzero - - - if (info /= 0) then - call psb_errpush(4010,name,a_err='Allocate') - goto 9999 - end if - - - if (ismth /= no_smth_) then - ! - !Smoothed Aggregation - ! - if (baseprecv(ilev)%iprcparm(glb_smth_) >0) then - - call psb_halo(mlprec_wrk(ilev-1)%ty,baseprecv(ilev-1)%base_desc,& - & info,work=work) - if(info /=0) goto 9999 - else - mlprec_wrk(ilev-1)%ty(n_row+1:max(n_row,n_col)) = zzero - end if - - call psb_csmm(zone,baseprecv(ilev)%av(sm_pr_t_),mlprec_wrk(ilev-1)%ty,zzero,& - & mlprec_wrk(ilev)%x2l,info) - if(info /=0) goto 9999 - - else - ! - ! Raw aggregation, may take shortcuts - ! - mlprec_wrk(ilev)%x2l = zzero - do i=1,n_row - mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) = & - & mlprec_wrk(ilev)%x2l(baseprecv(ilev)%mlia(i)) + & - & mlprec_wrk(ilev-1)%ty(i) - end do - end if - - if (baseprecv(ilev)%iprcparm(coarse_mat_)==mat_repl_) then - call psb_sum(ictxt,mlprec_wrk(ilev)%x2l(1:nrg)) - else if (baseprecv(ilev)%iprcparm(coarse_mat_) /= mat_distr_) then - write(0,*) 'Unknown value for baseprecv(2)%iprcparm(coarse_mat_) ',& - & baseprecv(ilev)%iprcparm(coarse_mat_) - endif - - call psb_geaxpby(zone,mlprec_wrk(ilev)%x2l,zzero,mlprec_wrk(ilev)%tx,& - & baseprecv(ilev)%base_desc,info) - if(info /=0) goto 9999 - - call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%x2l,& - & zzero,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%desc_data, 'N',work,info) - - if(info /=0) goto 9999 - - if(ilev < nlev) then - mlprec_wrk(ilev)%ty = mlprec_wrk(ilev)%x2l - call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& - & zone,mlprec_wrk(ilev)%ty,baseprecv(ilev)%base_desc,info,work=work) - if(info /=0) goto 9999 - endif - - enddo - - - do ilev=nlev-1, 1, -1 - - ismth=baseprecv(ilev+1)%iprcparm(smth_kind_) - if (ismth /= no_smth_) then - if (ismth == smth_omg_) & - & call psb_halo(mlprec_wrk(ilev+1)%y2l,baseprecv(ilev+1)%desc_data,& - & info,work=work) - call psb_csmm(zone,baseprecv(ilev+1)%av(sm_pr_),mlprec_wrk(ilev+1)%y2l,& - & zone,mlprec_wrk(ilev)%y2l,info) - if(info /=0) goto 9999 - - else - n_row = baseprecv(ilev)%base_desc%matrix_data(psb_n_row_) - do i=1, n_row - mlprec_wrk(ilev)%y2l(i) = mlprec_wrk(ilev)%y2l(i) + & - & mlprec_wrk(ilev+1)%y2l(baseprecv(ilev+1)%mlia(i)) - enddo - - end if - - call psb_spmm(-zone,baseprecv(ilev)%base_a,mlprec_wrk(ilev)%y2l,& - & zone,mlprec_wrk(ilev)%tx,baseprecv(ilev)%base_desc,info,work=work) - - if(info /=0) goto 9999 - - call psb_baseprc_aply(zone,baseprecv(ilev),mlprec_wrk(ilev)%tx,& - & zone,mlprec_wrk(ilev)%y2l,baseprecv(ilev)%base_desc, trans, work,info) - - if(info /=0) goto 9999 - - enddo - - call psb_geaxpby(alpha,mlprec_wrk(1)%y2l,beta,y,& - & baseprecv(1)%base_desc,info) - - if(info /=0) goto 9999 - - - case default - - call psb_errpush(4013,name,a_err='wrong smooth_pos',& - & i_Err=(/baseprecv(2)%iprcparm(smth_pos_),0,0,0,0/)) - goto 9999 - - end select - - case default - call psb_errpush(4013,name,a_err='wrong mltype',& - & i_Err=(/baseprecv(2)%iprcparm(ml_type_),0,0,0,0/)) - goto 9999 - - end select - - - call mlprec_wrk_free(mlprec_wrk) - deallocate(mlprec_wrk) - - call psb_erractionrestore(err_act) - return - -9999 continue - call psb_errpush(info,name) - call psb_erractionrestore(err_act) - if (err_act.eq.act_abort) then - call psb_error() - return - end if - return - -contains - subroutine mlprec_wrk_free(wrk) - type(psb_mlprec_wrk_type) :: wrk(:) - ! This will not be needed when we have allocatables, as - ! it is sufficient to deallocate the container, and - ! the compiler is supposed to recursively deallocate the - ! various components. - integer i - - do i=1, size(wrk) - if (associated(wrk(i)%tx)) deallocate(wrk(i)%tx) - if (associated(wrk(i)%ty)) deallocate(wrk(i)%ty) - if (associated(wrk(i)%x2l)) deallocate(wrk(i)%x2l) - if (associated(wrk(i)%y2l)) deallocate(wrk(i)%y2l) - if (associated(wrk(i)%b2l)) deallocate(wrk(i)%b2l) - if (associated(wrk(i)%tty)) deallocate(wrk(i)%tty) - end do - end subroutine mlprec_wrk_free - -end subroutine psb_zmlprc_aply - diff --git a/third_party/pygments/tests/run.py b/third_party/pygments/tests/run.py deleted file mode 100644 index 8167b9117..000000000 --- a/third_party/pygments/tests/run.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Pygments unit tests - ~~~~~~~~~~~~~~~~~~ - - Usage:: - - python run.py [testfile ...] - - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from __future__ import print_function - -import os -import sys - -# only find tests in this directory -if os.path.dirname(__file__): - os.chdir(os.path.dirname(__file__)) - - -try: - import nose -except ImportError: - print('nose is required to run the Pygments test suite') - sys.exit(1) - -# make sure the current source is first on sys.path -sys.path.insert(0, '..') - -if '--with-coverage' not in sys.argv: - # if running with coverage, pygments should not be imported before coverage - # is started, otherwise it will count already executed lines as uncovered - try: - import pygments - except ImportError as err: - print('Cannot find Pygments to test: %s' % err) - sys.exit(1) - else: - print('Pygments %s test suite running (Python %s)...' % - (pygments.__version__, sys.version.split()[0]), - file=sys.stderr) -else: - print('Pygments test suite running (Python %s)...' % sys.version.split()[0], - file=sys.stderr) - -nose.main() diff --git a/third_party/pygments/tests/string_asserts.py b/third_party/pygments/tests/string_asserts.py deleted file mode 100644 index 11f5c7f07..000000000 --- a/third_party/pygments/tests/string_asserts.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Pygments string assert utility - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -class StringTests(object): - - def assertStartsWith(self, haystack, needle, msg=None): - if msg is None: - msg = "'{0}' does not start with '{1}'".format(haystack, needle) - if not haystack.startswith(needle): - raise(AssertionError(msg)) - - def assertEndsWith(self, haystack, needle, msg=None): - if msg is None: - msg = "'{0}' does not end with '{1}'".format(haystack, needle) - if not haystack.endswith(needle): - raise(AssertionError(msg)) diff --git a/third_party/pygments/tests/support.py b/third_party/pygments/tests/support.py deleted file mode 100644 index c66ac6633..000000000 --- a/third_party/pygments/tests/support.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding: utf-8 -""" -Support for Pygments tests -""" - -import os - -from nose import SkipTest - - -def location(mod_name): - """ - Return the file and directory that the code for *mod_name* is in. - """ - source = mod_name.endswith("pyc") and mod_name[:-1] or mod_name - source = os.path.abspath(source) - return source, os.path.dirname(source) diff --git a/third_party/pygments/tests/support/tags b/third_party/pygments/tests/support/tags deleted file mode 100644 index 193779f6b..000000000 --- a/third_party/pygments/tests/support/tags +++ /dev/null @@ -1,36 +0,0 @@ -!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ -!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ -!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ -!_TAG_PROGRAM_NAME Exuberant Ctags // -!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ -!_TAG_PROGRAM_VERSION 5.8 // -HtmlFormatter test_html_formatter.py 19;" i -HtmlFormatterTest test_html_formatter.py 34;" c -NullFormatter test_html_formatter.py 19;" i -PythonLexer test_html_formatter.py 18;" i -StringIO test_html_formatter.py 13;" i -dirname test_html_formatter.py 16;" i -escape_html test_html_formatter.py 20;" i -fp test_html_formatter.py 27;" v -inspect test_html_formatter.py 15;" i -isfile test_html_formatter.py 16;" i -join test_html_formatter.py 16;" i -os test_html_formatter.py 10;" i -re test_html_formatter.py 11;" i -subprocess test_html_formatter.py 125;" i -support test_html_formatter.py 23;" i -tempfile test_html_formatter.py 14;" i -test_all_options test_html_formatter.py 72;" m class:HtmlFormatterTest -test_correct_output test_html_formatter.py 35;" m class:HtmlFormatterTest -test_ctags test_html_formatter.py 165;" m class:HtmlFormatterTest -test_external_css test_html_formatter.py 48;" m class:HtmlFormatterTest -test_get_style_defs test_html_formatter.py 141;" m class:HtmlFormatterTest -test_lineanchors test_html_formatter.py 98;" m class:HtmlFormatterTest -test_lineanchors_with_startnum test_html_formatter.py 106;" m class:HtmlFormatterTest -test_linenos test_html_formatter.py 82;" m class:HtmlFormatterTest -test_linenos_with_startnum test_html_formatter.py 90;" m class:HtmlFormatterTest -test_unicode_options test_html_formatter.py 155;" m class:HtmlFormatterTest -test_valid_output test_html_formatter.py 114;" m class:HtmlFormatterTest -tokensource test_html_formatter.py 29;" v -uni_open test_html_formatter.py 21;" i -unittest test_html_formatter.py 12;" i diff --git a/third_party/pygments/tests/test_basic_api.py b/third_party/pygments/tests/test_basic_api.py deleted file mode 100644 index 022e6c55a..000000000 --- a/third_party/pygments/tests/test_basic_api.py +++ /dev/null @@ -1,334 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Pygments basic API tests - ~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from __future__ import print_function - -import random -import unittest - -from pygments import lexers, formatters, lex, format -from pygments.token import _TokenType, Text -from pygments.lexer import RegexLexer -from pygments.formatters.img import FontNotFound -from pygments.util import text_type, StringIO, BytesIO, xrange, ClassNotFound - -import support - -TESTFILE, TESTDIR = support.location(__file__) - -test_content = [chr(i) for i in xrange(33, 128)] * 5 -random.shuffle(test_content) -test_content = ''.join(test_content) + '\n' - - -def test_lexer_instantiate_all(): - # instantiate every lexer, to see if the token type defs are correct - def verify(name): - getattr(lexers, name) - for x in lexers.LEXERS: - yield verify, x - - -def test_lexer_classes(): - # test that every lexer class has the correct public API - def verify(cls): - assert type(cls.name) is str - for attr in 'aliases', 'filenames', 'alias_filenames', 'mimetypes': - assert hasattr(cls, attr) - assert type(getattr(cls, attr)) is list, \ - "%s: %s attribute wrong" % (cls, attr) - result = cls.analyse_text("abc") - assert isinstance(result, float) and 0.0 <= result <= 1.0 - result = cls.analyse_text(".abc") - assert isinstance(result, float) and 0.0 <= result <= 1.0 - - assert all(al.lower() == al for al in cls.aliases) - - inst = cls(opt1="val1", opt2="val2") - if issubclass(cls, RegexLexer): - if not hasattr(cls, '_tokens'): - # if there's no "_tokens", the lexer has to be one with - # multiple tokendef variants - assert cls.token_variants - for variant in cls.tokens: - assert 'root' in cls.tokens[variant] - else: - assert 'root' in cls._tokens, \ - '%s has no root state' % cls - - if cls.name in ['XQuery', 'Opa']: # XXX temporary - return - - try: - tokens = list(inst.get_tokens(test_content)) - except KeyboardInterrupt: - raise KeyboardInterrupt( - 'interrupted %s.get_tokens(): test_content=%r' % - (cls.__name__, test_content)) - txt = "" - for token in tokens: - assert isinstance(token, tuple) - assert isinstance(token[0], _TokenType) - assert isinstance(token[1], text_type) - txt += token[1] - assert txt == test_content, "%s lexer roundtrip failed: %r != %r" % \ - (cls.name, test_content, txt) - - for lexer in lexers._iter_lexerclasses(plugins=False): - yield verify, lexer - - -def test_lexer_options(): - # test that the basic options work - def ensure(tokens, output): - concatenated = ''.join(token[1] for token in tokens) - assert concatenated == output, \ - '%s: %r != %r' % (lexer, concatenated, output) - - def verify(cls): - inst = cls(stripnl=False) - ensure(inst.get_tokens('a\nb'), 'a\nb\n') - ensure(inst.get_tokens('\n\n\n'), '\n\n\n') - inst = cls(stripall=True) - ensure(inst.get_tokens(' \n b\n\n\n'), 'b\n') - # some lexers require full lines in input - if ('ConsoleLexer' not in cls.__name__ and - 'SessionLexer' not in cls.__name__ and - not cls.__name__.startswith('Literate') and - cls.__name__ not in ('ErlangShellLexer', 'RobotFrameworkLexer')): - inst = cls(ensurenl=False) - ensure(inst.get_tokens('a\nb'), 'a\nb') - inst = cls(ensurenl=False, stripall=True) - ensure(inst.get_tokens('a\nb\n\n'), 'a\nb') - - for lexer in lexers._iter_lexerclasses(plugins=False): - if lexer.__name__ == 'RawTokenLexer': - # this one is special - continue - yield verify, lexer - - -def test_get_lexers(): - # test that the lexers functions work - def verify(func, args): - x = func(opt='val', *args) - assert isinstance(x, lexers.PythonLexer) - assert x.options["opt"] == "val" - - for func, args in [(lexers.get_lexer_by_name, ("python",)), - (lexers.get_lexer_for_filename, ("test.py",)), - (lexers.get_lexer_for_mimetype, ("text/x-python",)), - (lexers.guess_lexer, ("#!/usr/bin/python -O\nprint",)), - (lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>")) - ]: - yield verify, func, args - - for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items(): - assert cls == lexers.find_lexer_class(lname).__name__ - - for alias in aliases: - assert cls == lexers.get_lexer_by_name(alias).__class__.__name__ - - for mimetype in mimetypes: - assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__ - - try: - lexers.get_lexer_by_name(None) - except ClassNotFound: - pass - else: - raise Exception - - -def test_formatter_public_api(): - # test that every formatter class has the correct public API - ts = list(lexers.PythonLexer().get_tokens("def f(): pass")) - string_out = StringIO() - bytes_out = BytesIO() - - def verify(formatter): - info = formatters.FORMATTERS[formatter.__name__] - assert len(info) == 5 - assert info[1], "missing formatter name" - assert info[2], "missing formatter aliases" - assert info[4], "missing formatter docstring" - - try: - inst = formatter(opt1="val1") - except (ImportError, FontNotFound): - raise support.SkipTest - - try: - inst.get_style_defs() - except NotImplementedError: - # may be raised by formatters for which it doesn't make sense - pass - - if formatter.unicodeoutput: - inst.format(ts, string_out) - else: - inst.format(ts, bytes_out) - - for name in formatters.FORMATTERS: - formatter = getattr(formatters, name) - yield verify, formatter - - -def test_formatter_encodings(): - from pygments.formatters import HtmlFormatter - - # unicode output - fmt = HtmlFormatter() - tokens = [(Text, u"ä")] - out = format(tokens, fmt) - assert type(out) is text_type - assert u"ä" in out - - # encoding option - fmt = HtmlFormatter(encoding="latin1") - tokens = [(Text, u"ä")] - assert u"ä".encode("latin1") in format(tokens, fmt) - - # encoding and outencoding option - fmt = HtmlFormatter(encoding="latin1", outencoding="utf8") - tokens = [(Text, u"ä")] - assert u"ä".encode("utf8") in format(tokens, fmt) - - -def test_formatter_unicode_handling(): - # test that the formatter supports encoding and Unicode - tokens = list(lexers.PythonLexer(encoding='utf-8'). - get_tokens("def f(): 'ä'")) - - def verify(formatter): - try: - inst = formatter(encoding=None) - except (ImportError, FontNotFound): - # some dependency or font not installed - raise support.SkipTest - - if formatter.name != 'Raw tokens': - out = format(tokens, inst) - if formatter.unicodeoutput: - assert type(out) is text_type, '%s: %r' % (formatter, out) - - inst = formatter(encoding='utf-8') - out = format(tokens, inst) - assert type(out) is bytes, '%s: %r' % (formatter, out) - # Cannot test for encoding, since formatters may have to escape - # non-ASCII characters. - else: - inst = formatter() - out = format(tokens, inst) - assert type(out) is bytes, '%s: %r' % (formatter, out) - - for formatter, info in formatters.FORMATTERS.items(): - # this tests the automatic importing as well - fmter = getattr(formatters, formatter) - yield verify, fmter - - -def test_get_formatters(): - # test that the formatters functions work - x = formatters.get_formatter_by_name("html", opt="val") - assert isinstance(x, formatters.HtmlFormatter) - assert x.options["opt"] == "val" - - x = formatters.get_formatter_for_filename("a.html", opt="val") - assert isinstance(x, formatters.HtmlFormatter) - assert x.options["opt"] == "val" - - -def test_styles(): - # minimal style test - from pygments.formatters import HtmlFormatter - HtmlFormatter(style="pastie") - - -def test_bare_class_handler(): - from pygments.formatters import HtmlFormatter - from pygments.lexers import PythonLexer - try: - lex('test\n', PythonLexer) - except TypeError as e: - assert 'lex() argument must be a lexer instance' in str(e) - else: - assert False, 'nothing raised' - try: - format([], HtmlFormatter) - except TypeError as e: - assert 'format() argument must be a formatter instance' in str(e) - else: - assert False, 'nothing raised' - - -class FiltersTest(unittest.TestCase): - - def test_basic(self): - filters_args = [ - ('whitespace', {'spaces': True, 'tabs': True, 'newlines': True}), - ('whitespace', {'wstokentype': False, 'spaces': True}), - ('highlight', {'names': ['isinstance', 'lexers', 'x']}), - ('codetagify', {'codetags': 'API'}), - ('keywordcase', {'case': 'capitalize'}), - ('raiseonerror', {}), - ('gobble', {'n': 4}), - ('tokenmerge', {}), - ] - for x, args in filters_args: - lx = lexers.PythonLexer() - lx.add_filter(x, **args) - with open(TESTFILE, 'rb') as fp: - text = fp.read().decode('utf-8') - tokens = list(lx.get_tokens(text)) - self.assertTrue(all(isinstance(t[1], text_type) - for t in tokens), - '%s filter did not return Unicode' % x) - roundtext = ''.join([t[1] for t in tokens]) - if x not in ('whitespace', 'keywordcase', 'gobble'): - # these filters change the text - self.assertEqual(roundtext, text, - "lexer roundtrip with %s filter failed" % x) - - def test_raiseonerror(self): - lx = lexers.PythonLexer() - lx.add_filter('raiseonerror', excclass=RuntimeError) - self.assertRaises(RuntimeError, list, lx.get_tokens('$')) - - def test_whitespace(self): - lx = lexers.PythonLexer() - lx.add_filter('whitespace', spaces='%') - with open(TESTFILE, 'rb') as fp: - text = fp.read().decode('utf-8') - lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) - self.assertFalse(' ' in lxtext) - - def test_keywordcase(self): - lx = lexers.PythonLexer() - lx.add_filter('keywordcase', case='capitalize') - with open(TESTFILE, 'rb') as fp: - text = fp.read().decode('utf-8') - lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) - self.assertTrue('Def' in lxtext and 'Class' in lxtext) - - def test_codetag(self): - lx = lexers.PythonLexer() - lx.add_filter('codetagify') - text = u'# BUG: text' - tokens = list(lx.get_tokens(text)) - self.assertEqual('# ', tokens[0][1]) - self.assertEqual('BUG', tokens[1][1]) - - def test_codetag_boundary(self): - # ticket #368 - lx = lexers.PythonLexer() - lx.add_filter('codetagify') - text = u'# DEBUG: text' - tokens = list(lx.get_tokens(text)) - self.assertEqual('# DEBUG: text', tokens[0][1]) diff --git a/third_party/pygments/tests/test_cfm.py b/third_party/pygments/tests/test_cfm.py deleted file mode 100644 index 2585489af..000000000 --- a/third_party/pygments/tests/test_cfm.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Basic ColdfusionHtmlLexer Test - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import unittest -import os - -from pygments.token import Token -from pygments.lexers import ColdfusionHtmlLexer - - -class ColdfusionHtmlLexerTest(unittest.TestCase): - - def setUp(self): - self.lexer = ColdfusionHtmlLexer() - - def testBasicComment(self): - fragment = u'' - expected = [ - (Token.Text, u''), - (Token.Comment.Multiline, u''), - (Token.Text, u'\n'), - ] - self.assertEqual(expected, list(self.lexer.get_tokens(fragment))) - - def testNestedComment(self): - fragment = u' --->' - expected = [ - (Token.Text, u''), - (Token.Comment.Multiline, u''), - (Token.Comment.Multiline, u' '), - (Token.Comment.Multiline, u'--->'), - (Token.Text, u'\n'), - ] - self.assertEqual(expected, list(self.lexer.get_tokens(fragment))) diff --git a/third_party/pygments/tests/test_clexer.py b/third_party/pygments/tests/test_clexer.py deleted file mode 100644 index fd7f58fc2..000000000 --- a/third_party/pygments/tests/test_clexer.py +++ /dev/null @@ -1,259 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Basic CLexer Test - ~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import unittest -import os -import textwrap - -from pygments.token import Text, Number, Token -from pygments.lexers import CLexer - - -class CLexerTest(unittest.TestCase): - - def setUp(self): - self.lexer = CLexer() - - def testNumbers(self): - code = '42 23.42 23. .42 023 0xdeadbeef 23e+42 42e-23' - wanted = [] - for item in zip([Number.Integer, Number.Float, Number.Float, - Number.Float, Number.Oct, Number.Hex, - Number.Float, Number.Float], code.split()): - wanted.append(item) - wanted.append((Text, ' ')) - wanted = wanted[:-1] + [(Text, '\n')] - self.assertEqual(list(self.lexer.get_tokens(code)), wanted) - - def testSwitch(self): - fragment = u'''\ - int main() - { - switch (0) - { - case 0: - default: - ; - } - } - ''' - tokens = [ - (Token.Keyword.Type, u'int'), - (Token.Text, u' '), - (Token.Name.Function, u'main'), - (Token.Punctuation, u'('), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'switch'), - (Token.Text, u' '), - (Token.Punctuation, u'('), - (Token.Literal.Number.Integer, u'0'), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'case'), - (Token.Text, u' '), - (Token.Literal.Number.Integer, u'0'), - (Token.Operator, u':'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'default'), - (Token.Operator, u':'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Punctuation, u';'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) - - def testSwitchSpaceBeforeColon(self): - fragment = u'''\ - int main() - { - switch (0) - { - case 0 : - default : - ; - } - } - ''' - tokens = [ - (Token.Keyword.Type, u'int'), - (Token.Text, u' '), - (Token.Name.Function, u'main'), - (Token.Punctuation, u'('), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'switch'), - (Token.Text, u' '), - (Token.Punctuation, u'('), - (Token.Literal.Number.Integer, u'0'), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'case'), - (Token.Text, u' '), - (Token.Literal.Number.Integer, u'0'), - (Token.Text, u' '), - (Token.Operator, u':'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'default'), - (Token.Text, u' '), - (Token.Operator, u':'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Punctuation, u';'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) - - def testLabel(self): - fragment = u'''\ - int main() - { - foo: - goto foo; - } - ''' - tokens = [ - (Token.Keyword.Type, u'int'), - (Token.Text, u' '), - (Token.Name.Function, u'main'), - (Token.Punctuation, u'('), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Name.Label, u'foo'), - (Token.Punctuation, u':'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'goto'), - (Token.Text, u' '), - (Token.Name, u'foo'), - (Token.Punctuation, u';'), - (Token.Text, u'\n'), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) - - def testLabelSpaceBeforeColon(self): - fragment = u'''\ - int main() - { - foo : - goto foo; - } - ''' - tokens = [ - (Token.Keyword.Type, u'int'), - (Token.Text, u' '), - (Token.Name.Function, u'main'), - (Token.Punctuation, u'('), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Name.Label, u'foo'), - (Token.Text, u' '), - (Token.Punctuation, u':'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'goto'), - (Token.Text, u' '), - (Token.Name, u'foo'), - (Token.Punctuation, u';'), - (Token.Text, u'\n'), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) - - def testLabelFollowedByStatement(self): - fragment = u'''\ - int main() - { - foo:return 0; - goto foo; - } - ''' - tokens = [ - (Token.Keyword.Type, u'int'), - (Token.Text, u' '), - (Token.Name.Function, u'main'), - (Token.Punctuation, u'('), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Punctuation, u'{'), - (Token.Text, u'\n'), - (Token.Name.Label, u'foo'), - (Token.Punctuation, u':'), - (Token.Keyword, u'return'), - (Token.Text, u' '), - (Token.Literal.Number.Integer, u'0'), - (Token.Punctuation, u';'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'goto'), - (Token.Text, u' '), - (Token.Name, u'foo'), - (Token.Punctuation, u';'), - (Token.Text, u'\n'), - (Token.Punctuation, u'}'), - (Token.Text, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment)))) - - def testPreprocFile(self): - fragment = u'#include \n' - tokens = [ - (Token.Comment.Preproc, u'#'), - (Token.Comment.Preproc, u'include'), - (Token.Text, u' '), - (Token.Comment.PreprocFile, u''), - (Token.Comment.Preproc, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(fragment))) - - def testPreprocFile2(self): - fragment = u'#include "foo.h"\n' - tokens = [ - (Token.Comment.Preproc, u'#'), - (Token.Comment.Preproc, u'include'), - (Token.Text, u' '), - (Token.Comment.PreprocFile, u'"foo.h"'), - (Token.Comment.Preproc, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(fragment))) - diff --git a/third_party/pygments/tests/test_cmdline.py b/third_party/pygments/tests/test_cmdline.py deleted file mode 100644 index 5883fb5cb..000000000 --- a/third_party/pygments/tests/test_cmdline.py +++ /dev/null @@ -1,252 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Command line test - ~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from __future__ import print_function - -import io -import os -import re -import sys -import tempfile -import unittest - -import support -from pygments import cmdline, highlight -from pygments.util import BytesIO, StringIO - - -TESTFILE, TESTDIR = support.location(__file__) -TESTCODE = '''\ -def func(args): - pass -''' - - -def run_cmdline(*args, **kwds): - saved_stdin = sys.stdin - saved_stdout = sys.stdout - saved_stderr = sys.stderr - if sys.version_info > (3,): - stdin_buffer = BytesIO() - stdout_buffer = BytesIO() - stderr_buffer = BytesIO() - new_stdin = sys.stdin = io.TextIOWrapper(stdin_buffer, 'utf-8') - new_stdout = sys.stdout = io.TextIOWrapper(stdout_buffer, 'utf-8') - new_stderr = sys.stderr = io.TextIOWrapper(stderr_buffer, 'utf-8') - else: - stdin_buffer = new_stdin = sys.stdin = StringIO() - stdout_buffer = new_stdout = sys.stdout = StringIO() - stderr_buffer = new_stderr = sys.stderr = StringIO() - new_stdin.write(kwds.get('stdin', '')) - new_stdin.seek(0, 0) - try: - ret = cmdline.main(['pygmentize'] + list(args)) - finally: - sys.stdin = saved_stdin - sys.stdout = saved_stdout - sys.stderr = saved_stderr - new_stdout.flush() - new_stderr.flush() - out, err = stdout_buffer.getvalue().decode('utf-8'), \ - stderr_buffer.getvalue().decode('utf-8') - return (ret, out, err) - - -class CmdLineTest(unittest.TestCase): - - def check_success(self, *cmdline, **kwds): - code, out, err = run_cmdline(*cmdline, **kwds) - self.assertEqual(code, 0) - self.assertEqual(err, '') - return out - - def check_failure(self, *cmdline, **kwds): - expected_code = kwds.pop('code', 1) - code, out, err = run_cmdline(*cmdline, **kwds) - self.assertEqual(code, expected_code) - self.assertEqual(out, '') - return err - - def test_normal(self): - # test that cmdline gives the same output as library api - from pygments.lexers import PythonLexer - from pygments.formatters import HtmlFormatter - filename = TESTFILE - with open(filename, 'rb') as fp: - code = fp.read() - - output = highlight(code, PythonLexer(), HtmlFormatter()) - - o = self.check_success('-lpython', '-fhtml', filename) - self.assertEqual(o, output) - - def test_stdin(self): - o = self.check_success('-lpython', '-fhtml', stdin=TESTCODE) - o = re.sub('<[^>]*>', '', o) - # rstrip is necessary since HTML inserts a \n after the last
    - self.assertEqual(o.rstrip(), TESTCODE.rstrip()) - - # guess if no lexer given - o = self.check_success('-fhtml', stdin=TESTCODE) - o = re.sub('<[^>]*>', '', o) - # rstrip is necessary since HTML inserts a \n after the last
    - self.assertEqual(o.rstrip(), TESTCODE.rstrip()) - - def test_outfile(self): - # test that output file works with and without encoding - fd, name = tempfile.mkstemp() - os.close(fd) - for opts in [['-fhtml', '-o', name, TESTFILE], - ['-flatex', '-o', name, TESTFILE], - ['-fhtml', '-o', name, '-O', 'encoding=utf-8', TESTFILE]]: - try: - self.check_success(*opts) - finally: - os.unlink(name) - - def test_stream_opt(self): - o = self.check_success('-lpython', '-s', '-fterminal', stdin=TESTCODE) - o = re.sub(r'\x1b\[.*?m', '', o) - self.assertEqual(o.replace('\r\n', '\n'), TESTCODE) - - def test_h_opt(self): - o = self.check_success('-h') - self.assertTrue('Usage:' in o) - - def test_L_opt(self): - o = self.check_success('-L') - self.assertTrue('Lexers' in o and 'Formatters' in o and - 'Filters' in o and 'Styles' in o) - o = self.check_success('-L', 'lexer') - self.assertTrue('Lexers' in o and 'Formatters' not in o) - self.check_success('-L', 'lexers') - - def test_O_opt(self): - filename = TESTFILE - o = self.check_success('-Ofull=1,linenos=true,foo=bar', - '-fhtml', filename) - self.assertTrue('foo, bar=baz=,' in o) - - def test_F_opt(self): - filename = TESTFILE - o = self.check_success('-Fhighlight:tokentype=Name.Blubb,' - 'names=TESTFILE filename', - '-fhtml', filename) - self.assertTrue('_filename ' - 'for overriding, thus no lexer found.' - % fn) - yield check_lexer, lx, fn - - N = 7 - stats = list(STATS.items()) - stats.sort(key=lambda x: x[1][1]) - print('\nExample files that took longest absolute time:') - for fn, t in stats[-N:]: - print('%-30s %6d chars %8.2f ms %7.3f ms/char' % ((fn,) + t)) - print() - stats.sort(key=lambda x: x[1][2]) - print('\nExample files that took longest relative time:') - for fn, t in stats[-N:]: - print('%-30s %6d chars %8.2f ms %7.3f ms/char' % ((fn,) + t)) - - -def check_lexer(lx, fn): - if os.name == 'java' and fn in BAD_FILES_FOR_JYTHON: - raise support.SkipTest - absfn = os.path.join(TESTDIR, 'examplefiles', fn) - with open(absfn, 'rb') as fp: - text = fp.read() - text = text.replace(b'\r\n', b'\n') - text = text.strip(b'\n') + b'\n' - try: - text = text.decode('utf-8') - if text.startswith(u'\ufeff'): - text = text[len(u'\ufeff'):] - except UnicodeError: - text = text.decode('latin1') - ntext = [] - tokens = [] - import time - t1 = time.time() - for type, val in lx.get_tokens(text): - ntext.append(val) - assert type != Error, \ - 'lexer %s generated error token for %s: %r at position %d' % \ - (lx, absfn, val, len(u''.join(ntext))) - tokens.append((type, val)) - t2 = time.time() - STATS[os.path.basename(absfn)] = (len(text), - 1000 * (t2 - t1), 1000 * (t2 - t1) / len(text)) - if u''.join(ntext) != text: - print('\n'.join(difflib.unified_diff(u''.join(ntext).splitlines(), - text.splitlines()))) - raise AssertionError('round trip failed for ' + absfn) - - # check output against previous run if enabled - if STORE_OUTPUT: - # no previous output -- store it - outfn = os.path.join(TESTDIR, 'examplefiles', 'output', fn) - if not os.path.isfile(outfn): - with open(outfn, 'wb') as fp: - pickle.dump(tokens, fp) - return - # otherwise load it and compare - with open(outfn, 'rb') as fp: - stored_tokens = pickle.load(fp) - if stored_tokens != tokens: - f1 = pprint.pformat(stored_tokens) - f2 = pprint.pformat(tokens) - print('\n'.join(difflib.unified_diff(f1.splitlines(), - f2.splitlines()))) - assert False, absfn diff --git a/third_party/pygments/tests/test_ezhil.py b/third_party/pygments/tests/test_ezhil.py deleted file mode 100644 index 23b9cb418..000000000 --- a/third_party/pygments/tests/test_ezhil.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Basic EzhilLexer Test - ~~~~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2015 Muthiah Annamalai - :license: BSD, see LICENSE for details. -""" - -import unittest - -from pygments.token import Operator, Number, Text, Token -from pygments.lexers import EzhilLexer - - -class EzhilTest(unittest.TestCase): - - def setUp(self): - self.lexer = EzhilLexer() - self.maxDiff = None - - def testSum(self): - fragment = u'1+3\n' - tokens = [ - (Number.Integer, u'1'), - (Operator, u'+'), - (Number.Integer, u'3'), - (Text, u'\n'), - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(fragment))) - - def testGCDExpr(self): - fragment = u'1^3+(5-5)*gcd(a,b)\n' - tokens = [ - (Token.Number.Integer,u'1'), - (Token.Operator,u'^'), - (Token.Literal.Number.Integer, u'3'), - (Token.Operator, u'+'), - (Token.Punctuation, u'('), - (Token.Literal.Number.Integer, u'5'), - (Token.Operator, u'-'), - (Token.Literal.Number.Integer, u'5'), - (Token.Punctuation, u')'), - (Token.Operator, u'*'), - (Token.Name, u'gcd'), - (Token.Punctuation, u'('), - (Token.Name, u'a'), - (Token.Operator, u','), - (Token.Name, u'b'), - (Token.Punctuation, u')'), - (Token.Text, u'\n') - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(fragment))) - - def testIfStatement(self): - fragment = u"""@( 0 > 3 ) ஆனால் - பதிப்பி "wont print" -முடி""" - tokens = [ - (Token.Operator, u'@'), - (Token.Punctuation, u'('), - (Token.Text, u' '), - (Token.Literal.Number.Integer,u'0'), - (Token.Text, u' '), - (Token.Operator,u'>'), - (Token.Text, u' '), - (Token.Literal.Number.Integer, u'3'), - (Token.Text, u' '), - (Token.Punctuation, u')'), - (Token.Text, u' '), - (Token.Keyword, u'ஆனால்'), - (Token.Text, u'\n'), - (Token.Text, u'\t'), - (Token.Keyword, u'பதிப்பி'), - (Token.Text, u' '), - (Token.Literal.String, u'"wont print"'), - (Token.Text, u'\t'), - (Token.Text, u'\n'), - (Token.Keyword, u'முடி'), - (Token.Text, u'\n') - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(fragment))) - - def testFunction(self): - fragment = u"""# (C) முத்தையா அண்ணாமலை 2013, 2015 -நிரல்பாகம் gcd ( x, y ) - மு = max(x,y) - q = min(x,y) - - @( q == 0 ) ஆனால் - பின்கொடு மு - முடி - பின்கொடு gcd( மு - q , q ) -முடி\n""" - tokens = [ - (Token.Comment.Single, - u'# (C) \u0bae\u0bc1\u0ba4\u0bcd\u0ba4\u0bc8\u0baf\u0bbe \u0b85\u0ba3\u0bcd\u0ba3\u0bbe\u0bae\u0bb2\u0bc8 2013, 2015\n'), - (Token.Keyword,u'நிரல்பாகம்'), - (Token.Text, u' '), - (Token.Name, u'gcd'), - (Token.Text, u' '), - (Token.Punctuation, u'('), - (Token.Text, u' '), - (Token.Name, u'x'), - (Token.Operator, u','), - (Token.Text, u' '), - (Token.Name, u'y'), - (Token.Text, u' '), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Name, u'\u0bae\u0bc1'), - (Token.Text, u' '), - (Token.Operator, u'='), - (Token.Text, u' '), - (Token.Name.Builtin, u'max'), - (Token.Punctuation, u'('), - (Token.Name, u'x'), - (Token.Operator, u','), - (Token.Name, u'y'), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Name, u'q'), - (Token.Text, u' '), - (Token.Operator, u'='), - (Token.Text, u' '), - (Token.Name.Builtin, u'min'), - (Token.Punctuation, u'('), - (Token.Name, u'x'), - (Token.Operator, u','), - (Token.Name, u'y'), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Operator, u'@'), - (Token.Punctuation, u'('), - (Token.Text, u' '), - (Token.Name, u'q'), - (Token.Text, u' '), - (Token.Operator, u'=='), - (Token.Text, u' '), - (Token.Literal.Number.Integer, u'0'), - (Token.Text, u' '), - (Token.Punctuation, u')'), - (Token.Text, u' '), - (Token.Keyword, u'ஆனால்'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'பின்கொடு'), - (Token.Text, u' '), - (Token.Name, u'\u0bae\u0bc1'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'முடி'), - (Token.Text, u'\n'), - (Token.Text, u' '), - (Token.Keyword, u'\u0baa\u0bbf\u0ba9\u0bcd\u0b95\u0bca\u0b9f\u0bc1'), - (Token.Text, u' '), - (Token.Name, u'gcd'), - (Token.Punctuation, u'('), - (Token.Text, u' '), - (Token.Name, u'\u0bae\u0bc1'), - (Token.Text, u' '), - (Token.Operator, u'-'), - (Token.Text, u' '), - (Token.Name, u'q'), - (Token.Text, u' '), - (Token.Operator, u','), - (Token.Text, u' '), - (Token.Name, u'q'), - (Token.Text, u' '), - (Token.Punctuation, u')'), - (Token.Text, u'\n'), - (Token.Keyword, u'முடி'), #u'\u0bae\u0bc1\u0b9f\u0bbf'), - (Token.Text, u'\n') - ] - self.assertEqual(tokens, list(self.lexer.get_tokens(fragment))) - -if __name__ == "__main__": - unittest.main() diff --git a/third_party/pygments/tests/test_html_formatter.py b/third_party/pygments/tests/test_html_formatter.py deleted file mode 100644 index 596d9fbc3..000000000 --- a/third_party/pygments/tests/test_html_formatter.py +++ /dev/null @@ -1,202 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Pygments HTML formatter tests - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from __future__ import print_function - -import io -import os -import re -import unittest -import tempfile -from os.path import join, dirname, isfile - -from pygments.util import StringIO -from pygments.lexers import PythonLexer -from pygments.formatters import HtmlFormatter, NullFormatter -from pygments.formatters.html import escape_html - -import support - -TESTFILE, TESTDIR = support.location(__file__) - -with io.open(TESTFILE, encoding='utf-8') as fp: - tokensource = list(PythonLexer().get_tokens(fp.read())) - - -class HtmlFormatterTest(unittest.TestCase): - def test_correct_output(self): - hfmt = HtmlFormatter(nowrap=True) - houtfile = StringIO() - hfmt.format(tokensource, houtfile) - - nfmt = NullFormatter() - noutfile = StringIO() - nfmt.format(tokensource, noutfile) - - stripped_html = re.sub('<.*?>', '', houtfile.getvalue()) - escaped_text = escape_html(noutfile.getvalue()) - self.assertEqual(stripped_html, escaped_text) - - def test_external_css(self): - # test correct behavior - # CSS should be in /tmp directory - fmt1 = HtmlFormatter(full=True, cssfile='fmt1.css', outencoding='utf-8') - # CSS should be in TESTDIR (TESTDIR is absolute) - fmt2 = HtmlFormatter(full=True, cssfile=join(TESTDIR, 'fmt2.css'), - outencoding='utf-8') - tfile = tempfile.NamedTemporaryFile(suffix='.html') - fmt1.format(tokensource, tfile) - try: - fmt2.format(tokensource, tfile) - self.assertTrue(isfile(join(TESTDIR, 'fmt2.css'))) - except IOError: - # test directory not writable - pass - tfile.close() - - self.assertTrue(isfile(join(dirname(tfile.name), 'fmt1.css'))) - os.unlink(join(dirname(tfile.name), 'fmt1.css')) - try: - os.unlink(join(TESTDIR, 'fmt2.css')) - except OSError: - pass - - def test_all_options(self): - def check(optdict): - outfile = StringIO() - fmt = HtmlFormatter(**optdict) - fmt.format(tokensource, outfile) - - for optdict in [ - dict(nowrap=True), - dict(linenos=True, full=True), - dict(linenos=True, linespans='L'), - dict(hl_lines=[1, 5, 10, 'xxx']), - dict(hl_lines=[1, 5, 10], noclasses=True), - ]: - check(optdict) - - for linenos in [False, 'table', 'inline']: - for noclasses in [False, True]: - for linenospecial in [0, 5]: - for anchorlinenos in [False, True]: - optdict = dict( - linenos=linenos, - noclasses=noclasses, - linenospecial=linenospecial, - anchorlinenos=anchorlinenos, - ) - check(optdict) - - def test_linenos(self): - optdict = dict(linenos=True) - outfile = StringIO() - fmt = HtmlFormatter(**optdict) - fmt.format(tokensource, outfile) - html = outfile.getvalue() - self.assertTrue(re.search("
    \s+1\s+2\s+3", html))
    -
    -    def test_linenos_with_startnum(self):
    -        optdict = dict(linenos=True, linenostart=5)
    -        outfile = StringIO()
    -        fmt = HtmlFormatter(**optdict)
    -        fmt.format(tokensource, outfile)
    -        html = outfile.getvalue()
    -        self.assertTrue(re.search("
    \s+5\s+6\s+7", html))
    -
    -    def test_lineanchors(self):
    -        optdict = dict(lineanchors="foo")
    -        outfile = StringIO()
    -        fmt = HtmlFormatter(**optdict)
    -        fmt.format(tokensource, outfile)
    -        html = outfile.getvalue()
    -        self.assertTrue(re.search("
    ", html))
    -
    -    def test_lineanchors_with_startnum(self):
    -        optdict = dict(lineanchors="foo", linenostart=5)
    -        outfile = StringIO()
    -        fmt = HtmlFormatter(**optdict)
    -        fmt.format(tokensource, outfile)
    -        html = outfile.getvalue()
    -        self.assertTrue(re.search("
    ", html))
    -
    -    def test_valid_output(self):
    -        # test all available wrappers
    -        fmt = HtmlFormatter(full=True, linenos=True, noclasses=True,
    -                            outencoding='utf-8')
    -
    -        handle, pathname = tempfile.mkstemp('.html')
    -        tfile = os.fdopen(handle, 'w+b')
    -        fmt.format(tokensource, tfile)
    -        tfile.close()
    -        catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc')
    -        try:
    -            import subprocess
    -            po = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname],
    -                                  stdout=subprocess.PIPE)
    -            ret = po.wait()
    -            output = po.stdout.read()
    -            po.stdout.close()
    -        except OSError:
    -            # nsgmls not available
    -            pass
    -        else:
    -            if ret:
    -                print(output)
    -            self.assertFalse(ret, 'nsgmls run reported errors')
    -
    -        os.unlink(pathname)
    -
    -    def test_get_style_defs(self):
    -        fmt = HtmlFormatter()
    -        sd = fmt.get_style_defs()
    -        self.assertTrue(sd.startswith('.'))
    -
    -        fmt = HtmlFormatter(cssclass='foo')
    -        sd = fmt.get_style_defs()
    -        self.assertTrue(sd.startswith('.foo'))
    -        sd = fmt.get_style_defs('.bar')
    -        self.assertTrue(sd.startswith('.bar'))
    -        sd = fmt.get_style_defs(['.bar', '.baz'])
    -        fl = sd.splitlines()[0]
    -        self.assertTrue('.bar' in fl and '.baz' in fl)
    -
    -    def test_unicode_options(self):
    -        fmt = HtmlFormatter(title=u'Föö',
    -                            cssclass=u'bär',
    -                            cssstyles=u'div:before { content: \'bäz\' }',
    -                            encoding='utf-8')
    -        handle, pathname = tempfile.mkstemp('.html')
    -        tfile = os.fdopen(handle, 'w+b')
    -        fmt.format(tokensource, tfile)
    -        tfile.close()
    -
    -    def test_ctags(self):
    -        try:
    -            import ctags
    -        except ImportError:
    -            # we can't check without the ctags module, but at least check the exception
    -            self.assertRaises(RuntimeError, HtmlFormatter, tagsfile='support/tags')
    -        else:
    -            # this tagfile says that test_ctags() is on line 165, even if it isn't
    -            # anymore in the actual source
    -            fmt = HtmlFormatter(tagsfile='support/tags', lineanchors='L',
    -                                tagurlformat='%(fname)s%(fext)s')
    -            outfile = StringIO()
    -            fmt.format(tokensource, outfile)
    -            self.assertTrue('test_ctags'
    -                            in outfile.getvalue())
    -
    -    def test_filename(self):
    -        optdict = dict(filename="test.py")
    -        outfile = StringIO()
    -        fmt = HtmlFormatter(**optdict)
    -        fmt.format(tokensource, outfile)
    -        html = outfile.getvalue()
    -        self.assertTrue(re.search("test.py
    ", html))
    diff --git a/third_party/pygments/tests/test_inherit.py b/third_party/pygments/tests/test_inherit.py
    deleted file mode 100644
    index 34033a082..000000000
    --- a/third_party/pygments/tests/test_inherit.py
    +++ /dev/null
    @@ -1,94 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Tests for inheritance in RegexLexer
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.lexer import RegexLexer, inherit
    -from pygments.token import Text
    -
    -
    -class InheritTest(unittest.TestCase):
    -    def test_single_inheritance_position(self):
    -        t = Two()
    -        pats = [x[0].__self__.pattern for x in t._tokens['root']]
    -        self.assertEqual(['x', 'a', 'b', 'y'], pats)
    -    def test_multi_inheritance_beginning(self):
    -        t = Beginning()
    -        pats = [x[0].__self__.pattern for x in t._tokens['root']]
    -        self.assertEqual(['x', 'a', 'b', 'y', 'm'], pats)
    -    def test_multi_inheritance_end(self):
    -        t = End()
    -        pats = [x[0].__self__.pattern for x in t._tokens['root']]
    -        self.assertEqual(['m', 'x', 'a', 'b', 'y'], pats)
    -
    -    def test_multi_inheritance_position(self):
    -        t = Three()
    -        pats = [x[0].__self__.pattern for x in t._tokens['root']]
    -        self.assertEqual(['i', 'x', 'a', 'b', 'y', 'j'], pats)
    -
    -    def test_single_inheritance_with_skip(self):
    -        t = Skipped()
    -        pats = [x[0].__self__.pattern for x in t._tokens['root']]
    -        self.assertEqual(['x', 'a', 'b', 'y'], pats)
    -
    -
    -class One(RegexLexer):
    -    tokens = {
    -        'root': [
    -            ('a', Text),
    -            ('b', Text),
    -        ],
    -    }
    -
    -class Two(One):
    -    tokens = {
    -        'root': [
    -            ('x', Text),
    -            inherit,
    -            ('y', Text),
    -        ],
    -    }
    -
    -class Three(Two):
    -    tokens = {
    -        'root': [
    -            ('i', Text),
    -            inherit,
    -            ('j', Text),
    -        ],
    -    }
    -
    -class Beginning(Two):
    -    tokens = {
    -        'root': [
    -            inherit,
    -            ('m', Text),
    -        ],
    -    }
    -
    -class End(Two):
    -    tokens = {
    -        'root': [
    -            ('m', Text),
    -            inherit,
    -        ],
    -    }
    -
    -class Empty(One):
    -    tokens = {}
    -
    -class Skipped(Empty):
    -    tokens = {
    -        'root': [
    -            ('x', Text),
    -            inherit,
    -            ('y', Text),
    -        ],
    -    }
    -
    diff --git a/third_party/pygments/tests/test_irc_formatter.py b/third_party/pygments/tests/test_irc_formatter.py
    deleted file mode 100644
    index 16a8fd30c..000000000
    --- a/third_party/pygments/tests/test_irc_formatter.py
    +++ /dev/null
    @@ -1,30 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments IRC formatter tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -from __future__ import print_function
    -
    -import re
    -import unittest
    -
    -from pygments.util import StringIO
    -from pygments.lexers import PythonLexer
    -from pygments.formatters import IRCFormatter
    -
    -import support
    -
    -tokensource = list(PythonLexer().get_tokens("lambda x: 123"))
    -
    -class IRCFormatterTest(unittest.TestCase):
    -    def test_correct_output(self):
    -        hfmt = IRCFormatter()
    -        houtfile = StringIO()
    -        hfmt.format(tokensource, houtfile)
    -
    -        self.assertEqual(u'\x0302lambda\x03 x: \x0302123\x03\n', houtfile.getvalue())
    -
    diff --git a/third_party/pygments/tests/test_java.py b/third_party/pygments/tests/test_java.py
    deleted file mode 100644
    index f4096647b..000000000
    --- a/third_party/pygments/tests/test_java.py
    +++ /dev/null
    @@ -1,78 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Basic JavaLexer Test
    -    ~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.token import Text, Name, Operator, Keyword, Number
    -from pygments.lexers import JavaLexer
    -
    -
    -class JavaTest(unittest.TestCase):
    -
    -    def setUp(self):
    -        self.lexer = JavaLexer()
    -        self.maxDiff = None
    -
    -    def testEnhancedFor(self):
    -        fragment = u'label:\nfor(String var2: var1) {}\n'
    -        tokens = [
    -            (Name.Label, u'label:'),
    -            (Text, u'\n'),
    -            (Keyword, u'for'),
    -            (Operator, u'('),
    -            (Name, u'String'),
    -            (Text, u' '),
    -            (Name, u'var2'),
    -            (Operator, u':'),
    -            (Text, u' '),
    -            (Name, u'var1'),
    -            (Operator, u')'),
    -            (Text, u' '),
    -            (Operator, u'{'),
    -            (Operator, u'}'),
    -            (Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testNumericLiterals(self):
    -        fragment = '0 5L 9__542_72l 0xbEEf 0X9_A 0_35 01 0b0___101_0'
    -        fragment += ' 0. .7_17F 3e-1_3d 1f 6_01.9e+3 0x.1Fp3 0XEP8D\n'
    -        tokens = [
    -            (Number.Integer, '0'),
    -            (Text, ' '),
    -            (Number.Integer, '5L'),
    -            (Text, ' '),
    -            (Number.Integer, '9__542_72l'),
    -            (Text, ' '),
    -            (Number.Hex, '0xbEEf'),
    -            (Text, ' '),
    -            (Number.Hex, '0X9_A'),
    -            (Text, ' '),
    -            (Number.Oct, '0_35'),
    -            (Text, ' '),
    -            (Number.Oct, '01'),
    -            (Text, ' '),
    -            (Number.Bin, '0b0___101_0'),
    -            (Text, ' '),
    -            (Number.Float, '0.'),
    -            (Text, ' '),
    -            (Number.Float, '.7_17F'),
    -            (Text, ' '),
    -            (Number.Float, '3e-1_3d'),
    -            (Text, ' '),
    -            (Number.Float, '1f'),
    -            (Text, ' '),
    -            (Number.Float, '6_01.9e+3'),
    -            (Text, ' '),
    -            (Number.Float, '0x.1Fp3'),
    -            (Text, ' '),
    -            (Number.Float, '0XEP8D'),
    -            (Text, '\n')
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    diff --git a/third_party/pygments/tests/test_latex_formatter.py b/third_party/pygments/tests/test_latex_formatter.py
    deleted file mode 100644
    index 05a6c3ace..000000000
    --- a/third_party/pygments/tests/test_latex_formatter.py
    +++ /dev/null
    @@ -1,54 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments LaTeX formatter tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -from __future__ import print_function
    -
    -import os
    -import unittest
    -import tempfile
    -
    -from pygments.formatters import LatexFormatter
    -from pygments.lexers import PythonLexer
    -
    -import support
    -
    -TESTFILE, TESTDIR = support.location(__file__)
    -
    -
    -class LatexFormatterTest(unittest.TestCase):
    -
    -    def test_valid_output(self):
    -        with open(TESTFILE) as fp:
    -            tokensource = list(PythonLexer().get_tokens(fp.read()))
    -        fmt = LatexFormatter(full=True, encoding='latin1')
    -
    -        handle, pathname = tempfile.mkstemp('.tex')
    -        # place all output files in /tmp too
    -        old_wd = os.getcwd()
    -        os.chdir(os.path.dirname(pathname))
    -        tfile = os.fdopen(handle, 'wb')
    -        fmt.format(tokensource, tfile)
    -        tfile.close()
    -        try:
    -            import subprocess
    -            po = subprocess.Popen(['latex', '-interaction=nonstopmode',
    -                                   pathname], stdout=subprocess.PIPE)
    -            ret = po.wait()
    -            output = po.stdout.read()
    -            po.stdout.close()
    -        except OSError:
    -            # latex not available
    -            raise support.SkipTest
    -        else:
    -            if ret:
    -                print(output)
    -            self.assertFalse(ret, 'latex run reported errors')
    -
    -        os.unlink(pathname)
    -        os.chdir(old_wd)
    diff --git a/third_party/pygments/tests/test_lexers_other.py b/third_party/pygments/tests/test_lexers_other.py
    deleted file mode 100644
    index bb667c052..000000000
    --- a/third_party/pygments/tests/test_lexers_other.py
    +++ /dev/null
    @@ -1,80 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Tests for other lexers
    -    ~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -import glob
    -import os
    -import unittest
    -
    -from pygments.lexers import guess_lexer
    -from pygments.lexers.scripting import EasytrieveLexer, JclLexer, RexxLexer
    -
    -def _exampleFilePath(filename):
    -    return os.path.join(os.path.dirname(__file__), 'examplefiles', filename)
    -
    -
    -class AnalyseTextTest(unittest.TestCase):
    -    def _testCanRecognizeAndGuessExampleFiles(self, lexer):
    -        assert lexer is not None
    -
    -        for pattern in lexer.filenames:
    -            exampleFilesPattern = _exampleFilePath(pattern)
    -            for exampleFilePath in glob.glob(exampleFilesPattern):
    -                with open(exampleFilePath, 'rb') as fp:
    -                    text = fp.read().decode('utf-8')
    -                probability = lexer.analyse_text(text)
    -                self.assertTrue(probability > 0,
    -                    '%s must recognize %r' % (
    -                    lexer.name, exampleFilePath))
    -                guessedLexer = guess_lexer(text)
    -                self.assertEqual(guessedLexer.name, lexer.name)
    -
    -    def testCanRecognizeAndGuessExampleFiles(self):
    -        LEXERS_TO_TEST = [
    -            EasytrieveLexer,
    -            JclLexer,
    -            RexxLexer,
    -        ]
    -        for lexerToTest in LEXERS_TO_TEST:
    -            self._testCanRecognizeAndGuessExampleFiles(lexerToTest)
    -
    -
    -class EasyTrieveLexerTest(unittest.TestCase):
    -    def testCanGuessFromText(self):
    -        self.assertLess(0, EasytrieveLexer.analyse_text('MACRO'))
    -        self.assertLess(0, EasytrieveLexer.analyse_text('\nMACRO'))
    -        self.assertLess(0, EasytrieveLexer.analyse_text(' \nMACRO'))
    -        self.assertLess(0, EasytrieveLexer.analyse_text(' \n MACRO'))
    -        self.assertLess(0, EasytrieveLexer.analyse_text('*\nMACRO'))
    -        self.assertLess(0, EasytrieveLexer.analyse_text(
    -            '*\n *\n\n \n*\n MACRO'))
    -
    -
    -class RexxLexerTest(unittest.TestCase):
    -    def testCanGuessFromText(self):
    -        self.assertAlmostEqual(0.01,
    -            RexxLexer.analyse_text('/* */'))
    -        self.assertAlmostEqual(1.0,
    -            RexxLexer.analyse_text('''/* Rexx */
    -                say "hello world"'''))
    -        val = RexxLexer.analyse_text('/* */\n'
    -                'hello:pRoceduRe\n'
    -                '  say "hello world"')
    -        self.assertTrue(val > 0.5, val)
    -        val = RexxLexer.analyse_text('''/* */
    -                if 1 > 0 then do
    -                    say "ok"
    -                end
    -                else do
    -                    say "huh?"
    -                end''')
    -        self.assertTrue(val > 0.2, val)
    -        val = RexxLexer.analyse_text('''/* */
    -                greeting = "hello world!"
    -                parse value greeting "hello" name "!"
    -                say name''')
    -        self.assertTrue(val > 0.2, val)
    diff --git a/third_party/pygments/tests/test_objectiveclexer.py b/third_party/pygments/tests/test_objectiveclexer.py
    deleted file mode 100644
    index 90bd680f0..000000000
    --- a/third_party/pygments/tests/test_objectiveclexer.py
    +++ /dev/null
    @@ -1,81 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Basic CLexer Test
    -    ~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -import os
    -
    -from pygments.token import Token
    -from pygments.lexers import ObjectiveCLexer
    -
    -
    -class ObjectiveCLexerTest(unittest.TestCase):
    -
    -    def setUp(self):
    -        self.lexer = ObjectiveCLexer()
    -
    -    def testLiteralNumberInt(self):
    -        fragment = u'@(1);\n'
    -        expected = [
    -            (Token.Literal, u'@('),
    -            (Token.Literal.Number.Integer, u'1'),
    -            (Token.Literal, u')'),
    -            (Token.Punctuation, u';'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    -
    -    def testLiteralNumberExpression(self):
    -        fragment = u'@(1+2);\n'
    -        expected = [
    -            (Token.Literal, u'@('),
    -            (Token.Literal.Number.Integer, u'1'),
    -            (Token.Operator, u'+'),
    -            (Token.Literal.Number.Integer, u'2'),
    -            (Token.Literal, u')'),
    -            (Token.Punctuation, u';'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    -
    -    def testLiteralNumberNestedExpression(self):
    -        fragment = u'@(1+(2+3));\n'
    -        expected = [
    -            (Token.Literal, u'@('),
    -            (Token.Literal.Number.Integer, u'1'),
    -            (Token.Operator, u'+'),
    -            (Token.Punctuation, u'('),
    -            (Token.Literal.Number.Integer, u'2'),
    -            (Token.Operator, u'+'),
    -            (Token.Literal.Number.Integer, u'3'),
    -            (Token.Punctuation, u')'),
    -            (Token.Literal, u')'),
    -            (Token.Punctuation, u';'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    -
    -    def testLiteralNumberBool(self):
    -        fragment = u'@NO;\n'
    -        expected = [
    -            (Token.Literal.Number, u'@NO'),
    -            (Token.Punctuation, u';'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    -
    -    def testLieralNumberBoolExpression(self):
    -        fragment = u'@(YES);\n'
    -        expected = [
    -            (Token.Literal, u'@('),
    -            (Token.Name.Builtin, u'YES'),
    -            (Token.Literal, u')'),
    -            (Token.Punctuation, u';'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    diff --git a/third_party/pygments/tests/test_perllexer.py b/third_party/pygments/tests/test_perllexer.py
    deleted file mode 100644
    index 26b2d0a71..000000000
    --- a/third_party/pygments/tests/test_perllexer.py
    +++ /dev/null
    @@ -1,137 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments regex lexer tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import time
    -import unittest
    -
    -from pygments.token import String
    -from pygments.lexers.perl import PerlLexer
    -
    -
    -class RunawayRegexTest(unittest.TestCase):
    -    # A previous version of the Perl lexer would spend a great deal of
    -    # time backtracking when given particular strings.  These tests show that
    -    # the runaway backtracking doesn't happen any more (at least for the given
    -    # cases).
    -
    -    lexer = PerlLexer()
    -
    -    ### Test helpers.
    -
    -    def assert_single_token(self, s, token):
    -        """Show that a given string generates only one token."""
    -        tokens = list(self.lexer.get_tokens_unprocessed(s))
    -        self.assertEqual(len(tokens), 1, tokens)
    -        self.assertEqual(s, tokens[0][2])
    -        self.assertEqual(token, tokens[0][1])
    -
    -    def assert_tokens(self, strings, expected_tokens):
    -        """Show that a given string generates the expected tokens."""
    -        tokens = list(self.lexer.get_tokens_unprocessed(''.join(strings)))
    -        self.assertEqual(len(tokens), len(expected_tokens), tokens)
    -        for index, s in enumerate(strings):
    -            self.assertEqual(s, tokens[index][2])
    -            self.assertEqual(expected_tokens[index], tokens[index][1])
    -
    -    def assert_fast_tokenization(self, s):
    -        """Show that a given string is tokenized quickly."""
    -        start = time.time()
    -        tokens = list(self.lexer.get_tokens_unprocessed(s))
    -        end = time.time()
    -        # Isn't 10 seconds kind of a long time?  Yes, but we don't want false
    -        # positives when the tests are starved for CPU time.
    -        if end-start > 10:
    -            self.fail('tokenization took too long')
    -        return tokens
    -
    -    ### Strings.
    -
    -    def test_single_quote_strings(self):
    -        self.assert_single_token(r"'foo\tbar\\\'baz'", String)
    -        self.assert_fast_tokenization("'" + '\\'*999)
    -
    -    def test_double_quote_strings(self):
    -        self.assert_single_token(r'"foo\tbar\\\"baz"', String)
    -        self.assert_fast_tokenization('"' + '\\'*999)
    -
    -    def test_backtick_strings(self):
    -        self.assert_single_token(r'`foo\tbar\\\`baz`', String.Backtick)
    -        self.assert_fast_tokenization('`' + '\\'*999)
    -
    -    ### Regex matches with various delimiters.
    -
    -    def test_match(self):
    -        self.assert_single_token(r'/aa\tbb/', String.Regex)
    -        self.assert_fast_tokenization('/' + '\\'*999)
    -
    -    def test_match_with_slash(self):
    -        self.assert_tokens(['m', '/\n\\t\\\\/'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m/xxx\n' + '\\'*999)
    -
    -    def test_match_with_bang(self):
    -        self.assert_tokens(['m', r'!aa\t\!bb!'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m!' + '\\'*999)
    -
    -    def test_match_with_brace(self):
    -        self.assert_tokens(['m', r'{aa\t\}bb}'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m{' + '\\'*999)
    -
    -    def test_match_with_angle_brackets(self):
    -        self.assert_tokens(['m', r'bb>'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m<' + '\\'*999)
    -
    -    def test_match_with_parenthesis(self):
    -        self.assert_tokens(['m', r'(aa\t\)bb)'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m(' + '\\'*999)
    -
    -    def test_match_with_at_sign(self):
    -        self.assert_tokens(['m', r'@aa\t\@bb@'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m@' + '\\'*999)
    -
    -    def test_match_with_percent_sign(self):
    -        self.assert_tokens(['m', r'%aa\t\%bb%'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m%' + '\\'*999)
    -
    -    def test_match_with_dollar_sign(self):
    -        self.assert_tokens(['m', r'$aa\t\$bb$'], [String.Regex, String.Regex])
    -        self.assert_fast_tokenization('m$' + '\\'*999)
    -
    -    ### Regex substitutions with various delimeters.
    -
    -    def test_substitution_with_slash(self):
    -        self.assert_single_token('s/aaa/bbb/g', String.Regex)
    -        self.assert_fast_tokenization('s/foo/' + '\\'*999)
    -
    -    def test_substitution_with_at_sign(self):
    -        self.assert_single_token(r's@aaa@bbb@g', String.Regex)
    -        self.assert_fast_tokenization('s@foo@' + '\\'*999)
    -
    -    def test_substitution_with_percent_sign(self):
    -        self.assert_single_token(r's%aaa%bbb%g', String.Regex)
    -        self.assert_fast_tokenization('s%foo%' + '\\'*999)
    -
    -    def test_substitution_with_brace(self):
    -        self.assert_single_token(r's{aaa}', String.Regex)
    -        self.assert_fast_tokenization('s{' + '\\'*999)
    -
    -    def test_substitution_with_angle_bracket(self):
    -        self.assert_single_token(r's', String.Regex)
    -        self.assert_fast_tokenization('s<' + '\\'*999)
    -
    -    def test_substitution_with_angle_bracket(self):
    -        self.assert_single_token(r's', String.Regex)
    -        self.assert_fast_tokenization('s<' + '\\'*999)
    -
    -    def test_substitution_with_square_bracket(self):
    -        self.assert_single_token(r's[aaa]', String.Regex)
    -        self.assert_fast_tokenization('s[' + '\\'*999)
    -
    -    def test_substitution_with_parenthesis(self):
    -        self.assert_single_token(r's(aaa)', String.Regex)
    -        self.assert_fast_tokenization('s(' + '\\'*999)
    diff --git a/third_party/pygments/tests/test_qbasiclexer.py b/third_party/pygments/tests/test_qbasiclexer.py
    deleted file mode 100644
    index 8b790cee2..000000000
    --- a/third_party/pygments/tests/test_qbasiclexer.py
    +++ /dev/null
    @@ -1,43 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Tests for QBasic
    -    ~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import glob
    -import os
    -import unittest
    -
    -from pygments.token import Token
    -from pygments.lexers.basic import QBasicLexer
    -
    -
    -class QBasicTest(unittest.TestCase):
    -    def setUp(self):
    -        self.lexer = QBasicLexer()
    -        self.maxDiff = None
    -
    -    def testKeywordsWithDollar(self):
    -        fragment = u'DIM x\nx = RIGHT$("abc", 1)\n'
    -        expected = [
    -            (Token.Keyword.Declaration, u'DIM'),
    -            (Token.Text.Whitespace, u' '),
    -            (Token.Name.Variable.Global, u'x'),
    -            (Token.Text, u'\n'),
    -            (Token.Name.Variable.Global, u'x'),
    -            (Token.Text.Whitespace, u' '),
    -            (Token.Operator, u'='),
    -            (Token.Text.Whitespace, u' '),
    -            (Token.Keyword.Reserved, u'RIGHT$'),
    -            (Token.Punctuation, u'('),
    -            (Token.Literal.String.Double, u'"abc"'),
    -            (Token.Punctuation, u','),
    -            (Token.Text.Whitespace, u' '),
    -            (Token.Literal.Number.Integer.Long, u'1'),
    -            (Token.Punctuation, u')'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
    diff --git a/third_party/pygments/tests/test_regexlexer.py b/third_party/pygments/tests/test_regexlexer.py
    deleted file mode 100644
    index eb25be612..000000000
    --- a/third_party/pygments/tests/test_regexlexer.py
    +++ /dev/null
    @@ -1,54 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments regex lexer tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.token import Text
    -from pygments.lexer import RegexLexer
    -from pygments.lexer import bygroups
    -from pygments.lexer import default
    -
    -
    -class TestLexer(RegexLexer):
    -    """Test tuple state transitions including #pop."""
    -    tokens = {
    -        'root': [
    -            ('a', Text.Root, 'rag'),
    -            ('e', Text.Root),
    -            default(('beer', 'beer'))
    -        ],
    -        'beer': [
    -            ('d', Text.Beer, ('#pop', '#pop')),
    -        ],
    -        'rag': [
    -            ('b', Text.Rag, '#push'),
    -            ('c', Text.Rag, ('#pop', 'beer')),
    -        ],
    -    }
    -
    -
    -class TupleTransTest(unittest.TestCase):
    -    def test(self):
    -        lx = TestLexer()
    -        toks = list(lx.get_tokens_unprocessed('abcde'))
    -        self.assertEqual(toks,
    -           [(0, Text.Root, 'a'), (1, Text.Rag, 'b'), (2, Text.Rag, 'c'),
    -            (3, Text.Beer, 'd'), (4, Text.Root, 'e')])
    -
    -    def test_multiline(self):
    -        lx = TestLexer()
    -        toks = list(lx.get_tokens_unprocessed('a\ne'))
    -        self.assertEqual(toks,
    -           [(0, Text.Root, 'a'), (1, Text, u'\n'),
    -            (2, Text.Root, 'e')])
    -
    -    def test_default(self):
    -        lx = TestLexer()
    -        toks = list(lx.get_tokens_unprocessed('d'))
    -        self.assertEqual(toks, [(0, Text.Beer, 'd')])
    diff --git a/third_party/pygments/tests/test_regexopt.py b/third_party/pygments/tests/test_regexopt.py
    deleted file mode 100644
    index dd56a4466..000000000
    --- a/third_party/pygments/tests/test_regexopt.py
    +++ /dev/null
    @@ -1,76 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Tests for pygments.regexopt
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import re
    -import random
    -import unittest
    -import itertools
    -
    -from pygments.regexopt import regex_opt
    -
    -ALPHABET = ['a', 'b', 'c', 'd', 'e']
    -
    -try:
    -    from itertools import combinations_with_replacement
    -    N_TRIES = 15
    -except ImportError:
    -    # Python 2.6
    -    def combinations_with_replacement(iterable, r):
    -        pool = tuple(iterable)
    -        n = len(pool)
    -        for indices in itertools.product(range(n), repeat=r):
    -            if sorted(indices) == list(indices):
    -                yield tuple(pool[i] for i in indices)
    -    N_TRIES = 9
    -
    -
    -class RegexOptTestCase(unittest.TestCase):
    -
    -    def generate_keywordlist(self, length):
    -        return [''.join(p) for p in
    -                combinations_with_replacement(ALPHABET, length)]
    -
    -    def test_randomly(self):
    -        # generate a list of all possible keywords of a certain length using
    -        # a restricted alphabet, then choose some to match and make sure only
    -        # those do
    -        for n in range(3, N_TRIES):
    -            kwlist = self.generate_keywordlist(n)
    -            to_match = random.sample(kwlist,
    -                                     random.randint(1, len(kwlist) - 1))
    -            no_match = set(kwlist) - set(to_match)
    -            rex = re.compile(regex_opt(to_match))
    -            for w in to_match:
    -                self.assertTrue(rex.match(w))
    -            for w in no_match:
    -                self.assertFalse(rex.match(w))
    -
    -    def test_prefix(self):
    -        opt = regex_opt(('a', 'b'), prefix=r':{1,2}')
    -        print(opt)
    -        rex = re.compile(opt)
    -        self.assertFalse(rex.match('a'))
    -        self.assertTrue(rex.match('::a'))
    -        self.assertFalse(rex.match(':::')) # fullmatch
    -
    -    def test_suffix(self):
    -        opt = regex_opt(('a', 'b'), suffix=r':{1,2}')
    -        print(opt)
    -        rex = re.compile(opt)
    -        self.assertFalse(rex.match('a'))
    -        self.assertTrue(rex.match('a::'))
    -        self.assertFalse(rex.match(':::')) # fullmatch
    -
    -    def test_suffix_opt(self):
    -        # test that detected suffixes remain sorted.
    -        opt = regex_opt(('afoo', 'abfoo'))
    -        print(opt)
    -        rex = re.compile(opt)
    -        m = rex.match('abfoo')
    -        self.assertEqual(5, m.end())
    diff --git a/third_party/pygments/tests/test_rtf_formatter.py b/third_party/pygments/tests/test_rtf_formatter.py
    deleted file mode 100644
    index 25784743b..000000000
    --- a/third_party/pygments/tests/test_rtf_formatter.py
    +++ /dev/null
    @@ -1,109 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments RTF formatter tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -from string_asserts import StringTests
    -
    -from pygments.util import StringIO
    -from pygments.formatters import RtfFormatter
    -from pygments.lexers.special import TextLexer
    -
    -class RtfFormatterTest(StringTests, unittest.TestCase):
    -    foot = (r'\par' '\n' r'}')
    -
    -    def _escape(self, string):
    -        return(string.replace("\n", r"\n"))
    -
    -    def _build_message(self, *args, **kwargs):
    -        string = kwargs.get('string', None)
    -        t = self._escape(kwargs.get('t', ''))
    -        expected = self._escape(kwargs.get('expected', ''))
    -        result = self._escape(kwargs.get('result', ''))
    -
    -        if string is None:
    -            string = (u"The expected output of '{t}'\n"
    -                      u"\t\tShould be '{expected}'\n"
    -                      u"\t\tActually outputs '{result}'\n"
    -                      u"\t(WARNING: Partial Output of Result!)")
    -
    -        end = -(len(self._escape(self.foot)))
    -        start = end-len(expected)
    -
    -        return string.format(t=t,
    -                             result = result[start:end],
    -                             expected = expected)
    -
    -    def format_rtf(self, t):
    -        tokensource = list(TextLexer().get_tokens(t))
    -        fmt = RtfFormatter()
    -        buf = StringIO()
    -        fmt.format(tokensource, buf)
    -        result = buf.getvalue()
    -        buf.close()
    -        return result
    -
    -    def test_rtf_header(self):
    -        t = u''
    -        result = self.format_rtf(t)
    -        expected = r'{\rtf1\ansi\uc0'
    -        msg = (u"RTF documents are expected to start with '{expected}'\n"
    -               u"\t\tStarts intead with '{result}'\n"
    -               u"\t(WARNING: Partial Output of Result!)".format(
    -                   expected = expected,
    -                   result = result[:len(expected)]))
    -        self.assertStartsWith(result, expected, msg)
    -
    -    def test_rtf_footer(self):
    -        t = u''
    -        result = self.format_rtf(t)
    -        expected = self.foot
    -        msg = (u"RTF documents are expected to end with '{expected}'\n"
    -               u"\t\tEnds intead with '{result}'\n"
    -               u"\t(WARNING: Partial Output of Result!)".format(
    -                   expected = self._escape(expected),
    -                   result = self._escape(result[-len(expected):])))
    -        self.assertEndsWith(result, expected, msg)
    -
    -    def test_ascii_characters(self):
    -        t = u'a b c d ~'
    -        result = self.format_rtf(t)
    -        expected = (r'a b c d ~')
    -        if not result.endswith(self.foot):
    -            return(unittest.skip('RTF Footer incorrect'))
    -        msg = self._build_message(t=t, result=result, expected=expected)
    -        self.assertEndsWith(result, expected+self.foot, msg)
    -
    -    def test_escape_characters(self):
    -        t = u'\ {{'
    -        result = self.format_rtf(t)
    -        expected = (r'\\ \{\{')
    -        if not result.endswith(self.foot):
    -            return(unittest.skip('RTF Footer incorrect'))
    -        msg = self._build_message(t=t, result=result, expected=expected)
    -        self.assertEndsWith(result, expected+self.foot, msg)
    -
    -    def test_single_characters(self):
    -        t = u'â € ¤ каждой'
    -        result = self.format_rtf(t)
    -        expected = (r'{\u226} {\u8364} {\u164} '
    -                    r'{\u1082}{\u1072}{\u1078}{\u1076}{\u1086}{\u1081}')
    -        if not result.endswith(self.foot):
    -            return(unittest.skip('RTF Footer incorrect'))
    -        msg = self._build_message(t=t, result=result, expected=expected)
    -        self.assertEndsWith(result, expected+self.foot, msg)
    -
    -    def test_double_characters(self):
    -        t = u'က 힣 ↕ ↕︎ 鼖'
    -        result = self.format_rtf(t)
    -        expected = (r'{\u4096} {\u55203} {\u8597} '
    -                    r'{\u8597}{\u65038} {\u55422}{\u56859}')
    -        if not result.endswith(self.foot):
    -            return(unittest.skip('RTF Footer incorrect'))
    -        msg = self._build_message(t=t, result=result, expected=expected)
    -        self.assertEndsWith(result, expected+self.foot, msg)
    diff --git a/third_party/pygments/tests/test_ruby.py b/third_party/pygments/tests/test_ruby.py
    deleted file mode 100644
    index ab210badf..000000000
    --- a/third_party/pygments/tests/test_ruby.py
    +++ /dev/null
    @@ -1,145 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Basic RubyLexer Test
    -    ~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.token import Operator, Number, Text, Token
    -from pygments.lexers import RubyLexer
    -
    -
    -class RubyTest(unittest.TestCase):
    -
    -    def setUp(self):
    -        self.lexer = RubyLexer()
    -        self.maxDiff = None
    -
    -    def testRangeSyntax1(self):
    -        fragment = u'1..3\n'
    -        tokens = [
    -            (Number.Integer, u'1'),
    -            (Operator, u'..'),
    -            (Number.Integer, u'3'),
    -            (Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testRangeSyntax2(self):
    -        fragment = u'1...3\n'
    -        tokens = [
    -            (Number.Integer, u'1'),
    -            (Operator, u'...'),
    -            (Number.Integer, u'3'),
    -            (Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testRangeSyntax3(self):
    -        fragment = u'1 .. 3\n'
    -        tokens = [
    -            (Number.Integer, u'1'),
    -            (Text, u' '),
    -            (Operator, u'..'),
    -            (Text, u' '),
    -            (Number.Integer, u'3'),
    -            (Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testInterpolationNestedCurly(self):
    -        fragment = (
    -            u'"A#{ (3..5).group_by { |x| x/2}.map '
    -            u'do |k,v| "#{k}" end.join }" + "Z"\n')
    -
    -        tokens = [
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Literal.String.Double, u'A'),
    -            (Token.Literal.String.Interpol, u'#{'),
    -            (Token.Text, u' '),
    -            (Token.Punctuation, u'('),
    -            (Token.Literal.Number.Integer, u'3'),
    -            (Token.Operator, u'..'),
    -            (Token.Literal.Number.Integer, u'5'),
    -            (Token.Punctuation, u')'),
    -            (Token.Operator, u'.'),
    -            (Token.Name, u'group_by'),
    -            (Token.Text, u' '),
    -            (Token.Literal.String.Interpol, u'{'),
    -            (Token.Text, u' '),
    -            (Token.Operator, u'|'),
    -            (Token.Name, u'x'),
    -            (Token.Operator, u'|'),
    -            (Token.Text, u' '),
    -            (Token.Name, u'x'),
    -            (Token.Operator, u'/'),
    -            (Token.Literal.Number.Integer, u'2'),
    -            (Token.Literal.String.Interpol, u'}'),
    -            (Token.Operator, u'.'),
    -            (Token.Name, u'map'),
    -            (Token.Text, u' '),
    -            (Token.Keyword, u'do'),
    -            (Token.Text, u' '),
    -            (Token.Operator, u'|'),
    -            (Token.Name, u'k'),
    -            (Token.Punctuation, u','),
    -            (Token.Name, u'v'),
    -            (Token.Operator, u'|'),
    -            (Token.Text, u' '),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Literal.String.Interpol, u'#{'),
    -            (Token.Name, u'k'),
    -            (Token.Literal.String.Interpol, u'}'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u' '),
    -            (Token.Keyword, u'end'),
    -            (Token.Operator, u'.'),
    -            (Token.Name, u'join'),
    -            (Token.Text, u' '),
    -            (Token.Literal.String.Interpol, u'}'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u' '),
    -            (Token.Operator, u'+'),
    -            (Token.Text, u' '),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Literal.String.Double, u'Z'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testOperatorMethods(self):
    -        fragment = u'x.==4\n'
    -        tokens = [
    -            (Token.Name, u'x'),
    -            (Token.Operator, u'.'),
    -            (Token.Name.Operator, u'=='),
    -            (Token.Literal.Number.Integer, u'4'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testEscapedBracestring(self):
    -        fragment = u'str.gsub(%r{\\\\\\\\}, "/")\n'
    -        tokens = [
    -            (Token.Name, u'str'),
    -            (Token.Operator, u'.'),
    -            (Token.Name, u'gsub'),
    -            (Token.Punctuation, u'('),
    -            (Token.Literal.String.Regex, u'%r{'),
    -            (Token.Literal.String.Regex, u'\\\\'),
    -            (Token.Literal.String.Regex, u'\\\\'),
    -            (Token.Literal.String.Regex, u'}'),
    -            (Token.Punctuation, u','),
    -            (Token.Text, u' '),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Literal.String.Double, u'/'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Punctuation, u')'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    diff --git a/third_party/pygments/tests/test_shell.py b/third_party/pygments/tests/test_shell.py
    deleted file mode 100644
    index 4eb5a15aa..000000000
    --- a/third_party/pygments/tests/test_shell.py
    +++ /dev/null
    @@ -1,89 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Basic Shell Tests
    -    ~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.token import Token
    -from pygments.lexers import BashLexer
    -
    -
    -class BashTest(unittest.TestCase):
    -
    -    def setUp(self):
    -        self.lexer = BashLexer()
    -        self.maxDiff = None
    -
    -    def testCurlyNoEscapeAndQuotes(self):
    -        fragment = u'echo "${a//["b"]/}"\n'
    -        tokens = [
    -            (Token.Name.Builtin, u'echo'),
    -            (Token.Text, u' '),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.String.Interpol, u'${'),
    -            (Token.Name.Variable, u'a'),
    -            (Token.Punctuation, u'//['),
    -            (Token.Literal.String.Double, u'"b"'),
    -            (Token.Punctuation, u']/'),
    -            (Token.String.Interpol, u'}'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testCurlyWithEscape(self):
    -        fragment = u'echo ${a//[\\"]/}\n'
    -        tokens = [
    -            (Token.Name.Builtin, u'echo'),
    -            (Token.Text, u' '),
    -            (Token.String.Interpol, u'${'),
    -            (Token.Name.Variable, u'a'),
    -            (Token.Punctuation, u'//['),
    -            (Token.Literal.String.Escape, u'\\"'),
    -            (Token.Punctuation, u']/'),
    -            (Token.String.Interpol, u'}'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testParsedSingle(self):
    -        fragment = u"a=$'abc\\''\n"
    -        tokens = [
    -            (Token.Name.Variable, u'a'),
    -            (Token.Operator, u'='),
    -            (Token.Literal.String.Single, u"$'abc\\''"),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    -    def testShortVariableNames(self):
    -        fragment = u'x="$"\ny="$_"\nz="$abc"\n'
    -        tokens = [
    -            # single lone $
    -            (Token.Name.Variable, u'x'),
    -            (Token.Operator, u'='),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u'$'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u'\n'),
    -            # single letter shell var
    -            (Token.Name.Variable, u'y'),
    -            (Token.Operator, u'='),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Name.Variable, u'$_'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u'\n'),
    -            # multi-letter user var
    -            (Token.Name.Variable, u'z'),
    -            (Token.Operator, u'='),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Name.Variable, u'$abc'),
    -            (Token.Literal.String.Double, u'"'),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    diff --git a/third_party/pygments/tests/test_smarty.py b/third_party/pygments/tests/test_smarty.py
    deleted file mode 100644
    index 450e4e6bd..000000000
    --- a/third_party/pygments/tests/test_smarty.py
    +++ /dev/null
    @@ -1,40 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Basic SmartyLexer Test
    -    ~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.token import Operator, Number, Text, Token
    -from pygments.lexers import SmartyLexer
    -
    -
    -class SmartyTest(unittest.TestCase):
    -
    -    def setUp(self):
    -        self.lexer = SmartyLexer()
    -
    -    def testNestedCurly(self):
    -        fragment = u'{templateFunction param={anotherFunction} param2=$something}\n'
    -        tokens = [
    -            (Token.Comment.Preproc, u'{'),
    -            (Token.Name.Function, u'templateFunction'),
    -            (Token.Text, u' '),
    -            (Token.Name.Attribute, u'param'),
    -            (Token.Operator, u'='),
    -            (Token.Comment.Preproc, u'{'),
    -            (Token.Name.Attribute, u'anotherFunction'),
    -            (Token.Comment.Preproc, u'}'),
    -            (Token.Text, u' '),
    -            (Token.Name.Attribute, u'param2'),
    -            (Token.Operator, u'='),
    -            (Token.Name.Variable, u'$something'),
    -            (Token.Comment.Preproc, u'}'),
    -            (Token.Other, u'\n'),
    -        ]
    -        self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
    -
    diff --git a/third_party/pygments/tests/test_string_asserts.py b/third_party/pygments/tests/test_string_asserts.py
    deleted file mode 100644
    index ba7b37fad..000000000
    --- a/third_party/pygments/tests/test_string_asserts.py
    +++ /dev/null
    @@ -1,35 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments string assert utility tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -from string_asserts import StringTests
    -
    -class TestStringTests(StringTests, unittest.TestCase):
    -
    -    def test_startswith_correct(self):
    -        self.assertStartsWith("AAA", "A")
    -
    -    # @unittest.expectedFailure not supported by nose
    -    def test_startswith_incorrect(self):
    -        self.assertRaises(AssertionError, self.assertStartsWith, "AAA", "B")
    -
    -    # @unittest.expectedFailure not supported by nose
    -    def test_startswith_short(self):
    -        self.assertRaises(AssertionError, self.assertStartsWith, "A", "AA")
    -
    -    def test_endswith_correct(self):
    -        self.assertEndsWith("AAA", "A")
    -
    -    # @unittest.expectedFailure not supported by nose
    -    def test_endswith_incorrect(self):
    -        self.assertRaises(AssertionError, self.assertEndsWith, "AAA", "B")
    -
    -    # @unittest.expectedFailure not supported by nose
    -    def test_endswith_short(self):
    -        self.assertRaises(AssertionError, self.assertEndsWith, "A", "AA")
    diff --git a/third_party/pygments/tests/test_terminal_formatter.py b/third_party/pygments/tests/test_terminal_formatter.py
    deleted file mode 100644
    index 07337cd50..000000000
    --- a/third_party/pygments/tests/test_terminal_formatter.py
    +++ /dev/null
    @@ -1,51 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments terminal formatter tests
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -from __future__ import print_function
    -
    -import unittest
    -import re
    -
    -from pygments.util import StringIO
    -from pygments.lexers.sql import PlPgsqlLexer
    -from pygments.formatters import TerminalFormatter
    -
    -DEMO_TEXT = '''\
    --- comment
    -select
    -* from bar;
    -'''
    -DEMO_LEXER = PlPgsqlLexer
    -DEMO_TOKENS = list(DEMO_LEXER().get_tokens(DEMO_TEXT))
    -
    -ANSI_RE = re.compile(r'\x1b[\w\W]*?m')
    -
    -def strip_ansi(x):
    -    return ANSI_RE.sub('', x)
    -
    -class TerminalFormatterTest(unittest.TestCase):
    -    def test_reasonable_output(self):
    -        out = StringIO()
    -        TerminalFormatter().format(DEMO_TOKENS, out)
    -        plain = strip_ansi(out.getvalue())
    -        self.assertEqual(DEMO_TEXT.count('\n'), plain.count('\n'))
    -        print(repr(plain))
    -
    -        for a, b in zip(DEMO_TEXT.splitlines(), plain.splitlines()):
    -            self.assertEqual(a, b)
    -
    -    def test_reasonable_output_lineno(self):
    -        out = StringIO()
    -        TerminalFormatter(linenos=True).format(DEMO_TOKENS, out)
    -        plain = strip_ansi(out.getvalue())
    -        self.assertEqual(DEMO_TEXT.count('\n') + 1, plain.count('\n'))
    -        print(repr(plain))
    -
    -        for a, b in zip(DEMO_TEXT.splitlines(), plain.splitlines()):
    -            self.assertTrue(a in b)
    diff --git a/third_party/pygments/tests/test_textfmts.py b/third_party/pygments/tests/test_textfmts.py
    deleted file mode 100644
    index d355ab681..000000000
    --- a/third_party/pygments/tests/test_textfmts.py
    +++ /dev/null
    @@ -1,41 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Basic Tests for textfmts
    -    ~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.token import Operator, Number, Text, Token
    -from pygments.lexers.textfmts import HttpLexer
    -
    -
    -class RubyTest(unittest.TestCase):
    -
    -    def setUp(self):
    -        self.lexer = HttpLexer()
    -        self.maxDiff = None
    -
    -    def testApplicationXml(self):
    -        fragment = u'GET / HTTP/1.0\nContent-Type: application/xml\n\n\n'
    -        tokens = [
    -            (Token.Name.Tag, u''),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(
    -            tokens, list(self.lexer.get_tokens(fragment))[-len(tokens):])
    -
    -    def testApplicationCalendarXml(self):
    -        fragment = u'GET / HTTP/1.0\nContent-Type: application/calendar+xml\n\n\n'
    -        tokens = [
    -            (Token.Name.Tag, u''),
    -            (Token.Text, u'\n'),
    -        ]
    -        self.assertEqual(
    -            tokens, list(self.lexer.get_tokens(fragment))[-len(tokens):])
    -
    diff --git a/third_party/pygments/tests/test_token.py b/third_party/pygments/tests/test_token.py
    deleted file mode 100644
    index 0c6b02bf8..000000000
    --- a/third_party/pygments/tests/test_token.py
    +++ /dev/null
    @@ -1,54 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Test suite for the token module
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import copy
    -import unittest
    -
    -from pygments import token
    -
    -
    -class TokenTest(unittest.TestCase):
    -
    -    def test_tokentype(self):
    -        e = self.assertEqual
    -
    -        t = token.String
    -
    -        e(t.split(), [token.Token, token.Literal, token.String])
    -
    -        e(t.__class__, token._TokenType)
    -
    -    def test_functions(self):
    -        self.assertTrue(token.is_token_subtype(token.String, token.String))
    -        self.assertTrue(token.is_token_subtype(token.String, token.Literal))
    -        self.assertFalse(token.is_token_subtype(token.Literal, token.String))
    -
    -        self.assertTrue(token.string_to_tokentype(token.String) is token.String)
    -        self.assertTrue(token.string_to_tokentype('') is token.Token)
    -        self.assertTrue(token.string_to_tokentype('String') is token.String)
    -
    -    def test_sanity_check(self):
    -        stp = token.STANDARD_TYPES.copy()
    -        stp[token.Token] = '---' # Token and Text do conflict, that is okay
    -        t = {}
    -        for k, v in stp.items():
    -            t.setdefault(v, []).append(k)
    -        if len(t) == len(stp):
    -            return # Okay
    -
    -        for k, v in t.items():
    -            if len(v) > 1:
    -                self.fail("%r has more than one key: %r" % (k, v))
    -
    -    def test_copying(self):
    -        # Token instances are supposed to be singletons, so copying or even
    -        # deepcopying should return themselves
    -        t = token.String
    -        self.assertIs(t, copy.copy(t))
    -        self.assertIs(t, copy.deepcopy(t))
    diff --git a/third_party/pygments/tests/test_unistring.py b/third_party/pygments/tests/test_unistring.py
    deleted file mode 100644
    index a414347c6..000000000
    --- a/third_party/pygments/tests/test_unistring.py
    +++ /dev/null
    @@ -1,48 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Test suite for the unistring module
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import re
    -import unittest
    -import random
    -
    -from pygments import unistring as uni
    -from pygments.util import unichr
    -
    -
    -class UnistringTest(unittest.TestCase):
    -    def test_cats_exist_and_compilable(self):
    -        for cat in uni.cats:
    -            s = getattr(uni, cat)
    -            if s == '':  # Probably Cs on Jython
    -                continue
    -            print("%s %r" % (cat, s))
    -            re.compile('[%s]' % s)
    -
    -    def _cats_that_match(self, c):
    -        matching_cats = []
    -        for cat in uni.cats:
    -            s = getattr(uni, cat)
    -            if s == '':  # Probably Cs on Jython
    -                continue
    -            if re.compile('[%s]' % s).match(c):
    -                matching_cats.append(cat)
    -        return matching_cats
    -
    -    def test_spot_check_types(self):
    -        # Each char should match one, and precisely one, category
    -        random.seed(0)
    -        for i in range(1000):
    -            o = random.randint(0, 65535)
    -            c = unichr(o)
    -            if o > 0xd800 and o <= 0xdfff and not uni.Cs:
    -                continue  # Bah, Jython.
    -            print(hex(o))
    -            cats = self._cats_that_match(c)
    -            self.assertEqual(len(cats), 1,
    -                             "%d (%s): %s" % (o, c, cats))
    diff --git a/third_party/pygments/tests/test_using_api.py b/third_party/pygments/tests/test_using_api.py
    deleted file mode 100644
    index 16d865e67..000000000
    --- a/third_party/pygments/tests/test_using_api.py
    +++ /dev/null
    @@ -1,40 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Pygments tests for using()
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import unittest
    -
    -from pygments.lexer import using, bygroups, this, RegexLexer
    -from pygments.token import String, Text, Keyword
    -
    -class TestLexer(RegexLexer):
    -    tokens = {
    -        'root': [
    -            (r'#.*',
    -             using(this, state='invalid')),
    -            (r'(")(.+?)(")',
    -             bygroups(String, using(this, state='string'), String)),
    -            (r'[^"]+', Text),
    -        ],
    -        'string': [
    -            (r'.+', Keyword),
    -        ],
    -    }
    -
    -
    -class UsingStateTest(unittest.TestCase):
    -    def test_basic(self):
    -        expected = [(Text, 'a'), (String, '"'), (Keyword, 'bcd'),
    -                    (String, '"'), (Text, 'e\n')]
    -        t = list(TestLexer().get_tokens('a"bcd"e'))
    -        self.assertEqual(t, expected)
    -
    -    def test_error(self):
    -        def gen():
    -            return list(TestLexer().get_tokens('#a'))
    -        self.assertRaises(KeyError, gen)
    diff --git a/third_party/pygments/tests/test_util.py b/third_party/pygments/tests/test_util.py
    deleted file mode 100644
    index 720b384af..000000000
    --- a/third_party/pygments/tests/test_util.py
    +++ /dev/null
    @@ -1,213 +0,0 @@
    -# -*- coding: utf-8 -*-
    -"""
    -    Test suite for the util module
    -    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -
    -    :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
    -    :license: BSD, see LICENSE for details.
    -"""
    -
    -import re
    -import unittest
    -
    -from pygments import util, console
    -
    -
    -class FakeLexer(object):
    -    def analyse(text):
    -        return text
    -    analyse = util.make_analysator(analyse)
    -
    -
    -class UtilTest(unittest.TestCase):
    -
    -    def test_getoptions(self):
    -        raises = self.assertRaises
    -        equals = self.assertEqual
    -
    -        equals(util.get_bool_opt({}, 'a', True), True)
    -        equals(util.get_bool_opt({}, 'a', 1), True)
    -        equals(util.get_bool_opt({}, 'a', 'true'), True)
    -        equals(util.get_bool_opt({}, 'a', 'no'), False)
    -        raises(util.OptionError, util.get_bool_opt, {}, 'a', [])
    -        raises(util.OptionError, util.get_bool_opt, {}, 'a', 'foo')
    -
    -        equals(util.get_int_opt({}, 'a', 1), 1)
    -        raises(util.OptionError, util.get_int_opt, {}, 'a', [])
    -        raises(util.OptionError, util.get_int_opt, {}, 'a', 'bar')
    -
    -        equals(util.get_list_opt({}, 'a', [1]), [1])
    -        equals(util.get_list_opt({}, 'a', '1 2'), ['1', '2'])
    -        raises(util.OptionError, util.get_list_opt, {}, 'a', 1)
    -
    -        equals(util.get_choice_opt({}, 'a', ['foo', 'bar'], 'bar'), 'bar')
    -        equals(util.get_choice_opt({}, 'a', ['foo', 'bar'], 'Bar', True), 'bar')
    -        raises(util.OptionError, util.get_choice_opt, {}, 'a',
    -               ['foo', 'bar'], 'baz')
    -
    -    def test_docstring_headline(self):
    -        def f1():
    -            """
    -            docstring headline
    -
    -            other text
    -            """
    -        def f2():
    -            """
    -            docstring
    -            headline
    -
    -            other text
    -            """
    -        def f3():
    -            pass
    -
    -        self.assertEqual(util.docstring_headline(f1), 'docstring headline')
    -        self.assertEqual(util.docstring_headline(f2), 'docstring headline')
    -        self.assertEqual(util.docstring_headline(f3), '')
    -
    -    def test_analysator_returns_float(self):
    -        # If an analysator wrapped by make_analysator returns a floating point
    -        # number, then that number will be returned by the wrapper.
    -        self.assertEqual(FakeLexer.analyse('0.5'), 0.5)
    -
    -    def test_analysator_returns_boolean(self):
    -        # If an analysator wrapped by make_analysator returns a boolean value,
    -        # then the wrapper will return 1.0 if the boolean was True or 0.0 if
    -        # it was False.
    -        self.assertEqual(FakeLexer.analyse(True), 1.0)
    -        self.assertEqual(FakeLexer.analyse(False), 0.0)
    -
    -    def test_analysator_raises_exception(self):
    -        # If an analysator wrapped by make_analysator raises an exception,
    -        # then the wrapper will return 0.0.
    -        class ErrorLexer(object):
    -            def analyse(text):
    -                raise RuntimeError('something bad happened')
    -            analyse = util.make_analysator(analyse)
    -        self.assertEqual(ErrorLexer.analyse(''), 0.0)
    -
    -    def test_analysator_value_error(self):
    -        # When converting the analysator's return value to a float a
    -        # ValueError may occur.  If that happens 0.0 is returned instead.
    -        self.assertEqual(FakeLexer.analyse('bad input'), 0.0)
    -
    -    def test_analysator_type_error(self):
    -        # When converting the analysator's return value to a float a
    -        # TypeError may occur.  If that happens 0.0 is returned instead.
    -        self.assertEqual(FakeLexer.analyse('xxx'), 0.0)
    -
    -    def test_shebang_matches(self):
    -        self.assertTrue(util.shebang_matches('#!/usr/bin/env python\n', r'python(2\.\d)?'))
    -        self.assertTrue(util.shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?'))
    -        self.assertTrue(util.shebang_matches('#!/usr/bin/startsomethingwith python',
    -                                             r'python(2\.\d)?'))
    -        self.assertTrue(util.shebang_matches('#!C:\\Python2.4\\Python.exe',
    -                                             r'python(2\.\d)?'))
    -
    -        self.assertFalse(util.shebang_matches('#!/usr/bin/python-ruby',
    -                                              r'python(2\.\d)?'))
    -        self.assertFalse(util.shebang_matches('#!/usr/bin/python/ruby',
    -                                              r'python(2\.\d)?'))
    -        self.assertFalse(util.shebang_matches('#!', r'python'))
    -
    -    def test_doctype_matches(self):
    -        self.assertTrue(util.doctype_matches(
    -            ' ', 'html.*'))
    -        self.assertFalse(util.doctype_matches(
    -            '  ', 'html.*'))
    -        self.assertTrue(util.html_doctype_matches(
    -            ''))
    -
    -    def test_xml(self):
    -        self.assertTrue(util.looks_like_xml(
    -            ''))
    -        self.assertTrue(util.looks_like_xml('abc'))
    -        self.assertFalse(util.looks_like_xml(''))
    -
    -    def test_unirange(self):
    -        first_non_bmp = u'\U00010000'
    -        r = re.compile(util.unirange(0x10000, 0x20000))
    -        m = r.match(first_non_bmp)
    -        self.assertTrue(m)
    -        self.assertEqual(m.end(), len(first_non_bmp))
    -        self.assertFalse(r.match(u'\uffff'))
    -        self.assertFalse(r.match(u'xxx'))
    -        # Tests that end is inclusive
    -        r = re.compile(util.unirange(0x10000, 0x10000) + '+')
    -        # Tests that the plus works for the entire unicode point, if narrow
    -        # build
    -        m = r.match(first_non_bmp * 2)
    -        self.assertTrue(m)
    -        self.assertEqual(m.end(), len(first_non_bmp) * 2)
    -
    -    def test_format_lines(self):
    -        lst = ['cat', 'dog']
    -        output = util.format_lines('var', lst)
    -        d = {}
    -        exec(output, d)
    -        self.assertTrue(isinstance(d['var'], tuple))
    -        self.assertEqual(('cat', 'dog'), d['var'])
    -
    -    def test_duplicates_removed_seq_types(self):
    -        # tuple
    -        x = util.duplicates_removed(('a', 'a', 'b'))
    -        self.assertEqual(['a', 'b'], x)
    -        # list
    -        x = util.duplicates_removed(['a', 'a', 'b'])
    -        self.assertEqual(['a', 'b'], x)
    -        # iterator
    -        x = util.duplicates_removed(iter(('a', 'a', 'b')))
    -        self.assertEqual(['a', 'b'], x)
    -
    -    def test_duplicates_removed_nonconsecutive(self):
    -        # keeps first
    -        x = util.duplicates_removed(('a', 'b', 'a'))
    -        self.assertEqual(['a', 'b'], x)
    -
    -    def test_guess_decode(self):
    -        # UTF-8 should be decoded as UTF-8
    -        s = util.guess_decode(u'\xff'.encode('utf-8'))
    -        self.assertEqual(s, (u'\xff', 'utf-8'))
    -
    -        # otherwise, it could be latin1 or the locale encoding...
    -        import locale
    -        s = util.guess_decode(b'\xff')
    -        self.assertTrue(s[1] in ('latin1', locale.getpreferredencoding()))
    -
    -    def test_guess_decode_from_terminal(self):
    -        class Term:
    -            encoding = 'utf-7'
    -
    -        s = util.guess_decode_from_terminal(u'\xff'.encode('utf-7'), Term)
    -        self.assertEqual(s, (u'\xff', 'utf-7'))
    -
    -        s = util.guess_decode_from_terminal(u'\xff'.encode('utf-8'), Term)
    -        self.assertEqual(s, (u'\xff', 'utf-8'))
    -
    -    def test_add_metaclass(self):
    -        class Meta(type):
    -            pass
    -
    -        @util.add_metaclass(Meta)
    -        class Cls:
    -            pass
    -
    -        self.assertEqual(type(Cls), Meta)
    -
    -
    -class ConsoleTest(unittest.TestCase):
    -
    -    def test_ansiformat(self):
    -        f = console.ansiformat
    -        c = console.codes
    -        all_attrs = f('+*_blue_*+', 'text')
    -        self.assertTrue(c['blue'] in all_attrs and c['blink'] in all_attrs
    -                        and c['bold'] in all_attrs and c['underline'] in all_attrs
    -                        and c['reset'] in all_attrs)
    -        self.assertRaises(KeyError, f, '*mauve*', 'text')
    -
    -    def test_functions(self):
    -        self.assertEqual(console.reset_color(), console.codes['reset'])
    -        self.assertEqual(console.colorize('blue', 'text'),
    -                         console.codes['blue'] + 'text' + console.codes['reset'])
    diff --git a/third_party/pygments/tox.ini b/third_party/pygments/tox.ini
    deleted file mode 100644
    index 8a33f99c0..000000000
    --- a/third_party/pygments/tox.ini
    +++ /dev/null
    @@ -1,7 +0,0 @@
    -[tox]
    -envlist = py26, py27, py33, py34
    -[testenv]
    -deps =
    -    nose
    -    coverage
    -commands = python -d tests/run.py {posargs}
    diff --git a/tools/generate.go b/tools/generate.go
    index ebf007695..ca4aabba1 100644
    --- a/tools/generate.go
    +++ b/tools/generate.go
    @@ -1,8 +1,13 @@
     package main
     
     import (
    +	"bytes"
     	"crypto/sha1"
     	"fmt"
    +	"github.com/alecthomas/chroma"
    +	"github.com/alecthomas/chroma/formatters/html"
    +	"github.com/alecthomas/chroma/lexers"
    +	"github.com/alecthomas/chroma/styles"
     	"io/ioutil"
     	"net/http"
     	"os"
    @@ -20,9 +25,6 @@ import (
     // program.
     var siteDir = "./public"
     
    -var cacheDir = "/tmp/gobyexample-cache"
    -var pygmentizeBin = "./third_party/pygments/pygmentize"
    -
     func verbose() bool {
     	return len(os.Getenv("VERBOSE")) > 0
     }
    @@ -77,22 +79,6 @@ func mustReadFile(path string) string {
     	return string(bytes)
     }
     
    -func cachedPygmentize(lex string, src string) string {
    -	ensureDir(cacheDir)
    -	arg := []string{"-l", lex, "-f", "html"}
    -	cachePath := cacheDir + "/pygmentize-" + strings.Join(arg, "-") + "-" + sha1Sum(src)
    -	cacheBytes, cacheErr := ioutil.ReadFile(cachePath)
    -	if cacheErr == nil {
    -		return string(cacheBytes)
    -	}
    -	renderBytes := pipe(pygmentizeBin, arg, src)
    -	// Newer versions of Pygments add silly empty spans.
    -	renderCleanString := strings.Replace(string(renderBytes), "", "", -1)
    -	writeErr := ioutil.WriteFile(cachePath, []byte(renderCleanString), 0600)
    -	check(writeErr)
    -	return renderCleanString
    -}
    -
     func markdown(src string) string {
     	return string(blackfriday.Run([]byte(src)))
     }
    @@ -217,6 +203,32 @@ func parseSegs(sourcePath string) ([]*Seg, string) {
     	return segs, filecontent
     }
     
    +func chromaFormat(code, filePath string) string {
    +
    +	lexer := lexers.Get(filePath)
    +	if lexer == nil {
    +		lexer = lexers.Fallback
    +	}
    +
    +	if strings.HasSuffix(filePath, ".sh") {
    +		lexer = SimpleShellOutputLexer
    +	}
    +
    +	lexer = chroma.Coalesce(lexer)
    +
    +	style := styles.Get("swapoff")
    +	if style == nil {
    +		style = styles.Fallback
    +	}
    +	formatter := html.New(html.WithClasses(true))
    +	iterator, err := lexer.Tokenise(nil, string(code))
    +	check(err)
    +	buf := new(bytes.Buffer)
    +	err = formatter.Format(buf, style, iterator)
    +	check(err)
    +	return buf.String()
    +}
    +
     func parseAndRenderSegs(sourcePath string) ([]*Seg, string) {
     	segs, filecontent := parseSegs(sourcePath)
     	lexer := whichLexer(sourcePath)
    @@ -225,7 +237,8 @@ func parseAndRenderSegs(sourcePath string) ([]*Seg, string) {
     			seg.DocsRendered = markdown(seg.Docs)
     		}
     		if seg.Code != "" {
    -			seg.CodeRendered = cachedPygmentize(lexer, seg.Code)
    +			seg.CodeRendered = chromaFormat(seg.Code, sourcePath)
    +
     			// adding the content to the js code for copying to the clipboard
     			if strings.HasSuffix(sourcePath, ".go") {
     				seg.CodeForJs = strings.Trim(seg.Code, "\n") + "\n"
    @@ -331,3 +344,38 @@ func main() {
     	renderIndex(examples)
     	renderExamples(examples)
     }
    +
    +var SimpleShellOutputLexer = chroma.MustNewLexer(
    +	&chroma.Config{
    +		Name:      "Shell Output",
    +		Aliases:   []string{"console"},
    +		Filenames: []string{"*.sh"},
    +		MimeTypes: []string{},
    +	},
    +	chroma.Rules{
    +		"root": {
    +			// $ or > triggers the start of prompt formatting
    +			{`^\$`, chroma.GenericPrompt, chroma.Push("prompt")},
    +			{`^>`, chroma.GenericPrompt, chroma.Push("prompt")},
    +
    +			// empty lines are just text
    +			{`^$\n`, chroma.Text, nil},
    +
    +			// otherwise its all output
    +			{`[^\n]+$\n?`, chroma.GenericOutput, nil},
    +		},
    +		"prompt": {
    +			// when we find newline, do output formatting rules
    +			{`\n`, chroma.Text, chroma.Push("output")},
    +			// otherwise its all text
    +			{`[^\n]+$`, chroma.Text, nil},
    +		},
    +		"output": {
    +			// sometimes there isn't output so we go right back to prompt
    +			{`^\$`, chroma.GenericPrompt, chroma.Pop(1)},
    +			{`^>`, chroma.GenericPrompt, chroma.Pop(1)},
    +			// otherwise its all output
    +			{`[^\n]+$\n?`, chroma.GenericOutput, nil},
    +		},
    +	},
    +)
    diff --git a/vendor/github.com/russross/blackfriday/v2/.gitignore b/vendor/github.com/russross/blackfriday/v2/.gitignore
    deleted file mode 100644
    index 75623dccc..000000000
    --- a/vendor/github.com/russross/blackfriday/v2/.gitignore
    +++ /dev/null
    @@ -1,8 +0,0 @@
    -*.out
    -*.swp
    -*.8
    -*.6
    -_obj
    -_test*
    -markdown
    -tags
    diff --git a/vendor/github.com/russross/blackfriday/v2/.travis.yml b/vendor/github.com/russross/blackfriday/v2/.travis.yml
    deleted file mode 100644
    index b0b525a5a..000000000
    --- a/vendor/github.com/russross/blackfriday/v2/.travis.yml
    +++ /dev/null
    @@ -1,17 +0,0 @@
    -sudo: false
    -language: go
    -go:
    -  - "1.10.x"
    -  - "1.11.x"
    -  - tip
    -matrix:
    -  fast_finish: true
    -  allow_failures:
    -    - go: tip
    -install:
    -  - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
    -script:
    -  - go get -t -v ./...
    -  - diff -u <(echo -n) <(gofmt -d -s .)
    -  - go tool vet .
    -  - go test -v ./...
    diff --git a/vendor/github.com/russross/blackfriday/v2/LICENSE.txt b/vendor/github.com/russross/blackfriday/v2/LICENSE.txt
    deleted file mode 100644
    index 2885af360..000000000
    --- a/vendor/github.com/russross/blackfriday/v2/LICENSE.txt
    +++ /dev/null
    @@ -1,29 +0,0 @@
    -Blackfriday is distributed under the Simplified BSD License:
    -
    -> Copyright © 2011 Russ Ross
    -> 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/vendor/github.com/russross/blackfriday/v2/README.md b/vendor/github.com/russross/blackfriday/v2/README.md
    deleted file mode 100644
    index d9c08a22f..000000000
    --- a/vendor/github.com/russross/blackfriday/v2/README.md
    +++ /dev/null
    @@ -1,335 +0,0 @@
    -Blackfriday
    -[![Build Status][BuildV2SVG]][BuildV2URL]
    -[![PkgGoDev][PkgGoDevV2SVG]][PkgGoDevV2URL]
    -===========
    -
    -Blackfriday is a [Markdown][1] processor implemented in [Go][2]. It
    -is paranoid about its input (so you can safely feed it user-supplied
    -data), it is fast, it supports common extensions (tables, smart
    -punctuation substitutions, etc.), and it is safe for all utf-8
    -(unicode) input.
    -
    -HTML output is currently supported, along with Smartypants
    -extensions.
    -
    -It started as a translation from C of [Sundown][3].
    -
    -
    -Installation
    -------------
    -
    -Blackfriday is compatible with modern Go releases in module mode.
    -With Go installed:
    -
    -    go get github.com/russross/blackfriday/v2
    -
    -will resolve and add the package to the current development module,
    -then build and install it. Alternatively, you can achieve the same
    -if you import it in a package:
    -
    -    import "github.com/russross/blackfriday/v2"
    -
    -and `go get` without parameters.
    -
    -Legacy GOPATH mode is unsupported.
    -
    -
    -Versions
    ---------
    -
    -Currently maintained and recommended version of Blackfriday is `v2`. It's being
    -developed on its own branch: https://github.com/russross/blackfriday/tree/v2 and the
    -documentation is available at
    -https://pkg.go.dev/github.com/russross/blackfriday/v2.
    -
    -It is `go get`-able in module mode at `github.com/russross/blackfriday/v2`.
    -
    -Version 2 offers a number of improvements over v1:
    -
    -* Cleaned up API
    -* A separate call to [`Parse`][4], which produces an abstract syntax tree for
    -  the document
    -* Latest bug fixes
    -* Flexibility to easily add your own rendering extensions
    -
    -Potential drawbacks:
    -
    -* Our benchmarks show v2 to be slightly slower than v1. Currently in the
    -  ballpark of around 15%.
    -* API breakage. If you can't afford modifying your code to adhere to the new API
    -  and don't care too much about the new features, v2 is probably not for you.
    -* Several bug fixes are trailing behind and still need to be forward-ported to
    -  v2. See issue [#348](https://github.com/russross/blackfriday/issues/348) for
    -  tracking.
    -
    -If you are still interested in the legacy `v1`, you can import it from
    -`github.com/russross/blackfriday`. Documentation for the legacy v1 can be found
    -here: https://pkg.go.dev/github.com/russross/blackfriday.
    -
    -
    -Usage
    ------
    -
    -For the most sensible markdown processing, it is as simple as getting your input
    -into a byte slice and calling:
    -
    -```go
    -output := blackfriday.Run(input)
    -```
    -
    -Your input will be parsed and the output rendered with a set of most popular
    -extensions enabled. If you want the most basic feature set, corresponding with
    -the bare Markdown specification, use:
    -
    -```go
    -output := blackfriday.Run(input, blackfriday.WithNoExtensions())
    -```
    -
    -### Sanitize untrusted content
    -
    -Blackfriday itself does nothing to protect against malicious content. If you are
    -dealing with user-supplied markdown, we recommend running Blackfriday's output
    -through HTML sanitizer such as [Bluemonday][5].
    -
    -Here's an example of simple usage of Blackfriday together with Bluemonday:
    -
    -```go
    -import (
    -    "github.com/microcosm-cc/bluemonday"
    -    "github.com/russross/blackfriday/v2"
    -)
    -
    -// ...
    -unsafe := blackfriday.Run(input)
    -html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
    -```
    -
    -### Custom options
    -
    -If you want to customize the set of options, use `blackfriday.WithExtensions`,
    -`blackfriday.WithRenderer` and `blackfriday.WithRefOverride`.
    -
    -### `blackfriday-tool`
    -
    -You can also check out `blackfriday-tool` for a more complete example
    -of how to use it. Download and install it using:
    -
    -    go get github.com/russross/blackfriday-tool
    -
    -This is a simple command-line tool that allows you to process a
    -markdown file using a standalone program.  You can also browse the
    -source directly on github if you are just looking for some example
    -code:
    -
    -* 
    -
    -Note that if you have not already done so, installing
    -`blackfriday-tool` will be sufficient to download and install
    -blackfriday in addition to the tool itself. The tool binary will be
    -installed in `$GOPATH/bin`.  This is a statically-linked binary that
    -can be copied to wherever you need it without worrying about
    -dependencies and library versions.
    -
    -### Sanitized anchor names
    -
    -Blackfriday includes an algorithm for creating sanitized anchor names
    -corresponding to a given input text. This algorithm is used to create
    -anchors for headings when `AutoHeadingIDs` extension is enabled. The
    -algorithm has a specification, so that other packages can create
    -compatible anchor names and links to those anchors.
    -
    -The specification is located at https://pkg.go.dev/github.com/russross/blackfriday/v2#hdr-Sanitized_Anchor_Names.
    -
    -[`SanitizedAnchorName`](https://pkg.go.dev/github.com/russross/blackfriday/v2#SanitizedAnchorName) exposes this functionality, and can be used to
    -create compatible links to the anchor names generated by blackfriday.
    -This algorithm is also implemented in a small standalone package at
    -[`github.com/shurcooL/sanitized_anchor_name`](https://pkg.go.dev/github.com/shurcooL/sanitized_anchor_name). It can be useful for clients
    -that want a small package and don't need full functionality of blackfriday.
    -
    -
    -Features
    ---------
    -
    -All features of Sundown are supported, including:
    -
    -*   **Compatibility**. The Markdown v1.0.3 test suite passes with
    -    the `--tidy` option.  Without `--tidy`, the differences are
    -    mostly in whitespace and entity escaping, where blackfriday is
    -    more consistent and cleaner.
    -
    -*   **Common extensions**, including table support, fenced code
    -    blocks, autolinks, strikethroughs, non-strict emphasis, etc.
    -
    -*   **Safety**. Blackfriday is paranoid when parsing, making it safe
    -    to feed untrusted user input without fear of bad things
    -    happening. The test suite stress tests this and there are no
    -    known inputs that make it crash.  If you find one, please let me
    -    know and send me the input that does it.
    -
    -    NOTE: "safety" in this context means *runtime safety only*. In order to
    -    protect yourself against JavaScript injection in untrusted content, see
    -    [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content).
    -
    -*   **Fast processing**. It is fast enough to render on-demand in
    -    most web applications without having to cache the output.
    -
    -*   **Thread safety**. You can run multiple parsers in different
    -    goroutines without ill effect. There is no dependence on global
    -    shared state.
    -
    -*   **Minimal dependencies**. Blackfriday only depends on standard
    -    library packages in Go. The source code is pretty
    -    self-contained, so it is easy to add to any project, including
    -    Google App Engine projects.
    -
    -*   **Standards compliant**. Output successfully validates using the
    -    W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional.
    -
    -
    -Extensions
    -----------
    -
    -In addition to the standard markdown syntax, this package
    -implements the following extensions:
    -
    -*   **Intra-word emphasis supression**. The `_` character is
    -    commonly used inside words when discussing code, so having
    -    markdown interpret it as an emphasis command is usually the
    -    wrong thing. Blackfriday lets you treat all emphasis markers as
    -    normal characters when they occur inside a word.
    -
    -*   **Tables**. Tables can be created by drawing them in the input
    -    using a simple syntax:
    -
    -    ```
    -    Name    | Age
    -    --------|------
    -    Bob     | 27
    -    Alice   | 23
    -    ```
    -
    -*   **Fenced code blocks**. In addition to the normal 4-space
    -    indentation to mark code blocks, you can explicitly mark them
    -    and supply a language (to make syntax highlighting simple). Just
    -    mark it like this:
    -
    -        ```go
    -        func getTrue() bool {
    -            return true
    -        }
    -        ```
    -
    -    You can use 3 or more backticks to mark the beginning of the
    -    block, and the same number to mark the end of the block.
    -
    -    To preserve classes of fenced code blocks while using the bluemonday
    -    HTML sanitizer, use the following policy:
    -
    -    ```go
    -    p := bluemonday.UGCPolicy()
    -    p.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code")
    -    html := p.SanitizeBytes(unsafe)
    -    ```
    -
    -*   **Definition lists**. A simple definition list is made of a single-line
    -    term followed by a colon and the definition for that term.
    -
    -        Cat
    -        : Fluffy animal everyone likes
    -
    -        Internet
    -        : Vector of transmission for pictures of cats
    -
    -    Terms must be separated from the previous definition by a blank line.
    -
    -*   **Footnotes**. A marker in the text that will become a superscript number;
    -    a footnote definition that will be placed in a list of footnotes at the
    -    end of the document. A footnote looks like this:
    -
    -        This is a footnote.[^1]
    -
    -        [^1]: the footnote text.
    -
    -*   **Autolinking**. Blackfriday can find URLs that have not been
    -    explicitly marked as links and turn them into links.
    -
    -*   **Strikethrough**. Use two tildes (`~~`) to mark text that
    -    should be crossed out.
    -
    -*   **Hard line breaks**. With this extension enabled newlines in the input
    -    translate into line breaks in the output. This extension is off by default.
    -
    -*   **Smart quotes**. Smartypants-style punctuation substitution is
    -    supported, turning normal double- and single-quote marks into
    -    curly quotes, etc.
    -
    -*   **LaTeX-style dash parsing** is an additional option, where `--`
    -    is translated into `–`, and `---` is translated into
    -    `—`. This differs from most smartypants processors, which
    -    turn a single hyphen into an ndash and a double hyphen into an
    -    mdash.
    -
    -*   **Smart fractions**, where anything that looks like a fraction
    -    is translated into suitable HTML (instead of just a few special
    -    cases like most smartypant processors). For example, `4/5`
    -    becomes `45`, which renders as
    -    45.
    -
    -
    -Other renderers
    ----------------
    -
    -Blackfriday is structured to allow alternative rendering engines. Here
    -are a few of note:
    -
    -*   [github_flavored_markdown](https://pkg.go.dev/github.com/shurcooL/github_flavored_markdown):
    -    provides a GitHub Flavored Markdown renderer with fenced code block
    -    highlighting, clickable heading anchor links.
    -
    -    It's not customizable, and its goal is to produce HTML output
    -    equivalent to the [GitHub Markdown API endpoint](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode),
    -    except the rendering is performed locally.
    -
    -*   [markdownfmt](https://github.com/shurcooL/markdownfmt): like gofmt,
    -    but for markdown.
    -
    -*   [LaTeX output](https://gitlab.com/ambrevar/blackfriday-latex):
    -    renders output as LaTeX.
    -
    -*   [bfchroma](https://github.com/Depado/bfchroma/): provides convenience
    -    integration with the [Chroma](https://github.com/alecthomas/chroma) code
    -    highlighting library. bfchroma is only compatible with v2 of Blackfriday and
    -    provides a drop-in renderer ready to use with Blackfriday, as well as
    -    options and means for further customization.
    -
    -*   [Blackfriday-Confluence](https://github.com/kentaro-m/blackfriday-confluence): provides a [Confluence Wiki Markup](https://confluence.atlassian.com/doc/confluence-wiki-markup-251003035.html) renderer.
    -
    -*   [Blackfriday-Slack](https://github.com/karriereat/blackfriday-slack): converts markdown to slack message style
    -
    -
    -TODO
    -----
    -
    -*   More unit testing
    -*   Improve Unicode support. It does not understand all Unicode
    -    rules (about what constitutes a letter, a punctuation symbol,
    -    etc.), so it may fail to detect word boundaries correctly in
    -    some instances. It is safe on all UTF-8 input.
    -
    -
    -License
    --------
    -
    -[Blackfriday is distributed under the Simplified BSD License](LICENSE.txt)
    -
    -
    -   [1]: https://daringfireball.net/projects/markdown/ "Markdown"
    -   [2]: https://golang.org/ "Go Language"
    -   [3]: https://github.com/vmg/sundown "Sundown"
    -   [4]: https://pkg.go.dev/github.com/russross/blackfriday/v2#Parse "Parse func"
    -   [5]: https://github.com/microcosm-cc/bluemonday "Bluemonday"
    -
    -   [BuildV2SVG]: https://travis-ci.org/russross/blackfriday.svg?branch=v2
    -   [BuildV2URL]: https://travis-ci.org/russross/blackfriday
    -   [PkgGoDevV2SVG]: https://pkg.go.dev/badge/github.com/russross/blackfriday/v2
    -   [PkgGoDevV2URL]: https://pkg.go.dev/github.com/russross/blackfriday/v2
    diff --git a/vendor/github.com/russross/blackfriday/v2/block.go b/vendor/github.com/russross/blackfriday/v2/block.go
    deleted file mode 100644
    index dcd61e6e3..000000000
    --- a/vendor/github.com/russross/blackfriday/v2/block.go
    +++ /dev/null
    @@ -1,1612 +0,0 @@
    -//
    -// Blackfriday Markdown Processor
    -// Available at http://github.com/russross/blackfriday
    -//
    -// Copyright © 2011 Russ Ross .
    -// Distributed under the Simplified BSD License.
    -// See README.md for details.
    -//
    -
    -//
    -// Functions to parse block-level elements.
    -//
    -
    -package blackfriday
    -
    -import (
    -	"bytes"
    -	"html"
    -	"regexp"
    -	"strings"
    -	"unicode"
    -)
    -
    -const (
    -	charEntity = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});"
    -	escapable  = "[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]"
    -)
    -
    -var (
    -	reBackslashOrAmp      = regexp.MustCompile("[\\&]")
    -	reEntityOrEscapedChar = regexp.MustCompile("(?i)\\\\" + escapable + "|" + charEntity)
    -)
    -
    -// Parse block-level data.
    -// Note: this function and many that it calls assume that
    -// the input buffer ends with a newline.
    -func (p *Markdown) block(data []byte) {
    -	// this is called recursively: enforce a maximum depth
    -	if p.nesting >= p.maxNesting {
    -		return
    -	}
    -	p.nesting++
    -
    -	// parse out one block-level construct at a time
    -	for len(data) > 0 {
    -		// prefixed heading:
    -		//
    -		// # Heading 1
    -		// ## Heading 2
    -		// ...
    -		// ###### Heading 6
    -		if p.isPrefixHeading(data) {
    -			data = data[p.prefixHeading(data):]
    -			continue
    -		}
    -
    -		// block of preformatted HTML:
    -		//
    -		// 
    - // ... - //
    - if data[0] == '<' { - if i := p.html(data, true); i > 0 { - data = data[i:] - continue - } - } - - // title block - // - // % stuff - // % more stuff - // % even more stuff - if p.extensions&Titleblock != 0 { - if data[0] == '%' { - if i := p.titleBlock(data, true); i > 0 { - data = data[i:] - continue - } - } - } - - // blank lines. note: returns the # of bytes to skip - if i := p.isEmpty(data); i > 0 { - data = data[i:] - continue - } - - // indented code block: - // - // func max(a, b int) int { - // if a > b { - // return a - // } - // return b - // } - if p.codePrefix(data) > 0 { - data = data[p.code(data):] - continue - } - - // fenced code block: - // - // ``` go - // func fact(n int) int { - // if n <= 1 { - // return n - // } - // return n * fact(n-1) - // } - // ``` - if p.extensions&FencedCode != 0 { - if i := p.fencedCodeBlock(data, true); i > 0 { - data = data[i:] - continue - } - } - - // horizontal rule: - // - // ------ - // or - // ****** - // or - // ______ - if p.isHRule(data) { - p.addBlock(HorizontalRule, nil) - var i int - for i = 0; i < len(data) && data[i] != '\n'; i++ { - } - data = data[i:] - continue - } - - // block quote: - // - // > A big quote I found somewhere - // > on the web - if p.quotePrefix(data) > 0 { - data = data[p.quote(data):] - continue - } - - // table: - // - // Name | Age | Phone - // ------|-----|--------- - // Bob | 31 | 555-1234 - // Alice | 27 | 555-4321 - if p.extensions&Tables != 0 { - if i := p.table(data); i > 0 { - data = data[i:] - continue - } - } - - // an itemized/unordered list: - // - // * Item 1 - // * Item 2 - // - // also works with + or - - if p.uliPrefix(data) > 0 { - data = data[p.list(data, 0):] - continue - } - - // a numbered/ordered list: - // - // 1. Item 1 - // 2. Item 2 - if p.oliPrefix(data) > 0 { - data = data[p.list(data, ListTypeOrdered):] - continue - } - - // definition lists: - // - // Term 1 - // : Definition a - // : Definition b - // - // Term 2 - // : Definition c - if p.extensions&DefinitionLists != 0 { - if p.dliPrefix(data) > 0 { - data = data[p.list(data, ListTypeDefinition):] - continue - } - } - - // anything else must look like a normal paragraph - // note: this finds underlined headings, too - data = data[p.paragraph(data):] - } - - p.nesting-- -} - -func (p *Markdown) addBlock(typ NodeType, content []byte) *Node { - p.closeUnmatchedBlocks() - container := p.addChild(typ, 0) - container.content = content - return container -} - -func (p *Markdown) isPrefixHeading(data []byte) bool { - if data[0] != '#' { - return false - } - - if p.extensions&SpaceHeadings != 0 { - level := 0 - for level < 6 && level < len(data) && data[level] == '#' { - level++ - } - if level == len(data) || data[level] != ' ' { - return false - } - } - return true -} - -func (p *Markdown) prefixHeading(data []byte) int { - level := 0 - for level < 6 && level < len(data) && data[level] == '#' { - level++ - } - i := skipChar(data, level, ' ') - end := skipUntilChar(data, i, '\n') - skip := end - id := "" - if p.extensions&HeadingIDs != 0 { - j, k := 0, 0 - // find start/end of heading id - for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ { - } - for k = j + 1; k < end && data[k] != '}'; k++ { - } - // extract heading id iff found - if j < end && k < end { - id = string(data[j+2 : k]) - end = j - skip = k + 1 - for end > 0 && data[end-1] == ' ' { - end-- - } - } - } - for end > 0 && data[end-1] == '#' { - if isBackslashEscaped(data, end-1) { - break - } - end-- - } - for end > 0 && data[end-1] == ' ' { - end-- - } - if end > i { - if id == "" && p.extensions&AutoHeadingIDs != 0 { - id = SanitizedAnchorName(string(data[i:end])) - } - block := p.addBlock(Heading, data[i:end]) - block.HeadingID = id - block.Level = level - } - return skip -} - -func (p *Markdown) isUnderlinedHeading(data []byte) int { - // test of level 1 heading - if data[0] == '=' { - i := skipChar(data, 1, '=') - i = skipChar(data, i, ' ') - if i < len(data) && data[i] == '\n' { - return 1 - } - return 0 - } - - // test of level 2 heading - if data[0] == '-' { - i := skipChar(data, 1, '-') - i = skipChar(data, i, ' ') - if i < len(data) && data[i] == '\n' { - return 2 - } - return 0 - } - - return 0 -} - -func (p *Markdown) titleBlock(data []byte, doRender bool) int { - if data[0] != '%' { - return 0 - } - splitData := bytes.Split(data, []byte("\n")) - var i int - for idx, b := range splitData { - if !bytes.HasPrefix(b, []byte("%")) { - i = idx // - 1 - break - } - } - - data = bytes.Join(splitData[0:i], []byte("\n")) - consumed := len(data) - data = bytes.TrimPrefix(data, []byte("% ")) - data = bytes.Replace(data, []byte("\n% "), []byte("\n"), -1) - block := p.addBlock(Heading, data) - block.Level = 1 - block.IsTitleblock = true - - return consumed -} - -func (p *Markdown) html(data []byte, doRender bool) int { - var i, j int - - // identify the opening tag - if data[0] != '<' { - return 0 - } - curtag, tagfound := p.htmlFindTag(data[1:]) - - // handle special cases - if !tagfound { - // check for an HTML comment - if size := p.htmlComment(data, doRender); size > 0 { - return size - } - - // check for an
    tag - if size := p.htmlHr(data, doRender); size > 0 { - return size - } - - // no special case recognized - return 0 - } - - // look for an unindented matching closing tag - // followed by a blank line - found := false - /* - closetag := []byte("\n") - j = len(curtag) + 1 - for !found { - // scan for a closing tag at the beginning of a line - if skip := bytes.Index(data[j:], closetag); skip >= 0 { - j += skip + len(closetag) - } else { - break - } - - // see if it is the only thing on the line - if skip := p.isEmpty(data[j:]); skip > 0 { - // see if it is followed by a blank line/eof - j += skip - if j >= len(data) { - found = true - i = j - } else { - if skip := p.isEmpty(data[j:]); skip > 0 { - j += skip - found = true - i = j - } - } - } - } - */ - - // if not found, try a second pass looking for indented match - // but not if tag is "ins" or "del" (following original Markdown.pl) - if !found && curtag != "ins" && curtag != "del" { - i = 1 - for i < len(data) { - i++ - for i < len(data) && !(data[i-1] == '<' && data[i] == '/') { - i++ - } - - if i+2+len(curtag) >= len(data) { - break - } - - j = p.htmlFindEnd(curtag, data[i-1:]) - - if j > 0 { - i += j - 1 - found = true - break - } - } - } - - if !found { - return 0 - } - - // the end of the block has been found - if doRender { - // trim newlines - end := i - for end > 0 && data[end-1] == '\n' { - end-- - } - finalizeHTMLBlock(p.addBlock(HTMLBlock, data[:end])) - } - - return i -} - -func finalizeHTMLBlock(block *Node) { - block.Literal = block.content - block.content = nil -} - -// HTML comment, lax form -func (p *Markdown) htmlComment(data []byte, doRender bool) int { - i := p.inlineHTMLComment(data) - // needs to end with a blank line - if j := p.isEmpty(data[i:]); j > 0 { - size := i + j - if doRender { - // trim trailing newlines - end := size - for end > 0 && data[end-1] == '\n' { - end-- - } - block := p.addBlock(HTMLBlock, data[:end]) - finalizeHTMLBlock(block) - } - return size - } - return 0 -} - -// HR, which is the only self-closing block tag considered -func (p *Markdown) htmlHr(data []byte, doRender bool) int { - if len(data) < 4 { - return 0 - } - if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') { - return 0 - } - if data[3] != ' ' && data[3] != '/' && data[3] != '>' { - // not an
    tag after all; at least not a valid one - return 0 - } - i := 3 - for i < len(data) && data[i] != '>' && data[i] != '\n' { - i++ - } - if i < len(data) && data[i] == '>' { - i++ - if j := p.isEmpty(data[i:]); j > 0 { - size := i + j - if doRender { - // trim newlines - end := size - for end > 0 && data[end-1] == '\n' { - end-- - } - finalizeHTMLBlock(p.addBlock(HTMLBlock, data[:end])) - } - return size - } - } - return 0 -} - -func (p *Markdown) htmlFindTag(data []byte) (string, bool) { - i := 0 - for i < len(data) && isalnum(data[i]) { - i++ - } - key := string(data[:i]) - if _, ok := blockTags[key]; ok { - return key, true - } - return "", false -} - -func (p *Markdown) htmlFindEnd(tag string, data []byte) int { - // assume data[0] == '<' && data[1] == '/' already tested - if tag == "hr" { - return 2 - } - // check if tag is a match - closetag := []byte("") - if !bytes.HasPrefix(data, closetag) { - return 0 - } - i := len(closetag) - - // check that the rest of the line is blank - skip := 0 - if skip = p.isEmpty(data[i:]); skip == 0 { - return 0 - } - i += skip - skip = 0 - - if i >= len(data) { - return i - } - - if p.extensions&LaxHTMLBlocks != 0 { - return i - } - if skip = p.isEmpty(data[i:]); skip == 0 { - // following line must be blank - return 0 - } - - return i + skip -} - -func (*Markdown) isEmpty(data []byte) int { - // it is okay to call isEmpty on an empty buffer - if len(data) == 0 { - return 0 - } - - var i int - for i = 0; i < len(data) && data[i] != '\n'; i++ { - if data[i] != ' ' && data[i] != '\t' { - return 0 - } - } - if i < len(data) && data[i] == '\n' { - i++ - } - return i -} - -func (*Markdown) isHRule(data []byte) bool { - i := 0 - - // skip up to three spaces - for i < 3 && data[i] == ' ' { - i++ - } - - // look at the hrule char - if data[i] != '*' && data[i] != '-' && data[i] != '_' { - return false - } - c := data[i] - - // the whole line must be the char or whitespace - n := 0 - for i < len(data) && data[i] != '\n' { - switch { - case data[i] == c: - n++ - case data[i] != ' ': - return false - } - i++ - } - - return n >= 3 -} - -// isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data, -// and returns the end index if so, or 0 otherwise. It also returns the marker found. -// If info is not nil, it gets set to the syntax specified in the fence line. -func isFenceLine(data []byte, info *string, oldmarker string) (end int, marker string) { - i, size := 0, 0 - - // skip up to three spaces - for i < len(data) && i < 3 && data[i] == ' ' { - i++ - } - - // check for the marker characters: ~ or ` - if i >= len(data) { - return 0, "" - } - if data[i] != '~' && data[i] != '`' { - return 0, "" - } - - c := data[i] - - // the whole line must be the same char or whitespace - for i < len(data) && data[i] == c { - size++ - i++ - } - - // the marker char must occur at least 3 times - if size < 3 { - return 0, "" - } - marker = string(data[i-size : i]) - - // if this is the end marker, it must match the beginning marker - if oldmarker != "" && marker != oldmarker { - return 0, "" - } - - // TODO(shurcooL): It's probably a good idea to simplify the 2 code paths here - // into one, always get the info string, and discard it if the caller doesn't care. - if info != nil { - infoLength := 0 - i = skipChar(data, i, ' ') - - if i >= len(data) { - if i == len(data) { - return i, marker - } - return 0, "" - } - - infoStart := i - - if data[i] == '{' { - i++ - infoStart++ - - for i < len(data) && data[i] != '}' && data[i] != '\n' { - infoLength++ - i++ - } - - if i >= len(data) || data[i] != '}' { - return 0, "" - } - - // strip all whitespace at the beginning and the end - // of the {} block - for infoLength > 0 && isspace(data[infoStart]) { - infoStart++ - infoLength-- - } - - for infoLength > 0 && isspace(data[infoStart+infoLength-1]) { - infoLength-- - } - i++ - i = skipChar(data, i, ' ') - } else { - for i < len(data) && !isverticalspace(data[i]) { - infoLength++ - i++ - } - } - - *info = strings.TrimSpace(string(data[infoStart : infoStart+infoLength])) - } - - if i == len(data) { - return i, marker - } - if i > len(data) || data[i] != '\n' { - return 0, "" - } - return i + 1, marker // Take newline into account. -} - -// fencedCodeBlock returns the end index if data contains a fenced code block at the beginning, -// or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects. -// If doRender is true, a final newline is mandatory to recognize the fenced code block. -func (p *Markdown) fencedCodeBlock(data []byte, doRender bool) int { - var info string - beg, marker := isFenceLine(data, &info, "") - if beg == 0 || beg >= len(data) { - return 0 - } - fenceLength := beg - 1 - - var work bytes.Buffer - work.Write([]byte(info)) - work.WriteByte('\n') - - for { - // safe to assume beg < len(data) - - // check for the end of the code block - fenceEnd, _ := isFenceLine(data[beg:], nil, marker) - if fenceEnd != 0 { - beg += fenceEnd - break - } - - // copy the current line - end := skipUntilChar(data, beg, '\n') + 1 - - // did we reach the end of the buffer without a closing marker? - if end >= len(data) { - return 0 - } - - // verbatim copy to the working buffer - if doRender { - work.Write(data[beg:end]) - } - beg = end - } - - if doRender { - block := p.addBlock(CodeBlock, work.Bytes()) // TODO: get rid of temp buffer - block.IsFenced = true - block.FenceLength = fenceLength - finalizeCodeBlock(block) - } - - return beg -} - -func unescapeChar(str []byte) []byte { - if str[0] == '\\' { - return []byte{str[1]} - } - return []byte(html.UnescapeString(string(str))) -} - -func unescapeString(str []byte) []byte { - if reBackslashOrAmp.Match(str) { - return reEntityOrEscapedChar.ReplaceAllFunc(str, unescapeChar) - } - return str -} - -func finalizeCodeBlock(block *Node) { - if block.IsFenced { - newlinePos := bytes.IndexByte(block.content, '\n') - firstLine := block.content[:newlinePos] - rest := block.content[newlinePos+1:] - block.Info = unescapeString(bytes.Trim(firstLine, "\n")) - block.Literal = rest - } else { - block.Literal = block.content - } - block.content = nil -} - -func (p *Markdown) table(data []byte) int { - table := p.addBlock(Table, nil) - i, columns := p.tableHeader(data) - if i == 0 { - p.tip = table.Parent - table.Unlink() - return 0 - } - - p.addBlock(TableBody, nil) - - for i < len(data) { - pipes, rowStart := 0, i - for ; i < len(data) && data[i] != '\n'; i++ { - if data[i] == '|' { - pipes++ - } - } - - if pipes == 0 { - i = rowStart - break - } - - // include the newline in data sent to tableRow - if i < len(data) && data[i] == '\n' { - i++ - } - p.tableRow(data[rowStart:i], columns, false) - } - - return i -} - -// check if the specified position is preceded by an odd number of backslashes -func isBackslashEscaped(data []byte, i int) bool { - backslashes := 0 - for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' { - backslashes++ - } - return backslashes&1 == 1 -} - -func (p *Markdown) tableHeader(data []byte) (size int, columns []CellAlignFlags) { - i := 0 - colCount := 1 - for i = 0; i < len(data) && data[i] != '\n'; i++ { - if data[i] == '|' && !isBackslashEscaped(data, i) { - colCount++ - } - } - - // doesn't look like a table header - if colCount == 1 { - return - } - - // include the newline in the data sent to tableRow - j := i - if j < len(data) && data[j] == '\n' { - j++ - } - header := data[:j] - - // column count ignores pipes at beginning or end of line - if data[0] == '|' { - colCount-- - } - if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) { - colCount-- - } - - columns = make([]CellAlignFlags, colCount) - - // move on to the header underline - i++ - if i >= len(data) { - return - } - - if data[i] == '|' && !isBackslashEscaped(data, i) { - i++ - } - i = skipChar(data, i, ' ') - - // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3 - // and trailing | optional on last column - col := 0 - for i < len(data) && data[i] != '\n' { - dashes := 0 - - if data[i] == ':' { - i++ - columns[col] |= TableAlignmentLeft - dashes++ - } - for i < len(data) && data[i] == '-' { - i++ - dashes++ - } - if i < len(data) && data[i] == ':' { - i++ - columns[col] |= TableAlignmentRight - dashes++ - } - for i < len(data) && data[i] == ' ' { - i++ - } - if i == len(data) { - return - } - // end of column test is messy - switch { - case dashes < 3: - // not a valid column - return - - case data[i] == '|' && !isBackslashEscaped(data, i): - // marker found, now skip past trailing whitespace - col++ - i++ - for i < len(data) && data[i] == ' ' { - i++ - } - - // trailing junk found after last column - if col >= colCount && i < len(data) && data[i] != '\n' { - return - } - - case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount: - // something else found where marker was required - return - - case data[i] == '\n': - // marker is optional for the last column - col++ - - default: - // trailing junk found after last column - return - } - } - if col != colCount { - return - } - - p.addBlock(TableHead, nil) - p.tableRow(header, columns, true) - size = i - if size < len(data) && data[size] == '\n' { - size++ - } - return -} - -func (p *Markdown) tableRow(data []byte, columns []CellAlignFlags, header bool) { - p.addBlock(TableRow, nil) - i, col := 0, 0 - - if data[i] == '|' && !isBackslashEscaped(data, i) { - i++ - } - - for col = 0; col < len(columns) && i < len(data); col++ { - for i < len(data) && data[i] == ' ' { - i++ - } - - cellStart := i - - for i < len(data) && (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' { - i++ - } - - cellEnd := i - - // skip the end-of-cell marker, possibly taking us past end of buffer - i++ - - for cellEnd > cellStart && cellEnd-1 < len(data) && data[cellEnd-1] == ' ' { - cellEnd-- - } - - cell := p.addBlock(TableCell, data[cellStart:cellEnd]) - cell.IsHeader = header - cell.Align = columns[col] - } - - // pad it out with empty columns to get the right number - for ; col < len(columns); col++ { - cell := p.addBlock(TableCell, nil) - cell.IsHeader = header - cell.Align = columns[col] - } - - // silently ignore rows with too many cells -} - -// returns blockquote prefix length -func (p *Markdown) quotePrefix(data []byte) int { - i := 0 - for i < 3 && i < len(data) && data[i] == ' ' { - i++ - } - if i < len(data) && data[i] == '>' { - if i+1 < len(data) && data[i+1] == ' ' { - return i + 2 - } - return i + 1 - } - return 0 -} - -// blockquote ends with at least one blank line -// followed by something without a blockquote prefix -func (p *Markdown) terminateBlockquote(data []byte, beg, end int) bool { - if p.isEmpty(data[beg:]) <= 0 { - return false - } - if end >= len(data) { - return true - } - return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0 -} - -// parse a blockquote fragment -func (p *Markdown) quote(data []byte) int { - block := p.addBlock(BlockQuote, nil) - var raw bytes.Buffer - beg, end := 0, 0 - for beg < len(data) { - end = beg - // Step over whole lines, collecting them. While doing that, check for - // fenced code and if one's found, incorporate it altogether, - // irregardless of any contents inside it - for end < len(data) && data[end] != '\n' { - if p.extensions&FencedCode != 0 { - if i := p.fencedCodeBlock(data[end:], false); i > 0 { - // -1 to compensate for the extra end++ after the loop: - end += i - 1 - break - } - } - end++ - } - if end < len(data) && data[end] == '\n' { - end++ - } - if pre := p.quotePrefix(data[beg:]); pre > 0 { - // skip the prefix - beg += pre - } else if p.terminateBlockquote(data, beg, end) { - break - } - // this line is part of the blockquote - raw.Write(data[beg:end]) - beg = end - } - p.block(raw.Bytes()) - p.finalize(block) - return end -} - -// returns prefix length for block code -func (p *Markdown) codePrefix(data []byte) int { - if len(data) >= 1 && data[0] == '\t' { - return 1 - } - if len(data) >= 4 && data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' { - return 4 - } - return 0 -} - -func (p *Markdown) code(data []byte) int { - var work bytes.Buffer - - i := 0 - for i < len(data) { - beg := i - for i < len(data) && data[i] != '\n' { - i++ - } - if i < len(data) && data[i] == '\n' { - i++ - } - - blankline := p.isEmpty(data[beg:i]) > 0 - if pre := p.codePrefix(data[beg:i]); pre > 0 { - beg += pre - } else if !blankline { - // non-empty, non-prefixed line breaks the pre - i = beg - break - } - - // verbatim copy to the working buffer - if blankline { - work.WriteByte('\n') - } else { - work.Write(data[beg:i]) - } - } - - // trim all the \n off the end of work - workbytes := work.Bytes() - eol := len(workbytes) - for eol > 0 && workbytes[eol-1] == '\n' { - eol-- - } - if eol != len(workbytes) { - work.Truncate(eol) - } - - work.WriteByte('\n') - - block := p.addBlock(CodeBlock, work.Bytes()) // TODO: get rid of temp buffer - block.IsFenced = false - finalizeCodeBlock(block) - - return i -} - -// returns unordered list item prefix -func (p *Markdown) uliPrefix(data []byte) int { - i := 0 - // start with up to 3 spaces - for i < len(data) && i < 3 && data[i] == ' ' { - i++ - } - if i >= len(data)-1 { - return 0 - } - // need one of {'*', '+', '-'} followed by a space or a tab - if (data[i] != '*' && data[i] != '+' && data[i] != '-') || - (data[i+1] != ' ' && data[i+1] != '\t') { - return 0 - } - return i + 2 -} - -// returns ordered list item prefix -func (p *Markdown) oliPrefix(data []byte) int { - i := 0 - - // start with up to 3 spaces - for i < 3 && i < len(data) && data[i] == ' ' { - i++ - } - - // count the digits - start := i - for i < len(data) && data[i] >= '0' && data[i] <= '9' { - i++ - } - if start == i || i >= len(data)-1 { - return 0 - } - - // we need >= 1 digits followed by a dot and a space or a tab - if data[i] != '.' || !(data[i+1] == ' ' || data[i+1] == '\t') { - return 0 - } - return i + 2 -} - -// returns definition list item prefix -func (p *Markdown) dliPrefix(data []byte) int { - if len(data) < 2 { - return 0 - } - i := 0 - // need a ':' followed by a space or a tab - if data[i] != ':' || !(data[i+1] == ' ' || data[i+1] == '\t') { - return 0 - } - for i < len(data) && data[i] == ' ' { - i++ - } - return i + 2 -} - -// parse ordered or unordered list block -func (p *Markdown) list(data []byte, flags ListType) int { - i := 0 - flags |= ListItemBeginningOfList - block := p.addBlock(List, nil) - block.ListFlags = flags - block.Tight = true - - for i < len(data) { - skip := p.listItem(data[i:], &flags) - if flags&ListItemContainsBlock != 0 { - block.ListData.Tight = false - } - i += skip - if skip == 0 || flags&ListItemEndOfList != 0 { - break - } - flags &= ^ListItemBeginningOfList - } - - above := block.Parent - finalizeList(block) - p.tip = above - return i -} - -// Returns true if the list item is not the same type as its parent list -func (p *Markdown) listTypeChanged(data []byte, flags *ListType) bool { - if p.dliPrefix(data) > 0 && *flags&ListTypeDefinition == 0 { - return true - } else if p.oliPrefix(data) > 0 && *flags&ListTypeOrdered == 0 { - return true - } else if p.uliPrefix(data) > 0 && (*flags&ListTypeOrdered != 0 || *flags&ListTypeDefinition != 0) { - return true - } - return false -} - -// Returns true if block ends with a blank line, descending if needed -// into lists and sublists. -func endsWithBlankLine(block *Node) bool { - // TODO: figure this out. Always false now. - for block != nil { - //if block.lastLineBlank { - //return true - //} - t := block.Type - if t == List || t == Item { - block = block.LastChild - } else { - break - } - } - return false -} - -func finalizeList(block *Node) { - block.open = false - item := block.FirstChild - for item != nil { - // check for non-final list item ending with blank line: - if endsWithBlankLine(item) && item.Next != nil { - block.ListData.Tight = false - break - } - // recurse into children of list item, to see if there are spaces - // between any of them: - subItem := item.FirstChild - for subItem != nil { - if endsWithBlankLine(subItem) && (item.Next != nil || subItem.Next != nil) { - block.ListData.Tight = false - break - } - subItem = subItem.Next - } - item = item.Next - } -} - -// Parse a single list item. -// Assumes initial prefix is already removed if this is a sublist. -func (p *Markdown) listItem(data []byte, flags *ListType) int { - // keep track of the indentation of the first line - itemIndent := 0 - if data[0] == '\t' { - itemIndent += 4 - } else { - for itemIndent < 3 && data[itemIndent] == ' ' { - itemIndent++ - } - } - - var bulletChar byte = '*' - i := p.uliPrefix(data) - if i == 0 { - i = p.oliPrefix(data) - } else { - bulletChar = data[i-2] - } - if i == 0 { - i = p.dliPrefix(data) - // reset definition term flag - if i > 0 { - *flags &= ^ListTypeTerm - } - } - if i == 0 { - // if in definition list, set term flag and continue - if *flags&ListTypeDefinition != 0 { - *flags |= ListTypeTerm - } else { - return 0 - } - } - - // skip leading whitespace on first line - for i < len(data) && data[i] == ' ' { - i++ - } - - // find the end of the line - line := i - for i > 0 && i < len(data) && data[i-1] != '\n' { - i++ - } - - // get working buffer - var raw bytes.Buffer - - // put the first line into the working buffer - raw.Write(data[line:i]) - line = i - - // process the following lines - containsBlankLine := false - sublist := 0 - codeBlockMarker := "" - -gatherlines: - for line < len(data) { - i++ - - // find the end of this line - for i < len(data) && data[i-1] != '\n' { - i++ - } - - // if it is an empty line, guess that it is part of this item - // and move on to the next line - if p.isEmpty(data[line:i]) > 0 { - containsBlankLine = true - line = i - continue - } - - // calculate the indentation - indent := 0 - indentIndex := 0 - if data[line] == '\t' { - indentIndex++ - indent += 4 - } else { - for indent < 4 && line+indent < i && data[line+indent] == ' ' { - indent++ - indentIndex++ - } - } - - chunk := data[line+indentIndex : i] - - if p.extensions&FencedCode != 0 { - // determine if in or out of codeblock - // if in codeblock, ignore normal list processing - _, marker := isFenceLine(chunk, nil, codeBlockMarker) - if marker != "" { - if codeBlockMarker == "" { - // start of codeblock - codeBlockMarker = marker - } else { - // end of codeblock. - codeBlockMarker = "" - } - } - // we are in a codeblock, write line, and continue - if codeBlockMarker != "" || marker != "" { - raw.Write(data[line+indentIndex : i]) - line = i - continue gatherlines - } - } - - // evaluate how this line fits in - switch { - // is this a nested list item? - case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) || - p.oliPrefix(chunk) > 0 || - p.dliPrefix(chunk) > 0: - - // to be a nested list, it must be indented more - // if not, it is either a different kind of list - // or the next item in the same list - if indent <= itemIndent { - if p.listTypeChanged(chunk, flags) { - *flags |= ListItemEndOfList - } else if containsBlankLine { - *flags |= ListItemContainsBlock - } - - break gatherlines - } - - if containsBlankLine { - *flags |= ListItemContainsBlock - } - - // is this the first item in the nested list? - if sublist == 0 { - sublist = raw.Len() - } - - // is this a nested prefix heading? - case p.isPrefixHeading(chunk): - // if the heading is not indented, it is not nested in the list - // and thus ends the list - if containsBlankLine && indent < 4 { - *flags |= ListItemEndOfList - break gatherlines - } - *flags |= ListItemContainsBlock - - // anything following an empty line is only part - // of this item if it is indented 4 spaces - // (regardless of the indentation of the beginning of the item) - case containsBlankLine && indent < 4: - if *flags&ListTypeDefinition != 0 && i < len(data)-1 { - // is the next item still a part of this list? - next := i - for next < len(data) && data[next] != '\n' { - next++ - } - for next < len(data)-1 && data[next] == '\n' { - next++ - } - if i < len(data)-1 && data[i] != ':' && data[next] != ':' { - *flags |= ListItemEndOfList - } - } else { - *flags |= ListItemEndOfList - } - break gatherlines - - // a blank line means this should be parsed as a block - case containsBlankLine: - raw.WriteByte('\n') - *flags |= ListItemContainsBlock - } - - // if this line was preceded by one or more blanks, - // re-introduce the blank into the buffer - if containsBlankLine { - containsBlankLine = false - raw.WriteByte('\n') - } - - // add the line into the working buffer without prefix - raw.Write(data[line+indentIndex : i]) - - line = i - } - - rawBytes := raw.Bytes() - - block := p.addBlock(Item, nil) - block.ListFlags = *flags - block.Tight = false - block.BulletChar = bulletChar - block.Delimiter = '.' // Only '.' is possible in Markdown, but ')' will also be possible in CommonMark - - // render the contents of the list item - if *flags&ListItemContainsBlock != 0 && *flags&ListTypeTerm == 0 { - // intermediate render of block item, except for definition term - if sublist > 0 { - p.block(rawBytes[:sublist]) - p.block(rawBytes[sublist:]) - } else { - p.block(rawBytes) - } - } else { - // intermediate render of inline item - if sublist > 0 { - child := p.addChild(Paragraph, 0) - child.content = rawBytes[:sublist] - p.block(rawBytes[sublist:]) - } else { - child := p.addChild(Paragraph, 0) - child.content = rawBytes - } - } - return line -} - -// render a single paragraph that has already been parsed out -func (p *Markdown) renderParagraph(data []byte) { - if len(data) == 0 { - return - } - - // trim leading spaces - beg := 0 - for data[beg] == ' ' { - beg++ - } - - end := len(data) - // trim trailing newline - if data[len(data)-1] == '\n' { - end-- - } - - // trim trailing spaces - for end > beg && data[end-1] == ' ' { - end-- - } - - p.addBlock(Paragraph, data[beg:end]) -} - -func (p *Markdown) paragraph(data []byte) int { - // prev: index of 1st char of previous line - // line: index of 1st char of current line - // i: index of cursor/end of current line - var prev, line, i int - tabSize := TabSizeDefault - if p.extensions&TabSizeEight != 0 { - tabSize = TabSizeDouble - } - // keep going until we find something to mark the end of the paragraph - for i < len(data) { - // mark the beginning of the current line - prev = line - current := data[i:] - line = i - - // did we find a reference or a footnote? If so, end a paragraph - // preceding it and report that we have consumed up to the end of that - // reference: - if refEnd := isReference(p, current, tabSize); refEnd > 0 { - p.renderParagraph(data[:i]) - return i + refEnd - } - - // did we find a blank line marking the end of the paragraph? - if n := p.isEmpty(current); n > 0 { - // did this blank line followed by a definition list item? - if p.extensions&DefinitionLists != 0 { - if i < len(data)-1 && data[i+1] == ':' { - return p.list(data[prev:], ListTypeDefinition) - } - } - - p.renderParagraph(data[:i]) - return i + n - } - - // an underline under some text marks a heading, so our paragraph ended on prev line - if i > 0 { - if level := p.isUnderlinedHeading(current); level > 0 { - // render the paragraph - p.renderParagraph(data[:prev]) - - // ignore leading and trailing whitespace - eol := i - 1 - for prev < eol && data[prev] == ' ' { - prev++ - } - for eol > prev && data[eol-1] == ' ' { - eol-- - } - - id := "" - if p.extensions&AutoHeadingIDs != 0 { - id = SanitizedAnchorName(string(data[prev:eol])) - } - - block := p.addBlock(Heading, data[prev:eol]) - block.Level = level - block.HeadingID = id - - // find the end of the underline - for i < len(data) && data[i] != '\n' { - i++ - } - return i - } - } - - // if the next line starts a block of HTML, then the paragraph ends here - if p.extensions&LaxHTMLBlocks != 0 { - if data[i] == '<' && p.html(current, false) > 0 { - // rewind to before the HTML block - p.renderParagraph(data[:i]) - return i - } - } - - // if there's a prefixed heading or a horizontal rule after this, paragraph is over - if p.isPrefixHeading(current) || p.isHRule(current) { - p.renderParagraph(data[:i]) - return i - } - - // if there's a fenced code block, paragraph is over - if p.extensions&FencedCode != 0 { - if p.fencedCodeBlock(current, false) > 0 { - p.renderParagraph(data[:i]) - return i - } - } - - // if there's a definition list item, prev line is a definition term - if p.extensions&DefinitionLists != 0 { - if p.dliPrefix(current) != 0 { - ret := p.list(data[prev:], ListTypeDefinition) - return ret - } - } - - // if there's a list after this, paragraph is over - if p.extensions&NoEmptyLineBeforeBlock != 0 { - if p.uliPrefix(current) != 0 || - p.oliPrefix(current) != 0 || - p.quotePrefix(current) != 0 || - p.codePrefix(current) != 0 { - p.renderParagraph(data[:i]) - return i - } - } - - // otherwise, scan to the beginning of the next line - nl := bytes.IndexByte(data[i:], '\n') - if nl >= 0 { - i += nl + 1 - } else { - i += len(data[i:]) - } - } - - p.renderParagraph(data[:i]) - return i -} - -func skipChar(data []byte, start int, char byte) int { - i := start - for i < len(data) && data[i] == char { - i++ - } - return i -} - -func skipUntilChar(text []byte, start int, char byte) int { - i := start - for i < len(text) && text[i] != char { - i++ - } - return i -} - -// SanitizedAnchorName returns a sanitized anchor name for the given text. -// -// It implements the algorithm specified in the package comment. -func SanitizedAnchorName(text string) string { - var anchorName []rune - futureDash := false - for _, r := range text { - switch { - case unicode.IsLetter(r) || unicode.IsNumber(r): - if futureDash && len(anchorName) > 0 { - anchorName = append(anchorName, '-') - } - futureDash = false - anchorName = append(anchorName, unicode.ToLower(r)) - default: - futureDash = true - } - } - return string(anchorName) -} diff --git a/vendor/github.com/russross/blackfriday/v2/doc.go b/vendor/github.com/russross/blackfriday/v2/doc.go deleted file mode 100644 index 57ff152a0..000000000 --- a/vendor/github.com/russross/blackfriday/v2/doc.go +++ /dev/null @@ -1,46 +0,0 @@ -// Package blackfriday is a markdown processor. -// -// It translates plain text with simple formatting rules into an AST, which can -// then be further processed to HTML (provided by Blackfriday itself) or other -// formats (provided by the community). -// -// The simplest way to invoke Blackfriday is to call the Run function. It will -// take a text input and produce a text output in HTML (or other format). -// -// A slightly more sophisticated way to use Blackfriday is to create a Markdown -// processor and to call Parse, which returns a syntax tree for the input -// document. You can leverage Blackfriday's parsing for content extraction from -// markdown documents. You can assign a custom renderer and set various options -// to the Markdown processor. -// -// If you're interested in calling Blackfriday from command line, see -// https://github.com/russross/blackfriday-tool. -// -// Sanitized Anchor Names -// -// Blackfriday includes an algorithm for creating sanitized anchor names -// corresponding to a given input text. This algorithm is used to create -// anchors for headings when AutoHeadingIDs extension is enabled. The -// algorithm is specified below, so that other packages can create -// compatible anchor names and links to those anchors. -// -// The algorithm iterates over the input text, interpreted as UTF-8, -// one Unicode code point (rune) at a time. All runes that are letters (category L) -// or numbers (category N) are considered valid characters. They are mapped to -// lower case, and included in the output. All other runes are considered -// invalid characters. Invalid characters that precede the first valid character, -// as well as invalid character that follow the last valid character -// are dropped completely. All other sequences of invalid characters -// between two valid characters are replaced with a single dash character '-'. -// -// SanitizedAnchorName exposes this functionality, and can be used to -// create compatible links to the anchor names generated by blackfriday. -// This algorithm is also implemented in a small standalone package at -// github.com/shurcooL/sanitized_anchor_name. It can be useful for clients -// that want a small package and don't need full functionality of blackfriday. -package blackfriday - -// NOTE: Keep Sanitized Anchor Name algorithm in sync with package -// github.com/shurcooL/sanitized_anchor_name. -// Otherwise, users of sanitized_anchor_name will get anchor names -// that are incompatible with those generated by blackfriday. diff --git a/vendor/github.com/russross/blackfriday/v2/entities.go b/vendor/github.com/russross/blackfriday/v2/entities.go deleted file mode 100644 index a2c3edb69..000000000 --- a/vendor/github.com/russross/blackfriday/v2/entities.go +++ /dev/null @@ -1,2236 +0,0 @@ -package blackfriday - -// Extracted from https://html.spec.whatwg.org/multipage/entities.json -var entities = map[string]bool{ - "Æ": true, - "Æ": true, - "&": true, - "&": true, - "Á": true, - "Á": true, - "Ă": true, - "Â": true, - "Â": true, - "А": true, - "𝔄": true, - "À": true, - "À": true, - "Α": true, - "Ā": true, - "⩓": true, - "Ą": true, - "𝔸": true, - "⁡": true, - "Å": true, - "Å": true, - "𝒜": true, - "≔": true, - "Ã": true, - "Ã": true, - "Ä": true, - "Ä": true, - "∖": true, - "⫧": true, - "⌆": true, - "Б": true, - "∵": true, - "ℬ": true, - "Β": true, - "𝔅": true, - "𝔹": true, - "˘": true, - "ℬ": true, - "≎": true, - "Ч": true, - "©": true, - "©": true, - "Ć": true, - "⋒": true, - "ⅅ": true, - "ℭ": true, - "Č": true, - "Ç": true, - "Ç": true, - "Ĉ": true, - "∰": true, - "Ċ": true, - "¸": true, - "·": true, - "ℭ": true, - "Χ": true, - "⊙": true, - "⊖": true, - "⊕": true, - "⊗": true, - "∲": true, - "”": true, - "’": true, - "∷": true, - "⩴": true, - "≡": true, - "∯": true, - "∮": true, - "ℂ": true, - "∐": true, - "∳": true, - "⨯": true, - "𝒞": true, - "⋓": true, - "≍": true, - "ⅅ": true, - "⤑": true, - "Ђ": true, - "Ѕ": true, - "Џ": true, - "‡": true, - "↡": true, - "⫤": true, - "Ď": true, - "Д": true, - "∇": true, - "Δ": true, - "𝔇": true, - "´": true, - "˙": true, - "˝": true, - "`": true, - "˜": true, - "⋄": true, - "ⅆ": true, - "𝔻": true, - "¨": true, - "⃜": true, - "≐": true, - "∯": true, - "¨": true, - "⇓": true, - "⇐": true, - "⇔": true, - "⫤": true, - "⟸": true, - "⟺": true, - "⟹": true, - "⇒": true, - "⊨": true, - "⇑": true, - "⇕": true, - "∥": true, - "↓": true, - "⤓": true, - "⇵": true, - "̑": true, - "⥐": true, - "⥞": true, - "↽": true, - "⥖": true, - "⥟": true, - "⇁": true, - "⥗": true, - "⊤": true, - "↧": true, - "⇓": true, - "𝒟": true, - "Đ": true, - "Ŋ": true, - "Ð": true, - "Ð": true, - "É": true, - "É": true, - "Ě": true, - "Ê": true, - "Ê": true, - "Э": true, - "Ė": true, - "𝔈": true, - "È": true, - "È": true, - "∈": true, - "Ē": true, - "◻": true, - "▫": true, - "Ę": true, - "𝔼": true, - "Ε": true, - "⩵": true, - "≂": true, - "⇌": true, - "ℰ": true, - "⩳": true, - "Η": true, - "Ë": true, - "Ë": true, - "∃": true, - "ⅇ": true, - "Ф": true, - "𝔉": true, - "◼": true, - "▪": true, - "𝔽": true, - "∀": true, - "ℱ": true, - "ℱ": true, - "Ѓ": true, - ">": true, - ">": true, - "Γ": true, - "Ϝ": true, - "Ğ": true, - "Ģ": true, - "Ĝ": true, - "Г": true, - "Ġ": true, - "𝔊": true, - "⋙": true, - "𝔾": true, - "≥": true, - "⋛": true, - "≧": true, - "⪢": true, - "≷": true, - "⩾": true, - "≳": true, - "𝒢": true, - "≫": true, - "Ъ": true, - "ˇ": true, - "^": true, - "Ĥ": true, - "ℌ": true, - "ℋ": true, - "ℍ": true, - "─": true, - "ℋ": true, - "Ħ": true, - "≎": true, - "≏": true, - "Е": true, - "IJ": true, - "Ё": true, - "Í": true, - "Í": true, - "Î": true, - "Î": true, - "И": true, - "İ": true, - "ℑ": true, - "Ì": true, - "Ì": true, - "ℑ": true, - "Ī": true, - "ⅈ": true, - "⇒": true, - "∬": true, - "∫": true, - "⋂": true, - "⁣": true, - "⁢": true, - "Į": true, - "𝕀": true, - "Ι": true, - "ℐ": true, - "Ĩ": true, - "І": true, - "Ï": true, - "Ï": true, - "Ĵ": true, - "Й": true, - "𝔍": true, - "𝕁": true, - "𝒥": true, - "Ј": true, - "Є": true, - "Х": true, - "Ќ": true, - "Κ": true, - "Ķ": true, - "К": true, - "𝔎": true, - "𝕂": true, - "𝒦": true, - "Љ": true, - "<": true, - "<": true, - "Ĺ": true, - "Λ": true, - "⟪": true, - "ℒ": true, - "↞": true, - "Ľ": true, - "Ļ": true, - "Л": true, - "⟨": true, - "←": true, - "⇤": true, - "⇆": true, - "⌈": true, - "⟦": true, - "⥡": true, - "⇃": true, - "⥙": true, - "⌊": true, - "↔": true, - "⥎": true, - "⊣": true, - "↤": true, - "⥚": true, - "⊲": true, - "⧏": true, - "⊴": true, - "⥑": true, - "⥠": true, - "↿": true, - "⥘": true, - "↼": true, - "⥒": true, - "⇐": true, - "⇔": true, - "⋚": true, - "≦": true, - "≶": true, - "⪡": true, - "⩽": true, - "≲": true, - "𝔏": true, - "⋘": true, - "⇚": true, - "Ŀ": true, - "⟵": true, - "⟷": true, - "⟶": true, - "⟸": true, - "⟺": true, - "⟹": true, - "𝕃": true, - "↙": true, - "↘": true, - "ℒ": true, - "↰": true, - "Ł": true, - "≪": true, - "⤅": true, - "М": true, - " ": true, - "ℳ": true, - "𝔐": true, - "∓": true, - "𝕄": true, - "ℳ": true, - "Μ": true, - "Њ": true, - "Ń": true, - "Ň": true, - "Ņ": true, - "Н": true, - "​": true, - "​": true, - "​": true, - "​": true, - "≫": true, - "≪": true, - " ": true, - "𝔑": true, - "⁠": true, - " ": true, - "ℕ": true, - "⫬": true, - "≢": true, - "≭": true, - "∦": true, - "∉": true, - "≠": true, - "≂̸": true, - "∄": true, - "≯": true, - "≱": true, - "≧̸": true, - "≫̸": true, - "≹": true, - "⩾̸": true, - "≵": true, - "≎̸": true, - "≏̸": true, - "⋪": true, - "⧏̸": true, - "⋬": true, - "≮": true, - "≰": true, - "≸": true, - "≪̸": true, - "⩽̸": true, - "≴": true, - "⪢̸": true, - "⪡̸": true, - "⊀": true, - "⪯̸": true, - "⋠": true, - "∌": true, - "⋫": true, - "⧐̸": true, - "⋭": true, - "⊏̸": true, - "⋢": true, - "⊐̸": true, - "⋣": true, - "⊂⃒": true, - "⊈": true, - "⊁": true, - "⪰̸": true, - "⋡": true, - "≿̸": true, - "⊃⃒": true, - "⊉": true, - "≁": true, - "≄": true, - "≇": true, - "≉": true, - "∤": true, - "𝒩": true, - "Ñ": true, - "Ñ": true, - "Ν": true, - "Œ": true, - "Ó": true, - "Ó": true, - "Ô": true, - "Ô": true, - "О": true, - "Ő": true, - "𝔒": true, - "Ò": true, - "Ò": true, - "Ō": true, - "Ω": true, - "Ο": true, - "𝕆": true, - "“": true, - "‘": true, - "⩔": true, - "𝒪": true, - "Ø": true, - "Ø": true, - "Õ": true, - "Õ": true, - "⨷": true, - "Ö": true, - "Ö": true, - "‾": true, - "⏞": true, - "⎴": true, - "⏜": true, - "∂": true, - "П": true, - "𝔓": true, - "Φ": true, - "Π": true, - "±": true, - "ℌ": true, - "ℙ": true, - "⪻": true, - "≺": true, - "⪯": true, - "≼": true, - "≾": true, - "″": true, - "∏": true, - "∷": true, - "∝": true, - "𝒫": true, - "Ψ": true, - """: true, - """: true, - "𝔔": true, - "ℚ": true, - "𝒬": true, - "⤐": true, - "®": true, - "®": true, - "Ŕ": true, - "⟫": true, - "↠": true, - "⤖": true, - "Ř": true, - "Ŗ": true, - "Р": true, - "ℜ": true, - "∋": true, - "⇋": true, - "⥯": true, - "ℜ": true, - "Ρ": true, - "⟩": true, - "→": true, - "⇥": true, - "⇄": true, - "⌉": true, - "⟧": true, - "⥝": true, - "⇂": true, - "⥕": true, - "⌋": true, - "⊢": true, - "↦": true, - "⥛": true, - "⊳": true, - "⧐": true, - "⊵": true, - "⥏": true, - "⥜": true, - "↾": true, - "⥔": true, - "⇀": true, - "⥓": true, - "⇒": true, - "ℝ": true, - "⥰": true, - "⇛": true, - "ℛ": true, - "↱": true, - "⧴": true, - "Щ": true, - "Ш": true, - "Ь": true, - "Ś": true, - "⪼": true, - "Š": true, - "Ş": true, - "Ŝ": true, - "С": true, - "𝔖": true, - "↓": true, - "←": true, - "→": true, - "↑": true, - "Σ": true, - "∘": true, - "𝕊": true, - "√": true, - "□": true, - "⊓": true, - "⊏": true, - "⊑": true, - "⊐": true, - "⊒": true, - "⊔": true, - "𝒮": true, - "⋆": true, - "⋐": true, - "⋐": true, - "⊆": true, - "≻": true, - "⪰": true, - "≽": true, - "≿": true, - "∋": true, - "∑": true, - "⋑": true, - "⊃": true, - "⊇": true, - "⋑": true, - "Þ": true, - "Þ": true, - "™": true, - "Ћ": true, - "Ц": true, - " ": true, - "Τ": true, - "Ť": true, - "Ţ": true, - "Т": true, - "𝔗": true, - "∴": true, - "Θ": true, - "  ": true, - " ": true, - "∼": true, - "≃": true, - "≅": true, - "≈": true, - "𝕋": true, - "⃛": true, - "𝒯": true, - "Ŧ": true, - "Ú": true, - "Ú": true, - "↟": true, - "⥉": true, - "Ў": true, - "Ŭ": true, - "Û": true, - "Û": true, - "У": true, - "Ű": true, - "𝔘": true, - "Ù": true, - "Ù": true, - "Ū": true, - "_": true, - "⏟": true, - "⎵": true, - "⏝": true, - "⋃": true, - "⊎": true, - "Ų": true, - "𝕌": true, - "↑": true, - "⤒": true, - "⇅": true, - "↕": true, - "⥮": true, - "⊥": true, - "↥": true, - "⇑": true, - "⇕": true, - "↖": true, - "↗": true, - "ϒ": true, - "Υ": true, - "Ů": true, - "𝒰": true, - "Ũ": true, - "Ü": true, - "Ü": true, - "⊫": true, - "⫫": true, - "В": true, - "⊩": true, - "⫦": true, - "⋁": true, - "‖": true, - "‖": true, - "∣": true, - "|": true, - "❘": true, - "≀": true, - " ": true, - "𝔙": true, - "𝕍": true, - "𝒱": true, - "⊪": true, - "Ŵ": true, - "⋀": true, - "𝔚": true, - "𝕎": true, - "𝒲": true, - "𝔛": true, - "Ξ": true, - "𝕏": true, - "𝒳": true, - "Я": true, - "Ї": true, - "Ю": true, - "Ý": true, - "Ý": true, - "Ŷ": true, - "Ы": true, - "𝔜": true, - "𝕐": true, - "𝒴": true, - "Ÿ": true, - "Ж": true, - "Ź": true, - "Ž": true, - "З": true, - "Ż": true, - "​": true, - "Ζ": true, - "ℨ": true, - "ℤ": true, - "𝒵": true, - "á": true, - "á": true, - "ă": true, - "∾": true, - "∾̳": true, - "∿": true, - "â": true, - "â": true, - "´": true, - "´": true, - "а": true, - "æ": true, - "æ": true, - "⁡": true, - "𝔞": true, - "à": true, - "à": true, - "ℵ": true, - "ℵ": true, - "α": true, - "ā": true, - "⨿": true, - "&": true, - "&": true, - "∧": true, - "⩕": true, - "⩜": true, - "⩘": true, - "⩚": true, - "∠": true, - "⦤": true, - "∠": true, - "∡": true, - "⦨": true, - "⦩": true, - "⦪": true, - "⦫": true, - "⦬": true, - "⦭": true, - "⦮": true, - "⦯": true, - "∟": true, - "⊾": true, - "⦝": true, - "∢": true, - "Å": true, - "⍼": true, - "ą": true, - "𝕒": true, - "≈": true, - "⩰": true, - "⩯": true, - "≊": true, - "≋": true, - "'": true, - "≈": true, - "≊": true, - "å": true, - "å": true, - "𝒶": true, - "*": true, - "≈": true, - "≍": true, - "ã": true, - "ã": true, - "ä": true, - "ä": true, - "∳": true, - "⨑": true, - "⫭": true, - "≌": true, - "϶": true, - "‵": true, - "∽": true, - "⋍": true, - "⊽": true, - "⌅": true, - "⌅": true, - "⎵": true, - "⎶": true, - "≌": true, - "б": true, - "„": true, - "∵": true, - "∵": true, - "⦰": true, - "϶": true, - "ℬ": true, - "β": true, - "ℶ": true, - "≬": true, - "𝔟": true, - "⋂": true, - "◯": true, - "⋃": true, - "⨀": true, - "⨁": true, - "⨂": true, - "⨆": true, - "★": true, - "▽": true, - "△": true, - "⨄": true, - "⋁": true, - "⋀": true, - "⤍": true, - "⧫": true, - "▪": true, - "▴": true, - "▾": true, - "◂": true, - "▸": true, - "␣": true, - "▒": true, - "░": true, - "▓": true, - "█": true, - "=⃥": true, - "≡⃥": true, - "⌐": true, - "𝕓": true, - "⊥": true, - "⊥": true, - "⋈": true, - "╗": true, - "╔": true, - "╖": true, - "╓": true, - "═": true, - "╦": true, - "╩": true, - "╤": true, - "╧": true, - "╝": true, - "╚": true, - "╜": true, - "╙": true, - "║": true, - "╬": true, - "╣": true, - "╠": true, - "╫": true, - "╢": true, - "╟": true, - "⧉": true, - "╕": true, - "╒": true, - "┐": true, - "┌": true, - "─": true, - "╥": true, - "╨": true, - "┬": true, - "┴": true, - "⊟": true, - "⊞": true, - "⊠": true, - "╛": true, - "╘": true, - "┘": true, - "└": true, - "│": true, - "╪": true, - "╡": true, - "╞": true, - "┼": true, - "┤": true, - "├": true, - "‵": true, - "˘": true, - "¦": true, - "¦": true, - "𝒷": true, - "⁏": true, - "∽": true, - "⋍": true, - "\": true, - "⧅": true, - "⟈": true, - "•": true, - "•": true, - "≎": true, - "⪮": true, - "≏": true, - "≏": true, - "ć": true, - "∩": true, - "⩄": true, - "⩉": true, - "⩋": true, - "⩇": true, - "⩀": true, - "∩︀": true, - "⁁": true, - "ˇ": true, - "⩍": true, - "č": true, - "ç": true, - "ç": true, - "ĉ": true, - "⩌": true, - "⩐": true, - "ċ": true, - "¸": true, - "¸": true, - "⦲": true, - "¢": true, - "¢": true, - "·": true, - "𝔠": true, - "ч": true, - "✓": true, - "✓": true, - "χ": true, - "○": true, - "⧃": true, - "ˆ": true, - "≗": true, - "↺": true, - "↻": true, - "®": true, - "Ⓢ": true, - "⊛": true, - "⊚": true, - "⊝": true, - "≗": true, - "⨐": true, - "⫯": true, - "⧂": true, - "♣": true, - "♣": true, - ":": true, - "≔": true, - "≔": true, - ",": true, - "@": true, - "∁": true, - "∘": true, - "∁": true, - "ℂ": true, - "≅": true, - "⩭": true, - "∮": true, - "𝕔": true, - "∐": true, - "©": true, - "©": true, - "℗": true, - "↵": true, - "✗": true, - "𝒸": true, - "⫏": true, - "⫑": true, - "⫐": true, - "⫒": true, - "⋯": true, - "⤸": true, - "⤵": true, - "⋞": true, - "⋟": true, - "↶": true, - "⤽": true, - "∪": true, - "⩈": true, - "⩆": true, - "⩊": true, - "⊍": true, - "⩅": true, - "∪︀": true, - "↷": true, - "⤼": true, - "⋞": true, - "⋟": true, - "⋎": true, - "⋏": true, - "¤": true, - "¤": true, - "↶": true, - "↷": true, - "⋎": true, - "⋏": true, - "∲": true, - "∱": true, - "⌭": true, - "⇓": true, - "⥥": true, - "†": true, - "ℸ": true, - "↓": true, - "‐": true, - "⊣": true, - "⤏": true, - "˝": true, - "ď": true, - "д": true, - "ⅆ": true, - "‡": true, - "⇊": true, - "⩷": true, - "°": true, - "°": true, - "δ": true, - "⦱": true, - "⥿": true, - "𝔡": true, - "⇃": true, - "⇂": true, - "⋄": true, - "⋄": true, - "♦": true, - "♦": true, - "¨": true, - "ϝ": true, - "⋲": true, - "÷": true, - "÷": true, - "÷": true, - "⋇": true, - "⋇": true, - "ђ": true, - "⌞": true, - "⌍": true, - "$": true, - "𝕕": true, - "˙": true, - "≐": true, - "≑": true, - "∸": true, - "∔": true, - "⊡": true, - "⌆": true, - "↓": true, - "⇊": true, - "⇃": true, - "⇂": true, - "⤐": true, - "⌟": true, - "⌌": true, - "𝒹": true, - "ѕ": true, - "⧶": true, - "đ": true, - "⋱": true, - "▿": true, - "▾": true, - "⇵": true, - "⥯": true, - "⦦": true, - "џ": true, - "⟿": true, - "⩷": true, - "≑": true, - "é": true, - "é": true, - "⩮": true, - "ě": true, - "≖": true, - "ê": true, - "ê": true, - "≕": true, - "э": true, - "ė": true, - "ⅇ": true, - "≒": true, - "𝔢": true, - "⪚": true, - "è": true, - "è": true, - "⪖": true, - "⪘": true, - "⪙": true, - "⏧": true, - "ℓ": true, - "⪕": true, - "⪗": true, - "ē": true, - "∅": true, - "∅": true, - "∅": true, - " ": true, - " ": true, - " ": true, - "ŋ": true, - " ": true, - "ę": true, - "𝕖": true, - "⋕": true, - "⧣": true, - "⩱": true, - "ε": true, - "ε": true, - "ϵ": true, - "≖": true, - "≕": true, - "≂": true, - "⪖": true, - "⪕": true, - "=": true, - "≟": true, - "≡": true, - "⩸": true, - "⧥": true, - "≓": true, - "⥱": true, - "ℯ": true, - "≐": true, - "≂": true, - "η": true, - "ð": true, - "ð": true, - "ë": true, - "ë": true, - "€": true, - "!": true, - "∃": true, - "ℰ": true, - "ⅇ": true, - "≒": true, - "ф": true, - "♀": true, - "ffi": true, - "ff": true, - "ffl": true, - "𝔣": true, - "fi": true, - "fj": true, - "♭": true, - "fl": true, - "▱": true, - "ƒ": true, - "𝕗": true, - "∀": true, - "⋔": true, - "⫙": true, - "⨍": true, - "½": true, - "½": true, - "⅓": true, - "¼": true, - "¼": true, - "⅕": true, - "⅙": true, - "⅛": true, - "⅔": true, - "⅖": true, - "¾": true, - "¾": true, - "⅗": true, - "⅜": true, - "⅘": true, - "⅚": true, - "⅝": true, - "⅞": true, - "⁄": true, - "⌢": true, - "𝒻": true, - "≧": true, - "⪌": true, - "ǵ": true, - "γ": true, - "ϝ": true, - "⪆": true, - "ğ": true, - "ĝ": true, - "г": true, - "ġ": true, - "≥": true, - "⋛": true, - "≥": true, - "≧": true, - "⩾": true, - "⩾": true, - "⪩": true, - "⪀": true, - "⪂": true, - "⪄": true, - "⋛︀": true, - "⪔": true, - "𝔤": true, - "≫": true, - "⋙": true, - "ℷ": true, - "ѓ": true, - "≷": true, - "⪒": true, - "⪥": true, - "⪤": true, - "≩": true, - "⪊": true, - "⪊": true, - "⪈": true, - "⪈": true, - "≩": true, - "⋧": true, - "𝕘": true, - "`": true, - "ℊ": true, - "≳": true, - "⪎": true, - "⪐": true, - ">": true, - ">": true, - "⪧": true, - "⩺": true, - "⋗": true, - "⦕": true, - "⩼": true, - "⪆": true, - "⥸": true, - "⋗": true, - "⋛": true, - "⪌": true, - "≷": true, - "≳": true, - "≩︀": true, - "≩︀": true, - "⇔": true, - " ": true, - "½": true, - "ℋ": true, - "ъ": true, - "↔": true, - "⥈": true, - "↭": true, - "ℏ": true, - "ĥ": true, - "♥": true, - "♥": true, - "…": true, - "⊹": true, - "𝔥": true, - "⤥": true, - "⤦": true, - "⇿": true, - "∻": true, - "↩": true, - "↪": true, - "𝕙": true, - "―": true, - "𝒽": true, - "ℏ": true, - "ħ": true, - "⁃": true, - "‐": true, - "í": true, - "í": true, - "⁣": true, - "î": true, - "î": true, - "и": true, - "е": true, - "¡": true, - "¡": true, - "⇔": true, - "𝔦": true, - "ì": true, - "ì": true, - "ⅈ": true, - "⨌": true, - "∭": true, - "⧜": true, - "℩": true, - "ij": true, - "ī": true, - "ℑ": true, - "ℐ": true, - "ℑ": true, - "ı": true, - "⊷": true, - "Ƶ": true, - "∈": true, - "℅": true, - "∞": true, - "⧝": true, - "ı": true, - "∫": true, - "⊺": true, - "ℤ": true, - "⊺": true, - "⨗": true, - "⨼": true, - "ё": true, - "į": true, - "𝕚": true, - "ι": true, - "⨼": true, - "¿": true, - "¿": true, - "𝒾": true, - "∈": true, - "⋹": true, - "⋵": true, - "⋴": true, - "⋳": true, - "∈": true, - "⁢": true, - "ĩ": true, - "і": true, - "ï": true, - "ï": true, - "ĵ": true, - "й": true, - "𝔧": true, - "ȷ": true, - "𝕛": true, - "𝒿": true, - "ј": true, - "є": true, - "κ": true, - "ϰ": true, - "ķ": true, - "к": true, - "𝔨": true, - "ĸ": true, - "х": true, - "ќ": true, - "𝕜": true, - "𝓀": true, - "⇚": true, - "⇐": true, - "⤛": true, - "⤎": true, - "≦": true, - "⪋": true, - "⥢": true, - "ĺ": true, - "⦴": true, - "ℒ": true, - "λ": true, - "⟨": true, - "⦑": true, - "⟨": true, - "⪅": true, - "«": true, - "«": true, - "←": true, - "⇤": true, - "⤟": true, - "⤝": true, - "↩": true, - "↫": true, - "⤹": true, - "⥳": true, - "↢": true, - "⪫": true, - "⤙": true, - "⪭": true, - "⪭︀": true, - "⤌": true, - "❲": true, - "{": true, - "[": true, - "⦋": true, - "⦏": true, - "⦍": true, - "ľ": true, - "ļ": true, - "⌈": true, - "{": true, - "л": true, - "⤶": true, - "“": true, - "„": true, - "⥧": true, - "⥋": true, - "↲": true, - "≤": true, - "←": true, - "↢": true, - "↽": true, - "↼": true, - "⇇": true, - "↔": true, - "⇆": true, - "⇋": true, - "↭": true, - "⋋": true, - "⋚": true, - "≤": true, - "≦": true, - "⩽": true, - "⩽": true, - "⪨": true, - "⩿": true, - "⪁": true, - "⪃": true, - "⋚︀": true, - "⪓": true, - "⪅": true, - "⋖": true, - "⋚": true, - "⪋": true, - "≶": true, - "≲": true, - "⥼": true, - "⌊": true, - "𝔩": true, - "≶": true, - "⪑": true, - "↽": true, - "↼": true, - "⥪": true, - "▄": true, - "љ": true, - "≪": true, - "⇇": true, - "⌞": true, - "⥫": true, - "◺": true, - "ŀ": true, - "⎰": true, - "⎰": true, - "≨": true, - "⪉": true, - "⪉": true, - "⪇": true, - "⪇": true, - "≨": true, - "⋦": true, - "⟬": true, - "⇽": true, - "⟦": true, - "⟵": true, - "⟷": true, - "⟼": true, - "⟶": true, - "↫": true, - "↬": true, - "⦅": true, - "𝕝": true, - "⨭": true, - "⨴": true, - "∗": true, - "_": true, - "◊": true, - "◊": true, - "⧫": true, - "(": true, - "⦓": true, - "⇆": true, - "⌟": true, - "⇋": true, - "⥭": true, - "‎": true, - "⊿": true, - "‹": true, - "𝓁": true, - "↰": true, - "≲": true, - "⪍": true, - "⪏": true, - "[": true, - "‘": true, - "‚": true, - "ł": true, - "<": true, - "<": true, - "⪦": true, - "⩹": true, - "⋖": true, - "⋋": true, - "⋉": true, - "⥶": true, - "⩻": true, - "⦖": true, - "◃": true, - "⊴": true, - "◂": true, - "⥊": true, - "⥦": true, - "≨︀": true, - "≨︀": true, - "∺": true, - "¯": true, - "¯": true, - "♂": true, - "✠": true, - "✠": true, - "↦": true, - "↦": true, - "↧": true, - "↤": true, - "↥": true, - "▮": true, - "⨩": true, - "м": true, - "—": true, - "∡": true, - "𝔪": true, - "℧": true, - "µ": true, - "µ": true, - "∣": true, - "*": true, - "⫰": true, - "·": true, - "·": true, - "−": true, - "⊟": true, - "∸": true, - "⨪": true, - "⫛": true, - "…": true, - "∓": true, - "⊧": true, - "𝕞": true, - "∓": true, - "𝓂": true, - "∾": true, - "μ": true, - "⊸": true, - "⊸": true, - "⋙̸": true, - "≫⃒": true, - "≫̸": true, - "⇍": true, - "⇎": true, - "⋘̸": true, - "≪⃒": true, - "≪̸": true, - "⇏": true, - "⊯": true, - "⊮": true, - "∇": true, - "ń": true, - "∠⃒": true, - "≉": true, - "⩰̸": true, - "≋̸": true, - "ʼn": true, - "≉": true, - "♮": true, - "♮": true, - "ℕ": true, - " ": true, - " ": true, - "≎̸": true, - "≏̸": true, - "⩃": true, - "ň": true, - "ņ": true, - "≇": true, - "⩭̸": true, - "⩂": true, - "н": true, - "–": true, - "≠": true, - "⇗": true, - "⤤": true, - "↗": true, - "↗": true, - "≐̸": true, - "≢": true, - "⤨": true, - "≂̸": true, - "∄": true, - "∄": true, - "𝔫": true, - "≧̸": true, - "≱": true, - "≱": true, - "≧̸": true, - "⩾̸": true, - "⩾̸": true, - "≵": true, - "≯": true, - "≯": true, - "⇎": true, - "↮": true, - "⫲": true, - "∋": true, - "⋼": true, - "⋺": true, - "∋": true, - "њ": true, - "⇍": true, - "≦̸": true, - "↚": true, - "‥": true, - "≰": true, - "↚": true, - "↮": true, - "≰": true, - "≦̸": true, - "⩽̸": true, - "⩽̸": true, - "≮": true, - "≴": true, - "≮": true, - "⋪": true, - "⋬": true, - "∤": true, - "𝕟": true, - "¬": true, - "¬": true, - "∉": true, - "⋹̸": true, - "⋵̸": true, - "∉": true, - "⋷": true, - "⋶": true, - "∌": true, - "∌": true, - "⋾": true, - "⋽": true, - "∦": true, - "∦": true, - "⫽⃥": true, - "∂̸": true, - "⨔": true, - "⊀": true, - "⋠": true, - "⪯̸": true, - "⊀": true, - "⪯̸": true, - "⇏": true, - "↛": true, - "⤳̸": true, - "↝̸": true, - "↛": true, - "⋫": true, - "⋭": true, - "⊁": true, - "⋡": true, - "⪰̸": true, - "𝓃": true, - "∤": true, - "∦": true, - "≁": true, - "≄": true, - "≄": true, - "∤": true, - "∦": true, - "⋢": true, - "⋣": true, - "⊄": true, - "⫅̸": true, - "⊈": true, - "⊂⃒": true, - "⊈": true, - "⫅̸": true, - "⊁": true, - "⪰̸": true, - "⊅": true, - "⫆̸": true, - "⊉": true, - "⊃⃒": true, - "⊉": true, - "⫆̸": true, - "≹": true, - "ñ": true, - "ñ": true, - "≸": true, - "⋪": true, - "⋬": true, - "⋫": true, - "⋭": true, - "ν": true, - "#": true, - "№": true, - " ": true, - "⊭": true, - "⤄": true, - "≍⃒": true, - "⊬": true, - "≥⃒": true, - ">⃒": true, - "⧞": true, - "⤂": true, - "≤⃒": true, - "<⃒": true, - "⊴⃒": true, - "⤃": true, - "⊵⃒": true, - "∼⃒": true, - "⇖": true, - "⤣": true, - "↖": true, - "↖": true, - "⤧": true, - "Ⓢ": true, - "ó": true, - "ó": true, - "⊛": true, - "⊚": true, - "ô": true, - "ô": true, - "о": true, - "⊝": true, - "ő": true, - "⨸": true, - "⊙": true, - "⦼": true, - "œ": true, - "⦿": true, - "𝔬": true, - "˛": true, - "ò": true, - "ò": true, - "⧁": true, - "⦵": true, - "Ω": true, - "∮": true, - "↺": true, - "⦾": true, - "⦻": true, - "‾": true, - "⧀": true, - "ō": true, - "ω": true, - "ο": true, - "⦶": true, - "⊖": true, - "𝕠": true, - "⦷": true, - "⦹": true, - "⊕": true, - "∨": true, - "↻": true, - "⩝": true, - "ℴ": true, - "ℴ": true, - "ª": true, - "ª": true, - "º": true, - "º": true, - "⊶": true, - "⩖": true, - "⩗": true, - "⩛": true, - "ℴ": true, - "ø": true, - "ø": true, - "⊘": true, - "õ": true, - "õ": true, - "⊗": true, - "⨶": true, - "ö": true, - "ö": true, - "⌽": true, - "∥": true, - "¶": true, - "¶": true, - "∥": true, - "⫳": true, - "⫽": true, - "∂": true, - "п": true, - "%": true, - ".": true, - "‰": true, - "⊥": true, - "‱": true, - "𝔭": true, - "φ": true, - "ϕ": true, - "ℳ": true, - "☎": true, - "π": true, - "⋔": true, - "ϖ": true, - "ℏ": true, - "ℎ": true, - "ℏ": true, - "+": true, - "⨣": true, - "⊞": true, - "⨢": true, - "∔": true, - "⨥": true, - "⩲": true, - "±": true, - "±": true, - "⨦": true, - "⨧": true, - "±": true, - "⨕": true, - "𝕡": true, - "£": true, - "£": true, - "≺": true, - "⪳": true, - "⪷": true, - "≼": true, - "⪯": true, - "≺": true, - "⪷": true, - "≼": true, - "⪯": true, - "⪹": true, - "⪵": true, - "⋨": true, - "≾": true, - "′": true, - "ℙ": true, - "⪵": true, - "⪹": true, - "⋨": true, - "∏": true, - "⌮": true, - "⌒": true, - "⌓": true, - "∝": true, - "∝": true, - "≾": true, - "⊰": true, - "𝓅": true, - "ψ": true, - " ": true, - "𝔮": true, - "⨌": true, - "𝕢": true, - "⁗": true, - "𝓆": true, - "ℍ": true, - "⨖": true, - "?": true, - "≟": true, - """: true, - """: true, - "⇛": true, - "⇒": true, - "⤜": true, - "⤏": true, - "⥤": true, - "∽̱": true, - "ŕ": true, - "√": true, - "⦳": true, - "⟩": true, - "⦒": true, - "⦥": true, - "⟩": true, - "»": true, - "»": true, - "→": true, - "⥵": true, - "⇥": true, - "⤠": true, - "⤳": true, - "⤞": true, - "↪": true, - "↬": true, - "⥅": true, - "⥴": true, - "↣": true, - "↝": true, - "⤚": true, - "∶": true, - "ℚ": true, - "⤍": true, - "❳": true, - "}": true, - "]": true, - "⦌": true, - "⦎": true, - "⦐": true, - "ř": true, - "ŗ": true, - "⌉": true, - "}": true, - "р": true, - "⤷": true, - "⥩": true, - "”": true, - "”": true, - "↳": true, - "ℜ": true, - "ℛ": true, - "ℜ": true, - "ℝ": true, - "▭": true, - "®": true, - "®": true, - "⥽": true, - "⌋": true, - "𝔯": true, - "⇁": true, - "⇀": true, - "⥬": true, - "ρ": true, - "ϱ": true, - "→": true, - "↣": true, - "⇁": true, - "⇀": true, - "⇄": true, - "⇌": true, - "⇉": true, - "↝": true, - "⋌": true, - "˚": true, - "≓": true, - "⇄": true, - "⇌": true, - "‏": true, - "⎱": true, - "⎱": true, - "⫮": true, - "⟭": true, - "⇾": true, - "⟧": true, - "⦆": true, - "𝕣": true, - "⨮": true, - "⨵": true, - ")": true, - "⦔": true, - "⨒": true, - "⇉": true, - "›": true, - "𝓇": true, - "↱": true, - "]": true, - "’": true, - "’": true, - "⋌": true, - "⋊": true, - "▹": true, - "⊵": true, - "▸": true, - "⧎": true, - "⥨": true, - "℞": true, - "ś": true, - "‚": true, - "≻": true, - "⪴": true, - "⪸": true, - "š": true, - "≽": true, - "⪰": true, - "ş": true, - "ŝ": true, - "⪶": true, - "⪺": true, - "⋩": true, - "⨓": true, - "≿": true, - "с": true, - "⋅": true, - "⊡": true, - "⩦": true, - "⇘": true, - "⤥": true, - "↘": true, - "↘": true, - "§": true, - "§": true, - ";": true, - "⤩": true, - "∖": true, - "∖": true, - "✶": true, - "𝔰": true, - "⌢": true, - "♯": true, - "щ": true, - "ш": true, - "∣": true, - "∥": true, - "­": true, - "­": true, - "σ": true, - "ς": true, - "ς": true, - "∼": true, - "⩪": true, - "≃": true, - "≃": true, - "⪞": true, - "⪠": true, - "⪝": true, - "⪟": true, - "≆": true, - "⨤": true, - "⥲": true, - "←": true, - "∖": true, - "⨳": true, - "⧤": true, - "∣": true, - "⌣": true, - "⪪": true, - "⪬": true, - "⪬︀": true, - "ь": true, - "/": true, - "⧄": true, - "⌿": true, - "𝕤": true, - "♠": true, - "♠": true, - "∥": true, - "⊓": true, - "⊓︀": true, - "⊔": true, - "⊔︀": true, - "⊏": true, - "⊑": true, - "⊏": true, - "⊑": true, - "⊐": true, - "⊒": true, - "⊐": true, - "⊒": true, - "□": true, - "□": true, - "▪": true, - "▪": true, - "→": true, - "𝓈": true, - "∖": true, - "⌣": true, - "⋆": true, - "☆": true, - "★": true, - "ϵ": true, - "ϕ": true, - "¯": true, - "⊂": true, - "⫅": true, - "⪽": true, - "⊆": true, - "⫃": true, - "⫁": true, - "⫋": true, - "⊊": true, - "⪿": true, - "⥹": true, - "⊂": true, - "⊆": true, - "⫅": true, - "⊊": true, - "⫋": true, - "⫇": true, - "⫕": true, - "⫓": true, - "≻": true, - "⪸": true, - "≽": true, - "⪰": true, - "⪺": true, - "⪶": true, - "⋩": true, - "≿": true, - "∑": true, - "♪": true, - "¹": true, - "¹": true, - "²": true, - "²": true, - "³": true, - "³": true, - "⊃": true, - "⫆": true, - "⪾": true, - "⫘": true, - "⊇": true, - "⫄": true, - "⟉": true, - "⫗": true, - "⥻": true, - "⫂": true, - "⫌": true, - "⊋": true, - "⫀": true, - "⊃": true, - "⊇": true, - "⫆": true, - "⊋": true, - "⫌": true, - "⫈": true, - "⫔": true, - "⫖": true, - "⇙": true, - "⤦": true, - "↙": true, - "↙": true, - "⤪": true, - "ß": true, - "ß": true, - "⌖": true, - "τ": true, - "⎴": true, - "ť": true, - "ţ": true, - "т": true, - "⃛": true, - "⌕": true, - "𝔱": true, - "∴": true, - "∴": true, - "θ": true, - "ϑ": true, - "ϑ": true, - "≈": true, - "∼": true, - " ": true, - "≈": true, - "∼": true, - "þ": true, - "þ": true, - "˜": true, - "×": true, - "×": true, - "⊠": true, - "⨱": true, - "⨰": true, - "∭": true, - "⤨": true, - "⊤": true, - "⌶": true, - "⫱": true, - "𝕥": true, - "⫚": true, - "⤩": true, - "‴": true, - "™": true, - "▵": true, - "▿": true, - "◃": true, - "⊴": true, - "≜": true, - "▹": true, - "⊵": true, - "◬": true, - "≜": true, - "⨺": true, - "⨹": true, - "⧍": true, - "⨻": true, - "⏢": true, - "𝓉": true, - "ц": true, - "ћ": true, - "ŧ": true, - "≬": true, - "↞": true, - "↠": true, - "⇑": true, - "⥣": true, - "ú": true, - "ú": true, - "↑": true, - "ў": true, - "ŭ": true, - "û": true, - "û": true, - "у": true, - "⇅": true, - "ű": true, - "⥮": true, - "⥾": true, - "𝔲": true, - "ù": true, - "ù": true, - "↿": true, - "↾": true, - "▀": true, - "⌜": true, - "⌜": true, - "⌏": true, - "◸": true, - "ū": true, - "¨": true, - "¨": true, - "ų": true, - "𝕦": true, - "↑": true, - "↕": true, - "↿": true, - "↾": true, - "⊎": true, - "υ": true, - "ϒ": true, - "υ": true, - "⇈": true, - "⌝": true, - "⌝": true, - "⌎": true, - "ů": true, - "◹": true, - "𝓊": true, - "⋰": true, - "ũ": true, - "▵": true, - "▴": true, - "⇈": true, - "ü": true, - "ü": true, - "⦧": true, - "⇕": true, - "⫨": true, - "⫩": true, - "⊨": true, - "⦜": true, - "ϵ": true, - "ϰ": true, - "∅": true, - "ϕ": true, - "ϖ": true, - "∝": true, - "↕": true, - "ϱ": true, - "ς": true, - "⊊︀": true, - "⫋︀": true, - "⊋︀": true, - "⫌︀": true, - "ϑ": true, - "⊲": true, - "⊳": true, - "в": true, - "⊢": true, - "∨": true, - "⊻": true, - "≚": true, - "⋮": true, - "|": true, - "|": true, - "𝔳": true, - "⊲": true, - "⊂⃒": true, - "⊃⃒": true, - "𝕧": true, - "∝": true, - "⊳": true, - "𝓋": true, - "⫋︀": true, - "⊊︀": true, - "⫌︀": true, - "⊋︀": true, - "⦚": true, - "ŵ": true, - "⩟": true, - "∧": true, - "≙": true, - "℘": true, - "𝔴": true, - "𝕨": true, - "℘": true, - "≀": true, - "≀": true, - "𝓌": true, - "⋂": true, - "◯": true, - "⋃": true, - "▽": true, - "𝔵": true, - "⟺": true, - "⟷": true, - "ξ": true, - "⟸": true, - "⟵": true, - "⟼": true, - "⋻": true, - "⨀": true, - "𝕩": true, - "⨁": true, - "⨂": true, - "⟹": true, - "⟶": true, - "𝓍": true, - "⨆": true, - "⨄": true, - "△": true, - "⋁": true, - "⋀": true, - "ý": true, - "ý": true, - "я": true, - "ŷ": true, - "ы": true, - "¥": true, - "¥": true, - "𝔶": true, - "ї": true, - "𝕪": true, - "𝓎": true, - "ю": true, - "ÿ": true, - "ÿ": true, - "ź": true, - "ž": true, - "з": true, - "ż": true, - "ℨ": true, - "ζ": true, - "𝔷": true, - "ж": true, - "⇝": true, - "𝕫": true, - "𝓏": true, - "‍": true, - "‌": true, -} diff --git a/vendor/github.com/russross/blackfriday/v2/esc.go b/vendor/github.com/russross/blackfriday/v2/esc.go deleted file mode 100644 index 6ab60102c..000000000 --- a/vendor/github.com/russross/blackfriday/v2/esc.go +++ /dev/null @@ -1,70 +0,0 @@ -package blackfriday - -import ( - "html" - "io" -) - -var htmlEscaper = [256][]byte{ - '&': []byte("&"), - '<': []byte("<"), - '>': []byte(">"), - '"': []byte("""), -} - -func escapeHTML(w io.Writer, s []byte) { - escapeEntities(w, s, false) -} - -func escapeAllHTML(w io.Writer, s []byte) { - escapeEntities(w, s, true) -} - -func escapeEntities(w io.Writer, s []byte, escapeValidEntities bool) { - var start, end int - for end < len(s) { - escSeq := htmlEscaper[s[end]] - if escSeq != nil { - isEntity, entityEnd := nodeIsEntity(s, end) - if isEntity && !escapeValidEntities { - w.Write(s[start : entityEnd+1]) - start = entityEnd + 1 - } else { - w.Write(s[start:end]) - w.Write(escSeq) - start = end + 1 - } - } - end++ - } - if start < len(s) && end <= len(s) { - w.Write(s[start:end]) - } -} - -func nodeIsEntity(s []byte, end int) (isEntity bool, endEntityPos int) { - isEntity = false - endEntityPos = end + 1 - - if s[end] == '&' { - for endEntityPos < len(s) { - if s[endEntityPos] == ';' { - if entities[string(s[end:endEntityPos+1])] { - isEntity = true - break - } - } - if !isalnum(s[endEntityPos]) && s[endEntityPos] != '&' && s[endEntityPos] != '#' { - break - } - endEntityPos++ - } - } - - return isEntity, endEntityPos -} - -func escLink(w io.Writer, text []byte) { - unesc := html.UnescapeString(string(text)) - escapeHTML(w, []byte(unesc)) -} diff --git a/vendor/github.com/russross/blackfriday/v2/go.mod b/vendor/github.com/russross/blackfriday/v2/go.mod deleted file mode 100644 index 620b74e0a..000000000 --- a/vendor/github.com/russross/blackfriday/v2/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/russross/blackfriday/v2 diff --git a/vendor/github.com/russross/blackfriday/v2/html.go b/vendor/github.com/russross/blackfriday/v2/html.go deleted file mode 100644 index cb4f26e30..000000000 --- a/vendor/github.com/russross/blackfriday/v2/html.go +++ /dev/null @@ -1,952 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// -// HTML rendering backend -// -// - -package blackfriday - -import ( - "bytes" - "fmt" - "io" - "regexp" - "strings" -) - -// HTMLFlags control optional behavior of HTML renderer. -type HTMLFlags int - -// HTML renderer configuration options. -const ( - HTMLFlagsNone HTMLFlags = 0 - SkipHTML HTMLFlags = 1 << iota // Skip preformatted HTML blocks - SkipImages // Skip embedded images - SkipLinks // Skip all links - Safelink // Only link to trusted protocols - NofollowLinks // Only link with rel="nofollow" - NoreferrerLinks // Only link with rel="noreferrer" - NoopenerLinks // Only link with rel="noopener" - HrefTargetBlank // Add a blank target - CompletePage // Generate a complete HTML page - UseXHTML // Generate XHTML output instead of HTML - FootnoteReturnLinks // Generate a link at the end of a footnote to return to the source - Smartypants // Enable smart punctuation substitutions - SmartypantsFractions // Enable smart fractions (with Smartypants) - SmartypantsDashes // Enable smart dashes (with Smartypants) - SmartypantsLatexDashes // Enable LaTeX-style dashes (with Smartypants) - SmartypantsAngledQuotes // Enable angled double quotes (with Smartypants) for double quotes rendering - SmartypantsQuotesNBSP // Enable « French guillemets » (with Smartypants) - TOC // Generate a table of contents -) - -var ( - htmlTagRe = regexp.MustCompile("(?i)^" + htmlTag) -) - -const ( - htmlTag = "(?:" + openTag + "|" + closeTag + "|" + htmlComment + "|" + - processingInstruction + "|" + declaration + "|" + cdata + ")" - closeTag = "]" - openTag = "<" + tagName + attribute + "*" + "\\s*/?>" - attribute = "(?:" + "\\s+" + attributeName + attributeValueSpec + "?)" - attributeValue = "(?:" + unquotedValue + "|" + singleQuotedValue + "|" + doubleQuotedValue + ")" - attributeValueSpec = "(?:" + "\\s*=" + "\\s*" + attributeValue + ")" - attributeName = "[a-zA-Z_:][a-zA-Z0-9:._-]*" - cdata = "" - declaration = "]*>" - doubleQuotedValue = "\"[^\"]*\"" - htmlComment = "|" - processingInstruction = "[<][?].*?[?][>]" - singleQuotedValue = "'[^']*'" - tagName = "[A-Za-z][A-Za-z0-9-]*" - unquotedValue = "[^\"'=<>`\\x00-\\x20]+" -) - -// HTMLRendererParameters is a collection of supplementary parameters tweaking -// the behavior of various parts of HTML renderer. -type HTMLRendererParameters struct { - // Prepend this text to each relative URL. - AbsolutePrefix string - // Add this text to each footnote anchor, to ensure uniqueness. - FootnoteAnchorPrefix string - // Show this text inside the tag for a footnote return link, if the - // HTML_FOOTNOTE_RETURN_LINKS flag is enabled. If blank, the string - // [return] is used. - FootnoteReturnLinkContents string - // If set, add this text to the front of each Heading ID, to ensure - // uniqueness. - HeadingIDPrefix string - // If set, add this text to the back of each Heading ID, to ensure uniqueness. - HeadingIDSuffix string - // Increase heading levels: if the offset is 1,

    becomes

    etc. - // Negative offset is also valid. - // Resulting levels are clipped between 1 and 6. - HeadingLevelOffset int - - Title string // Document title (used if CompletePage is set) - CSS string // Optional CSS file URL (used if CompletePage is set) - Icon string // Optional icon file URL (used if CompletePage is set) - - Flags HTMLFlags // Flags allow customizing this renderer's behavior -} - -// HTMLRenderer is a type that implements the Renderer interface for HTML output. -// -// Do not create this directly, instead use the NewHTMLRenderer function. -type HTMLRenderer struct { - HTMLRendererParameters - - closeTag string // how to end singleton tags: either " />" or ">" - - // Track heading IDs to prevent ID collision in a single generation. - headingIDs map[string]int - - lastOutputLen int - disableTags int - - sr *SPRenderer -} - -const ( - xhtmlClose = " />" - htmlClose = ">" -) - -// NewHTMLRenderer creates and configures an HTMLRenderer object, which -// satisfies the Renderer interface. -func NewHTMLRenderer(params HTMLRendererParameters) *HTMLRenderer { - // configure the rendering engine - closeTag := htmlClose - if params.Flags&UseXHTML != 0 { - closeTag = xhtmlClose - } - - if params.FootnoteReturnLinkContents == "" { - // U+FE0E is VARIATION SELECTOR-15. - // It suppresses automatic emoji presentation of the preceding - // U+21A9 LEFTWARDS ARROW WITH HOOK on iOS and iPadOS. - params.FootnoteReturnLinkContents = "↩\ufe0e" - } - - return &HTMLRenderer{ - HTMLRendererParameters: params, - - closeTag: closeTag, - headingIDs: make(map[string]int), - - sr: NewSmartypantsRenderer(params.Flags), - } -} - -func isHTMLTag(tag []byte, tagname string) bool { - found, _ := findHTMLTagPos(tag, tagname) - return found -} - -// Look for a character, but ignore it when it's in any kind of quotes, it -// might be JavaScript -func skipUntilCharIgnoreQuotes(html []byte, start int, char byte) int { - inSingleQuote := false - inDoubleQuote := false - inGraveQuote := false - i := start - for i < len(html) { - switch { - case html[i] == char && !inSingleQuote && !inDoubleQuote && !inGraveQuote: - return i - case html[i] == '\'': - inSingleQuote = !inSingleQuote - case html[i] == '"': - inDoubleQuote = !inDoubleQuote - case html[i] == '`': - inGraveQuote = !inGraveQuote - } - i++ - } - return start -} - -func findHTMLTagPos(tag []byte, tagname string) (bool, int) { - i := 0 - if i < len(tag) && tag[0] != '<' { - return false, -1 - } - i++ - i = skipSpace(tag, i) - - if i < len(tag) && tag[i] == '/' { - i++ - } - - i = skipSpace(tag, i) - j := 0 - for ; i < len(tag); i, j = i+1, j+1 { - if j >= len(tagname) { - break - } - - if strings.ToLower(string(tag[i]))[0] != tagname[j] { - return false, -1 - } - } - - if i == len(tag) { - return false, -1 - } - - rightAngle := skipUntilCharIgnoreQuotes(tag, i, '>') - if rightAngle >= i { - return true, rightAngle - } - - return false, -1 -} - -func skipSpace(tag []byte, i int) int { - for i < len(tag) && isspace(tag[i]) { - i++ - } - return i -} - -func isRelativeLink(link []byte) (yes bool) { - // a tag begin with '#' - if link[0] == '#' { - return true - } - - // link begin with '/' but not '//', the second maybe a protocol relative link - if len(link) >= 2 && link[0] == '/' && link[1] != '/' { - return true - } - - // only the root '/' - if len(link) == 1 && link[0] == '/' { - return true - } - - // current directory : begin with "./" - if bytes.HasPrefix(link, []byte("./")) { - return true - } - - // parent directory : begin with "../" - if bytes.HasPrefix(link, []byte("../")) { - return true - } - - return false -} - -func (r *HTMLRenderer) ensureUniqueHeadingID(id string) string { - for count, found := r.headingIDs[id]; found; count, found = r.headingIDs[id] { - tmp := fmt.Sprintf("%s-%d", id, count+1) - - if _, tmpFound := r.headingIDs[tmp]; !tmpFound { - r.headingIDs[id] = count + 1 - id = tmp - } else { - id = id + "-1" - } - } - - if _, found := r.headingIDs[id]; !found { - r.headingIDs[id] = 0 - } - - return id -} - -func (r *HTMLRenderer) addAbsPrefix(link []byte) []byte { - if r.AbsolutePrefix != "" && isRelativeLink(link) && link[0] != '.' { - newDest := r.AbsolutePrefix - if link[0] != '/' { - newDest += "/" - } - newDest += string(link) - return []byte(newDest) - } - return link -} - -func appendLinkAttrs(attrs []string, flags HTMLFlags, link []byte) []string { - if isRelativeLink(link) { - return attrs - } - val := []string{} - if flags&NofollowLinks != 0 { - val = append(val, "nofollow") - } - if flags&NoreferrerLinks != 0 { - val = append(val, "noreferrer") - } - if flags&NoopenerLinks != 0 { - val = append(val, "noopener") - } - if flags&HrefTargetBlank != 0 { - attrs = append(attrs, "target=\"_blank\"") - } - if len(val) == 0 { - return attrs - } - attr := fmt.Sprintf("rel=%q", strings.Join(val, " ")) - return append(attrs, attr) -} - -func isMailto(link []byte) bool { - return bytes.HasPrefix(link, []byte("mailto:")) -} - -func needSkipLink(flags HTMLFlags, dest []byte) bool { - if flags&SkipLinks != 0 { - return true - } - return flags&Safelink != 0 && !isSafeLink(dest) && !isMailto(dest) -} - -func isSmartypantable(node *Node) bool { - pt := node.Parent.Type - return pt != Link && pt != CodeBlock && pt != Code -} - -func appendLanguageAttr(attrs []string, info []byte) []string { - if len(info) == 0 { - return attrs - } - endOfLang := bytes.IndexAny(info, "\t ") - if endOfLang < 0 { - endOfLang = len(info) - } - return append(attrs, fmt.Sprintf("class=\"language-%s\"", info[:endOfLang])) -} - -func (r *HTMLRenderer) tag(w io.Writer, name []byte, attrs []string) { - w.Write(name) - if len(attrs) > 0 { - w.Write(spaceBytes) - w.Write([]byte(strings.Join(attrs, " "))) - } - w.Write(gtBytes) - r.lastOutputLen = 1 -} - -func footnoteRef(prefix string, node *Node) []byte { - urlFrag := prefix + string(slugify(node.Destination)) - anchor := fmt.Sprintf(`%d`, urlFrag, node.NoteID) - return []byte(fmt.Sprintf(`%s`, urlFrag, anchor)) -} - -func footnoteItem(prefix string, slug []byte) []byte { - return []byte(fmt.Sprintf(`
  • `, prefix, slug)) -} - -func footnoteReturnLink(prefix, returnLink string, slug []byte) []byte { - const format = ` %s` - return []byte(fmt.Sprintf(format, prefix, slug, returnLink)) -} - -func itemOpenCR(node *Node) bool { - if node.Prev == nil { - return false - } - ld := node.Parent.ListData - return !ld.Tight && ld.ListFlags&ListTypeDefinition == 0 -} - -func skipParagraphTags(node *Node) bool { - grandparent := node.Parent.Parent - if grandparent == nil || grandparent.Type != List { - return false - } - tightOrTerm := grandparent.Tight || node.Parent.ListFlags&ListTypeTerm != 0 - return grandparent.Type == List && tightOrTerm -} - -func cellAlignment(align CellAlignFlags) string { - switch align { - case TableAlignmentLeft: - return "left" - case TableAlignmentRight: - return "right" - case TableAlignmentCenter: - return "center" - default: - return "" - } -} - -func (r *HTMLRenderer) out(w io.Writer, text []byte) { - if r.disableTags > 0 { - w.Write(htmlTagRe.ReplaceAll(text, []byte{})) - } else { - w.Write(text) - } - r.lastOutputLen = len(text) -} - -func (r *HTMLRenderer) cr(w io.Writer) { - if r.lastOutputLen > 0 { - r.out(w, nlBytes) - } -} - -var ( - nlBytes = []byte{'\n'} - gtBytes = []byte{'>'} - spaceBytes = []byte{' '} -) - -var ( - brTag = []byte("
    ") - brXHTMLTag = []byte("
    ") - emTag = []byte("") - emCloseTag = []byte("") - strongTag = []byte("") - strongCloseTag = []byte("") - delTag = []byte("") - delCloseTag = []byte("") - ttTag = []byte("") - ttCloseTag = []byte("") - aTag = []byte("") - preTag = []byte("
    ")
    -	preCloseTag        = []byte("
    ") - codeTag = []byte("") - codeCloseTag = []byte("") - pTag = []byte("

    ") - pCloseTag = []byte("

    ") - blockquoteTag = []byte("
    ") - blockquoteCloseTag = []byte("
    ") - hrTag = []byte("
    ") - hrXHTMLTag = []byte("
    ") - ulTag = []byte("
      ") - ulCloseTag = []byte("
    ") - olTag = []byte("
      ") - olCloseTag = []byte("
    ") - dlTag = []byte("
    ") - dlCloseTag = []byte("
    ") - liTag = []byte("
  • ") - liCloseTag = []byte("
  • ") - ddTag = []byte("
    ") - ddCloseTag = []byte("
    ") - dtTag = []byte("
    ") - dtCloseTag = []byte("
    ") - tableTag = []byte("") - tableCloseTag = []byte("
    ") - tdTag = []byte("") - thTag = []byte("") - theadTag = []byte("") - theadCloseTag = []byte("") - tbodyTag = []byte("") - tbodyCloseTag = []byte("") - trTag = []byte("") - trCloseTag = []byte("") - h1Tag = []byte("") - h2Tag = []byte("") - h3Tag = []byte("") - h4Tag = []byte("") - h5Tag = []byte("") - h6Tag = []byte("") - - footnotesDivBytes = []byte("\n
    \n\n") - footnotesCloseDivBytes = []byte("\n
    \n") -) - -func headingTagsFromLevel(level int) ([]byte, []byte) { - if level <= 1 { - return h1Tag, h1CloseTag - } - switch level { - case 2: - return h2Tag, h2CloseTag - case 3: - return h3Tag, h3CloseTag - case 4: - return h4Tag, h4CloseTag - case 5: - return h5Tag, h5CloseTag - } - return h6Tag, h6CloseTag -} - -func (r *HTMLRenderer) outHRTag(w io.Writer) { - if r.Flags&UseXHTML == 0 { - r.out(w, hrTag) - } else { - r.out(w, hrXHTMLTag) - } -} - -// RenderNode is a default renderer of a single node of a syntax tree. For -// block nodes it will be called twice: first time with entering=true, second -// time with entering=false, so that it could know when it's working on an open -// tag and when on close. It writes the result to w. -// -// The return value is a way to tell the calling walker to adjust its walk -// pattern: e.g. it can terminate the traversal by returning Terminate. Or it -// can ask the walker to skip a subtree of this node by returning SkipChildren. -// The typical behavior is to return GoToNext, which asks for the usual -// traversal to the next node. -func (r *HTMLRenderer) RenderNode(w io.Writer, node *Node, entering bool) WalkStatus { - attrs := []string{} - switch node.Type { - case Text: - if r.Flags&Smartypants != 0 { - var tmp bytes.Buffer - escapeHTML(&tmp, node.Literal) - r.sr.Process(w, tmp.Bytes()) - } else { - if node.Parent.Type == Link { - escLink(w, node.Literal) - } else { - escapeHTML(w, node.Literal) - } - } - case Softbreak: - r.cr(w) - // TODO: make it configurable via out(renderer.softbreak) - case Hardbreak: - if r.Flags&UseXHTML == 0 { - r.out(w, brTag) - } else { - r.out(w, brXHTMLTag) - } - r.cr(w) - case Emph: - if entering { - r.out(w, emTag) - } else { - r.out(w, emCloseTag) - } - case Strong: - if entering { - r.out(w, strongTag) - } else { - r.out(w, strongCloseTag) - } - case Del: - if entering { - r.out(w, delTag) - } else { - r.out(w, delCloseTag) - } - case HTMLSpan: - if r.Flags&SkipHTML != 0 { - break - } - r.out(w, node.Literal) - case Link: - // mark it but don't link it if it is not a safe link: no smartypants - dest := node.LinkData.Destination - if needSkipLink(r.Flags, dest) { - if entering { - r.out(w, ttTag) - } else { - r.out(w, ttCloseTag) - } - } else { - if entering { - dest = r.addAbsPrefix(dest) - var hrefBuf bytes.Buffer - hrefBuf.WriteString("href=\"") - escLink(&hrefBuf, dest) - hrefBuf.WriteByte('"') - attrs = append(attrs, hrefBuf.String()) - if node.NoteID != 0 { - r.out(w, footnoteRef(r.FootnoteAnchorPrefix, node)) - break - } - attrs = appendLinkAttrs(attrs, r.Flags, dest) - if len(node.LinkData.Title) > 0 { - var titleBuff bytes.Buffer - titleBuff.WriteString("title=\"") - escapeHTML(&titleBuff, node.LinkData.Title) - titleBuff.WriteByte('"') - attrs = append(attrs, titleBuff.String()) - } - r.tag(w, aTag, attrs) - } else { - if node.NoteID != 0 { - break - } - r.out(w, aCloseTag) - } - } - case Image: - if r.Flags&SkipImages != 0 { - return SkipChildren - } - if entering { - dest := node.LinkData.Destination - dest = r.addAbsPrefix(dest) - if r.disableTags == 0 { - //if options.safe && potentiallyUnsafe(dest) { - //out(w, ``)
-				//} else {
-				r.out(w, []byte(`<img src=`)) - } - } - case Code: - r.out(w, codeTag) - escapeAllHTML(w, node.Literal) - r.out(w, codeCloseTag) - case Document: - break - case Paragraph: - if skipParagraphTags(node) { - break - } - if entering { - // TODO: untangle this clusterfuck about when the newlines need - // to be added and when not. - if node.Prev != nil { - switch node.Prev.Type { - case HTMLBlock, List, Paragraph, Heading, CodeBlock, BlockQuote, HorizontalRule: - r.cr(w) - } - } - if node.Parent.Type == BlockQuote && node.Prev == nil { - r.cr(w) - } - r.out(w, pTag) - } else { - r.out(w, pCloseTag) - if !(node.Parent.Type == Item && node.Next == nil) { - r.cr(w) - } - } - case BlockQuote: - if entering { - r.cr(w) - r.out(w, blockquoteTag) - } else { - r.out(w, blockquoteCloseTag) - r.cr(w) - } - case HTMLBlock: - if r.Flags&SkipHTML != 0 { - break - } - r.cr(w) - r.out(w, node.Literal) - r.cr(w) - case Heading: - headingLevel := r.HTMLRendererParameters.HeadingLevelOffset + node.Level - openTag, closeTag := headingTagsFromLevel(headingLevel) - if entering { - if node.IsTitleblock { - attrs = append(attrs, `class="title"`) - } - if node.HeadingID != "" { - id := r.ensureUniqueHeadingID(node.HeadingID) - if r.HeadingIDPrefix != "" { - id = r.HeadingIDPrefix + id - } - if r.HeadingIDSuffix != "" { - id = id + r.HeadingIDSuffix - } - attrs = append(attrs, fmt.Sprintf(`id="%s"`, id)) - } - r.cr(w) - r.tag(w, openTag, attrs) - } else { - r.out(w, closeTag) - if !(node.Parent.Type == Item && node.Next == nil) { - r.cr(w) - } - } - case HorizontalRule: - r.cr(w) - r.outHRTag(w) - r.cr(w) - case List: - openTag := ulTag - closeTag := ulCloseTag - if node.ListFlags&ListTypeOrdered != 0 { - openTag = olTag - closeTag = olCloseTag - } - if node.ListFlags&ListTypeDefinition != 0 { - openTag = dlTag - closeTag = dlCloseTag - } - if entering { - if node.IsFootnotesList { - r.out(w, footnotesDivBytes) - r.outHRTag(w) - r.cr(w) - } - r.cr(w) - if node.Parent.Type == Item && node.Parent.Parent.Tight { - r.cr(w) - } - r.tag(w, openTag[:len(openTag)-1], attrs) - r.cr(w) - } else { - r.out(w, closeTag) - //cr(w) - //if node.parent.Type != Item { - // cr(w) - //} - if node.Parent.Type == Item && node.Next != nil { - r.cr(w) - } - if node.Parent.Type == Document || node.Parent.Type == BlockQuote { - r.cr(w) - } - if node.IsFootnotesList { - r.out(w, footnotesCloseDivBytes) - } - } - case Item: - openTag := liTag - closeTag := liCloseTag - if node.ListFlags&ListTypeDefinition != 0 { - openTag = ddTag - closeTag = ddCloseTag - } - if node.ListFlags&ListTypeTerm != 0 { - openTag = dtTag - closeTag = dtCloseTag - } - if entering { - if itemOpenCR(node) { - r.cr(w) - } - if node.ListData.RefLink != nil { - slug := slugify(node.ListData.RefLink) - r.out(w, footnoteItem(r.FootnoteAnchorPrefix, slug)) - break - } - r.out(w, openTag) - } else { - if node.ListData.RefLink != nil { - slug := slugify(node.ListData.RefLink) - if r.Flags&FootnoteReturnLinks != 0 { - r.out(w, footnoteReturnLink(r.FootnoteAnchorPrefix, r.FootnoteReturnLinkContents, slug)) - } - } - r.out(w, closeTag) - r.cr(w) - } - case CodeBlock: - attrs = appendLanguageAttr(attrs, node.Info) - r.cr(w) - r.out(w, preTag) - r.tag(w, codeTag[:len(codeTag)-1], attrs) - escapeAllHTML(w, node.Literal) - r.out(w, codeCloseTag) - r.out(w, preCloseTag) - if node.Parent.Type != Item { - r.cr(w) - } - case Table: - if entering { - r.cr(w) - r.out(w, tableTag) - } else { - r.out(w, tableCloseTag) - r.cr(w) - } - case TableCell: - openTag := tdTag - closeTag := tdCloseTag - if node.IsHeader { - openTag = thTag - closeTag = thCloseTag - } - if entering { - align := cellAlignment(node.Align) - if align != "" { - attrs = append(attrs, fmt.Sprintf(`align="%s"`, align)) - } - if node.Prev == nil { - r.cr(w) - } - r.tag(w, openTag, attrs) - } else { - r.out(w, closeTag) - r.cr(w) - } - case TableHead: - if entering { - r.cr(w) - r.out(w, theadTag) - } else { - r.out(w, theadCloseTag) - r.cr(w) - } - case TableBody: - if entering { - r.cr(w) - r.out(w, tbodyTag) - // XXX: this is to adhere to a rather silly test. Should fix test. - if node.FirstChild == nil { - r.cr(w) - } - } else { - r.out(w, tbodyCloseTag) - r.cr(w) - } - case TableRow: - if entering { - r.cr(w) - r.out(w, trTag) - } else { - r.out(w, trCloseTag) - r.cr(w) - } - default: - panic("Unknown node type " + node.Type.String()) - } - return GoToNext -} - -// RenderHeader writes HTML document preamble and TOC if requested. -func (r *HTMLRenderer) RenderHeader(w io.Writer, ast *Node) { - r.writeDocumentHeader(w) - if r.Flags&TOC != 0 { - r.writeTOC(w, ast) - } -} - -// RenderFooter writes HTML document footer. -func (r *HTMLRenderer) RenderFooter(w io.Writer, ast *Node) { - if r.Flags&CompletePage == 0 { - return - } - io.WriteString(w, "\n\n\n") -} - -func (r *HTMLRenderer) writeDocumentHeader(w io.Writer) { - if r.Flags&CompletePage == 0 { - return - } - ending := "" - if r.Flags&UseXHTML != 0 { - io.WriteString(w, "\n") - io.WriteString(w, "\n") - ending = " /" - } else { - io.WriteString(w, "\n") - io.WriteString(w, "\n") - } - io.WriteString(w, "\n") - io.WriteString(w, " ") - if r.Flags&Smartypants != 0 { - r.sr.Process(w, []byte(r.Title)) - } else { - escapeHTML(w, []byte(r.Title)) - } - io.WriteString(w, "\n") - io.WriteString(w, " \n") - io.WriteString(w, " \n") - if r.CSS != "" { - io.WriteString(w, " \n") - } - if r.Icon != "" { - io.WriteString(w, " \n") - } - io.WriteString(w, "\n") - io.WriteString(w, "\n\n") -} - -func (r *HTMLRenderer) writeTOC(w io.Writer, ast *Node) { - buf := bytes.Buffer{} - - inHeading := false - tocLevel := 0 - headingCount := 0 - - ast.Walk(func(node *Node, entering bool) WalkStatus { - if node.Type == Heading && !node.HeadingData.IsTitleblock { - inHeading = entering - if entering { - node.HeadingID = fmt.Sprintf("toc_%d", headingCount) - if node.Level == tocLevel { - buf.WriteString("\n\n
  • ") - } else if node.Level < tocLevel { - for node.Level < tocLevel { - tocLevel-- - buf.WriteString("
  • \n") - } - buf.WriteString("\n\n
  • ") - } else { - for node.Level > tocLevel { - tocLevel++ - buf.WriteString("\n") - } - - if buf.Len() > 0 { - io.WriteString(w, "\n") - } - r.lastOutputLen = buf.Len() -} diff --git a/vendor/github.com/russross/blackfriday/v2/inline.go b/vendor/github.com/russross/blackfriday/v2/inline.go deleted file mode 100644 index d45bd9417..000000000 --- a/vendor/github.com/russross/blackfriday/v2/inline.go +++ /dev/null @@ -1,1228 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Functions to parse inline elements. -// - -package blackfriday - -import ( - "bytes" - "regexp" - "strconv" -) - -var ( - urlRe = `((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+` - anchorRe = regexp.MustCompile(`^(]+")?\s?>` + urlRe + `<\/a>)`) - - // https://www.w3.org/TR/html5/syntax.html#character-references - // highest unicode code point in 17 planes (2^20): 1,114,112d = - // 7 dec digits or 6 hex digits - // named entity references can be 2-31 characters with stuff like < - // at one end and ∳ at the other. There - // are also sometimes numbers at the end, although this isn't inherent - // in the specification; there are never numbers anywhere else in - // current character references, though; see ¾ and ▒, etc. - // https://www.w3.org/TR/html5/syntax.html#named-character-references - // - // entity := "&" (named group | number ref) ";" - // named group := [a-zA-Z]{2,31}[0-9]{0,2} - // number ref := "#" (dec ref | hex ref) - // dec ref := [0-9]{1,7} - // hex ref := ("x" | "X") [0-9a-fA-F]{1,6} - htmlEntityRe = regexp.MustCompile(`&([a-zA-Z]{2,31}[0-9]{0,2}|#([0-9]{1,7}|[xX][0-9a-fA-F]{1,6}));`) -) - -// Functions to parse text within a block -// Each function returns the number of chars taken care of -// data is the complete block being rendered -// offset is the number of valid chars before the current cursor - -func (p *Markdown) inline(currBlock *Node, data []byte) { - // handlers might call us recursively: enforce a maximum depth - if p.nesting >= p.maxNesting || len(data) == 0 { - return - } - p.nesting++ - beg, end := 0, 0 - for end < len(data) { - handler := p.inlineCallback[data[end]] - if handler != nil { - if consumed, node := handler(p, data, end); consumed == 0 { - // No action from the callback. - end++ - } else { - // Copy inactive chars into the output. - currBlock.AppendChild(text(data[beg:end])) - if node != nil { - currBlock.AppendChild(node) - } - // Skip past whatever the callback used. - beg = end + consumed - end = beg - } - } else { - end++ - } - } - if beg < len(data) { - if data[end-1] == '\n' { - end-- - } - currBlock.AppendChild(text(data[beg:end])) - } - p.nesting-- -} - -// single and double emphasis parsing -func emphasis(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - c := data[0] - - if len(data) > 2 && data[1] != c { - // whitespace cannot follow an opening emphasis; - // strikethrough only takes two characters '~~' - if c == '~' || isspace(data[1]) { - return 0, nil - } - ret, node := helperEmphasis(p, data[1:], c) - if ret == 0 { - return 0, nil - } - - return ret + 1, node - } - - if len(data) > 3 && data[1] == c && data[2] != c { - if isspace(data[2]) { - return 0, nil - } - ret, node := helperDoubleEmphasis(p, data[2:], c) - if ret == 0 { - return 0, nil - } - - return ret + 2, node - } - - if len(data) > 4 && data[1] == c && data[2] == c && data[3] != c { - if c == '~' || isspace(data[3]) { - return 0, nil - } - ret, node := helperTripleEmphasis(p, data, 3, c) - if ret == 0 { - return 0, nil - } - - return ret + 3, node - } - - return 0, nil -} - -func codeSpan(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - - nb := 0 - - // count the number of backticks in the delimiter - for nb < len(data) && data[nb] == '`' { - nb++ - } - - // find the next delimiter - i, end := 0, 0 - for end = nb; end < len(data) && i < nb; end++ { - if data[end] == '`' { - i++ - } else { - i = 0 - } - } - - // no matching delimiter? - if i < nb && end >= len(data) { - return 0, nil - } - - // trim outside whitespace - fBegin := nb - for fBegin < end && data[fBegin] == ' ' { - fBegin++ - } - - fEnd := end - nb - for fEnd > fBegin && data[fEnd-1] == ' ' { - fEnd-- - } - - // render the code span - if fBegin != fEnd { - code := NewNode(Code) - code.Literal = data[fBegin:fEnd] - return end, code - } - - return end, nil -} - -// newline preceded by two spaces becomes
    -func maybeLineBreak(p *Markdown, data []byte, offset int) (int, *Node) { - origOffset := offset - for offset < len(data) && data[offset] == ' ' { - offset++ - } - - if offset < len(data) && data[offset] == '\n' { - if offset-origOffset >= 2 { - return offset - origOffset + 1, NewNode(Hardbreak) - } - return offset - origOffset, nil - } - return 0, nil -} - -// newline without two spaces works when HardLineBreak is enabled -func lineBreak(p *Markdown, data []byte, offset int) (int, *Node) { - if p.extensions&HardLineBreak != 0 { - return 1, NewNode(Hardbreak) - } - return 0, nil -} - -type linkType int - -const ( - linkNormal linkType = iota - linkImg - linkDeferredFootnote - linkInlineFootnote -) - -func isReferenceStyleLink(data []byte, pos int, t linkType) bool { - if t == linkDeferredFootnote { - return false - } - return pos < len(data)-1 && data[pos] == '[' && data[pos+1] != '^' -} - -func maybeImage(p *Markdown, data []byte, offset int) (int, *Node) { - if offset < len(data)-1 && data[offset+1] == '[' { - return link(p, data, offset) - } - return 0, nil -} - -func maybeInlineFootnote(p *Markdown, data []byte, offset int) (int, *Node) { - if offset < len(data)-1 && data[offset+1] == '[' { - return link(p, data, offset) - } - return 0, nil -} - -// '[': parse a link or an image or a footnote -func link(p *Markdown, data []byte, offset int) (int, *Node) { - // no links allowed inside regular links, footnote, and deferred footnotes - if p.insideLink && (offset > 0 && data[offset-1] == '[' || len(data)-1 > offset && data[offset+1] == '^') { - return 0, nil - } - - var t linkType - switch { - // special case: ![^text] == deferred footnote (that follows something with - // an exclamation point) - case p.extensions&Footnotes != 0 && len(data)-1 > offset && data[offset+1] == '^': - t = linkDeferredFootnote - // ![alt] == image - case offset >= 0 && data[offset] == '!': - t = linkImg - offset++ - // ^[text] == inline footnote - // [^refId] == deferred footnote - case p.extensions&Footnotes != 0: - if offset >= 0 && data[offset] == '^' { - t = linkInlineFootnote - offset++ - } else if len(data)-1 > offset && data[offset+1] == '^' { - t = linkDeferredFootnote - } - // [text] == regular link - default: - t = linkNormal - } - - data = data[offset:] - - var ( - i = 1 - noteID int - title, link, altContent []byte - textHasNl = false - ) - - if t == linkDeferredFootnote { - i++ - } - - // look for the matching closing bracket - for level := 1; level > 0 && i < len(data); i++ { - switch { - case data[i] == '\n': - textHasNl = true - - case isBackslashEscaped(data, i): - continue - - case data[i] == '[': - level++ - - case data[i] == ']': - level-- - if level <= 0 { - i-- // compensate for extra i++ in for loop - } - } - } - - if i >= len(data) { - return 0, nil - } - - txtE := i - i++ - var footnoteNode *Node - - // skip any amount of whitespace or newline - // (this is much more lax than original markdown syntax) - for i < len(data) && isspace(data[i]) { - i++ - } - - // inline style link - switch { - case i < len(data) && data[i] == '(': - // skip initial whitespace - i++ - - for i < len(data) && isspace(data[i]) { - i++ - } - - linkB := i - - // look for link end: ' " ) - findlinkend: - for i < len(data) { - switch { - case data[i] == '\\': - i += 2 - - case data[i] == ')' || data[i] == '\'' || data[i] == '"': - break findlinkend - - default: - i++ - } - } - - if i >= len(data) { - return 0, nil - } - linkE := i - - // look for title end if present - titleB, titleE := 0, 0 - if data[i] == '\'' || data[i] == '"' { - i++ - titleB = i - - findtitleend: - for i < len(data) { - switch { - case data[i] == '\\': - i += 2 - - case data[i] == ')': - break findtitleend - - default: - i++ - } - } - - if i >= len(data) { - return 0, nil - } - - // skip whitespace after title - titleE = i - 1 - for titleE > titleB && isspace(data[titleE]) { - titleE-- - } - - // check for closing quote presence - if data[titleE] != '\'' && data[titleE] != '"' { - titleB, titleE = 0, 0 - linkE = i - } - } - - // remove whitespace at the end of the link - for linkE > linkB && isspace(data[linkE-1]) { - linkE-- - } - - // remove optional angle brackets around the link - if data[linkB] == '<' { - linkB++ - } - if data[linkE-1] == '>' { - linkE-- - } - - // build escaped link and title - if linkE > linkB { - link = data[linkB:linkE] - } - - if titleE > titleB { - title = data[titleB:titleE] - } - - i++ - - // reference style link - case isReferenceStyleLink(data, i, t): - var id []byte - altContentConsidered := false - - // look for the id - i++ - linkB := i - for i < len(data) && data[i] != ']' { - i++ - } - if i >= len(data) { - return 0, nil - } - linkE := i - - // find the reference - if linkB == linkE { - if textHasNl { - var b bytes.Buffer - - for j := 1; j < txtE; j++ { - switch { - case data[j] != '\n': - b.WriteByte(data[j]) - case data[j-1] != ' ': - b.WriteByte(' ') - } - } - - id = b.Bytes() - } else { - id = data[1:txtE] - altContentConsidered = true - } - } else { - id = data[linkB:linkE] - } - - // find the reference with matching id - lr, ok := p.getRef(string(id)) - if !ok { - return 0, nil - } - - // keep link and title from reference - link = lr.link - title = lr.title - if altContentConsidered { - altContent = lr.text - } - i++ - - // shortcut reference style link or reference or inline footnote - default: - var id []byte - - // craft the id - if textHasNl { - var b bytes.Buffer - - for j := 1; j < txtE; j++ { - switch { - case data[j] != '\n': - b.WriteByte(data[j]) - case data[j-1] != ' ': - b.WriteByte(' ') - } - } - - id = b.Bytes() - } else { - if t == linkDeferredFootnote { - id = data[2:txtE] // get rid of the ^ - } else { - id = data[1:txtE] - } - } - - footnoteNode = NewNode(Item) - if t == linkInlineFootnote { - // create a new reference - noteID = len(p.notes) + 1 - - var fragment []byte - if len(id) > 0 { - if len(id) < 16 { - fragment = make([]byte, len(id)) - } else { - fragment = make([]byte, 16) - } - copy(fragment, slugify(id)) - } else { - fragment = append([]byte("footnote-"), []byte(strconv.Itoa(noteID))...) - } - - ref := &reference{ - noteID: noteID, - hasBlock: false, - link: fragment, - title: id, - footnote: footnoteNode, - } - - p.notes = append(p.notes, ref) - - link = ref.link - title = ref.title - } else { - // find the reference with matching id - lr, ok := p.getRef(string(id)) - if !ok { - return 0, nil - } - - if t == linkDeferredFootnote { - lr.noteID = len(p.notes) + 1 - lr.footnote = footnoteNode - p.notes = append(p.notes, lr) - } - - // keep link and title from reference - link = lr.link - // if inline footnote, title == footnote contents - title = lr.title - noteID = lr.noteID - } - - // rewind the whitespace - i = txtE + 1 - } - - var uLink []byte - if t == linkNormal || t == linkImg { - if len(link) > 0 { - var uLinkBuf bytes.Buffer - unescapeText(&uLinkBuf, link) - uLink = uLinkBuf.Bytes() - } - - // links need something to click on and somewhere to go - if len(uLink) == 0 || (t == linkNormal && txtE <= 1) { - return 0, nil - } - } - - // call the relevant rendering function - var linkNode *Node - switch t { - case linkNormal: - linkNode = NewNode(Link) - linkNode.Destination = normalizeURI(uLink) - linkNode.Title = title - if len(altContent) > 0 { - linkNode.AppendChild(text(altContent)) - } else { - // links cannot contain other links, so turn off link parsing - // temporarily and recurse - insideLink := p.insideLink - p.insideLink = true - p.inline(linkNode, data[1:txtE]) - p.insideLink = insideLink - } - - case linkImg: - linkNode = NewNode(Image) - linkNode.Destination = uLink - linkNode.Title = title - linkNode.AppendChild(text(data[1:txtE])) - i++ - - case linkInlineFootnote, linkDeferredFootnote: - linkNode = NewNode(Link) - linkNode.Destination = link - linkNode.Title = title - linkNode.NoteID = noteID - linkNode.Footnote = footnoteNode - if t == linkInlineFootnote { - i++ - } - - default: - return 0, nil - } - - return i, linkNode -} - -func (p *Markdown) inlineHTMLComment(data []byte) int { - if len(data) < 5 { - return 0 - } - if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' { - return 0 - } - i := 5 - // scan for an end-of-comment marker, across lines if necessary - for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') { - i++ - } - // no end-of-comment marker - if i >= len(data) { - return 0 - } - return i + 1 -} - -func stripMailto(link []byte) []byte { - if bytes.HasPrefix(link, []byte("mailto://")) { - return link[9:] - } else if bytes.HasPrefix(link, []byte("mailto:")) { - return link[7:] - } else { - return link - } -} - -// autolinkType specifies a kind of autolink that gets detected. -type autolinkType int - -// These are the possible flag values for the autolink renderer. -const ( - notAutolink autolinkType = iota - normalAutolink - emailAutolink -) - -// '<' when tags or autolinks are allowed -func leftAngle(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - altype, end := tagLength(data) - if size := p.inlineHTMLComment(data); size > 0 { - end = size - } - if end > 2 { - if altype != notAutolink { - var uLink bytes.Buffer - unescapeText(&uLink, data[1:end+1-2]) - if uLink.Len() > 0 { - link := uLink.Bytes() - node := NewNode(Link) - node.Destination = link - if altype == emailAutolink { - node.Destination = append([]byte("mailto:"), link...) - } - node.AppendChild(text(stripMailto(link))) - return end, node - } - } else { - htmlTag := NewNode(HTMLSpan) - htmlTag.Literal = data[:end] - return end, htmlTag - } - } - - return end, nil -} - -// '\\' backslash escape -var escapeChars = []byte("\\`*_{}[]()#+-.!:|&<>~") - -func escape(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - - if len(data) > 1 { - if p.extensions&BackslashLineBreak != 0 && data[1] == '\n' { - return 2, NewNode(Hardbreak) - } - if bytes.IndexByte(escapeChars, data[1]) < 0 { - return 0, nil - } - - return 2, text(data[1:2]) - } - - return 2, nil -} - -func unescapeText(ob *bytes.Buffer, src []byte) { - i := 0 - for i < len(src) { - org := i - for i < len(src) && src[i] != '\\' { - i++ - } - - if i > org { - ob.Write(src[org:i]) - } - - if i+1 >= len(src) { - break - } - - ob.WriteByte(src[i+1]) - i += 2 - } -} - -// '&' escaped when it doesn't belong to an entity -// valid entities are assumed to be anything matching &#?[A-Za-z0-9]+; -func entity(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - - end := 1 - - if end < len(data) && data[end] == '#' { - end++ - } - - for end < len(data) && isalnum(data[end]) { - end++ - } - - if end < len(data) && data[end] == ';' { - end++ // real entity - } else { - return 0, nil // lone '&' - } - - ent := data[:end] - // undo & escaping or it will be converted to &amp; by another - // escaper in the renderer - if bytes.Equal(ent, []byte("&")) { - ent = []byte{'&'} - } - - return end, text(ent) -} - -func linkEndsWithEntity(data []byte, linkEnd int) bool { - entityRanges := htmlEntityRe.FindAllIndex(data[:linkEnd], -1) - return entityRanges != nil && entityRanges[len(entityRanges)-1][1] == linkEnd -} - -// hasPrefixCaseInsensitive is a custom implementation of -// strings.HasPrefix(strings.ToLower(s), prefix) -// we rolled our own because ToLower pulls in a huge machinery of lowercasing -// anything from Unicode and that's very slow. Since this func will only be -// used on ASCII protocol prefixes, we can take shortcuts. -func hasPrefixCaseInsensitive(s, prefix []byte) bool { - if len(s) < len(prefix) { - return false - } - delta := byte('a' - 'A') - for i, b := range prefix { - if b != s[i] && b != s[i]+delta { - return false - } - } - return true -} - -var protocolPrefixes = [][]byte{ - []byte("http://"), - []byte("https://"), - []byte("ftp://"), - []byte("file://"), - []byte("mailto:"), -} - -const shortestPrefix = 6 // len("ftp://"), the shortest of the above - -func maybeAutoLink(p *Markdown, data []byte, offset int) (int, *Node) { - // quick check to rule out most false hits - if p.insideLink || len(data) < offset+shortestPrefix { - return 0, nil - } - for _, prefix := range protocolPrefixes { - endOfHead := offset + 8 // 8 is the len() of the longest prefix - if endOfHead > len(data) { - endOfHead = len(data) - } - if hasPrefixCaseInsensitive(data[offset:endOfHead], prefix) { - return autoLink(p, data, offset) - } - } - return 0, nil -} - -func autoLink(p *Markdown, data []byte, offset int) (int, *Node) { - // Now a more expensive check to see if we're not inside an anchor element - anchorStart := offset - offsetFromAnchor := 0 - for anchorStart > 0 && data[anchorStart] != '<' { - anchorStart-- - offsetFromAnchor++ - } - - anchorStr := anchorRe.Find(data[anchorStart:]) - if anchorStr != nil { - anchorClose := NewNode(HTMLSpan) - anchorClose.Literal = anchorStr[offsetFromAnchor:] - return len(anchorStr) - offsetFromAnchor, anchorClose - } - - // scan backward for a word boundary - rewind := 0 - for offset-rewind > 0 && rewind <= 7 && isletter(data[offset-rewind-1]) { - rewind++ - } - if rewind > 6 { // longest supported protocol is "mailto" which has 6 letters - return 0, nil - } - - origData := data - data = data[offset-rewind:] - - if !isSafeLink(data) { - return 0, nil - } - - linkEnd := 0 - for linkEnd < len(data) && !isEndOfLink(data[linkEnd]) { - linkEnd++ - } - - // Skip punctuation at the end of the link - if (data[linkEnd-1] == '.' || data[linkEnd-1] == ',') && data[linkEnd-2] != '\\' { - linkEnd-- - } - - // But don't skip semicolon if it's a part of escaped entity: - if data[linkEnd-1] == ';' && data[linkEnd-2] != '\\' && !linkEndsWithEntity(data, linkEnd) { - linkEnd-- - } - - // See if the link finishes with a punctuation sign that can be closed. - var copen byte - switch data[linkEnd-1] { - case '"': - copen = '"' - case '\'': - copen = '\'' - case ')': - copen = '(' - case ']': - copen = '[' - case '}': - copen = '{' - default: - copen = 0 - } - - if copen != 0 { - bufEnd := offset - rewind + linkEnd - 2 - - openDelim := 1 - - /* Try to close the final punctuation sign in this same line; - * if we managed to close it outside of the URL, that means that it's - * not part of the URL. If it closes inside the URL, that means it - * is part of the URL. - * - * Examples: - * - * foo http://www.pokemon.com/Pikachu_(Electric) bar - * => http://www.pokemon.com/Pikachu_(Electric) - * - * foo (http://www.pokemon.com/Pikachu_(Electric)) bar - * => http://www.pokemon.com/Pikachu_(Electric) - * - * foo http://www.pokemon.com/Pikachu_(Electric)) bar - * => http://www.pokemon.com/Pikachu_(Electric)) - * - * (foo http://www.pokemon.com/Pikachu_(Electric)) bar - * => foo http://www.pokemon.com/Pikachu_(Electric) - */ - - for bufEnd >= 0 && origData[bufEnd] != '\n' && openDelim != 0 { - if origData[bufEnd] == data[linkEnd-1] { - openDelim++ - } - - if origData[bufEnd] == copen { - openDelim-- - } - - bufEnd-- - } - - if openDelim == 0 { - linkEnd-- - } - } - - var uLink bytes.Buffer - unescapeText(&uLink, data[:linkEnd]) - - if uLink.Len() > 0 { - node := NewNode(Link) - node.Destination = uLink.Bytes() - node.AppendChild(text(uLink.Bytes())) - return linkEnd, node - } - - return linkEnd, nil -} - -func isEndOfLink(char byte) bool { - return isspace(char) || char == '<' -} - -var validUris = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")} -var validPaths = [][]byte{[]byte("/"), []byte("./"), []byte("../")} - -func isSafeLink(link []byte) bool { - for _, path := range validPaths { - if len(link) >= len(path) && bytes.Equal(link[:len(path)], path) { - if len(link) == len(path) { - return true - } else if isalnum(link[len(path)]) { - return true - } - } - } - - for _, prefix := range validUris { - // TODO: handle unicode here - // case-insensitive prefix test - if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) { - return true - } - } - - return false -} - -// return the length of the given tag, or 0 is it's not valid -func tagLength(data []byte) (autolink autolinkType, end int) { - var i, j int - - // a valid tag can't be shorter than 3 chars - if len(data) < 3 { - return notAutolink, 0 - } - - // begins with a '<' optionally followed by '/', followed by letter or number - if data[0] != '<' { - return notAutolink, 0 - } - if data[1] == '/' { - i = 2 - } else { - i = 1 - } - - if !isalnum(data[i]) { - return notAutolink, 0 - } - - // scheme test - autolink = notAutolink - - // try to find the beginning of an URI - for i < len(data) && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-') { - i++ - } - - if i > 1 && i < len(data) && data[i] == '@' { - if j = isMailtoAutoLink(data[i:]); j != 0 { - return emailAutolink, i + j - } - } - - if i > 2 && i < len(data) && data[i] == ':' { - autolink = normalAutolink - i++ - } - - // complete autolink test: no whitespace or ' or " - switch { - case i >= len(data): - autolink = notAutolink - case autolink != notAutolink: - j = i - - for i < len(data) { - if data[i] == '\\' { - i += 2 - } else if data[i] == '>' || data[i] == '\'' || data[i] == '"' || isspace(data[i]) { - break - } else { - i++ - } - - } - - if i >= len(data) { - return autolink, 0 - } - if i > j && data[i] == '>' { - return autolink, i + 1 - } - - // one of the forbidden chars has been found - autolink = notAutolink - } - i += bytes.IndexByte(data[i:], '>') - if i < 0 { - return autolink, 0 - } - return autolink, i + 1 -} - -// look for the address part of a mail autolink and '>' -// this is less strict than the original markdown e-mail address matching -func isMailtoAutoLink(data []byte) int { - nb := 0 - - // address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@' - for i := 0; i < len(data); i++ { - if isalnum(data[i]) { - continue - } - - switch data[i] { - case '@': - nb++ - - case '-', '.', '_': - break - - case '>': - if nb == 1 { - return i + 1 - } - return 0 - default: - return 0 - } - } - - return 0 -} - -// look for the next emph char, skipping other constructs -func helperFindEmphChar(data []byte, c byte) int { - i := 0 - - for i < len(data) { - for i < len(data) && data[i] != c && data[i] != '`' && data[i] != '[' { - i++ - } - if i >= len(data) { - return 0 - } - // do not count escaped chars - if i != 0 && data[i-1] == '\\' { - i++ - continue - } - if data[i] == c { - return i - } - - if data[i] == '`' { - // skip a code span - tmpI := 0 - i++ - for i < len(data) && data[i] != '`' { - if tmpI == 0 && data[i] == c { - tmpI = i - } - i++ - } - if i >= len(data) { - return tmpI - } - i++ - } else if data[i] == '[' { - // skip a link - tmpI := 0 - i++ - for i < len(data) && data[i] != ']' { - if tmpI == 0 && data[i] == c { - tmpI = i - } - i++ - } - i++ - for i < len(data) && (data[i] == ' ' || data[i] == '\n') { - i++ - } - if i >= len(data) { - return tmpI - } - if data[i] != '[' && data[i] != '(' { // not a link - if tmpI > 0 { - return tmpI - } - continue - } - cc := data[i] - i++ - for i < len(data) && data[i] != cc { - if tmpI == 0 && data[i] == c { - return i - } - i++ - } - if i >= len(data) { - return tmpI - } - i++ - } - } - return 0 -} - -func helperEmphasis(p *Markdown, data []byte, c byte) (int, *Node) { - i := 0 - - // skip one symbol if coming from emph3 - if len(data) > 1 && data[0] == c && data[1] == c { - i = 1 - } - - for i < len(data) { - length := helperFindEmphChar(data[i:], c) - if length == 0 { - return 0, nil - } - i += length - if i >= len(data) { - return 0, nil - } - - if i+1 < len(data) && data[i+1] == c { - i++ - continue - } - - if data[i] == c && !isspace(data[i-1]) { - - if p.extensions&NoIntraEmphasis != 0 { - if !(i+1 == len(data) || isspace(data[i+1]) || ispunct(data[i+1])) { - continue - } - } - - emph := NewNode(Emph) - p.inline(emph, data[:i]) - return i + 1, emph - } - } - - return 0, nil -} - -func helperDoubleEmphasis(p *Markdown, data []byte, c byte) (int, *Node) { - i := 0 - - for i < len(data) { - length := helperFindEmphChar(data[i:], c) - if length == 0 { - return 0, nil - } - i += length - - if i+1 < len(data) && data[i] == c && data[i+1] == c && i > 0 && !isspace(data[i-1]) { - nodeType := Strong - if c == '~' { - nodeType = Del - } - node := NewNode(nodeType) - p.inline(node, data[:i]) - return i + 2, node - } - i++ - } - return 0, nil -} - -func helperTripleEmphasis(p *Markdown, data []byte, offset int, c byte) (int, *Node) { - i := 0 - origData := data - data = data[offset:] - - for i < len(data) { - length := helperFindEmphChar(data[i:], c) - if length == 0 { - return 0, nil - } - i += length - - // skip whitespace preceded symbols - if data[i] != c || isspace(data[i-1]) { - continue - } - - switch { - case i+2 < len(data) && data[i+1] == c && data[i+2] == c: - // triple symbol found - strong := NewNode(Strong) - em := NewNode(Emph) - strong.AppendChild(em) - p.inline(em, data[:i]) - return i + 3, strong - case (i+1 < len(data) && data[i+1] == c): - // double symbol found, hand over to emph1 - length, node := helperEmphasis(p, origData[offset-2:], c) - if length == 0 { - return 0, nil - } - return length - 2, node - default: - // single symbol found, hand over to emph2 - length, node := helperDoubleEmphasis(p, origData[offset-1:], c) - if length == 0 { - return 0, nil - } - return length - 1, node - } - } - return 0, nil -} - -func text(s []byte) *Node { - node := NewNode(Text) - node.Literal = s - return node -} - -func normalizeURI(s []byte) []byte { - return s // TODO: implement -} diff --git a/vendor/github.com/russross/blackfriday/v2/markdown.go b/vendor/github.com/russross/blackfriday/v2/markdown.go deleted file mode 100644 index 58d2e4538..000000000 --- a/vendor/github.com/russross/blackfriday/v2/markdown.go +++ /dev/null @@ -1,950 +0,0 @@ -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. - -package blackfriday - -import ( - "bytes" - "fmt" - "io" - "strings" - "unicode/utf8" -) - -// -// Markdown parsing and processing -// - -// Version string of the package. Appears in the rendered document when -// CompletePage flag is on. -const Version = "2.0" - -// Extensions is a bitwise or'ed collection of enabled Blackfriday's -// extensions. -type Extensions int - -// These are the supported markdown parsing extensions. -// OR these values together to select multiple extensions. -const ( - NoExtensions Extensions = 0 - NoIntraEmphasis Extensions = 1 << iota // Ignore emphasis markers inside words - Tables // Render tables - FencedCode // Render fenced code blocks - Autolink // Detect embedded URLs that are not explicitly marked - Strikethrough // Strikethrough text using ~~test~~ - LaxHTMLBlocks // Loosen up HTML block parsing rules - SpaceHeadings // Be strict about prefix heading rules - HardLineBreak // Translate newlines into line breaks - TabSizeEight // Expand tabs to eight spaces instead of four - Footnotes // Pandoc-style footnotes - NoEmptyLineBeforeBlock // No need to insert an empty line to start a (code, quote, ordered list, unordered list) block - HeadingIDs // specify heading IDs with {#id} - Titleblock // Titleblock ala pandoc - AutoHeadingIDs // Create the heading ID from the text - BackslashLineBreak // Translate trailing backslashes into line breaks - DefinitionLists // Render definition lists - - CommonHTMLFlags HTMLFlags = UseXHTML | Smartypants | - SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes - - CommonExtensions Extensions = NoIntraEmphasis | Tables | FencedCode | - Autolink | Strikethrough | SpaceHeadings | HeadingIDs | - BackslashLineBreak | DefinitionLists -) - -// ListType contains bitwise or'ed flags for list and list item objects. -type ListType int - -// These are the possible flag values for the ListItem renderer. -// Multiple flag values may be ORed together. -// These are mostly of interest if you are writing a new output format. -const ( - ListTypeOrdered ListType = 1 << iota - ListTypeDefinition - ListTypeTerm - - ListItemContainsBlock - ListItemBeginningOfList // TODO: figure out if this is of any use now - ListItemEndOfList -) - -// CellAlignFlags holds a type of alignment in a table cell. -type CellAlignFlags int - -// These are the possible flag values for the table cell renderer. -// Only a single one of these values will be used; they are not ORed together. -// These are mostly of interest if you are writing a new output format. -const ( - TableAlignmentLeft CellAlignFlags = 1 << iota - TableAlignmentRight - TableAlignmentCenter = (TableAlignmentLeft | TableAlignmentRight) -) - -// The size of a tab stop. -const ( - TabSizeDefault = 4 - TabSizeDouble = 8 -) - -// blockTags is a set of tags that are recognized as HTML block tags. -// Any of these can be included in markdown text without special escaping. -var blockTags = map[string]struct{}{ - "blockquote": {}, - "del": {}, - "div": {}, - "dl": {}, - "fieldset": {}, - "form": {}, - "h1": {}, - "h2": {}, - "h3": {}, - "h4": {}, - "h5": {}, - "h6": {}, - "iframe": {}, - "ins": {}, - "math": {}, - "noscript": {}, - "ol": {}, - "pre": {}, - "p": {}, - "script": {}, - "style": {}, - "table": {}, - "ul": {}, - - // HTML5 - "address": {}, - "article": {}, - "aside": {}, - "canvas": {}, - "figcaption": {}, - "figure": {}, - "footer": {}, - "header": {}, - "hgroup": {}, - "main": {}, - "nav": {}, - "output": {}, - "progress": {}, - "section": {}, - "video": {}, -} - -// Renderer is the rendering interface. This is mostly of interest if you are -// implementing a new rendering format. -// -// Only an HTML implementation is provided in this repository, see the README -// for external implementations. -type Renderer interface { - // RenderNode is the main rendering method. It will be called once for - // every leaf node and twice for every non-leaf node (first with - // entering=true, then with entering=false). The method should write its - // rendition of the node to the supplied writer w. - RenderNode(w io.Writer, node *Node, entering bool) WalkStatus - - // RenderHeader is a method that allows the renderer to produce some - // content preceding the main body of the output document. The header is - // understood in the broad sense here. For example, the default HTML - // renderer will write not only the HTML document preamble, but also the - // table of contents if it was requested. - // - // The method will be passed an entire document tree, in case a particular - // implementation needs to inspect it to produce output. - // - // The output should be written to the supplied writer w. If your - // implementation has no header to write, supply an empty implementation. - RenderHeader(w io.Writer, ast *Node) - - // RenderFooter is a symmetric counterpart of RenderHeader. - RenderFooter(w io.Writer, ast *Node) -} - -// Callback functions for inline parsing. One such function is defined -// for each character that triggers a response when parsing inline data. -type inlineParser func(p *Markdown, data []byte, offset int) (int, *Node) - -// Markdown is a type that holds extensions and the runtime state used by -// Parse, and the renderer. You can not use it directly, construct it with New. -type Markdown struct { - renderer Renderer - referenceOverride ReferenceOverrideFunc - refs map[string]*reference - inlineCallback [256]inlineParser - extensions Extensions - nesting int - maxNesting int - insideLink bool - - // Footnotes need to be ordered as well as available to quickly check for - // presence. If a ref is also a footnote, it's stored both in refs and here - // in notes. Slice is nil if footnotes not enabled. - notes []*reference - - doc *Node - tip *Node // = doc - oldTip *Node - lastMatchedContainer *Node // = doc - allClosed bool -} - -func (p *Markdown) getRef(refid string) (ref *reference, found bool) { - if p.referenceOverride != nil { - r, overridden := p.referenceOverride(refid) - if overridden { - if r == nil { - return nil, false - } - return &reference{ - link: []byte(r.Link), - title: []byte(r.Title), - noteID: 0, - hasBlock: false, - text: []byte(r.Text)}, true - } - } - // refs are case insensitive - ref, found = p.refs[strings.ToLower(refid)] - return ref, found -} - -func (p *Markdown) finalize(block *Node) { - above := block.Parent - block.open = false - p.tip = above -} - -func (p *Markdown) addChild(node NodeType, offset uint32) *Node { - return p.addExistingChild(NewNode(node), offset) -} - -func (p *Markdown) addExistingChild(node *Node, offset uint32) *Node { - for !p.tip.canContain(node.Type) { - p.finalize(p.tip) - } - p.tip.AppendChild(node) - p.tip = node - return node -} - -func (p *Markdown) closeUnmatchedBlocks() { - if !p.allClosed { - for p.oldTip != p.lastMatchedContainer { - parent := p.oldTip.Parent - p.finalize(p.oldTip) - p.oldTip = parent - } - p.allClosed = true - } -} - -// -// -// Public interface -// -// - -// Reference represents the details of a link. -// See the documentation in Options for more details on use-case. -type Reference struct { - // Link is usually the URL the reference points to. - Link string - // Title is the alternate text describing the link in more detail. - Title string - // Text is the optional text to override the ref with if the syntax used was - // [refid][] - Text string -} - -// ReferenceOverrideFunc is expected to be called with a reference string and -// return either a valid Reference type that the reference string maps to or -// nil. If overridden is false, the default reference logic will be executed. -// See the documentation in Options for more details on use-case. -type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool) - -// New constructs a Markdown processor. You can use the same With* functions as -// for Run() to customize parser's behavior and the renderer. -func New(opts ...Option) *Markdown { - var p Markdown - for _, opt := range opts { - opt(&p) - } - p.refs = make(map[string]*reference) - p.maxNesting = 16 - p.insideLink = false - docNode := NewNode(Document) - p.doc = docNode - p.tip = docNode - p.oldTip = docNode - p.lastMatchedContainer = docNode - p.allClosed = true - // register inline parsers - p.inlineCallback[' '] = maybeLineBreak - p.inlineCallback['*'] = emphasis - p.inlineCallback['_'] = emphasis - if p.extensions&Strikethrough != 0 { - p.inlineCallback['~'] = emphasis - } - p.inlineCallback['`'] = codeSpan - p.inlineCallback['\n'] = lineBreak - p.inlineCallback['['] = link - p.inlineCallback['<'] = leftAngle - p.inlineCallback['\\'] = escape - p.inlineCallback['&'] = entity - p.inlineCallback['!'] = maybeImage - p.inlineCallback['^'] = maybeInlineFootnote - if p.extensions&Autolink != 0 { - p.inlineCallback['h'] = maybeAutoLink - p.inlineCallback['m'] = maybeAutoLink - p.inlineCallback['f'] = maybeAutoLink - p.inlineCallback['H'] = maybeAutoLink - p.inlineCallback['M'] = maybeAutoLink - p.inlineCallback['F'] = maybeAutoLink - } - if p.extensions&Footnotes != 0 { - p.notes = make([]*reference, 0) - } - return &p -} - -// Option customizes the Markdown processor's default behavior. -type Option func(*Markdown) - -// WithRenderer allows you to override the default renderer. -func WithRenderer(r Renderer) Option { - return func(p *Markdown) { - p.renderer = r - } -} - -// WithExtensions allows you to pick some of the many extensions provided by -// Blackfriday. You can bitwise OR them. -func WithExtensions(e Extensions) Option { - return func(p *Markdown) { - p.extensions = e - } -} - -// WithNoExtensions turns off all extensions and custom behavior. -func WithNoExtensions() Option { - return func(p *Markdown) { - p.extensions = NoExtensions - p.renderer = NewHTMLRenderer(HTMLRendererParameters{ - Flags: HTMLFlagsNone, - }) - } -} - -// WithRefOverride sets an optional function callback that is called every -// time a reference is resolved. -// -// In Markdown, the link reference syntax can be made to resolve a link to -// a reference instead of an inline URL, in one of the following ways: -// -// * [link text][refid] -// * [refid][] -// -// Usually, the refid is defined at the bottom of the Markdown document. If -// this override function is provided, the refid is passed to the override -// function first, before consulting the defined refids at the bottom. If -// the override function indicates an override did not occur, the refids at -// the bottom will be used to fill in the link details. -func WithRefOverride(o ReferenceOverrideFunc) Option { - return func(p *Markdown) { - p.referenceOverride = o - } -} - -// Run is the main entry point to Blackfriday. It parses and renders a -// block of markdown-encoded text. -// -// The simplest invocation of Run takes one argument, input: -// output := Run(input) -// This will parse the input with CommonExtensions enabled and render it with -// the default HTMLRenderer (with CommonHTMLFlags). -// -// Variadic arguments opts can customize the default behavior. Since Markdown -// type does not contain exported fields, you can not use it directly. Instead, -// use the With* functions. For example, this will call the most basic -// functionality, with no extensions: -// output := Run(input, WithNoExtensions()) -// -// You can use any number of With* arguments, even contradicting ones. They -// will be applied in order of appearance and the latter will override the -// former: -// output := Run(input, WithNoExtensions(), WithExtensions(exts), -// WithRenderer(yourRenderer)) -func Run(input []byte, opts ...Option) []byte { - r := NewHTMLRenderer(HTMLRendererParameters{ - Flags: CommonHTMLFlags, - }) - optList := []Option{WithRenderer(r), WithExtensions(CommonExtensions)} - optList = append(optList, opts...) - parser := New(optList...) - ast := parser.Parse(input) - var buf bytes.Buffer - parser.renderer.RenderHeader(&buf, ast) - ast.Walk(func(node *Node, entering bool) WalkStatus { - return parser.renderer.RenderNode(&buf, node, entering) - }) - parser.renderer.RenderFooter(&buf, ast) - return buf.Bytes() -} - -// Parse is an entry point to the parsing part of Blackfriday. It takes an -// input markdown document and produces a syntax tree for its contents. This -// tree can then be rendered with a default or custom renderer, or -// analyzed/transformed by the caller to whatever non-standard needs they have. -// The return value is the root node of the syntax tree. -func (p *Markdown) Parse(input []byte) *Node { - p.block(input) - // Walk the tree and finish up some of unfinished blocks - for p.tip != nil { - p.finalize(p.tip) - } - // Walk the tree again and process inline markdown in each block - p.doc.Walk(func(node *Node, entering bool) WalkStatus { - if node.Type == Paragraph || node.Type == Heading || node.Type == TableCell { - p.inline(node, node.content) - node.content = nil - } - return GoToNext - }) - p.parseRefsToAST() - return p.doc -} - -func (p *Markdown) parseRefsToAST() { - if p.extensions&Footnotes == 0 || len(p.notes) == 0 { - return - } - p.tip = p.doc - block := p.addBlock(List, nil) - block.IsFootnotesList = true - block.ListFlags = ListTypeOrdered - flags := ListItemBeginningOfList - // Note: this loop is intentionally explicit, not range-form. This is - // because the body of the loop will append nested footnotes to p.notes and - // we need to process those late additions. Range form would only walk over - // the fixed initial set. - for i := 0; i < len(p.notes); i++ { - ref := p.notes[i] - p.addExistingChild(ref.footnote, 0) - block := ref.footnote - block.ListFlags = flags | ListTypeOrdered - block.RefLink = ref.link - if ref.hasBlock { - flags |= ListItemContainsBlock - p.block(ref.title) - } else { - p.inline(block, ref.title) - } - flags &^= ListItemBeginningOfList | ListItemContainsBlock - } - above := block.Parent - finalizeList(block) - p.tip = above - block.Walk(func(node *Node, entering bool) WalkStatus { - if node.Type == Paragraph || node.Type == Heading { - p.inline(node, node.content) - node.content = nil - } - return GoToNext - }) -} - -// -// Link references -// -// This section implements support for references that (usually) appear -// as footnotes in a document, and can be referenced anywhere in the document. -// The basic format is: -// -// [1]: http://www.google.com/ "Google" -// [2]: http://www.github.com/ "Github" -// -// Anywhere in the document, the reference can be linked by referring to its -// label, i.e., 1 and 2 in this example, as in: -// -// This library is hosted on [Github][2], a git hosting site. -// -// Actual footnotes as specified in Pandoc and supported by some other Markdown -// libraries such as php-markdown are also taken care of. They look like this: -// -// This sentence needs a bit of further explanation.[^note] -// -// [^note]: This is the explanation. -// -// Footnotes should be placed at the end of the document in an ordered list. -// Finally, there are inline footnotes such as: -// -// Inline footnotes^[Also supported.] provide a quick inline explanation, -// but are rendered at the bottom of the document. -// - -// reference holds all information necessary for a reference-style links or -// footnotes. -// -// Consider this markdown with reference-style links: -// -// [link][ref] -// -// [ref]: /url/ "tooltip title" -// -// It will be ultimately converted to this HTML: -// -//

    link

    -// -// And a reference structure will be populated as follows: -// -// p.refs["ref"] = &reference{ -// link: "/url/", -// title: "tooltip title", -// } -// -// Alternatively, reference can contain information about a footnote. Consider -// this markdown: -// -// Text needing a footnote.[^a] -// -// [^a]: This is the note -// -// A reference structure will be populated as follows: -// -// p.refs["a"] = &reference{ -// link: "a", -// title: "This is the note", -// noteID: , -// } -// -// TODO: As you can see, it begs for splitting into two dedicated structures -// for refs and for footnotes. -type reference struct { - link []byte - title []byte - noteID int // 0 if not a footnote ref - hasBlock bool - footnote *Node // a link to the Item node within a list of footnotes - - text []byte // only gets populated by refOverride feature with Reference.Text -} - -func (r *reference) String() string { - return fmt.Sprintf("{link: %q, title: %q, text: %q, noteID: %d, hasBlock: %v}", - r.link, r.title, r.text, r.noteID, r.hasBlock) -} - -// Check whether or not data starts with a reference link. -// If so, it is parsed and stored in the list of references -// (in the render struct). -// Returns the number of bytes to skip to move past it, -// or zero if the first line is not a reference. -func isReference(p *Markdown, data []byte, tabSize int) int { - // up to 3 optional leading spaces - if len(data) < 4 { - return 0 - } - i := 0 - for i < 3 && data[i] == ' ' { - i++ - } - - noteID := 0 - - // id part: anything but a newline between brackets - if data[i] != '[' { - return 0 - } - i++ - if p.extensions&Footnotes != 0 { - if i < len(data) && data[i] == '^' { - // we can set it to anything here because the proper noteIds will - // be assigned later during the second pass. It just has to be != 0 - noteID = 1 - i++ - } - } - idOffset := i - for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' { - i++ - } - if i >= len(data) || data[i] != ']' { - return 0 - } - idEnd := i - // footnotes can have empty ID, like this: [^], but a reference can not be - // empty like this: []. Break early if it's not a footnote and there's no ID - if noteID == 0 && idOffset == idEnd { - return 0 - } - // spacer: colon (space | tab)* newline? (space | tab)* - i++ - if i >= len(data) || data[i] != ':' { - return 0 - } - i++ - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - if i < len(data) && (data[i] == '\n' || data[i] == '\r') { - i++ - if i < len(data) && data[i] == '\n' && data[i-1] == '\r' { - i++ - } - } - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - if i >= len(data) { - return 0 - } - - var ( - linkOffset, linkEnd int - titleOffset, titleEnd int - lineEnd int - raw []byte - hasBlock bool - ) - - if p.extensions&Footnotes != 0 && noteID != 0 { - linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize) - lineEnd = linkEnd - } else { - linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i) - } - if lineEnd == 0 { - return 0 - } - - // a valid ref has been found - - ref := &reference{ - noteID: noteID, - hasBlock: hasBlock, - } - - if noteID > 0 { - // reusing the link field for the id since footnotes don't have links - ref.link = data[idOffset:idEnd] - // if footnote, it's not really a title, it's the contained text - ref.title = raw - } else { - ref.link = data[linkOffset:linkEnd] - ref.title = data[titleOffset:titleEnd] - } - - // id matches are case-insensitive - id := string(bytes.ToLower(data[idOffset:idEnd])) - - p.refs[id] = ref - - return lineEnd -} - -func scanLinkRef(p *Markdown, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) { - // link: whitespace-free sequence, optionally between angle brackets - if data[i] == '<' { - i++ - } - linkOffset = i - for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' { - i++ - } - linkEnd = i - if data[linkOffset] == '<' && data[linkEnd-1] == '>' { - linkOffset++ - linkEnd-- - } - - // optional spacer: (space | tab)* (newline | '\'' | '"' | '(' ) - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' { - return - } - - // compute end-of-line - if i >= len(data) || data[i] == '\r' || data[i] == '\n' { - lineEnd = i - } - if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' { - lineEnd++ - } - - // optional (space|tab)* spacer after a newline - if lineEnd > 0 { - i = lineEnd + 1 - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - } - - // optional title: any non-newline sequence enclosed in '"() alone on its line - if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') { - i++ - titleOffset = i - - // look for EOL - for i < len(data) && data[i] != '\n' && data[i] != '\r' { - i++ - } - if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' { - titleEnd = i + 1 - } else { - titleEnd = i - } - - // step back - i-- - for i > titleOffset && (data[i] == ' ' || data[i] == '\t') { - i-- - } - if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') { - lineEnd = titleEnd - titleEnd = i - } - } - - return -} - -// The first bit of this logic is the same as Parser.listItem, but the rest -// is much simpler. This function simply finds the entire block and shifts it -// over by one tab if it is indeed a block (just returns the line if it's not). -// blockEnd is the end of the section in the input buffer, and contents is the -// extracted text that was shifted over one tab. It will need to be rendered at -// the end of the document. -func scanFootnote(p *Markdown, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) { - if i == 0 || len(data) == 0 { - return - } - - // skip leading whitespace on first line - for i < len(data) && data[i] == ' ' { - i++ - } - - blockStart = i - - // find the end of the line - blockEnd = i - for i < len(data) && data[i-1] != '\n' { - i++ - } - - // get working buffer - var raw bytes.Buffer - - // put the first line into the working buffer - raw.Write(data[blockEnd:i]) - blockEnd = i - - // process the following lines - containsBlankLine := false - -gatherLines: - for blockEnd < len(data) { - i++ - - // find the end of this line - for i < len(data) && data[i-1] != '\n' { - i++ - } - - // if it is an empty line, guess that it is part of this item - // and move on to the next line - if p.isEmpty(data[blockEnd:i]) > 0 { - containsBlankLine = true - blockEnd = i - continue - } - - n := 0 - if n = isIndented(data[blockEnd:i], indentSize); n == 0 { - // this is the end of the block. - // we don't want to include this last line in the index. - break gatherLines - } - - // if there were blank lines before this one, insert a new one now - if containsBlankLine { - raw.WriteByte('\n') - containsBlankLine = false - } - - // get rid of that first tab, write to buffer - raw.Write(data[blockEnd+n : i]) - hasBlock = true - - blockEnd = i - } - - if data[blockEnd-1] != '\n' { - raw.WriteByte('\n') - } - - contents = raw.Bytes() - - return -} - -// -// -// Miscellaneous helper functions -// -// - -// Test if a character is a punctuation symbol. -// Taken from a private function in regexp in the stdlib. -func ispunct(c byte) bool { - for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { - if c == r { - return true - } - } - return false -} - -// Test if a character is a whitespace character. -func isspace(c byte) bool { - return ishorizontalspace(c) || isverticalspace(c) -} - -// Test if a character is a horizontal whitespace character. -func ishorizontalspace(c byte) bool { - return c == ' ' || c == '\t' -} - -// Test if a character is a vertical character. -func isverticalspace(c byte) bool { - return c == '\n' || c == '\r' || c == '\f' || c == '\v' -} - -// Test if a character is letter. -func isletter(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -// Test if a character is a letter or a digit. -// TODO: check when this is looking for ASCII alnum and when it should use unicode -func isalnum(c byte) bool { - return (c >= '0' && c <= '9') || isletter(c) -} - -// Replace tab characters with spaces, aligning to the next TAB_SIZE column. -// always ends output with a newline -func expandTabs(out *bytes.Buffer, line []byte, tabSize int) { - // first, check for common cases: no tabs, or only tabs at beginning of line - i, prefix := 0, 0 - slowcase := false - for i = 0; i < len(line); i++ { - if line[i] == '\t' { - if prefix == i { - prefix++ - } else { - slowcase = true - break - } - } - } - - // no need to decode runes if all tabs are at the beginning of the line - if !slowcase { - for i = 0; i < prefix*tabSize; i++ { - out.WriteByte(' ') - } - out.Write(line[prefix:]) - return - } - - // the slow case: we need to count runes to figure out how - // many spaces to insert for each tab - column := 0 - i = 0 - for i < len(line) { - start := i - for i < len(line) && line[i] != '\t' { - _, size := utf8.DecodeRune(line[i:]) - i += size - column++ - } - - if i > start { - out.Write(line[start:i]) - } - - if i >= len(line) { - break - } - - for { - out.WriteByte(' ') - column++ - if column%tabSize == 0 { - break - } - } - - i++ - } -} - -// Find if a line counts as indented or not. -// Returns number of characters the indent is (0 = not indented). -func isIndented(data []byte, indentSize int) int { - if len(data) == 0 { - return 0 - } - if data[0] == '\t' { - return 1 - } - if len(data) < indentSize { - return 0 - } - for i := 0; i < indentSize; i++ { - if data[i] != ' ' { - return 0 - } - } - return indentSize -} - -// Create a url-safe slug for fragments -func slugify(in []byte) []byte { - if len(in) == 0 { - return in - } - out := make([]byte, 0, len(in)) - sym := false - - for _, ch := range in { - if isalnum(ch) { - sym = false - out = append(out, ch) - } else if sym { - continue - } else { - out = append(out, '-') - sym = true - } - } - var a, b int - var ch byte - for a, ch = range out { - if ch != '-' { - break - } - } - for b = len(out) - 1; b > 0; b-- { - if out[b] != '-' { - break - } - } - return out[a : b+1] -} diff --git a/vendor/github.com/russross/blackfriday/v2/node.go b/vendor/github.com/russross/blackfriday/v2/node.go deleted file mode 100644 index 04e6050ce..000000000 --- a/vendor/github.com/russross/blackfriday/v2/node.go +++ /dev/null @@ -1,360 +0,0 @@ -package blackfriday - -import ( - "bytes" - "fmt" -) - -// NodeType specifies a type of a single node of a syntax tree. Usually one -// node (and its type) corresponds to a single markdown feature, e.g. emphasis -// or code block. -type NodeType int - -// Constants for identifying different types of nodes. See NodeType. -const ( - Document NodeType = iota - BlockQuote - List - Item - Paragraph - Heading - HorizontalRule - Emph - Strong - Del - Link - Image - Text - HTMLBlock - CodeBlock - Softbreak - Hardbreak - Code - HTMLSpan - Table - TableCell - TableHead - TableBody - TableRow -) - -var nodeTypeNames = []string{ - Document: "Document", - BlockQuote: "BlockQuote", - List: "List", - Item: "Item", - Paragraph: "Paragraph", - Heading: "Heading", - HorizontalRule: "HorizontalRule", - Emph: "Emph", - Strong: "Strong", - Del: "Del", - Link: "Link", - Image: "Image", - Text: "Text", - HTMLBlock: "HTMLBlock", - CodeBlock: "CodeBlock", - Softbreak: "Softbreak", - Hardbreak: "Hardbreak", - Code: "Code", - HTMLSpan: "HTMLSpan", - Table: "Table", - TableCell: "TableCell", - TableHead: "TableHead", - TableBody: "TableBody", - TableRow: "TableRow", -} - -func (t NodeType) String() string { - return nodeTypeNames[t] -} - -// ListData contains fields relevant to a List and Item node type. -type ListData struct { - ListFlags ListType - Tight bool // Skip

    s around list item data if true - BulletChar byte // '*', '+' or '-' in bullet lists - Delimiter byte // '.' or ')' after the number in ordered lists - RefLink []byte // If not nil, turns this list item into a footnote item and triggers different rendering - IsFootnotesList bool // This is a list of footnotes -} - -// LinkData contains fields relevant to a Link node type. -type LinkData struct { - Destination []byte // Destination is what goes into a href - Title []byte // Title is the tooltip thing that goes in a title attribute - NoteID int // NoteID contains a serial number of a footnote, zero if it's not a footnote - Footnote *Node // If it's a footnote, this is a direct link to the footnote Node. Otherwise nil. -} - -// CodeBlockData contains fields relevant to a CodeBlock node type. -type CodeBlockData struct { - IsFenced bool // Specifies whether it's a fenced code block or an indented one - Info []byte // This holds the info string - FenceChar byte - FenceLength int - FenceOffset int -} - -// TableCellData contains fields relevant to a TableCell node type. -type TableCellData struct { - IsHeader bool // This tells if it's under the header row - Align CellAlignFlags // This holds the value for align attribute -} - -// HeadingData contains fields relevant to a Heading node type. -type HeadingData struct { - Level int // This holds the heading level number - HeadingID string // This might hold heading ID, if present - IsTitleblock bool // Specifies whether it's a title block -} - -// Node is a single element in the abstract syntax tree of the parsed document. -// It holds connections to the structurally neighboring nodes and, for certain -// types of nodes, additional information that might be needed when rendering. -type Node struct { - Type NodeType // Determines the type of the node - Parent *Node // Points to the parent - FirstChild *Node // Points to the first child, if any - LastChild *Node // Points to the last child, if any - Prev *Node // Previous sibling; nil if it's the first child - Next *Node // Next sibling; nil if it's the last child - - Literal []byte // Text contents of the leaf nodes - - HeadingData // Populated if Type is Heading - ListData // Populated if Type is List - CodeBlockData // Populated if Type is CodeBlock - LinkData // Populated if Type is Link - TableCellData // Populated if Type is TableCell - - content []byte // Markdown content of the block nodes - open bool // Specifies an open block node that has not been finished to process yet -} - -// NewNode allocates a node of a specified type. -func NewNode(typ NodeType) *Node { - return &Node{ - Type: typ, - open: true, - } -} - -func (n *Node) String() string { - ellipsis := "" - snippet := n.Literal - if len(snippet) > 16 { - snippet = snippet[:16] - ellipsis = "..." - } - return fmt.Sprintf("%s: '%s%s'", n.Type, snippet, ellipsis) -} - -// Unlink removes node 'n' from the tree. -// It panics if the node is nil. -func (n *Node) Unlink() { - if n.Prev != nil { - n.Prev.Next = n.Next - } else if n.Parent != nil { - n.Parent.FirstChild = n.Next - } - if n.Next != nil { - n.Next.Prev = n.Prev - } else if n.Parent != nil { - n.Parent.LastChild = n.Prev - } - n.Parent = nil - n.Next = nil - n.Prev = nil -} - -// AppendChild adds a node 'child' as a child of 'n'. -// It panics if either node is nil. -func (n *Node) AppendChild(child *Node) { - child.Unlink() - child.Parent = n - if n.LastChild != nil { - n.LastChild.Next = child - child.Prev = n.LastChild - n.LastChild = child - } else { - n.FirstChild = child - n.LastChild = child - } -} - -// InsertBefore inserts 'sibling' immediately before 'n'. -// It panics if either node is nil. -func (n *Node) InsertBefore(sibling *Node) { - sibling.Unlink() - sibling.Prev = n.Prev - if sibling.Prev != nil { - sibling.Prev.Next = sibling - } - sibling.Next = n - n.Prev = sibling - sibling.Parent = n.Parent - if sibling.Prev == nil { - sibling.Parent.FirstChild = sibling - } -} - -// IsContainer returns true if 'n' can contain children. -func (n *Node) IsContainer() bool { - switch n.Type { - case Document: - fallthrough - case BlockQuote: - fallthrough - case List: - fallthrough - case Item: - fallthrough - case Paragraph: - fallthrough - case Heading: - fallthrough - case Emph: - fallthrough - case Strong: - fallthrough - case Del: - fallthrough - case Link: - fallthrough - case Image: - fallthrough - case Table: - fallthrough - case TableHead: - fallthrough - case TableBody: - fallthrough - case TableRow: - fallthrough - case TableCell: - return true - default: - return false - } -} - -// IsLeaf returns true if 'n' is a leaf node. -func (n *Node) IsLeaf() bool { - return !n.IsContainer() -} - -func (n *Node) canContain(t NodeType) bool { - if n.Type == List { - return t == Item - } - if n.Type == Document || n.Type == BlockQuote || n.Type == Item { - return t != Item - } - if n.Type == Table { - return t == TableHead || t == TableBody - } - if n.Type == TableHead || n.Type == TableBody { - return t == TableRow - } - if n.Type == TableRow { - return t == TableCell - } - return false -} - -// WalkStatus allows NodeVisitor to have some control over the tree traversal. -// It is returned from NodeVisitor and different values allow Node.Walk to -// decide which node to go to next. -type WalkStatus int - -const ( - // GoToNext is the default traversal of every node. - GoToNext WalkStatus = iota - // SkipChildren tells walker to skip all children of current node. - SkipChildren - // Terminate tells walker to terminate the traversal. - Terminate -) - -// NodeVisitor is a callback to be called when traversing the syntax tree. -// Called twice for every node: once with entering=true when the branch is -// first visited, then with entering=false after all the children are done. -type NodeVisitor func(node *Node, entering bool) WalkStatus - -// Walk is a convenience method that instantiates a walker and starts a -// traversal of subtree rooted at n. -func (n *Node) Walk(visitor NodeVisitor) { - w := newNodeWalker(n) - for w.current != nil { - status := visitor(w.current, w.entering) - switch status { - case GoToNext: - w.next() - case SkipChildren: - w.entering = false - w.next() - case Terminate: - return - } - } -} - -type nodeWalker struct { - current *Node - root *Node - entering bool -} - -func newNodeWalker(root *Node) *nodeWalker { - return &nodeWalker{ - current: root, - root: root, - entering: true, - } -} - -func (nw *nodeWalker) next() { - if (!nw.current.IsContainer() || !nw.entering) && nw.current == nw.root { - nw.current = nil - return - } - if nw.entering && nw.current.IsContainer() { - if nw.current.FirstChild != nil { - nw.current = nw.current.FirstChild - nw.entering = true - } else { - nw.entering = false - } - } else if nw.current.Next == nil { - nw.current = nw.current.Parent - nw.entering = false - } else { - nw.current = nw.current.Next - nw.entering = true - } -} - -func dump(ast *Node) { - fmt.Println(dumpString(ast)) -} - -func dumpR(ast *Node, depth int) string { - if ast == nil { - return "" - } - indent := bytes.Repeat([]byte("\t"), depth) - content := ast.Literal - if content == nil { - content = ast.content - } - result := fmt.Sprintf("%s%s(%q)\n", indent, ast.Type, content) - for n := ast.FirstChild; n != nil; n = n.Next { - result += dumpR(n, depth+1) - } - return result -} - -func dumpString(ast *Node) string { - return dumpR(ast, 0) -} diff --git a/vendor/github.com/russross/blackfriday/v2/smartypants.go b/vendor/github.com/russross/blackfriday/v2/smartypants.go deleted file mode 100644 index 3a220e942..000000000 --- a/vendor/github.com/russross/blackfriday/v2/smartypants.go +++ /dev/null @@ -1,457 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// -// SmartyPants rendering -// -// - -package blackfriday - -import ( - "bytes" - "io" -) - -// SPRenderer is a struct containing state of a Smartypants renderer. -type SPRenderer struct { - inSingleQuote bool - inDoubleQuote bool - callbacks [256]smartCallback -} - -func wordBoundary(c byte) bool { - return c == 0 || isspace(c) || ispunct(c) -} - -func tolower(c byte) byte { - if c >= 'A' && c <= 'Z' { - return c - 'A' + 'a' - } - return c -} - -func isdigit(c byte) bool { - return c >= '0' && c <= '9' -} - -func smartQuoteHelper(out *bytes.Buffer, previousChar byte, nextChar byte, quote byte, isOpen *bool, addNBSP bool) bool { - // edge of the buffer is likely to be a tag that we don't get to see, - // so we treat it like text sometimes - - // enumerate all sixteen possibilities for (previousChar, nextChar) - // each can be one of {0, space, punct, other} - switch { - case previousChar == 0 && nextChar == 0: - // context is not any help here, so toggle - *isOpen = !*isOpen - case isspace(previousChar) && nextChar == 0: - // [ "] might be [ "foo...] - *isOpen = true - case ispunct(previousChar) && nextChar == 0: - // [!"] hmm... could be [Run!"] or [("...] - *isOpen = false - case /* isnormal(previousChar) && */ nextChar == 0: - // [a"] is probably a close - *isOpen = false - case previousChar == 0 && isspace(nextChar): - // [" ] might be [...foo" ] - *isOpen = false - case isspace(previousChar) && isspace(nextChar): - // [ " ] context is not any help here, so toggle - *isOpen = !*isOpen - case ispunct(previousChar) && isspace(nextChar): - // [!" ] is probably a close - *isOpen = false - case /* isnormal(previousChar) && */ isspace(nextChar): - // [a" ] this is one of the easy cases - *isOpen = false - case previousChar == 0 && ispunct(nextChar): - // ["!] hmm... could be ["$1.95] or ["!...] - *isOpen = false - case isspace(previousChar) && ispunct(nextChar): - // [ "!] looks more like [ "$1.95] - *isOpen = true - case ispunct(previousChar) && ispunct(nextChar): - // [!"!] context is not any help here, so toggle - *isOpen = !*isOpen - case /* isnormal(previousChar) && */ ispunct(nextChar): - // [a"!] is probably a close - *isOpen = false - case previousChar == 0 /* && isnormal(nextChar) */ : - // ["a] is probably an open - *isOpen = true - case isspace(previousChar) /* && isnormal(nextChar) */ : - // [ "a] this is one of the easy cases - *isOpen = true - case ispunct(previousChar) /* && isnormal(nextChar) */ : - // [!"a] is probably an open - *isOpen = true - default: - // [a'b] maybe a contraction? - *isOpen = false - } - - // Note that with the limited lookahead, this non-breaking - // space will also be appended to single double quotes. - if addNBSP && !*isOpen { - out.WriteString(" ") - } - - out.WriteByte('&') - if *isOpen { - out.WriteByte('l') - } else { - out.WriteByte('r') - } - out.WriteByte(quote) - out.WriteString("quo;") - - if addNBSP && *isOpen { - out.WriteString(" ") - } - - return true -} - -func (r *SPRenderer) smartSingleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 2 { - t1 := tolower(text[1]) - - if t1 == '\'' { - nextChar := byte(0) - if len(text) >= 3 { - nextChar = text[2] - } - if smartQuoteHelper(out, previousChar, nextChar, 'd', &r.inDoubleQuote, false) { - return 1 - } - } - - if (t1 == 's' || t1 == 't' || t1 == 'm' || t1 == 'd') && (len(text) < 3 || wordBoundary(text[2])) { - out.WriteString("’") - return 0 - } - - if len(text) >= 3 { - t2 := tolower(text[2]) - - if ((t1 == 'r' && t2 == 'e') || (t1 == 'l' && t2 == 'l') || (t1 == 'v' && t2 == 'e')) && - (len(text) < 4 || wordBoundary(text[3])) { - out.WriteString("’") - return 0 - } - } - } - - nextChar := byte(0) - if len(text) > 1 { - nextChar = text[1] - } - if smartQuoteHelper(out, previousChar, nextChar, 's', &r.inSingleQuote, false) { - return 0 - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartParens(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 3 { - t1 := tolower(text[1]) - t2 := tolower(text[2]) - - if t1 == 'c' && t2 == ')' { - out.WriteString("©") - return 2 - } - - if t1 == 'r' && t2 == ')' { - out.WriteString("®") - return 2 - } - - if len(text) >= 4 && t1 == 't' && t2 == 'm' && text[3] == ')' { - out.WriteString("™") - return 3 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartDash(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 2 { - if text[1] == '-' { - out.WriteString("—") - return 1 - } - - if wordBoundary(previousChar) && wordBoundary(text[1]) { - out.WriteString("–") - return 0 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartDashLatex(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 3 && text[1] == '-' && text[2] == '-' { - out.WriteString("—") - return 2 - } - if len(text) >= 2 && text[1] == '-' { - out.WriteString("–") - return 1 - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartAmpVariant(out *bytes.Buffer, previousChar byte, text []byte, quote byte, addNBSP bool) int { - if bytes.HasPrefix(text, []byte(""")) { - nextChar := byte(0) - if len(text) >= 7 { - nextChar = text[6] - } - if smartQuoteHelper(out, previousChar, nextChar, quote, &r.inDoubleQuote, addNBSP) { - return 5 - } - } - - if bytes.HasPrefix(text, []byte("�")) { - return 3 - } - - out.WriteByte('&') - return 0 -} - -func (r *SPRenderer) smartAmp(angledQuotes, addNBSP bool) func(*bytes.Buffer, byte, []byte) int { - var quote byte = 'd' - if angledQuotes { - quote = 'a' - } - - return func(out *bytes.Buffer, previousChar byte, text []byte) int { - return r.smartAmpVariant(out, previousChar, text, quote, addNBSP) - } -} - -func (r *SPRenderer) smartPeriod(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 3 && text[1] == '.' && text[2] == '.' { - out.WriteString("…") - return 2 - } - - if len(text) >= 5 && text[1] == ' ' && text[2] == '.' && text[3] == ' ' && text[4] == '.' { - out.WriteString("…") - return 4 - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartBacktick(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 2 && text[1] == '`' { - nextChar := byte(0) - if len(text) >= 3 { - nextChar = text[2] - } - if smartQuoteHelper(out, previousChar, nextChar, 'd', &r.inDoubleQuote, false) { - return 1 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartNumberGeneric(out *bytes.Buffer, previousChar byte, text []byte) int { - if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 { - // is it of the form digits/digits(word boundary)?, i.e., \d+/\d+\b - // note: check for regular slash (/) or fraction slash (⁄, 0x2044, or 0xe2 81 84 in utf-8) - // and avoid changing dates like 1/23/2005 into fractions. - numEnd := 0 - for len(text) > numEnd && isdigit(text[numEnd]) { - numEnd++ - } - if numEnd == 0 { - out.WriteByte(text[0]) - return 0 - } - denStart := numEnd + 1 - if len(text) > numEnd+3 && text[numEnd] == 0xe2 && text[numEnd+1] == 0x81 && text[numEnd+2] == 0x84 { - denStart = numEnd + 3 - } else if len(text) < numEnd+2 || text[numEnd] != '/' { - out.WriteByte(text[0]) - return 0 - } - denEnd := denStart - for len(text) > denEnd && isdigit(text[denEnd]) { - denEnd++ - } - if denEnd == denStart { - out.WriteByte(text[0]) - return 0 - } - if len(text) == denEnd || wordBoundary(text[denEnd]) && text[denEnd] != '/' { - out.WriteString("") - out.Write(text[:numEnd]) - out.WriteString("") - out.Write(text[denStart:denEnd]) - out.WriteString("") - return denEnd - 1 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartNumber(out *bytes.Buffer, previousChar byte, text []byte) int { - if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 { - if text[0] == '1' && text[1] == '/' && text[2] == '2' { - if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' { - out.WriteString("½") - return 2 - } - } - - if text[0] == '1' && text[1] == '/' && text[2] == '4' { - if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 5 && tolower(text[3]) == 't' && tolower(text[4]) == 'h') { - out.WriteString("¼") - return 2 - } - } - - if text[0] == '3' && text[1] == '/' && text[2] == '4' { - if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 6 && tolower(text[3]) == 't' && tolower(text[4]) == 'h' && tolower(text[5]) == 's') { - out.WriteString("¾") - return 2 - } - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartDoubleQuoteVariant(out *bytes.Buffer, previousChar byte, text []byte, quote byte) int { - nextChar := byte(0) - if len(text) > 1 { - nextChar = text[1] - } - if !smartQuoteHelper(out, previousChar, nextChar, quote, &r.inDoubleQuote, false) { - out.WriteString(""") - } - - return 0 -} - -func (r *SPRenderer) smartDoubleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { - return r.smartDoubleQuoteVariant(out, previousChar, text, 'd') -} - -func (r *SPRenderer) smartAngledDoubleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { - return r.smartDoubleQuoteVariant(out, previousChar, text, 'a') -} - -func (r *SPRenderer) smartLeftAngle(out *bytes.Buffer, previousChar byte, text []byte) int { - i := 0 - - for i < len(text) && text[i] != '>' { - i++ - } - - out.Write(text[:i+1]) - return i -} - -type smartCallback func(out *bytes.Buffer, previousChar byte, text []byte) int - -// NewSmartypantsRenderer constructs a Smartypants renderer object. -func NewSmartypantsRenderer(flags HTMLFlags) *SPRenderer { - var ( - r SPRenderer - - smartAmpAngled = r.smartAmp(true, false) - smartAmpAngledNBSP = r.smartAmp(true, true) - smartAmpRegular = r.smartAmp(false, false) - smartAmpRegularNBSP = r.smartAmp(false, true) - - addNBSP = flags&SmartypantsQuotesNBSP != 0 - ) - - if flags&SmartypantsAngledQuotes == 0 { - r.callbacks['"'] = r.smartDoubleQuote - if !addNBSP { - r.callbacks['&'] = smartAmpRegular - } else { - r.callbacks['&'] = smartAmpRegularNBSP - } - } else { - r.callbacks['"'] = r.smartAngledDoubleQuote - if !addNBSP { - r.callbacks['&'] = smartAmpAngled - } else { - r.callbacks['&'] = smartAmpAngledNBSP - } - } - r.callbacks['\''] = r.smartSingleQuote - r.callbacks['('] = r.smartParens - if flags&SmartypantsDashes != 0 { - if flags&SmartypantsLatexDashes == 0 { - r.callbacks['-'] = r.smartDash - } else { - r.callbacks['-'] = r.smartDashLatex - } - } - r.callbacks['.'] = r.smartPeriod - if flags&SmartypantsFractions == 0 { - r.callbacks['1'] = r.smartNumber - r.callbacks['3'] = r.smartNumber - } else { - for ch := '1'; ch <= '9'; ch++ { - r.callbacks[ch] = r.smartNumberGeneric - } - } - r.callbacks['<'] = r.smartLeftAngle - r.callbacks['`'] = r.smartBacktick - return &r -} - -// Process is the entry point of the Smartypants renderer. -func (r *SPRenderer) Process(w io.Writer, text []byte) { - mark := 0 - for i := 0; i < len(text); i++ { - if action := r.callbacks[text[i]]; action != nil { - if i > mark { - w.Write(text[mark:i]) - } - previousChar := byte(0) - if i > 0 { - previousChar = text[i-1] - } - var tmp bytes.Buffer - i += action(&tmp, previousChar, text[i:]) - w.Write(tmp.Bytes()) - mark = i + 1 - } - } - if mark < len(text) { - w.Write(text[mark:]) - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt deleted file mode 100644 index 5bf0b08bd..000000000 --- a/vendor/modules.txt +++ /dev/null @@ -1,5 +0,0 @@ -# github.com/russross/blackfriday v1.6.0 -## explicit -# github.com/russross/blackfriday/v2 v2.1.0 -## explicit -github.com/russross/blackfriday/v2 From 7a5cb99b84b6a6e0ed96c27c126aae5312b40af6 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 26 Aug 2021 15:50:29 -0700 Subject: [PATCH 075/283] Add myself to footer (#386) * Add myself to footer * Add myself to the example template as well, and rebuild --- public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 2 +- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 2 +- public/collection-functions | 2 +- public/command-line-arguments | 2 +- public/command-line-flags | 2 +- public/command-line-subcommands | 2 +- public/constants | 2 +- public/context | 2 +- public/defer | 2 +- public/directories | 2 +- public/environment-variables | 2 +- public/epoch | 2 +- public/errors | 2 +- public/execing-processes | 2 +- public/exit | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/goroutines | 2 +- public/hello-world | 2 +- public/http-clients | 2 +- public/http-servers | 2 +- public/if-else | 2 +- public/index.html | 2 +- public/interfaces | 2 +- public/json | 2 +- public/line-filters | 2 +- public/maps | 2 +- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 2 +- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 2 +- public/random-numbers | 2 +- public/range | 2 +- public/range-over-channels | 2 +- public/rate-limiting | 2 +- public/reading-files | 2 +- public/recursion | 2 +- public/regular-expressions | 2 +- public/select | 2 +- public/sha1-hashes | 2 +- public/signals | 2 +- public/slices | 2 +- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 2 +- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- templates/example.tmpl | 2 +- templates/index.tmpl | 2 +- 78 files changed, 78 insertions(+), 78 deletions(-) diff --git a/public/arrays b/public/arrays index e72e16a38..f2ddcb1b6 100644 --- a/public/arrays +++ b/public/arrays @@ -197,7 +197,7 @@ typical Go. We’ll look at slices next.

  • diff --git a/public/reading-files b/public/reading-files index 0c5f12ef9..94100f8be 100644 --- a/public/reading-files +++ b/public/reading-files @@ -43,7 +43,7 @@ reading files.

    - +
    package main
     
    @@ -59,7 +59,6 @@ reading files.

    "bufio" "fmt" "io" - "io/ioutil" "os" )
    @@ -104,7 +103,7 @@ slurping a file’s entire contents into memory.

    -    dat, err := ioutil.ReadFile("/tmp/dat")
    +    dat, err := os.ReadFile("/tmp/dat")
         check(err)
         fmt.Print(string(dat))
     
    @@ -282,7 +281,7 @@ be scheduled immediately after Opening with
    diff --git a/public/spawning-processes b/public/spawning-processes index dfc10dd51..c5781ece0 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -46,7 +46,7 @@ of spawning processes from Go.

    - +
    package main
     
    @@ -60,7 +60,7 @@ of spawning processes from Go.

    import (
         "fmt"
    -    "io/ioutil"
    +    "io"
         "os/exec"
     )
     
    @@ -146,7 +146,7 @@ to exit.

    grepCmd.Start() grepIn.Write([]byte("hello grep\ngoodbye grep")) grepIn.Close() - grepBytes, _ := ioutil.ReadAll(grepOut) + grepBytes, _ := io.ReadAll(grepOut) grepCmd.Wait()
    @@ -251,7 +251,7 @@ as if we had run them directly from the command-line.

    diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 9ee4aba6f..7d3cbaa8d 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -45,7 +45,7 @@ time.

    - +
    package main
     
    @@ -59,7 +59,6 @@ time.

    import (
         "fmt"
    -    "io/ioutil"
         "os"
         "path/filepath"
     )
    @@ -96,16 +95,16 @@ time.

    The easiest way to create a temporary file is by -calling ioutil.TempFile. It creates a file and +calling os.CreateTemp. It creates a file and opens it for reading and writing. We provide "" -as the first argument, so ioutil.TempFile will +as the first argument, so os.CreateTemp will create the file in the default location for our OS.

    -    f, err := ioutil.TempFile("", "sample")
    +    f, err := os.CreateTemp("", "sample")
         check(err)
     
    @@ -116,7 +115,7 @@ create the file in the default location for our OS.

    Display the name of the temporary file. On Unix-based OSes the directory will likely be /tmp. The file name starts with the prefix given as the -second argument to ioutil.TempFile and the rest +second argument to os.CreateTemp and the rest is chosen automatically to ensure that concurrent calls will always create different file names.

    @@ -163,15 +162,15 @@ explicitly.

    If we intend to write many temporary files, we may prefer to create a temporary directory. -ioutil.TempDir’s arguments are the same as -TempFile’s, but it returns a directory name +os.MkdirTemp’s arguments are the same as +CreateTemp’s, but it returns a directory name rather than an open file.

    -    dname, err := ioutil.TempDir("", "sampledir")
    +    dname, err := os.MkdirTemp("", "sampledir")
         check(err)
         fmt.Println("Temp dir name:", dname)
     
    @@ -199,7 +198,7 @@ prefixing them with our temporary directory.

         fname := filepath.Join(dname, "file1")
    -    err = ioutil.WriteFile(fname, []byte{1, 2}, 0666)
    +    err = os.WriteFile(fname, []byte{1, 2}, 0666)
         check(err)
     }
     
    @@ -235,7 +234,7 @@ prefixing them with our temporary directory.

    diff --git a/public/writing-files b/public/writing-files index 5591288ab..d26e7d52d 100644 --- a/public/writing-files +++ b/public/writing-files @@ -42,7 +42,7 @@ ones we saw earlier for reading.

    - +
    package main
     
    @@ -57,7 +57,6 @@ ones we saw earlier for reading.

    import (
         "bufio"
         "fmt"
    -    "io/ioutil"
         "os"
     )
     
    @@ -100,7 +99,7 @@ bytes) into a file.

         d1 := []byte("hello\ngo\n")
    -    err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
    +    err := os.WriteFile("/tmp/dat1", d1, 0644)
         check(err)
     
    @@ -282,7 +281,7 @@ we’ve just seen to the stdin and stdout streams. diff --git a/tools/generate.go b/tools/generate.go index ca4aabba1..c45a0a654 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -4,11 +4,7 @@ import ( "bytes" "crypto/sha1" "fmt" - "github.com/alecthomas/chroma" - "github.com/alecthomas/chroma/formatters/html" - "github.com/alecthomas/chroma/lexers" - "github.com/alecthomas/chroma/styles" - "io/ioutil" + "io" "net/http" "os" "os/exec" @@ -17,6 +13,11 @@ import ( "strings" "text/template" + "github.com/alecthomas/chroma" + "github.com/alecthomas/chroma/formatters/html" + "github.com/alecthomas/chroma/lexers" + "github.com/alecthomas/chroma/styles" + "github.com/russross/blackfriday/v2" ) @@ -41,9 +42,9 @@ func ensureDir(dir string) { } func copyFile(src, dst string) { - dat, err := ioutil.ReadFile(src) + dat, err := os.ReadFile(src) check(err) - err = ioutil.WriteFile(dst, dat, 0644) + err = os.WriteFile(dst, dat, 0644) check(err) } @@ -59,7 +60,7 @@ func pipe(bin string, arg []string, src string) []byte { check(err) err = in.Close() check(err) - bytes, err := ioutil.ReadAll(out) + bytes, err := io.ReadAll(out) check(err) err = cmd.Wait() check(err) @@ -74,7 +75,7 @@ func sha1Sum(s string) string { } func mustReadFile(path string) string { - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) check(err) return string(bytes) } @@ -141,11 +142,11 @@ func resetURLHashFile(codehash, code, sourcePath string) string { resp, err := http.Post("https://play.golang.org/share", "text/plain", payload) check(err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) check(err) urlkey := string(body) data := fmt.Sprintf("%s\n%s\n", codehash, urlkey) - ioutil.WriteFile(sourcePath, []byte(data), 0644) + os.WriteFile(sourcePath, []byte(data), 0644) return urlkey } diff --git a/tools/measure.go b/tools/measure.go index eb2637861..7c9d6beb1 100644 --- a/tools/measure.go +++ b/tools/measure.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -17,7 +16,7 @@ func check(err error) { } func readLines(path string) []string { - srcBytes, err := ioutil.ReadFile(path) + srcBytes, err := os.ReadFile(path) check(err) return strings.Split(string(srcBytes), "\n") } From a9507f5bbb3e26974ccecf7b3e5ec6fff5f6fcdc Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 30 Aug 2021 07:17:25 -0700 Subject: [PATCH 081/283] Clarify comment for the goroutines sample (#366) * Clarify comment for the goroutines sample. The current comment may be interpreted to say that the output must be interleaved, when in fact it doesn't have to be (it depends on the order the goroutines are run). Make the comment more permissive to avoid the confusion. Fixes #365 * Fix phrasing in comment --- examples/goroutines/goroutines.sh | 7 ++++--- public/goroutines | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/examples/goroutines/goroutines.sh b/examples/goroutines/goroutines.sh index 1d42ee279..38506edba 100644 --- a/examples/goroutines/goroutines.sh +++ b/examples/goroutines/goroutines.sh @@ -1,7 +1,8 @@ # When we run this program, we see the output of the -# blocking call first, then the interleaved output of the -# two goroutines. This interleaving reflects the -# goroutines being run concurrently by the Go runtime. +# blocking call first, then the output of the two +# goroutines. The goroutines' output may be interleaved, +# because goroutines are being run concurrently by the +# Go runtime. $ go run goroutines.go direct : 0 direct : 1 diff --git a/public/goroutines b/public/goroutines index 808ca2291..c6fbd8731 100644 --- a/public/goroutines +++ b/public/goroutines @@ -157,9 +157,10 @@ separate goroutines now. Wait for them to finish

    When we run this program, we see the output of the -blocking call first, then the interleaved output of the -two goroutines. This interleaving reflects the -goroutines being run concurrently by the Go runtime.

    +blocking call first, then the output of the two +goroutines. The goroutines’ output may be interleaved, +because goroutines are being run concurrently by the +Go runtime.

    From df8a378a22b204976bce4329e08299c99f3ed235 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 30 Aug 2021 07:24:48 -0700 Subject: [PATCH 082/283] Remove outdated link from an example gobyexample doesn't use pygments anymore, so the generate program doesn't spawn anything. --- examples/spawning-processes/spawning-processes.go | 6 +----- examples/spawning-processes/spawning-processes.hash | 4 ++-- public/spawning-processes | 8 ++------ 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/examples/spawning-processes/spawning-processes.go b/examples/spawning-processes/spawning-processes.go index b4db3abfc..908fad391 100644 --- a/examples/spawning-processes/spawning-processes.go +++ b/examples/spawning-processes/spawning-processes.go @@ -1,9 +1,5 @@ // Sometimes our Go programs need to spawn other, non-Go -// processes. For example, the syntax highlighting on this -// site is [implemented](https://github.com/mmcgrana/gobyexample/blob/master/tools/generate.go) -// by spawning a [`pygmentize`](http://pygments.org/) -// process from a Go program. Let's look at a few examples -// of spawning processes from Go. +// processes. package main diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index c0f815f56..9721992f4 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -b6e1e4b70a494be9f344a9f31aff520116d0ac24 -YJs_YtJY0sS +aaedc48f74409cef2b8e9ad624aa1c4639ce630d +s-T7gxeD7hH diff --git a/public/spawning-processes b/public/spawning-processes index c5781ece0..91ed4c0d0 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -28,11 +28,7 @@

    Sometimes our Go programs need to spawn other, non-Go -processes. For example, the syntax highlighting on this -site is implemented -by spawning a pygmentize -process from a Go program. Let’s look at a few examples -of spawning processes from Go.

    +processes.

    @@ -46,7 +42,7 @@ of spawning processes from Go.

    - +
    package main
     
    From 69efd4b8c091af10203ad9914e260a6fa9b7bc34 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 30 Aug 2021 09:18:16 -0700 Subject: [PATCH 083/283] Add note to waitgroups example about errgroup Fixes #308 --- examples/waitgroups/waitgroups.go | 5 +++++ examples/waitgroups/waitgroups.hash | 4 ++-- public/waitgroups | 21 ++++++++++++++++++--- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index c3c85801c..9e045d4dc 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -39,4 +39,9 @@ func main() { // Block until the WaitGroup counter goes back to 0; // all the workers notified they're done. wg.Wait() + + // Note that this approach has no straightforward way + // to propagate errors from workers. For more + // advanced use cases, consider using the + // [errgroup package](https://pkg.go.dev/golang.org/x/sync/errgroup). } diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index ab9311b42..2de67d2b2 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -fd77f5122e6df1669c0a2e0d2c4dfbd30631c21f -7mWXl0yVe6I +b87ababcf7e1ce54107252c658840097bb6060a7 +vXBl8zQpDYj diff --git a/public/waitgroups b/public/waitgroups index 2fc1a33d1..21feb59e2 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    - +
    package main
     
    @@ -165,10 +165,25 @@ counter for each.

    all the workers notified they’re done.

    - +
         wg.Wait()
    +
    + + + + + +

    Note that this approach has no straightforward way +to propagate errors from workers. For more +advanced use cases, consider using the +errgroup package.

    + + + + +
     }
     
    @@ -223,7 +238,7 @@ is likely to be different for each invocation.

    From 95a10027c6fe4558b7b6643727e738de5810b079 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 31 Aug 2021 06:23:50 -0700 Subject: [PATCH 084/283] Create initial GitHub actions workflow --- .github/workflows/test.yml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..424474a06 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,33 @@ +name: test + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + + build: + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + go-version: [1.17.x] + include: + - go-version: 1.16.x + os: ubuntu-latest + + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v2 + + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: ${{ matrix.go-version }} + + - name: Test + run: tools/build + env: + VERBOSE: 1 + TESTING: 1 From 5525fed5aeeed3a51ec033910ce10049f997d5d5 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 31 Aug 2021 06:28:21 -0700 Subject: [PATCH 085/283] Remove Travis and fix badge link in README --- .travis.yml | 16 ---------------- README.md | 2 +- 2 files changed, 1 insertion(+), 17 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 2e8f2ad03..000000000 --- a/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go - -go: - - 1.16 - - 1.17 - -before_install: - -install: - - go mod download - -script: - - tools/build - -env: - - VERBOSE=1 TESTING=1 diff --git a/README.md b/README.md index c548254ac..90c7f86ff 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ CloudFront, for example. ### Building -[![Build Status](https://app.travis-ci.com/mmcgrana/gobyexample.svg?branch=master)](https://app.travis-ci.com/mmcgrana/gobyexample) +[![Build Status](https://github.com/mmcgrana/gobyexample/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/mmcgrana/gobyexample/actions) To build the site you'll need Go installed. Run: From 91c8ceec2ce1f3f370a62c9ad9c225e994f42fc9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 1 Sep 2021 08:51:00 -0700 Subject: [PATCH 086/283] Adding a new example: recover With thanks to @LaryBattle for the discussion in #46 and @kilaka for the discussion in #344. Fixes #46 Closes #344 --- examples.txt | 1 + examples/recover/recover.go | 41 +++++++ examples/recover/recover.hash | 2 + examples/recover/recover.sh | 2 + public/collection-functions | 2 +- public/defer | 4 +- public/index.html | 2 + public/recover | 196 ++++++++++++++++++++++++++++++++++ 8 files changed, 247 insertions(+), 3 deletions(-) create mode 100644 examples/recover/recover.go create mode 100644 examples/recover/recover.hash create mode 100644 examples/recover/recover.sh create mode 100644 public/recover diff --git a/examples.txt b/examples.txt index 27b9df570..cadc52c72 100644 --- a/examples.txt +++ b/examples.txt @@ -41,6 +41,7 @@ Sorting Sorting by Functions Panic Defer +Recover Collection Functions String Functions String Formatting diff --git a/examples/recover/recover.go b/examples/recover/recover.go new file mode 100644 index 000000000..7cf728720 --- /dev/null +++ b/examples/recover/recover.go @@ -0,0 +1,41 @@ +// Go makes it possible to _recover_ from a panic, by +// using the `recover` built-in function. A `recover` can +// stop a `panic` from aborting the program and let it +// continue with execution instead. + +// An example of where this can be useful: a server +// wouldn't want to crash if one of the client connections +// exhibits a critical error. Instead, the server would +// want to close that connection and continue serving +// other clients. In fact, this is what Go's `net/http` +// does by default for HTTP servers. + +package main + +import "fmt" + +// This function panics. +func mayPanic() { + panic("a problem") +} + +func main() { + // `recover` must be called within a deferred function. + // When the enclosing function panics, the defer will + // activate and a `recover` call within it will catch + // the panic. + defer func() { + if r := recover(); r != nil { + // The return value of `recover` is the error raised in + // the call to `panic`. + fmt.Println("Recovered. Error:\n", r) + } + }() + + mayPanic() + + // This code will not run, because `mayPanic` panics. + // The execution of `main` stops at the point of the + // panic and resumes in the deferred closure. + fmt.Println("After mayPanic()") +} diff --git a/examples/recover/recover.hash b/examples/recover/recover.hash new file mode 100644 index 000000000..4aa77d592 --- /dev/null +++ b/examples/recover/recover.hash @@ -0,0 +1,2 @@ +053ecbddb4f4a1d881aa40086de99da4e78b9990 +Sk-SVdofEIZ diff --git a/examples/recover/recover.sh b/examples/recover/recover.sh new file mode 100644 index 000000000..df26fc4f4 --- /dev/null +++ b/examples/recover/recover.sh @@ -0,0 +1,2 @@ +Recovered. Error: + a problem diff --git a/public/collection-functions b/public/collection-functions index 3dc5de019..ae5f9c680 100644 --- a/public/collection-functions +++ b/public/collection-functions @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'defer'; + window.location.href = 'recover'; } diff --git a/public/defer b/public/defer index 647f667a1..00c1a13ec 100644 --- a/public/defer +++ b/public/defer @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'collection-functions'; + window.location.href = 'recover'; } } @@ -195,7 +195,7 @@ after being written.

    - Next example: Collection Functions. + Next example: Recover.

    Go by Example

  • Defer
  • +
  • Recover
  • +
  • Collection Functions
  • String Functions
  • diff --git a/public/recover b/public/recover new file mode 100644 index 000000000..64cf86acb --- /dev/null +++ b/public/recover @@ -0,0 +1,196 @@ + + + + + Go by Example: Recover + + + + +
    +

    Go by Example: Recover

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Go makes it possible to recover from a panic, by +using the recover built-in function. A recover can +stop a panic from aborting the program and let it +continue with execution instead.

    + +
    + + +
    +

    An example of where this can be useful: a server +wouldn’t want to crash if one of the client connections +exhibits a critical error. Instead, the server would +want to close that connection and continue serving +other clients. In fact, this is what Go’s net/http +does by default for HTTP servers.

    + +
    + + +
    + + + +
    package main
    +
    +
    + + + +
    import "fmt"
    +
    +
    +

    This function panics.

    + +
    + +
    +func mayPanic() {
    +    panic("a problem")
    +}
    +
    +
    +

    recover must be called within a deferred function. +When the enclosing function panics, the defer will +activate and a recover call within it will catch +the panic.

    + +
    + +
    func main() {
    +
    +
    +

    The return value of recover is the error raised in +the call to panic.

    + +
    + +
        defer func() {
    +        if r := recover(); r != nil {
    +
    +
    + + + +
                fmt.Println("Recovered. Error:\n", r)
    +        }
    +    }()
    +
    +
    + + + +
        mayPanic()
    +
    +
    +

    This code will not run, because mayPanic panics. +The execution of main stops at the point of the +panic and resumes in the deferred closure.

    + +
    + +
    +    fmt.Println("After mayPanic()")
    +}
    +
    +
    + + + + + + + + +
    + + + +
    Recovered. Error:
    + a problem
    +
    + + +

    + Next example: Collection Functions. +

    + + +
    + + + + From 2acace92c06cdad3262efe38fb767c5a7c20d3fa Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 05:42:07 -0700 Subject: [PATCH 087/283] Clarify the panic example with a comment about unreachable code Fixes #390 --- examples/panic/panic.sh | 5 +++++ public/panic | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/examples/panic/panic.sh b/examples/panic/panic.sh index a851be97f..c5a7e1d8c 100644 --- a/examples/panic/panic.sh +++ b/examples/panic/panic.sh @@ -1,6 +1,11 @@ # Running this program will cause it to panic, print # an error message and goroutine traces, and exit with # a non-zero status. + +# When first panic in `main` fires, the program exits +# without reaching the rest of the code. If you'd like +# to see the program try to create a temp file, comment +# the first panic out. $ go run panic.go panic: a problem diff --git a/public/panic b/public/panic index 2da4cff6f..cb3ce8724 100644 --- a/public/panic +++ b/public/panic @@ -117,6 +117,20 @@ returns an error value that we don’t know how to an error message and goroutine traces, and exit with a non-zero status.

    + + + + + + + + + +

    When first panic in main fires, the program exits +without reaching the rest of the code. If you’d like +to see the program try to create a temp file, comment +the first panic out.

    + @@ -166,7 +180,7 @@ to use error-indicating return values wherever possible.

    From d037acd3e6130c362133f1463fd4735db533717d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 05:53:30 -0700 Subject: [PATCH 088/283] Update Recursion example to demonstrate recursive closures Fixes #389 --- examples/recursion/recursion.go | 17 ++++++++ examples/recursion/recursion.hash | 4 +- examples/recursion/recursion.sh | 1 + public/recursion | 64 +++++++++++++++++++++++++++++-- 4 files changed, 80 insertions(+), 6 deletions(-) diff --git a/examples/recursion/recursion.go b/examples/recursion/recursion.go index a88b1e59e..fbc022b42 100644 --- a/examples/recursion/recursion.go +++ b/examples/recursion/recursion.go @@ -17,4 +17,21 @@ func fact(n int) int { func main() { fmt.Println(fact(7)) + + // Closures can also be recursive, but this requires the + // closure to be declared with a typed `var` explicitly + // before it's defined. + var fib func(n int) int + + fib = func(n int) int { + if n < 2 { + return n + } + return fib(n-1) + fib(n-2) + + // Since `fib` was previously declared in `main`, Go + // knows which function to call with `fib` here. + } + + fmt.Println(fib(7)) } diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index ac2db783c..2a19ed1ad 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -9bfb2f870007082835a3c0efaac9aa1c3bc2c15c -smWim1q9ofu +55d9633a4f0fd0eac2f243b2a2ddb35ae91ed4a9 +LnBMavPrkuf diff --git a/examples/recursion/recursion.sh b/examples/recursion/recursion.sh index 53b8e15a8..ac854846a 100644 --- a/examples/recursion/recursion.sh +++ b/examples/recursion/recursion.sh @@ -1,2 +1,3 @@ $ go run recursion.go 5040 +13 diff --git a/public/recursion b/public/recursion index 28a9475f1..f218a0505 100644 --- a/public/recursion +++ b/public/recursion @@ -43,7 +43,7 @@ Here’s a classic factorial example.

    - +
    package main
     
    @@ -83,10 +83,65 @@ base case of fact(0).

    - +
    func main() {
         fmt.Println(fact(7))
    +
    + + + + + +

    Closures can also be recursive, but this requires the +closure to be declared with a typed var explicitly +before it’s defined.

    + + + + +
    +    var fib func(n int) int
    +
    + + + + + + + + + +
        fib = func(n int) int {
    +        if n < 2 {
    +            return n
    +        }
    +        return fib(n-1) + fib(n-2)
    +
    + + + + + +

    Since fib was previously declared in main, Go +knows which function to call with fib here.

    + + + + +
    +    }
    +
    + + + + + + + + + +
        fmt.Println(fib(7))
     }
     
    @@ -103,7 +158,8 @@ base case of fact(0).

    $ go run recursion.go 
    -5040
    +5040 +13
    @@ -120,7 +176,7 @@ base case of fact(0).

    From 364c6642114fa85a3a2401b605f5b35360d9d247 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 06:19:19 -0700 Subject: [PATCH 089/283] Initial version of the Go uploader to S3 It works using a test bucket --- go.mod | 17 +++++++++- go.sum | 31 +++++++++++++++++++ tools/upload.go | 82 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 tools/upload.go diff --git a/go.mod b/go.mod index af76a5e0b..908809f02 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,23 @@ module github.com/mmcgrana/gobyexample -go 1.15 +go 1.17 require ( github.com/alecthomas/chroma v0.8.2 github.com/russross/blackfriday/v2 v2.1.0 ) + +require ( + github.com/aws/aws-sdk-go-v2 v1.9.0 // indirect + github.com/aws/aws-sdk-go-v2/config v1.7.0 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.4.0 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0 // indirect + github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 // indirect + github.com/aws/smithy-go v1.8.0 // indirect +) diff --git a/go.sum b/go.sum index b1e8da40d..a2bcae3b7 100644 --- a/go.sum +++ b/go.sum @@ -7,6 +7,30 @@ github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBo github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY= github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= +github.com/aws/aws-sdk-go-v2 v1.9.0 h1:+S+dSqQCN3MSU5vJRu1HqHrq00cJn6heIMU7X9hcsoo= +github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= +github.com/aws/aws-sdk-go-v2/config v1.7.0 h1:J2cZ7qe+3IpqBEXnHUrFrOjoB9BlsXg7j53vxcl5IVg= +github.com/aws/aws-sdk-go-v2/config v1.7.0/go.mod h1:w9+nMZ7soXCe5nT46Ri354SNhXDQ6v+V5wqDjnZE+GY= +github.com/aws/aws-sdk-go-v2/credentials v1.4.0 h1:kmvesfjY861FzlCU9mvAfe01D9aeXcG2ZuC+k9F2YLM= +github.com/aws/aws-sdk-go-v2/credentials v1.4.0/go.mod h1:dgGR+Qq7Wjcd4AOAW5Rf5Tnv3+x7ed6kETXyS9WCuAY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0 h1:OxTAgH8Y4BXHD6PGCJ8DHx2kaZPCQfSTqmDsdRZFezE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0/go.mod h1:CpNzHK9VEFUCknu50kkB8z58AH2B5DvPP7ea1LHve/Y= +github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2 h1:d95cddM3yTm4qffj3P6EnP+TzX1SSkWaQypXSgT/hpA= +github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2/go.mod h1:BQV0agm+JEhqR+2RT5e1XTFIDcAAV0eW6z2trp+iduw= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0 h1:gceOysEWNNwLd6cki65IMBZ4WAM0MwgBQq2n7kejoT8= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0/go.mod h1:v8ygadNyATSm6elwJ/4gzJwcFhri9RqS8skgHKiwXPU= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0 h1:VNJ5NLBteVXEwE2F1zEXVmyIH58mZ6kIQGJoC7C+vkg= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0/go.mod h1:R1KK+vY8AfalhG1AOu5e35pOD2SdoPKQCFLTvnxiohk= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0 h1:B/1pIeV/oFnrOwhoMA6ASX+qT4FzMqn1MYsPiIXgMqQ= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0/go.mod h1:LKb3cKNQIMh+itGnEpKGcnL/6OIjPZqrtYah1w5f+3o= +github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 h1:nR9j0xMxpXk6orC/C03fbHNrbb1NaXp8LdVV7V1oVLE= +github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0/go.mod h1:Qit9H3zjAmF7CLHOkrepE9b2ndX/2l3scstsM5g2jSk= +github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 h1:sHXMIKYS6YiLPzmKSvDpPmOpJDHxmAUgbiF49YNVztg= +github.com/aws/aws-sdk-go-v2/service/sso v1.4.0/go.mod h1:+1fpWnL96DL23aXPpMGbsmKe8jLTEfbjuQoA4WS1VaA= +github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 h1:1at4e5P+lvHNl2nUktdM2/v+rpICg/QSEr9TO/uW9vU= +github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= +github.com/aws/smithy-go v1.8.0 h1:AEwwwXQZtUwP5Mz506FeXXrKBe0jA8gVM+1gEcSRooc= +github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -14,6 +38,10 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= @@ -33,3 +61,6 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200413165638-669c56c373c4 h1:opSr2sbRXk5X5/givKrrKj9HXxFpW2sdCiP8MJSKLQY= golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/tools/upload.go b/tools/upload.go new file mode 100644 index 000000000..193148c91 --- /dev/null +++ b/tools/upload.go @@ -0,0 +1,82 @@ +// Uploads the generated site from the public/ directory to the S3 bucket from +// which it's served. +// To invoke this program, the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY +// env vars have to be set appropriately, and the -region and -bucket flags +// have to be passed in. +package main + +import ( + "context" + "flag" + "log" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +// guessContentType guesses the HTTP content type appropriate for the given +// filename. +func guessContentType(filename string) string { + switch filepath.Ext(filename) { + case ".ico": + return "image/x-icon" + case ".png": + return "image/png" + case ".css": + return "text/css" + default: + return "text/html" + } +} + +func main() { + region := flag.String("region", "", "S3 region") + bucket := flag.String("bucket", "", "S3 bucket name") + flag.Parse() + + if len(*region) == 0 || len(*bucket) == 0 { + log.Fatalf("region and bucket must be specified [region=%s, bucket=%s]", *region, *bucket) + } + + cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(*region)) + if err != nil { + log.Fatal(err) + } + + // Create an Amazon S3 service client + client := s3.NewFromConfig(cfg) + + publicDir := "./public/" + c, err := os.ReadDir(publicDir) + if err != nil { + log.Fatal(err) + } + + for _, entry := range c { + if !entry.IsDir() { + file, err := os.Open(filepath.Join(publicDir, entry.Name())) + if err != nil { + log.Fatal(err) + } + defer file.Close() + + contentType := guessContentType(entry.Name()) + log.Printf("Uploading %s (%s)", entry.Name(), contentType) + + input := &s3.PutObjectInput{ + Bucket: bucket, + Key: aws.String(entry.Name()), + Body: file, + ContentType: aws.String(contentType), + } + + _, err = client.PutObject(context.TODO(), input) + if err != nil { + log.Fatal(err) + } + } + } +} From 198349f68365246bb4c44762bd3c8b0f811533f2 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 06:40:02 -0700 Subject: [PATCH 090/283] Add comments and clean up code --- tools/upload.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tools/upload.go b/tools/upload.go index 193148c91..50dbbbf1e 100644 --- a/tools/upload.go +++ b/tools/upload.go @@ -46,9 +46,10 @@ func main() { log.Fatal(err) } - // Create an Amazon S3 service client client := s3.NewFromConfig(cfg) + // The whole contents of the public/ directory are uploaded. This code assumes + // the directory structure is flat - there are no subdirectories. publicDir := "./public/" c, err := os.ReadDir(publicDir) if err != nil { @@ -66,14 +67,14 @@ func main() { contentType := guessContentType(entry.Name()) log.Printf("Uploading %s (%s)", entry.Name(), contentType) - input := &s3.PutObjectInput{ + cfg := &s3.PutObjectInput{ Bucket: bucket, Key: aws.String(entry.Name()), Body: file, ContentType: aws.String(contentType), } - _, err = client.PutObject(context.TODO(), input) + _, err = client.PutObject(context.TODO(), cfg) if err != nil { log.Fatal(err) } From 68cc690ca4295cd0bd9afb64974ff33a4d13441b Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 06:42:17 -0700 Subject: [PATCH 091/283] Add a wrapper script for tools/upload.go The script sets up the -region and -bucket flags to point to the right S3 location. AWS_* env vars should still be set manually. The old Ruby uploading code is moved to upload-ruby-old for now (will be deleted later) --- tools/upload | 43 ++----------------------------------------- tools/upload-ruby-old | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 41 deletions(-) create mode 100755 tools/upload-ruby-old diff --git a/tools/upload b/tools/upload index b1eda68ed..5ca34efbe 100755 --- a/tools/upload +++ b/tools/upload @@ -1,42 +1,3 @@ -#!/usr/bin/env ruby +#!/bin/bash -# Upload the contents in public/ to the S3 bucket from which we serve -# gobyexample.com. We use this instead of `aws iam sync` because that command -# doesn't correctly guess the text/html mime time of the extension-less files. -# We didn't write this in Go because we had already written it in Ruby for -# another website and didn't want to re-write it. - -require "aws-sdk" -require "set" - -s3 = Aws::S3::Client.new( - region: "us-east-1", - credentials: Aws::Credentials.new(ENV["AWS_ACCESS_KEY_ID"], ENV["AWS_SECRET_ACCESS_KEY"]) -) - -# (Re-)upload each file to S3. We're not worried about what's currently there. -Dir.glob("./public/**/**").each do |local_path| - next if File.directory?(local_path) - - # Derive final path. - s3_path = local_path.sub("./public/", "") - - # Infer content type, including for HTML files that need pretty URLs. - content_type = - case s3_path - when /\.ico$/ then "image/x-icon" - when /\.png$/ then "image/png" - when /\.css$/ then "text/css" - else "text/html" - end - - puts("Uploading #{s3_path} (#{content_type})") - - File.open(local_path, "rb") do |local_file| - s3.put_object( - bucket: "gobyexample.com", - key: s3_path, - content_type: content_type, - body: local_file) - end -end +exec go run tools/upload.go -region us-east-1 -bucket gobyexample.com diff --git a/tools/upload-ruby-old b/tools/upload-ruby-old new file mode 100755 index 000000000..b1eda68ed --- /dev/null +++ b/tools/upload-ruby-old @@ -0,0 +1,42 @@ +#!/usr/bin/env ruby + +# Upload the contents in public/ to the S3 bucket from which we serve +# gobyexample.com. We use this instead of `aws iam sync` because that command +# doesn't correctly guess the text/html mime time of the extension-less files. +# We didn't write this in Go because we had already written it in Ruby for +# another website and didn't want to re-write it. + +require "aws-sdk" +require "set" + +s3 = Aws::S3::Client.new( + region: "us-east-1", + credentials: Aws::Credentials.new(ENV["AWS_ACCESS_KEY_ID"], ENV["AWS_SECRET_ACCESS_KEY"]) +) + +# (Re-)upload each file to S3. We're not worried about what's currently there. +Dir.glob("./public/**/**").each do |local_path| + next if File.directory?(local_path) + + # Derive final path. + s3_path = local_path.sub("./public/", "") + + # Infer content type, including for HTML files that need pretty URLs. + content_type = + case s3_path + when /\.ico$/ then "image/x-icon" + when /\.png$/ then "image/png" + when /\.css$/ then "text/css" + else "text/html" + end + + puts("Uploading #{s3_path} (#{content_type})") + + File.open(local_path, "rb") do |local_file| + s3.put_object( + bucket: "gobyexample.com", + key: s3_path, + content_type: content_type, + body: local_file) + end +end From b4568f30258828b7de8f77d84ee52251f6557136 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 10:26:17 -0700 Subject: [PATCH 092/283] Refactor page footer to separate template Fixes #387 --- public/arrays | 8 +++++--- public/atomic-counters | 8 +++++--- public/base64-encoding | 8 +++++--- public/channel-buffering | 8 +++++--- public/channel-directions | 8 +++++--- public/channel-synchronization | 8 +++++--- public/channels | 8 +++++--- public/closing-channels | 8 +++++--- public/closures | 8 +++++--- public/collection-functions | 8 +++++--- public/command-line-arguments | 8 +++++--- public/command-line-flags | 8 +++++--- public/command-line-subcommands | 8 +++++--- public/constants | 8 +++++--- public/context | 8 +++++--- public/defer | 8 +++++--- public/directories | 8 +++++--- public/environment-variables | 8 +++++--- public/epoch | 8 +++++--- public/errors | 8 +++++--- public/execing-processes | 8 +++++--- public/exit | 8 +++++--- public/file-paths | 8 +++++--- public/for | 8 +++++--- public/functions | 8 +++++--- public/goroutines | 8 +++++--- public/hello-world | 8 +++++--- public/http-clients | 8 +++++--- public/http-servers | 8 +++++--- public/if-else | 8 +++++--- public/index.html | 8 +++++--- public/interfaces | 8 +++++--- public/json | 8 +++++--- public/line-filters | 8 +++++--- public/maps | 8 +++++--- public/methods | 8 +++++--- public/multiple-return-values | 8 +++++--- public/mutexes | 8 +++++--- public/non-blocking-channel-operations | 8 +++++--- public/number-parsing | 8 +++++--- public/panic | 8 +++++--- public/pointers | 8 +++++--- public/random-numbers | 8 +++++--- public/range | 8 +++++--- public/range-over-channels | 8 +++++--- public/rate-limiting | 8 +++++--- public/reading-files | 8 +++++--- public/recover | 8 +++++--- public/recursion | 8 +++++--- public/regular-expressions | 8 +++++--- public/select | 8 +++++--- public/sha1-hashes | 8 +++++--- public/signals | 8 +++++--- public/slices | 8 +++++--- public/sorting | 8 +++++--- public/sorting-by-functions | 8 +++++--- public/spawning-processes | 8 +++++--- public/stateful-goroutines | 8 +++++--- public/string-formatting | 8 +++++--- public/string-functions | 8 +++++--- public/structs | 8 +++++--- public/switch | 8 +++++--- public/temporary-files-and-directories | 8 +++++--- public/testing | 8 +++++--- public/tickers | 8 +++++--- public/time | 8 +++++--- public/time-formatting-parsing | 8 +++++--- public/timeouts | 8 +++++--- public/timers | 8 +++++--- public/url-parsing | 8 +++++--- public/values | 8 +++++--- public/variables | 8 +++++--- public/variadic-functions | 8 +++++--- public/waitgroups | 8 +++++--- public/worker-pools | 8 +++++--- public/writing-files | 8 +++++--- public/xml | 8 +++++--- templates/example.tmpl | 4 +--- templates/footer.tmpl | 5 +++++ templates/index.tmpl | 4 +--- tools/generate.go | 8 ++++++-- 81 files changed, 398 insertions(+), 239 deletions(-) create mode 100644 templates/footer.tmpl diff --git a/public/arrays b/public/arrays index f2ddcb1b6..f361bac76 100644 --- a/public/arrays +++ b/public/arrays @@ -196,9 +196,11 @@ typical Go. We’ll look at slices next.

    Next example: Slices.

    - + + + From 2570a9c13658c6a42cfa41aa93ef2334c187cf88 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 8 Sep 2021 05:49:47 -0700 Subject: [PATCH 096/283] Remove old Ruby-based upload script The new Go-based code works fine and has successfully uploaded the site several times now. This removes a dependency on a non-Go flow which should make development easier. --- README.md | 1 - tools/upload-ruby-old | 42 ------------------------------------------ 2 files changed, 43 deletions(-) delete mode 100755 tools/upload-ruby-old diff --git a/README.md b/README.md index 90c7f86ff..baea15948 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,6 @@ and open `http://127.0.0.1:8000/` in your browser. To upload the site: ```console -$ gem install aws-sdk $ export AWS_ACCESS_KEY_ID=... $ export AWS_SECRET_ACCESS_KEY=... $ tools/upload diff --git a/tools/upload-ruby-old b/tools/upload-ruby-old deleted file mode 100755 index b1eda68ed..000000000 --- a/tools/upload-ruby-old +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env ruby - -# Upload the contents in public/ to the S3 bucket from which we serve -# gobyexample.com. We use this instead of `aws iam sync` because that command -# doesn't correctly guess the text/html mime time of the extension-less files. -# We didn't write this in Go because we had already written it in Ruby for -# another website and didn't want to re-write it. - -require "aws-sdk" -require "set" - -s3 = Aws::S3::Client.new( - region: "us-east-1", - credentials: Aws::Credentials.new(ENV["AWS_ACCESS_KEY_ID"], ENV["AWS_SECRET_ACCESS_KEY"]) -) - -# (Re-)upload each file to S3. We're not worried about what's currently there. -Dir.glob("./public/**/**").each do |local_path| - next if File.directory?(local_path) - - # Derive final path. - s3_path = local_path.sub("./public/", "") - - # Infer content type, including for HTML files that need pretty URLs. - content_type = - case s3_path - when /\.ico$/ then "image/x-icon" - when /\.png$/ then "image/png" - when /\.css$/ then "text/css" - else "text/html" - end - - puts("Uploading #{s3_path} (#{content_type})") - - File.open(local_path, "rb") do |local_file| - s3.put_object( - bucket: "gobyexample.com", - key: s3_path, - content_type: content_type, - body: local_file) - end -end From 4de485a514606b62c04dfefe8c5cbd62a8991644 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 10 Sep 2021 05:56:40 -0700 Subject: [PATCH 097/283] Add partial prefixes in some places to regular-expressions See #394 for details. This closes #288 by providing a lighter-weight approach. --- .../regular-expressions/regular-expressions.go | 6 +++--- .../regular-expressions.hash | 4 ++-- .../regular-expressions/regular-expressions.sh | 8 ++++---- public/regular-expressions | 18 +++++++++--------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/examples/regular-expressions/regular-expressions.go b/examples/regular-expressions/regular-expressions.go index f05d26955..e10e934a4 100644 --- a/examples/regular-expressions/regular-expressions.go +++ b/examples/regular-expressions/regular-expressions.go @@ -31,7 +31,7 @@ func main() { // This also finds the first match but returns the // start and end indexes for the match instead of the // matching text. - fmt.Println(r.FindStringIndex("peach punch")) + fmt.Println("idx:", r.FindStringIndex("peach punch")) // The `Submatch` variants include information about // both the whole-pattern matches and the submatches @@ -50,7 +50,7 @@ func main() { // These `All` variants are available for the other // functions we saw above as well. - fmt.Println(r.FindAllStringSubmatchIndex( + fmt.Println("all:", r.FindAllStringSubmatchIndex( "peach punch pinch", -1)) // Providing a non-negative integer as the second @@ -70,7 +70,7 @@ func main() { // returning an error, which makes it safer to use for // global variables. r = regexp.MustCompile("p([a-z]+)ch") - fmt.Println(r) + fmt.Println("regexp:", r) // The `regexp` package can also be used to replace // subsets of strings with other values. diff --git a/examples/regular-expressions/regular-expressions.hash b/examples/regular-expressions/regular-expressions.hash index bffd78787..63ee8ef17 100644 --- a/examples/regular-expressions/regular-expressions.hash +++ b/examples/regular-expressions/regular-expressions.hash @@ -1,2 +1,2 @@ -c0dd720036ac70269ce233bf47c5d6aefd43161f -LEKGY_d3Nu_P +5c3bcf9f8c61fc074143f766c4517e445a6d9b0f +htCqJrLdh9Q diff --git a/examples/regular-expressions/regular-expressions.sh b/examples/regular-expressions/regular-expressions.sh index 1f3882c34..ec4f20145 100644 --- a/examples/regular-expressions/regular-expressions.sh +++ b/examples/regular-expressions/regular-expressions.sh @@ -1,15 +1,15 @@ -$ go run regular-expressions.go +$ go run regular-expressions.go true true peach -[0 5] +idx: [0 5] [peach ea] [0 5 1 3] [peach punch pinch] -[[0 5 1 3] [6 11 7 9] [12 17 13 15]] +all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]] [peach punch] true -p([a-z]+)ch +regexp: p([a-z]+)ch a a PEACH diff --git a/public/regular-expressions b/public/regular-expressions index f1eeb4a20..e6592eaf3 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -43,7 +43,7 @@ in Go.

    - +
    package main
     
    @@ -141,7 +141,7 @@ matching text.

    -    fmt.Println(r.FindStringIndex("peach punch"))
    +    fmt.Println("idx:", r.FindStringIndex("peach punch"))
     
    @@ -200,7 +200,7 @@ functions we saw above as well.

    -    fmt.Println(r.FindAllStringSubmatchIndex(
    +    fmt.Println("all:", r.FindAllStringSubmatchIndex(
             "peach punch pinch", -1))
     
    @@ -250,7 +250,7 @@ global variables.

         r = regexp.MustCompile("p([a-z]+)ch")
    -    fmt.Println(r)
    +    fmt.Println("regexp:", r)
     
    @@ -296,18 +296,18 @@ text with a given function.

    -
    $ go run regular-expressions.go 
    +          
    $ go run regular-expressions.go
     true
     true
     peach
    -[0 5]
    +idx: [0 5]
     [peach ea]
     [0 5 1 3]
     [peach punch pinch]
    -[[0 5 1 3] [6 11 7 9] [12 17 13 15]]
    +all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
     [peach punch]
     true
    -p([a-z]+)ch
    +regexp: p([a-z]+)ch
     a <fruit>
     a PEACH
    @@ -340,7 +340,7 @@ the regexp package docs From b1ef4998210b0d692bda73589c3e7478c428c29c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 10 Sep 2021 06:11:56 -0700 Subject: [PATCH 098/283] Rewrite the WaitGroup example to be more idiomatic A wrapper closure invokes wg.Done Still mention the pass-by-pointer requirements on the WaitGroup Fixes #278 --- examples/waitgroups/waitgroups.go | 26 +++++++++---- examples/waitgroups/waitgroups.hash | 4 +- public/waitgroups | 57 +++++++++++++++++------------ 3 files changed, 54 insertions(+), 33 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index 9e045d4dc..c32cd244e 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -10,12 +10,7 @@ import ( ) // This is the function we'll run in every goroutine. -// Note that a WaitGroup must be passed to functions by -// pointer. -func worker(id int, wg *sync.WaitGroup) { - // On return, notify the WaitGroup that we're done. - defer wg.Done() - +func worker(id int) { fmt.Printf("Worker %d starting\n", id) // Sleep to simulate an expensive task. @@ -26,14 +21,29 @@ func worker(id int, wg *sync.WaitGroup) { func main() { // This WaitGroup is used to wait for all the - // goroutines launched here to finish. + // goroutines launched here to finish. Note: if a WaitGroup is + // explicitly passed into functions, it should be done *by pointer*. + // This would be important if, for example, our worker had to launch + // additional goroutines. var wg sync.WaitGroup // Launch several goroutines and increment the WaitGroup // counter for each. for i := 1; i <= 5; i++ { wg.Add(1) - go worker(i, &wg) + // Avoid re-use of the same `i` value in each goroutine closure. + // See [the FAQ](https://golang.org/doc/faq#closures_and_goroutines) + // for more details. + i := i + + // Wrap the worker call in a closure that makes sure to tell + // the WaitGroup that this worker is done. This way the worker + // itself does not have to be aware of the concurrency primitives + // involved in its execution. + go func() { + defer wg.Done() + worker(i) + }() } // Block until the WaitGroup counter goes back to 0; diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index 2de67d2b2..9dea057a8 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -b87ababcf7e1ce54107252c658840097bb6060a7 -vXBl8zQpDYj +58031ceb701a1cab27498efd89adadbf1ea6b3e6 +vmjCBfN6MJE diff --git a/public/waitgroups b/public/waitgroups index b8379836c..d1b609a42 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    - +
    package main
     
    @@ -65,28 +65,29 @@ use a wait group.

    -

    This is the function we’ll run in every goroutine. -Note that a WaitGroup must be passed to functions by -pointer.

    +

    This is the function we’ll run in every goroutine.

    -func worker(id int, wg *sync.WaitGroup) {
    +func worker(id int) {
    +    fmt.Printf("Worker %d starting\n", id)
     
    -

    On return, notify the WaitGroup that we’re done.

    +

    Sleep to simulate an expensive task.

    -    defer wg.Done()
    +    time.Sleep(time.Second)
    +    fmt.Printf("Worker %d done\n", id)
    +}
     
    @@ -97,63 +98,73 @@ pointer.

    -
        fmt.Printf("Worker %d starting\n", id)
    +          
    func main() {
     
    -

    Sleep to simulate an expensive task.

    +

    This WaitGroup is used to wait for all the +goroutines launched here to finish. Note: if a WaitGroup is +explicitly passed into functions, it should be done by pointer. +This would be important if, for example, our worker had to launch +additional goroutines.

    -    time.Sleep(time.Second)
    -    fmt.Printf("Worker %d done\n", id)
    -}
    +    var wg sync.WaitGroup
     
    - +

    Launch several goroutines and increment the WaitGroup +counter for each.

    + -
    func main() {
    +          
    +    for i := 1; i <= 5; i++ {
    +        wg.Add(1)
     
    -

    This WaitGroup is used to wait for all the -goroutines launched here to finish.

    +

    Avoid re-use of the same i value in each goroutine closure. +See the FAQ +for more details.

    -    var wg sync.WaitGroup
    +        i := i
     
    -

    Launch several goroutines and increment the WaitGroup -counter for each.

    +

    Wrap the worker call in a closure that makes sure to tell +the WaitGroup that this worker is done. This way the worker +itself does not have to be aware of the concurrency primitives +involved in its execution.

    -    for i := 1; i <= 5; i++ {
    -        wg.Add(1)
    -        go worker(i, &wg)
    +        go func() {
    +            defer wg.Done()
    +            worker(i)
    +        }()
         }
     
    @@ -240,7 +251,7 @@ is likely to be different for each invocation.

    From 8367c3ee2c51363b6d4cd8c49a185515d87951ae Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 10 Sep 2021 06:35:31 -0700 Subject: [PATCH 099/283] Update .gitattributes We no longer have a `vendor` folder. Make public/** matching stronger --- .gitattributes | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitattributes b/.gitattributes index ac8f8c3d4..c46259652 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,2 @@ -public/* linguist-generated=true -vendor/* linguist-vendored=true +public/** linguist-generated From eac677615948ee32eb70388820993137af1edba9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 10 Sep 2021 07:19:33 -0700 Subject: [PATCH 100/283] Clarify comment Remove an ambiguous part of the comment that can cause confusion - passing a WaitGroup by pointer is always mandatory. --- examples/waitgroups/waitgroups.go | 2 -- examples/waitgroups/waitgroups.hash | 4 ++-- public/waitgroups | 6 ++---- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index c32cd244e..5ac70b52f 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -23,8 +23,6 @@ func main() { // This WaitGroup is used to wait for all the // goroutines launched here to finish. Note: if a WaitGroup is // explicitly passed into functions, it should be done *by pointer*. - // This would be important if, for example, our worker had to launch - // additional goroutines. var wg sync.WaitGroup // Launch several goroutines and increment the WaitGroup diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index 9dea057a8..5fdeaf5d4 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -58031ceb701a1cab27498efd89adadbf1ea6b3e6 -vmjCBfN6MJE +66d1c1cdb7e60f63b9b30938aa9c63b2262463ac +S98GjeaGBX0 diff --git a/public/waitgroups b/public/waitgroups index d1b609a42..6b0da369d 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    - +
    package main
     
    @@ -107,9 +107,7 @@ use a wait group.

    This WaitGroup is used to wait for all the goroutines launched here to finish. Note: if a WaitGroup is -explicitly passed into functions, it should be done by pointer. -This would be important if, for example, our worker had to launch -additional goroutines.

    +explicitly passed into functions, it should be done by pointer.

    From 15c92ee528587c0d152870ec4ce32a69873326b9 Mon Sep 17 00:00:00 2001 From: Gautam Kotian Date: Mon, 20 Sep 2021 15:37:55 +0200 Subject: [PATCH 101/283] Minor fixes (#396) * Add missing word * Rename `boolPtr` to `forkPtr` This is in order to be consistent with the other flags `wordPtr` & `numbPtr` which are based on the name of the flag and not the type of the flag. --- CONTRIBUTING.md | 2 +- examples/command-line-flags/command-line-flags.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 40439fe1b..5a135481e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,5 +14,5 @@ Thanks for your interest in contributing to Go by Example! first_. * We're not going to change the navigation of the site, in particular adding - a "previous section" link or an "index" link other than the on the title + a "previous section" link or an "index" link other than the one on the title text. diff --git a/examples/command-line-flags/command-line-flags.go b/examples/command-line-flags/command-line-flags.go index 96647f5ff..886de077f 100644 --- a/examples/command-line-flags/command-line-flags.go +++ b/examples/command-line-flags/command-line-flags.go @@ -26,7 +26,7 @@ func main() { // This declares `numb` and `fork` flags, using a // similar approach to the `word` flag. numbPtr := flag.Int("numb", 42, "an int") - boolPtr := flag.Bool("fork", false, "a bool") + forkPtr := flag.Bool("fork", false, "a bool") // It's also possible to declare an option that uses an // existing var declared elsewhere in the program. @@ -45,7 +45,7 @@ func main() { // to get the actual option values. fmt.Println("word:", *wordPtr) fmt.Println("numb:", *numbPtr) - fmt.Println("fork:", *boolPtr) + fmt.Println("fork:", *forkPtr) fmt.Println("svar:", svar) fmt.Println("tail:", flag.Args()) } From e10011f90fdc24c80584b1d9809d1b9fc60c3cef Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 20 Sep 2021 06:38:52 -0700 Subject: [PATCH 102/283] Rebuild example to public after previous PR's change --- examples/command-line-flags/command-line-flags.hash | 4 ++-- public/command-line-flags | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/command-line-flags/command-line-flags.hash b/examples/command-line-flags/command-line-flags.hash index f59c45a7e..5c128dac6 100644 --- a/examples/command-line-flags/command-line-flags.hash +++ b/examples/command-line-flags/command-line-flags.hash @@ -1,2 +1,2 @@ -e86d2c60cee18fa926ce1eea60bd082837bd950b -fD0SmjD4GdZ +08e716a5ee3b5f74ef826d7b5ce157cb3b44c4f7 +-zzqphwtdJq diff --git a/public/command-line-flags b/public/command-line-flags index 15175b3fc..6e5b46e43 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -44,7 +44,7 @@ command-line flag.

    - +
    package main
     
    @@ -107,7 +107,7 @@ similar approach to the word flag.

         numbPtr := flag.Int("numb", 42, "an int")
    -    boolPtr := flag.Bool("fork", false, "a bool")
    +    forkPtr := flag.Bool("fork", false, "a bool")
     
    @@ -156,7 +156,7 @@ to get the actual option values.

         fmt.Println("word:", *wordPtr)
         fmt.Println("numb:", *numbPtr)
    -    fmt.Println("fork:", *boolPtr)
    +    fmt.Println("fork:", *forkPtr)
         fmt.Println("svar:", svar)
         fmt.Println("tail:", flag.Args())
     }
    @@ -303,7 +303,7 @@ and show the help text again.

    From f09cadcbd999c8433cc94da256f7f626190b74c3 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 30 Oct 2021 06:20:02 -0700 Subject: [PATCH 103/283] Change mutexes example to make it simpler and more predictable Fixes #364 --- examples/mutexes/mutexes.go | 110 ++++++++++-------------- examples/mutexes/mutexes.hash | 4 +- examples/mutexes/mutexes.sh | 9 +- public/mutexes | 155 +++++++++++----------------------- 4 files changed, 98 insertions(+), 180 deletions(-) diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index 59e736def..fce601967 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -7,79 +7,57 @@ package main import ( "fmt" - "math/rand" "sync" - "sync/atomic" - "time" ) -func main() { - - // For our example the `state` will be a map. - var state = make(map[int]int) - - // This `mutex` will synchronize access to `state`. - var mutex = &sync.Mutex{} - - // We'll keep track of how many read and write - // operations we do. - var readOps uint64 - var writeOps uint64 - - // Here we start 100 goroutines to execute repeated - // reads against the state, once per millisecond in - // each goroutine. - for r := 0; r < 100; r++ { - go func() { - total := 0 - for { - - // For each read we pick a key to access, - // `Lock()` the `mutex` to ensure - // exclusive access to the `state`, read - // the value at the chosen key, - // `Unlock()` the mutex, and increment - // the `readOps` count. - key := rand.Intn(5) - mutex.Lock() - total += state[key] - mutex.Unlock() - atomic.AddUint64(&readOps, 1) +// Container holds a map of counters; since we want to +// update it concurrently from multiple goroutines, we +// add a `Mutex` to synchronize access. The mutex is +// _embedded_ in this `struct`; this is idiomatic in Go. +// Note that mutexes must not be copied, so if this +// `struct` is passed around, it should be done by +// pointer. +type Container struct { + sync.Mutex + counters map[string]int +} - // Wait a bit between reads. - time.Sleep(time.Millisecond) - } - }() - } +func (c *Container) inc(name string) { + // Lock the mutex before accessing `counters`; unlock + // it at the end of the function using a [defer](defer) + // statement. Since the mutex is embedded into + // `Container`, we can call the mutex's methods like + // `Lock` directly on `c`. + c.Lock() + defer c.Unlock() + c.counters[name]++ +} - // We'll also start 10 goroutines to simulate writes, - // using the same pattern we did for reads. - for w := 0; w < 10; w++ { - go func() { - for { - key := rand.Intn(5) - val := rand.Intn(100) - mutex.Lock() - state[key] = val - mutex.Unlock() - atomic.AddUint64(&writeOps, 1) - time.Sleep(time.Millisecond) - } - }() +func main() { + c := Container{ + counters: map[string]int{"a": 0, "b": 0}, } - // Let the 10 goroutines work on the `state` and - // `mutex` for a second. - time.Sleep(time.Second) + var wg sync.WaitGroup - // Take and report final operation counts. - readOpsFinal := atomic.LoadUint64(&readOps) - fmt.Println("readOps:", readOpsFinal) - writeOpsFinal := atomic.LoadUint64(&writeOps) - fmt.Println("writeOps:", writeOpsFinal) + // This function increments a named counter + // in a loop. + doIncrement := func(name string, n int) { + for i := 0; i < n; i++ { + c.inc(name) + } + wg.Done() + } - // With a final lock of `state`, show how it ended up. - mutex.Lock() - fmt.Println("state:", state) - mutex.Unlock() + // Run several goroutines concurrently; note + // that they all access the same `Container`, + // and two of them access the same counter. + wg.Add(3) + go doIncrement("a", 10000) + go doIncrement("a", 10000) + go doIncrement("b", 10000) + + // Wait a for the goroutines to finish + wg.Wait() + fmt.Println(c.counters) } diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 4455e8c7e..70c6f65b1 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -253b089b8145fc57a90ae4024346b6db2ec1659b -CHCDredHCOz +07179e54fb3466ab01ac8aa9550feb213a206785 +i50fhu4l-n0 diff --git a/examples/mutexes/mutexes.sh b/examples/mutexes/mutexes.sh index 185f4fafa..d379c1f22 100644 --- a/examples/mutexes/mutexes.sh +++ b/examples/mutexes/mutexes.sh @@ -1,10 +1,7 @@ -# Running the program shows that we executed about -# 90,000 total operations against our `mutex`-synchronized -# `state`. +# Running the program shows that the counters +# updated as expected. $ go run mutexes.go -readOps: 83285 -writeOps: 8320 -state: map[1:97 4:53 0:33 2:15 3:2] +map[a:20000 b:10000] # Next we'll look at implementing this same state # management task using only goroutines and channels. diff --git a/public/mutexes b/public/mutexes index 0624b0a53..4fd5e957e 100644 --- a/public/mutexes +++ b/public/mutexes @@ -44,7 +44,7 @@ to safely access data across multiple goroutines.

    - +
    package main
     
    @@ -58,10 +58,7 @@ to safely access data across multiple goroutines.

    import (
         "fmt"
    -    "math/rand"
         "sync"
    -    "sync/atomic"
    -    "time"
     )
     
    @@ -69,107 +66,65 @@ to safely access data across multiple goroutines.

    - - - - -
    func main() {
    -
    - - - - - -

    For our example the state will be a map.

    +

    Container holds a map of counters; since we want to +update it concurrently from multiple goroutines, we +add a Mutex to synchronize access. The mutex is +embedded in this struct; this is idiomatic in Go. +Note that mutexes must not be copied, so if this +struct is passed around, it should be done by +pointer.

    -    var state = make(map[int]int)
    +type Container struct {
    +    sync.Mutex
    +    counters map[string]int
    +}
     
    -

    This mutex will synchronize access to state.

    +

    Lock the mutex before accessing counters; unlock +it at the end of the function using a defer +statement. Since the mutex is embedded into +Container, we can call the mutex’s methods like +Lock directly on c.

    -
    -    var mutex = &sync.Mutex{}
    +          
    func (c *Container) inc(name string) {
     
    -

    We’ll keep track of how many read and write -operations we do.

    - - - -
    -    var readOps uint64
    -    var writeOps uint64
    -
    - - - - - -

    Here we start 100 goroutines to execute repeated -reads against the state, once per millisecond in -each goroutine.

    - -
    -    for r := 0; r < 100; r++ {
    -        go func() {
    -            total := 0
    -            for {
    +          
        c.Lock()
    +    defer c.Unlock()
    +    c.counters[name]++
    +}
     
    -

    For each read we pick a key to access, -Lock() the mutex to ensure -exclusive access to the state, read -the value at the chosen key, -Unlock() the mutex, and increment -the readOps count.

    - - - -
    -                key := rand.Intn(5)
    -                mutex.Lock()
    -                total += state[key]
    -                mutex.Unlock()
    -                atomic.AddUint64(&readOps, 1)
    -
    - - - - - -

    Wait a bit between reads.

    - -
    -                time.Sleep(time.Millisecond)
    -            }
    -        }()
    +          
    func main() {
    +    c := Container{
    +        counters: map[string]int{"a": 0, "b": 0},
         }
     
    @@ -177,71 +132,62 @@ the readOps count.

    -

    We’ll also start 10 goroutines to simulate writes, -using the same pattern we did for reads.

    - + -
    -    for w := 0; w < 10; w++ {
    -        go func() {
    -            for {
    -                key := rand.Intn(5)
    -                val := rand.Intn(100)
    -                mutex.Lock()
    -                state[key] = val
    -                mutex.Unlock()
    -                atomic.AddUint64(&writeOps, 1)
    -                time.Sleep(time.Millisecond)
    -            }
    -        }()
    -    }
    +          
        var wg sync.WaitGroup
     
    -

    Let the 10 goroutines work on the state and -mutex for a second.

    +

    This function increments a named counter +in a loop.

    -    time.Sleep(time.Second)
    +    doIncrement := func(name string, n int) {
    +        for i := 0; i < n; i++ {
    +            c.inc(name)
    +        }
    +        wg.Done()
    +    }
     
    -

    Take and report final operation counts.

    +

    Run several goroutines concurrently; note +that they all access the same Container, +and two of them access the same counter.

    -    readOpsFinal := atomic.LoadUint64(&readOps)
    -    fmt.Println("readOps:", readOpsFinal)
    -    writeOpsFinal := atomic.LoadUint64(&writeOps)
    -    fmt.Println("writeOps:", writeOpsFinal)
    +    wg.Add(3)
    +    go doIncrement("a", 10000)
    +    go doIncrement("a", 10000)
    +    go doIncrement("b", 10000)
     
    -

    With a final lock of state, show how it ended up.

    +

    Wait a for the goroutines to finish

    -    mutex.Lock()
    -    fmt.Println("state:", state)
    -    mutex.Unlock()
    +    wg.Wait()
    +    fmt.Println(c.counters)
     }
     
    @@ -253,18 +199,15 @@ using the same pattern we did for reads.

    -

    Running the program shows that we executed about -90,000 total operations against our mutex-synchronized -state.

    +

    Running the program shows that the counters +updated as expected.

     $ go run mutexes.go
    -readOps: 83285
    -writeOps: 8320
    -state: map[1:97 4:53 0:33 2:15 3:2]
    +map[a:20000 b:10000]
    @@ -295,7 +238,7 @@ management task using only goroutines and channels.

    From 35ad9cc35c4a9b4c89fd17ba61bdf67d7725e10c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 22 Nov 2021 12:48:11 -0800 Subject: [PATCH 104/283] Add example of struct embedding in Go Also mention implementing interfaces with embedding Fixes #381 Fixes #398 --- examples.txt | 1 + examples/embedding/embedding.go | 59 +++++++ examples/embedding/embedding.hash | 2 + examples/embedding/embedding.sh | 5 + public/embedding | 248 ++++++++++++++++++++++++++++++ public/errors | 2 +- public/index.html | 2 + public/interfaces | 4 +- 8 files changed, 320 insertions(+), 3 deletions(-) create mode 100644 examples/embedding/embedding.go create mode 100644 examples/embedding/embedding.hash create mode 100644 examples/embedding/embedding.sh create mode 100644 public/embedding diff --git a/examples.txt b/examples.txt index cadc52c72..3f1d3e0bd 100644 --- a/examples.txt +++ b/examples.txt @@ -18,6 +18,7 @@ Pointers Structs Methods Interfaces +Embedding Errors Goroutines Channels diff --git a/examples/embedding/embedding.go b/examples/embedding/embedding.go new file mode 100644 index 000000000..f198dafef --- /dev/null +++ b/examples/embedding/embedding.go @@ -0,0 +1,59 @@ +// Go support _embedding_ of structs and interfaces +// to express a more seamless _composition_ of types. + +package main + +import "fmt" + +type base struct { + num int +} + +func (b base) describe() string { + return fmt.Sprintf("base with num=%v", b.num) +} + +// A `container` _embeds_ a `base`. An embedding looks +// like a field without a name. +type container struct { + base + str string +} + +func main() { + + // When creating structs with literals, we have to + // initialize the embedding explicitly; here the + // embedded type serves as the field name. + co := container{ + base: base{ + num: 1, + }, + str: "some name", + } + + // We can access the base's fields directly on `co`, + // e.g. `co.num`. + fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str) + + // Alternatively, we can spell out the full path using + // the embedded type name. + fmt.Println("also num:", co.base.num) + + // Since `container` embeds `base`, the methods of + // `base` also become methods of a `container`. Here + // we invoke a method that was embedded from `base` + // directly on `co`. + fmt.Println("describe:", co.describe()) + + type describer interface { + describe() string + } + + // Embedding structs with methods may be used to bestow + // interface implementations onto other structs. Here + // we see that a `container` now implements the + // `describer` interface because it embeds `base`. + var d describer = co + fmt.Println("describer:", d.describe()) +} diff --git a/examples/embedding/embedding.hash b/examples/embedding/embedding.hash new file mode 100644 index 000000000..fb9c19510 --- /dev/null +++ b/examples/embedding/embedding.hash @@ -0,0 +1,2 @@ +8a15291c6e82b9c6873002e2aa5cef65907a3405 +Xtg07j06zBv diff --git a/examples/embedding/embedding.sh b/examples/embedding/embedding.sh new file mode 100644 index 000000000..316095e55 --- /dev/null +++ b/examples/embedding/embedding.sh @@ -0,0 +1,5 @@ +$ go run embedding.go +co={num: 1, str: some name} +also num: 1 +describe: base with num=1 +describer: base with num=1 diff --git a/public/embedding b/public/embedding new file mode 100644 index 000000000..7e089e121 --- /dev/null +++ b/public/embedding @@ -0,0 +1,248 @@ + + + + + Go by Example: Embedding + + + + +
    +

    Go by Example: Embedding

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Go support embedding of structs and interfaces +to express a more seamless composition of types.

    + +
    + + +
    + + + +
    package main
    +
    +
    + + + +
    import "fmt"
    +
    +
    + + + +
    type base struct {
    +    num int
    +}
    +
    +
    + + + +
    func (b base) describe() string {
    +    return fmt.Sprintf("base with num=%v", b.num)
    +}
    +
    +
    +

    A container embeds a base. An embedding looks +like a field without a name.

    + +
    + +
    +type container struct {
    +    base
    +    str string
    +}
    +
    +
    + + + +
    func main() {
    +
    +
    +

    When creating structs with literals, we have to +initialize the embedding explicitly; here the +embedded type serves as the field name.

    + +
    + +
    +    co := container{
    +        base: base{
    +            num: 1,
    +        },
    +        str: "some name",
    +    }
    +
    +
    +

    We can access the base’s fields directly on co, +e.g. co.num.

    + +
    + +
    +    fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
    +
    +
    +

    Alternatively, we can spell out the full path using +the embedded type name.

    + +
    + +
    +    fmt.Println("also num:", co.base.num)
    +
    +
    +

    Since container embeds base, the methods of +base also become methods of a container. Here +we invoke a method that was embedded from base +directly on co.

    + +
    + +
    +    fmt.Println("describe:", co.describe())
    +
    +
    + + + +
        type describer interface {
    +        describe() string
    +    }
    +
    +
    +

    Embedding structs with methods may be used to bestow +interface implementations onto other structs. Here +we see that a container now implements the +describer interface because it embeds base.

    + +
    + +
    +    var d describer = co
    +    fmt.Println("describer:", d.describe())
    +}
    +
    +
    + + + + + + + + +
    + + + +
    $ go run embedding.go
    +co={num: 1, str: some name}
    +also num: 1
    +describe: base with num=1
    +describer: base with num=1
    +
    + + +

    + Next example: Errors. +

    + + + + +
    + + + + diff --git a/public/errors b/public/errors index ba8282efe..4ac669ad1 100644 --- a/public/errors +++ b/public/errors @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'interfaces'; + window.location.href = 'embedding'; } diff --git a/public/index.html b/public/index.html index 3e5e0af57..279ae86ac 100644 --- a/public/index.html +++ b/public/index.html @@ -67,6 +67,8 @@

    Go by Example

  • Interfaces
  • +
  • Embedding
  • +
  • Errors
  • Goroutines
  • diff --git a/public/interfaces b/public/interfaces index e743386eb..578bfabd9 100644 --- a/public/interfaces +++ b/public/interfaces @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'errors'; + window.location.href = 'embedding'; } } @@ -222,7 +222,7 @@ these structs as arguments to measure.

    - Next example: Errors. + Next example: Embedding.

    From 2621c73d29c995802696e1dd8b5899b78c343ca9 Mon Sep 17 00:00:00 2001 From: Nate Finch Date: Mon, 22 Nov 2021 15:51:49 -0500 Subject: [PATCH 105/283] don't embed the mutex (#400) Do not embed the mutex in the mutex example --- examples/mutexes/mutexes.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index fce601967..0a340105c 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -12,29 +12,28 @@ import ( // Container holds a map of counters; since we want to // update it concurrently from multiple goroutines, we -// add a `Mutex` to synchronize access. The mutex is -// _embedded_ in this `struct`; this is idiomatic in Go. +// add a `Mutex` to synchronize access. // Note that mutexes must not be copied, so if this // `struct` is passed around, it should be done by // pointer. type Container struct { - sync.Mutex + mu sync.Mutex counters map[string]int } func (c *Container) inc(name string) { // Lock the mutex before accessing `counters`; unlock // it at the end of the function using a [defer](defer) - // statement. Since the mutex is embedded into - // `Container`, we can call the mutex's methods like - // `Lock` directly on `c`. - c.Lock() - defer c.Unlock() + // statement. + c.mu.Lock() + defer c.mu.Unlock() c.counters[name]++ } func main() { c := Container{ + // Note that the zero value of a mutex is usable as-is, so no + // initialization is required here. counters: map[string]int{"a": 0, "b": 0}, } From c93e7c1cf8287fe2cee40ba5b4fd2829bc91db6c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 22 Nov 2021 12:53:10 -0800 Subject: [PATCH 106/283] Generate public/* for mutex --- examples/mutexes/mutexes.go | 2 +- examples/mutexes/mutexes.hash | 4 ++-- public/mutexes | 33 +++++++++++++++++++++------------ 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index 0a340105c..448eb6c73 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -17,7 +17,7 @@ import ( // `struct` is passed around, it should be done by // pointer. type Container struct { - mu sync.Mutex + mu sync.Mutex counters map[string]int } diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 70c6f65b1..974d7272a 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -07179e54fb3466ab01ac8aa9550feb213a206785 -i50fhu4l-n0 +3688453f408d8c7cc6db91ab7fd5e0ac06ade7ea +tDqeib2-yZA diff --git a/public/mutexes b/public/mutexes index 4fd5e957e..9abb3ada3 100644 --- a/public/mutexes +++ b/public/mutexes @@ -44,7 +44,7 @@ to safely access data across multiple goroutines.

    - +
    package main
     
    @@ -68,8 +68,7 @@ to safely access data across multiple goroutines.

    Container holds a map of counters; since we want to update it concurrently from multiple goroutines, we -add a Mutex to synchronize access. The mutex is -embedded in this struct; this is idiomatic in Go. +add a Mutex to synchronize access. Note that mutexes must not be copied, so if this struct is passed around, it should be done by pointer.

    @@ -79,7 +78,7 @@ pointer.

     type Container struct {
    -    sync.Mutex
    +    mu       sync.Mutex
         counters map[string]int
     }
     
    @@ -90,9 +89,7 @@ pointer.

    Lock the mutex before accessing counters; unlock it at the end of the function using a defer -statement. Since the mutex is embedded into -Container, we can call the mutex’s methods like -Lock directly on c.

    +statement.

    @@ -108,8 +105,8 @@ statement. Since the mutex is embedded into -
        c.Lock()
    -    defer c.Unlock()
    +          
        c.mu.Lock()
    +    defer c.mu.Unlock()
         c.counters[name]++
     }
     
    @@ -118,13 +115,25 @@ statement. Since the mutex is embedded into - +

    Note that the zero value of a mutex is usable as-is, so no +initialization is required here.

    +
    func main() {
         c := Container{
    -        counters: map[string]int{"a": 0, "b": 0},
    +
    + + + + + + + + + +
            counters: map[string]int{"a": 0, "b": 0},
         }
     
    @@ -238,7 +247,7 @@ management task using only goroutines and channels.

    From dad9113134000a8ea2701d480c6dde256255ed62 Mon Sep 17 00:00:00 2001 From: Adrien Lacquemant Date: Wed, 1 Dec 2021 17:52:32 -0500 Subject: [PATCH 107/283] Fix incorrect link in README.md (#404) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index baea15948..0b8bbabf9 100644 --- a/README.md +++ b/README.md @@ -76,5 +76,5 @@ Contributor translations of the Go by Example site are available in: ### Thanks Thanks to [Jeremy Ashkenas](https://github.com/jashkenas) -for [Docco](http://jashkenas.github.com/docco/), which +for [Docco](http://jashkenas.github.io/docco/), which inspired this project. From 80fb5ebddf380fed64fce8414db3a985a1e7956e Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Dec 2021 06:31:37 -0800 Subject: [PATCH 108/283] Clarify the signals example slightly Based on feedback in #402 --- examples/signals/signals.go | 17 +++++++++------ examples/signals/signals.hash | 4 ++-- examples/testing/main_test.go | 6 ++++++ examples/testing/testing.hash | 4 ++-- public/signals | 40 ++++++++++++++++++++++++++++------- public/testing | 21 +++++++++++++++--- 6 files changed, 71 insertions(+), 21 deletions(-) diff --git a/examples/signals/signals.go b/examples/signals/signals.go index 4cd373b2f..1fd225b5b 100644 --- a/examples/signals/signals.go +++ b/examples/signals/signals.go @@ -18,19 +18,24 @@ func main() { // Go signal notification works by sending `os.Signal` // values on a channel. We'll create a channel to - // receive these notifications (we'll also make one to - // notify us when the program can exit). + // receive these notifications. Note that this channel + // should be buffered. sigs := make(chan os.Signal, 1) - done := make(chan bool, 1) // `signal.Notify` registers the given channel to // receive notifications of the specified signals. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) - // This goroutine executes a blocking receive for - // signals. When it gets one it'll print it out - // and then notify the program that it can finish. + // We could receive from `sigs` here in the main + // function, but let's see how this could also be + // done in a separate goroutine, to demonstrate + // a more realistic scenario of graceful shutdown. + done := make(chan bool, 1) + go func() { + // This goroutine executes a blocking receive for + // signals. When it gets one it'll print it out + // and then notify the program that it can finish. sig := <-sigs fmt.Println() fmt.Println(sig) diff --git a/examples/signals/signals.hash b/examples/signals/signals.hash index 205ac6905..3735e8ff5 100644 --- a/examples/signals/signals.hash +++ b/examples/signals/signals.hash @@ -1,2 +1,2 @@ -ccee3fe41771b7cf56d64de38b12588022458154 -YRV64KEXJW1 +cd15508731199185f3205692af0f80cbdee4fcd7 +LauPuRo3v9l diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index e409d9d2e..25531daf1 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -66,3 +66,9 @@ func TestIntMinTableDriven(t *testing.T) { }) } } + +func BenchmarkIntMin(b *testing.B) { + for i := 0; i < b.N; i++ { + IntMin(1, 2) + } +} diff --git a/examples/testing/testing.hash b/examples/testing/testing.hash index 6dc53a9ef..4572b5189 100644 --- a/examples/testing/testing.hash +++ b/examples/testing/testing.hash @@ -1,2 +1,2 @@ -c9ca6b71d9f762b689f1f08a490d8c7f7764fcb3 -vY8PN0c6BSx +25e8941d63b555a590e6d44a95ae0e41ecadadca +ALL2BVLkYEr diff --git a/public/signals b/public/signals index da60f15e6..c2ae6e265 100644 --- a/public/signals +++ b/public/signals @@ -46,7 +46,7 @@ Here’s how to handle signals in Go with channels.

    - +
    package main
     
    @@ -83,15 +83,14 @@ Here’s how to handle signals in Go with channels.

    Go signal notification works by sending os.Signal values on a channel. We’ll create a channel to -receive these notifications (we’ll also make one to -notify us when the program can exit).

    +receive these notifications. Note that this channel +should be buffered.

         sigs := make(chan os.Signal, 1)
    -    done := make(chan bool, 1)
     
    @@ -110,6 +109,22 @@ receive notifications of the specified signals.

    + + +

    We could receive from sigs here in the main +function, but let’s see how this could also be +done in a separate goroutine, to demonstrate +a more realistic scenario of graceful shutdown.

    + + + + +
    +    done := make(chan bool, 1)
    +
    + + +

    This goroutine executes a blocking receive for @@ -119,9 +134,18 @@ and then notify the program that it can finish.

    -
    -    go func() {
    -        sig := <-sigs
    +          
        go func() {
    +
    + + + + + + + + + +
            sig := <-sigs
             fmt.Println()
             fmt.Println(sig)
             done <- true
    @@ -186,7 +210,7 @@ causing the program to print interrupt and then exit.

    diff --git a/public/testing b/public/testing index 8a665070a..afb9fa454 100644 --- a/public/testing +++ b/public/testing @@ -47,7 +47,7 @@ typically lives in the same package as the code it tests.

    - +
     package main
     
    @@ -167,7 +167,7 @@ when executing go test -v.

    - +
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
             t.Run(testname, func(t *testing.T) {
    @@ -178,6 +178,21 @@ when executing go test -v.

    }) } } +
    + + + + + + + + + +
    func BenchmarkIntMin(b *testing.B) {
    +    for i := 0; i < b.N; i++ {
    +        IntMin(1, 2)
    +    }
    +}
     
    @@ -229,7 +244,7 @@ when executing go test -v.

    From dadb6bdeae7630909d3f16a1029ca695861e5875 Mon Sep 17 00:00:00 2001 From: Johanan Idicula Date: Thu, 2 Dec 2021 10:04:59 -0500 Subject: [PATCH 109/283] feat: Add benchmark example (#403) * feat: Add benchmark example Adds a simple benchmark example and its invocation. * fix: Address PR comments - Clarify meaning of `b.N`. - Nix verbose flag in run example. * fix: Reword b.N comment * fix: Missing period --- examples/testing/main_test.go | 6 +++++ examples/testing/main_test.sh | 11 +++++++++ examples/testing/testing.hash | 4 +-- public/testing | 46 ++++++++++++++++++++++++++++++++--- 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/examples/testing/main_test.go b/examples/testing/main_test.go index 25531daf1..86111d4c0 100644 --- a/examples/testing/main_test.go +++ b/examples/testing/main_test.go @@ -67,7 +67,13 @@ func TestIntMinTableDriven(t *testing.T) { } } +// Benchmark tests typically go in `_test.go` files and are +// named beginning with `Benchmark`. The `testing` runner +// executes each benchmark function several times, increasing +// `b.N` on each run until it collects a precise measurement. func BenchmarkIntMin(b *testing.B) { + // Typically the benchmark runs a function we're + // benchmarking in a loop `b.N` times. for i := 0; i < b.N; i++ { IntMin(1, 2) } diff --git a/examples/testing/main_test.sh b/examples/testing/main_test.sh index 58e0615e5..b04fdb2dc 100644 --- a/examples/testing/main_test.sh +++ b/examples/testing/main_test.sh @@ -16,3 +16,14 @@ $ go test -v --- PASS: TestIntMinTableDriven/-1,0 (0.00s) PASS ok examples/testing 0.023s + +# Run all benchmarks in the current project in verbose +# mode. All tests are run prior to benchmarks. The `bench` +# flag receives a regex for benchmark function names. +$ go test -bench=. +goos: darwin +goarch: arm64 +pkg: examples/testing +BenchmarkIntMin-8 1000000000 0.3136 ns/op +PASS +ok examples/testing 0.351s diff --git a/examples/testing/testing.hash b/examples/testing/testing.hash index 4572b5189..7ecf04f85 100644 --- a/examples/testing/testing.hash +++ b/examples/testing/testing.hash @@ -1,2 +1,2 @@ -25e8941d63b555a590e6d44a95ae0e41ecadadca -ALL2BVLkYEr +3671aaf0eee9f6d2b68e51b09997be767edfe97c +PlzU16wwEWE diff --git a/public/testing b/public/testing index afb9fa454..530d0b2e8 100644 --- a/public/testing +++ b/public/testing @@ -47,7 +47,7 @@ typically lives in the same package as the code it tests.

    - +
     package main
     
    @@ -184,11 +184,29 @@ when executing go test -v.

    +

    Benchmark tests typically go in _test.go files and are +named beginning with Benchmark. The testing runner +executes each benchmark function several times, increasing +b.N on each run until it collects a precise measurement.

    + + + +
    +func BenchmarkIntMin(b *testing.B) {
    +
    + + + + + +

    Typically the benchmark runs a function we’re +benchmarking in a loop b.N times.

    + -
    func BenchmarkIntMin(b *testing.B) {
    +          
         for i := 0; i < b.N; i++ {
             IntMin(1, 2)
         }
    @@ -206,7 +224,7 @@ when executing go test -v.

    Run all tests in the current project in verbose mode.

    - +
     $ go test -v
    @@ -229,6 +247,26 @@ when executing go test -v.

    + + +

    Run all benchmarks in the current project in verbose +mode. All tests are run prior to benchmarks. The bench +flag receives a regex for benchmark function names.

    + + + + +
    +$ go test -bench=.
    +goos: darwin
    +goarch: arm64
    +pkg: examples/testing
    +BenchmarkIntMin-8 1000000000 0.3136 ns/op
    +PASS
    +ok      examples/testing    0.351s
    + + + @@ -244,7 +282,7 @@ when executing go test -v.

    From 99902be3b2005a6d263ded469dfe89280a143466 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Dec 2021 07:09:23 -0800 Subject: [PATCH 110/283] Slightly tweak comments after #403 --- examples/testing/main_test.sh | 6 +++--- public/testing | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/testing/main_test.sh b/examples/testing/main_test.sh index b04fdb2dc..1e922b648 100644 --- a/examples/testing/main_test.sh +++ b/examples/testing/main_test.sh @@ -17,9 +17,9 @@ $ go test -v PASS ok examples/testing 0.023s -# Run all benchmarks in the current project in verbose -# mode. All tests are run prior to benchmarks. The `bench` -# flag receives a regex for benchmark function names. +# Run all benchmarks in the current project. All tests +# are run prior to benchmarks. The `bench` flag filters +# benchmark function names with a regexp. $ go test -bench=. goos: darwin goarch: arm64 diff --git a/public/testing b/public/testing index 530d0b2e8..4251984c8 100644 --- a/public/testing +++ b/public/testing @@ -249,9 +249,9 @@ benchmarking in a loop b.N times.

    -

    Run all benchmarks in the current project in verbose -mode. All tests are run prior to benchmarks. The bench -flag receives a regex for benchmark function names.

    +

    Run all benchmarks in the current project. All tests +are run prior to benchmarks. The bench flag filters +benchmark function names with a regexp.

    From 061b2f64555956d46a421e94e2de0a8eba932f0f Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Dec 2021 07:12:23 -0800 Subject: [PATCH 111/283] Rename testing --> testing-and-benchmarking --- examples.txt | 2 +- .../main_test.go | 0 .../main_test.sh | 4 +- .../testing.hash | 0 public/command-line-arguments | 2 +- public/index.html | 2 +- public/temporary-files-and-directories | 4 +- public/testing-and-benchmarking | 289 ++++++++++++++++++ 8 files changed, 296 insertions(+), 7 deletions(-) rename examples/{testing => testing-and-benchmarking}/main_test.go (100%) rename examples/{testing => testing-and-benchmarking}/main_test.sh (90%) rename examples/{testing => testing-and-benchmarking}/testing.hash (100%) create mode 100644 public/testing-and-benchmarking diff --git a/examples.txt b/examples.txt index 3f1d3e0bd..88fb70c74 100644 --- a/examples.txt +++ b/examples.txt @@ -63,7 +63,7 @@ Line Filters File Paths Directories Temporary Files and Directories -Testing +Testing and Benchmarking Command-Line Arguments Command-Line Flags Command-Line Subcommands diff --git a/examples/testing/main_test.go b/examples/testing-and-benchmarking/main_test.go similarity index 100% rename from examples/testing/main_test.go rename to examples/testing-and-benchmarking/main_test.go diff --git a/examples/testing/main_test.sh b/examples/testing-and-benchmarking/main_test.sh similarity index 90% rename from examples/testing/main_test.sh rename to examples/testing-and-benchmarking/main_test.sh index 1e922b648..73411fe42 100644 --- a/examples/testing/main_test.sh +++ b/examples/testing-and-benchmarking/main_test.sh @@ -15,7 +15,7 @@ $ go test -v --- PASS: TestIntMinTableDriven/0,-1 (0.00s) --- PASS: TestIntMinTableDriven/-1,0 (0.00s) PASS -ok examples/testing 0.023s +ok examples/testing-and-benchmarking 0.023s # Run all benchmarks in the current project. All tests # are run prior to benchmarks. The `bench` flag filters @@ -26,4 +26,4 @@ goarch: arm64 pkg: examples/testing BenchmarkIntMin-8 1000000000 0.3136 ns/op PASS -ok examples/testing 0.351s +ok examples/testing-and-benchmarking 0.351s diff --git a/examples/testing/testing.hash b/examples/testing-and-benchmarking/testing.hash similarity index 100% rename from examples/testing/testing.hash rename to examples/testing-and-benchmarking/testing.hash diff --git a/public/command-line-arguments b/public/command-line-arguments index 9ccbc4a38..76324164d 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'testing'; + window.location.href = 'testing-and-benchmarking'; } diff --git a/public/index.html b/public/index.html index 279ae86ac..125edc3ac 100644 --- a/public/index.html +++ b/public/index.html @@ -157,7 +157,7 @@

    Go by Example

  • Temporary Files and Directories
  • -
  • Testing
  • +
  • Testing and Benchmarking
  • Command-Line Arguments
  • diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 098402bd2..91ca3a659 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'testing'; + window.location.href = 'testing-and-benchmarking'; } } @@ -225,7 +225,7 @@ prefixing them with our temporary directory.

    - Next example: Testing. + Next example: Testing and Benchmarking.

    diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking new file mode 100644 index 000000000..975dbb22e --- /dev/null +++ b/public/testing-and-benchmarking @@ -0,0 +1,289 @@ + + + + + Go by Example: Testing and Benchmarking + + + + +
    +

    Go by Example: Testing and Benchmarking

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Unit testing is an important part of writing +principled Go programs. The testing package +provides the tools we need to write unit tests +and the go test command runs tests.

    + +
    + + +
    +

    For the sake of demonstration, this code is in package +main, but it could be any package. Testing code +typically lives in the same package as the code it tests.

    + +
    + +
    +package main
    +
    +
    + + + +
    import (
    +    "fmt"
    +    "testing"
    +)
    +
    +
    +

    We’ll be testing this simple implementation of an +integer minimum. Typically, the code we’re testing +would be in a source file named something like +intutils.go, and the test file for it would then +be named intutils_test.go.

    + +
    + +
    +func IntMin(a, b int) int {
    +    if a < b {
    +        return a
    +    }
    +    return b
    +}
    +
    +
    +

    A test is created by writing a function with a name +beginning with Test.

    + +
    + +
    +func TestIntMinBasic(t *testing.T) {
    +    ans := IntMin(2, -2)
    +    if ans != -2 {
    +
    +
    +

    t.Error* will report test failures but continue +executing the test. t.Fatal* will report test +failures and stop the test immediately.

    + +
    + +
    +        t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    +    }
    +}
    +
    +
    +

    Writing tests can be repetitive, so it’s idiomatic to +use a table-driven style, where test inputs and +expected outputs are listed in a table and a single loop +walks over them and performs the test logic.

    + +
    + +
    +func TestIntMinTableDriven(t *testing.T) {
    +    var tests = []struct {
    +        a, b int
    +        want int
    +    }{
    +        {0, 1, 0},
    +        {1, 0, 0},
    +        {2, -2, -2},
    +        {0, -1, -1},
    +        {-1, 0, -1},
    +    }
    +
    +
    +

    t.Run enables running “subtests”, one for each +table entry. These are shown separately +when executing go test -v.

    + +
    + +
        for _, tt := range tests {
    +
    +
    + + + +
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
    +        t.Run(testname, func(t *testing.T) {
    +            ans := IntMin(tt.a, tt.b)
    +            if ans != tt.want {
    +                t.Errorf("got %d, want %d", ans, tt.want)
    +            }
    +        })
    +    }
    +}
    +
    +
    +

    Benchmark tests typically go in _test.go files and are +named beginning with Benchmark. The testing runner +executes each benchmark function several times, increasing +b.N on each run until it collects a precise measurement.

    + +
    + +
    +func BenchmarkIntMin(b *testing.B) {
    +
    +
    +

    Typically the benchmark runs a function we’re +benchmarking in a loop b.N times.

    + +
    + +
    +    for i := 0; i < b.N; i++ {
    +        IntMin(1, 2)
    +    }
    +}
    +
    +
    + + + + + + + + + + + + + +
    +

    Run all tests in the current project in verbose mode.

    + +
    + +
    +$ go test -v
    +== RUN   TestIntMinBasic
    +--- PASS: TestIntMinBasic (0.00s)
    +=== RUN   TestIntMinTableDriven
    +=== RUN   TestIntMinTableDriven/0,1
    +=== RUN   TestIntMinTableDriven/1,0
    +=== RUN   TestIntMinTableDriven/2,-2
    +=== RUN   TestIntMinTableDriven/0,-1
    +=== RUN   TestIntMinTableDriven/-1,0
    +--- PASS: TestIntMinTableDriven (0.00s)
    +    --- PASS: TestIntMinTableDriven/0,1 (0.00s)
    +    --- PASS: TestIntMinTableDriven/1,0 (0.00s)
    +    --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
    +    --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
    +    --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
    +PASS
    +ok      examples/testing-and-benchmarking    0.023s
    +
    +

    Run all benchmarks in the current project. All tests +are run prior to benchmarks. The bench flag filters +benchmark function names with a regexp.

    + +
    + +
    +$ go test -bench=.
    +goos: darwin
    +goarch: arm64
    +pkg: examples/testing
    +BenchmarkIntMin-8 1000000000 0.3136 ns/op
    +PASS
    +ok      examples/testing-and-benchmarking    0.351s
    +
    + + +

    + Next example: Command-Line Arguments. +

    + + + + +
    + + + + From 3397ebcf08e7f00502e37737c97c4326dd4a3632 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Dec 2021 07:13:06 -0800 Subject: [PATCH 112/283] Remove old public/testing, since the source was renamed --- public/testing | 289 ------------------------------------------------- 1 file changed, 289 deletions(-) delete mode 100644 public/testing diff --git a/public/testing b/public/testing deleted file mode 100644 index 4251984c8..000000000 --- a/public/testing +++ /dev/null @@ -1,289 +0,0 @@ - - - - - Go by Example: Testing - - - - -
    -

    Go by Example: Testing

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    Unit testing is an important part of writing -principled Go programs. The testing package -provides the tools we need to write unit tests -and the go test command runs tests.

    - -
    - - -
    -

    For the sake of demonstration, this code is in package -main, but it could be any package. Testing code -typically lives in the same package as the code it tests.

    - -
    - -
    -package main
    -
    -
    - - - -
    import (
    -    "fmt"
    -    "testing"
    -)
    -
    -
    -

    We’ll be testing this simple implementation of an -integer minimum. Typically, the code we’re testing -would be in a source file named something like -intutils.go, and the test file for it would then -be named intutils_test.go.

    - -
    - -
    -func IntMin(a, b int) int {
    -    if a < b {
    -        return a
    -    }
    -    return b
    -}
    -
    -
    -

    A test is created by writing a function with a name -beginning with Test.

    - -
    - -
    -func TestIntMinBasic(t *testing.T) {
    -    ans := IntMin(2, -2)
    -    if ans != -2 {
    -
    -
    -

    t.Error* will report test failures but continue -executing the test. t.Fatal* will report test -failures and stop the test immediately.

    - -
    - -
    -        t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    -    }
    -}
    -
    -
    -

    Writing tests can be repetitive, so it’s idiomatic to -use a table-driven style, where test inputs and -expected outputs are listed in a table and a single loop -walks over them and performs the test logic.

    - -
    - -
    -func TestIntMinTableDriven(t *testing.T) {
    -    var tests = []struct {
    -        a, b int
    -        want int
    -    }{
    -        {0, 1, 0},
    -        {1, 0, 0},
    -        {2, -2, -2},
    -        {0, -1, -1},
    -        {-1, 0, -1},
    -    }
    -
    -
    -

    t.Run enables running “subtests”, one for each -table entry. These are shown separately -when executing go test -v.

    - -
    - -
        for _, tt := range tests {
    -
    -
    - - - -
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
    -        t.Run(testname, func(t *testing.T) {
    -            ans := IntMin(tt.a, tt.b)
    -            if ans != tt.want {
    -                t.Errorf("got %d, want %d", ans, tt.want)
    -            }
    -        })
    -    }
    -}
    -
    -
    -

    Benchmark tests typically go in _test.go files and are -named beginning with Benchmark. The testing runner -executes each benchmark function several times, increasing -b.N on each run until it collects a precise measurement.

    - -
    - -
    -func BenchmarkIntMin(b *testing.B) {
    -
    -
    -

    Typically the benchmark runs a function we’re -benchmarking in a loop b.N times.

    - -
    - -
    -    for i := 0; i < b.N; i++ {
    -        IntMin(1, 2)
    -    }
    -}
    -
    -
    - - - - - - - - - - - - - -
    -

    Run all tests in the current project in verbose mode.

    - -
    - -
    -$ go test -v
    -== RUN   TestIntMinBasic
    ---- PASS: TestIntMinBasic (0.00s)
    -=== RUN   TestIntMinTableDriven
    -=== RUN   TestIntMinTableDriven/0,1
    -=== RUN   TestIntMinTableDriven/1,0
    -=== RUN   TestIntMinTableDriven/2,-2
    -=== RUN   TestIntMinTableDriven/0,-1
    -=== RUN   TestIntMinTableDriven/-1,0
    ---- PASS: TestIntMinTableDriven (0.00s)
    -    --- PASS: TestIntMinTableDriven/0,1 (0.00s)
    -    --- PASS: TestIntMinTableDriven/1,0 (0.00s)
    -    --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
    -    --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
    -    --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
    -PASS
    -ok      examples/testing    0.023s
    -
    -

    Run all benchmarks in the current project. All tests -are run prior to benchmarks. The bench flag filters -benchmark function names with a regexp.

    - -
    - -
    -$ go test -bench=.
    -goos: darwin
    -goarch: arm64
    -pkg: examples/testing
    -BenchmarkIntMin-8 1000000000 0.3136 ns/op
    -PASS
    -ok      examples/testing    0.351s
    -
    - - -

    - Next example: Command-Line Arguments. -

    - - - - -
    - - - - From 668ecb97321c60cf25ff7c0b36a9c8551127dc06 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 16 Dec 2021 20:16:44 -0800 Subject: [PATCH 113/283] Add brief FAQ section in the README to clarify common questions --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index 0b8bbabf9..992a7694d 100644 --- a/README.md +++ b/README.md @@ -78,3 +78,19 @@ Contributor translations of the Go by Example site are available in: Thanks to [Jeremy Ashkenas](https://github.com/jashkenas) for [Docco](http://jashkenas.github.io/docco/), which inspired this project. + +### FAQ + +#### I'm getting output in a different order from the example. Is the example wrong? + +Some of the examples demonstrate concurrent code which has a non-deterministic +execution order. It depends on how the Go runtime schedules its goroutines and +may vary by operating system, CPU architecture, or even Go version. + +It doesn't mean anything is wrong with the example. Typically the code in these +examples will be insensitive to the actual order of the output; if the code is +sensitive to the order - that's probably a bug - so feel free to report it. + + + + From 1c7180a00fd618c14c9484ef9e4d8c519ec47411 Mon Sep 17 00:00:00 2001 From: Sandeep Date: Mon, 10 Jan 2022 05:42:31 -0800 Subject: [PATCH 114/283] Update `Epoch` example to add UnixMilli from Time package (#409) Standard library time package has support for UnixMilli - https://pkg.go.dev/time#Time.UnixMilli Updated the example to use the method on Time instead of calculating. --- examples/epoch/epoch.go | 22 ++++++++-------------- examples/epoch/epoch.hash | 4 ++-- public/epoch | 29 +++++++++++------------------ 3 files changed, 21 insertions(+), 34 deletions(-) diff --git a/examples/epoch/epoch.go b/examples/epoch/epoch.go index ed7f442f7..ff37ce54d 100644 --- a/examples/epoch/epoch.go +++ b/examples/epoch/epoch.go @@ -12,24 +12,18 @@ import ( func main() { - // Use `time.Now` with `Unix` or `UnixNano` to get - // elapsed time since the Unix epoch in seconds or - // nanoseconds, respectively. + // Use `time.Now` with `Unix` or `UnixMilli` or `UnixNano` + // to get elapsed time since the Unix epoch in seconds or + // milliseconds or nanoseconds, respectively. now := time.Now() - secs := now.Unix() - nanos := now.UnixNano() fmt.Println(now) - // Note that there is no `UnixMillis`, so to get the - // milliseconds since epoch you'll need to manually - // divide from nanoseconds. - millis := nanos / 1000000 - fmt.Println(secs) - fmt.Println(millis) - fmt.Println(nanos) + fmt.Println(now.Unix()) + fmt.Println(now.UnixMilli()) + fmt.Println(now.UnixNano()) // You can also convert integer seconds or nanoseconds // since the epoch into the corresponding `time`. - fmt.Println(time.Unix(secs, 0)) - fmt.Println(time.Unix(0, nanos)) + fmt.Println(time.Unix(now.Unix(), 0)) + fmt.Println(time.Unix(0, now.UnixNano())) } diff --git a/examples/epoch/epoch.hash b/examples/epoch/epoch.hash index ad0a47164..e0920daa6 100644 --- a/examples/epoch/epoch.hash +++ b/examples/epoch/epoch.hash @@ -1,2 +1,2 @@ -3b1fc502f41a978f1c8150335801aa9096db8954 -0ooeler0RfR +53610b08e885c8a36dc1a2c63a70e415ce6dfe2a +LSdohP_slOu diff --git a/public/epoch b/public/epoch index 0998c94d9..3d69363cc 100644 --- a/public/epoch +++ b/public/epoch @@ -44,7 +44,7 @@ Here’s how to do it in Go.

    - +
    package main
     
    @@ -77,17 +77,15 @@ Here’s how to do it in Go.

    -

    Use time.Now with Unix or UnixNano to get -elapsed time since the Unix epoch in seconds or -nanoseconds, respectively.

    +

    Use time.Now with Unix or UnixMilli or UnixNano +to get elapsed time since the Unix epoch in seconds or +milliseconds or nanoseconds, respectively.

         now := time.Now()
    -    secs := now.Unix()
    -    nanos := now.UnixNano()
         fmt.Println(now)
     
    @@ -95,18 +93,13 @@ nanoseconds, respectively.

    -

    Note that there is no UnixMillis, so to get the -milliseconds since epoch you’ll need to manually -divide from nanoseconds.

    - + -
    -    millis := nanos / 1000000
    -    fmt.Println(secs)
    -    fmt.Println(millis)
    -    fmt.Println(nanos)
    +          
        fmt.Println(now.Unix())
    +    fmt.Println(now.UnixMilli())
    +    fmt.Println(now.UnixNano())
     
    @@ -120,8 +113,8 @@ since the epoch into the corresponding time.

    -    fmt.Println(time.Unix(secs, 0))
    -    fmt.Println(time.Unix(0, nanos))
    +    fmt.Println(time.Unix(now.Unix(), 0))
    +    fmt.Println(time.Unix(0, now.UnixNano()))
     }
     
    @@ -174,7 +167,7 @@ parsing and formatting.

    From 63ed62348e641c37a36bed58af2b4ddad8edf7d9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 10 Jan 2022 05:45:35 -0800 Subject: [PATCH 115/283] Slight comment rewording following the previous commit --- examples/epoch/epoch.go | 4 ++-- examples/epoch/epoch.hash | 4 ++-- public/epoch | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/epoch/epoch.go b/examples/epoch/epoch.go index ff37ce54d..a48ece968 100644 --- a/examples/epoch/epoch.go +++ b/examples/epoch/epoch.go @@ -12,8 +12,8 @@ import ( func main() { - // Use `time.Now` with `Unix` or `UnixMilli` or `UnixNano` - // to get elapsed time since the Unix epoch in seconds or + // Use `time.Now` with `Unix`, `UnixMilli` or `UnixNano` + // to get elapsed time since the Unix epoch in seconds, // milliseconds or nanoseconds, respectively. now := time.Now() fmt.Println(now) diff --git a/examples/epoch/epoch.hash b/examples/epoch/epoch.hash index e0920daa6..7248790a8 100644 --- a/examples/epoch/epoch.hash +++ b/examples/epoch/epoch.hash @@ -1,2 +1,2 @@ -53610b08e885c8a36dc1a2c63a70e415ce6dfe2a -LSdohP_slOu +54e66c2e84334f2adbf87aaeb62065111c5644ea +iG_EcjJp4ss diff --git a/public/epoch b/public/epoch index 3d69363cc..c0943c6fc 100644 --- a/public/epoch +++ b/public/epoch @@ -44,7 +44,7 @@ Here’s how to do it in Go.

    - +
    package main
     
    @@ -77,8 +77,8 @@ Here’s how to do it in Go.

    -

    Use time.Now with Unix or UnixMilli or UnixNano -to get elapsed time since the Unix epoch in seconds or +

    Use time.Now with Unix, UnixMilli or UnixNano +to get elapsed time since the Unix epoch in seconds, milliseconds or nanoseconds, respectively.

    From 364f0c2f69adb06e7bc39ced3fbb07a6cce3a545 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 10 Jan 2022 05:48:21 -0800 Subject: [PATCH 116/283] Run CI on latest version of Go only --- .github/workflows/test.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 424474a06..b49f3d46c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,9 +13,6 @@ jobs: matrix: os: [ubuntu-latest, macos-latest] go-version: [1.17.x] - include: - - go-version: 1.16.x - os: ubuntu-latest runs-on: ${{ matrix.os }} steps: From 57ac312e309ddea7aab23129edc96f41c97ff85b Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 10 Jan 2022 05:52:57 -0800 Subject: [PATCH 117/283] Update README.md --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 992a7694d..37eeefb38 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,16 @@ inspired this project. ### FAQ +#### What version of Go is required to run these examples? + +Given Go's strong [backwards compatibility guarantees](https://go.dev/doc/go1compat), +we expect the vast majority of examples to work on the latest released version of Go +as well as many older releases going back years. + +That said, some examples show off new features added in the latest release; therefore, +it's recommended to try running examples with the latest officially released Go version +(see Go's [release history](https://go.dev/doc/devel/release) for details). + #### I'm getting output in a different order from the example. Is the example wrong? Some of the examples demonstrate concurrent code which has a non-deterministic From 2885fc22986dd09e6b30ae1cd1176691506675f0 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 28 Jan 2022 09:26:30 -0800 Subject: [PATCH 118/283] Move around commend in recursion sample for better rendering This way the commend renders next to the right code block --- examples/recursion/recursion.go | 2 +- examples/recursion/recursion.hash | 4 ++-- public/recursion | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/recursion/recursion.go b/examples/recursion/recursion.go index 515a7ca25..f0ce4e1ea 100644 --- a/examples/recursion/recursion.go +++ b/examples/recursion/recursion.go @@ -27,10 +27,10 @@ func main() { if n < 2 { return n } - return fib(n-1) + fib(n-2) // Since `fib` was previously declared in `main`, Go // knows which function to call with `fib` here. + return fib(n-1) + fib(n-2) } fmt.Println(fib(7)) diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index 2157ee241..026010039 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -02b9ee049def729d92a63fa13eddef5ce5358640 -yDJXBAPUR7V +9ac9b5af828c33eb20dd322fd1a991334242c4b3 +7hD-3-bIuSp diff --git a/public/recursion b/public/recursion index 84f8aee28..1ead8266c 100644 --- a/public/recursion +++ b/public/recursion @@ -43,7 +43,7 @@ Here’s a classic example.

    - +
    package main
     
    @@ -116,7 +116,6 @@ before it’s defined.

    if n < 2 { return n } - return fib(n-1) + fib(n-2)
    @@ -130,6 +129,7 @@ knows which function to call with fib here.

    +        return fib(n-1) + fib(n-2)
         }
     
    @@ -178,7 +178,7 @@ knows which function to call with fib here.

    From ff399c700162fc63556faf3014552d1e3fcb2298 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 4 Feb 2022 16:49:44 -0800 Subject: [PATCH 119/283] Starting a strings-runes example For now just the code, no output, no comments For #411 --- examples/strings-runes/strings-runes.go | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 examples/strings-runes/strings-runes.go diff --git a/examples/strings-runes/strings-runes.go b/examples/strings-runes/strings-runes.go new file mode 100644 index 000000000..cbac78ec9 --- /dev/null +++ b/examples/strings-runes/strings-runes.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "unicode/utf8" +) + +// TODO: Thai hello, vowels + +func main() { + const hello = "สวัสดี" + foo(hello) +} + +func foo(s string) { + fmt.Println("Len:", len(s)) + + for i := 0; i < len(s); i++ { + fmt.Printf("%x ", s[i]) + } + fmt.Println() + + fmt.Println("Rune count:", utf8.RuneCountInString(s)) + + for idx, runeValue := range s { + fmt.Printf("%#U starts at %d\n", runeValue, idx) + } + + fmt.Println("\nUsing DecodeRuneInString") + for i, w := 0, 0; i < len(s); i += w { + runeValue, width := utf8.DecodeRuneInString(s[i:]) + fmt.Printf("%#U starts at %d\n", runeValue, i) + w = width + + examineRune(runeValue) + } +} + +func examineRune(r rune) { + if r == 't' { + fmt.Println("found tee") + } else if r == 'ส' { + fmt.Println("found so sua") + } +} From b2057ccfd28904a7eb6cb1866853ec8155eafbe1 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 5 Feb 2022 07:08:26 -0800 Subject: [PATCH 120/283] strings-and-runes: added comments, output and listed in examples --- examples.txt | 1 + .../strings-and-runes/strings-and-runes.go | 73 +++++ .../strings-and-runes/strings-and-runes.hash | 2 + .../strings-and-runes/strings-and-runes.sh | 20 ++ examples/strings-runes/strings-runes.go | 45 --- public/index.html | 2 + public/pointers | 4 +- public/strings-and-runes | 287 ++++++++++++++++++ public/structs | 2 +- 9 files changed, 388 insertions(+), 48 deletions(-) create mode 100644 examples/strings-and-runes/strings-and-runes.go create mode 100644 examples/strings-and-runes/strings-and-runes.hash create mode 100644 examples/strings-and-runes/strings-and-runes.sh delete mode 100644 examples/strings-runes/strings-runes.go create mode 100644 public/strings-and-runes diff --git a/examples.txt b/examples.txt index 88fb70c74..961eea23a 100644 --- a/examples.txt +++ b/examples.txt @@ -15,6 +15,7 @@ Variadic Functions Closures Recursion Pointers +Strings and Runes Structs Methods Interfaces diff --git a/examples/strings-and-runes/strings-and-runes.go b/examples/strings-and-runes/strings-and-runes.go new file mode 100644 index 000000000..d46b99ae3 --- /dev/null +++ b/examples/strings-and-runes/strings-and-runes.go @@ -0,0 +1,73 @@ +// A Go string is a read-only slice of bytes. The language +// and the standard library treat strings specially - as +// containers of text encoded in [UTF-8](https://en.wikipedia.org/wiki/UTF-8). +// In other languages, strings are made of "characters". +// In Go, the concept of a character is called a `rune` - it's +// an integer that represents a Unicode code point. +// [This Go blog post](https://go.dev/blog/strings) is a good +// introduction to the topic. + +package main + +import ( + "fmt" + "unicode/utf8" +) + +func main() { + + // `s` is a `string` assigned a literal value + // representing the world "hello" in the Thai + // language. Go string literals are UTF-8 + // encoded text. + const s = "สวัสดี" + + // Since strings are equivalent to `[]byte`, this + // will produce the length of the raw bytes stored within. + fmt.Println("Len:", len(s)) + + // Indexing into a string produces the raw byte values at + // each index. This loop generates the hex values of all + // the bytes that constitute the code points in `s`. + for i := 0; i < len(s); i++ { + fmt.Printf("%x ", s[i]) + } + fmt.Println() + + // To count how many _runes_ are in a string, we can use + // the `utf8` package. Note that the run-time of + // `RuneCountInString` dependes on the size of the string, + // because it has to decode each UTF-8 rune sequentially. + // Some Thai characters are represented by multiple UTF-8 + // code points, so the result of this count may be surprising. + fmt.Println("Rune count:", utf8.RuneCountInString(s)) + + // A `range` loop handles strings specially and decodes + // each `rune` along with its offset in the string. + for idx, runeValue := range s { + fmt.Printf("%#U starts at %d\n", runeValue, idx) + } + + // We can achieve the same iteration by using the + // `utf8.DecodeRuneInString` function explicitly. + fmt.Println("\nUsing DecodeRuneInString") + for i, w := 0, 0; i < len(s); i += w { + runeValue, width := utf8.DecodeRuneInString(s[i:]) + fmt.Printf("%#U starts at %d\n", runeValue, i) + w = width + + // This demonstrates passing a `rune` value to a function. + examineRune(runeValue) + } +} + +func examineRune(r rune) { + + // Values enclosed in single quotes are _rune literals_. We + // can compare a `rune` value to a rune literal directly. + if r == 't' { + fmt.Println("found tee") + } else if r == 'ส' { + fmt.Println("found so sua") + } +} diff --git a/examples/strings-and-runes/strings-and-runes.hash b/examples/strings-and-runes/strings-and-runes.hash new file mode 100644 index 000000000..47b900602 --- /dev/null +++ b/examples/strings-and-runes/strings-and-runes.hash @@ -0,0 +1,2 @@ +c96321f2951af50985c648779a3a41d0b48007a7 +jDBFShEYIwP diff --git a/examples/strings-and-runes/strings-and-runes.sh b/examples/strings-and-runes/strings-and-runes.sh new file mode 100644 index 000000000..34bb1f6da --- /dev/null +++ b/examples/strings-and-runes/strings-and-runes.sh @@ -0,0 +1,20 @@ +$ go run strings-and-runes.go +Len: 18 +e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5 +Rune count: 6 +U+0E2A 'ส' starts at 0 +U+0E27 'ว' starts at 3 +U+0E31 'ั' starts at 6 +U+0E2A 'ส' starts at 9 +U+0E14 'ด' starts at 12 +U+0E35 'ี' starts at 15 + +Using DecodeRuneInString +U+0E2A 'ส' starts at 0 +found so sua +U+0E27 'ว' starts at 3 +U+0E31 'ั' starts at 6 +U+0E2A 'ส' starts at 9 +found so sua +U+0E14 'ด' starts at 12 +U+0E35 'ี' starts at 15 diff --git a/examples/strings-runes/strings-runes.go b/examples/strings-runes/strings-runes.go deleted file mode 100644 index cbac78ec9..000000000 --- a/examples/strings-runes/strings-runes.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "fmt" - "unicode/utf8" -) - -// TODO: Thai hello, vowels - -func main() { - const hello = "สวัสดี" - foo(hello) -} - -func foo(s string) { - fmt.Println("Len:", len(s)) - - for i := 0; i < len(s); i++ { - fmt.Printf("%x ", s[i]) - } - fmt.Println() - - fmt.Println("Rune count:", utf8.RuneCountInString(s)) - - for idx, runeValue := range s { - fmt.Printf("%#U starts at %d\n", runeValue, idx) - } - - fmt.Println("\nUsing DecodeRuneInString") - for i, w := 0, 0; i < len(s); i += w { - runeValue, width := utf8.DecodeRuneInString(s[i:]) - fmt.Printf("%#U starts at %d\n", runeValue, i) - w = width - - examineRune(runeValue) - } -} - -func examineRune(r rune) { - if r == 't' { - fmt.Println("found tee") - } else if r == 'ส' { - fmt.Println("found so sua") - } -} diff --git a/public/index.html b/public/index.html index 125edc3ac..4ec3917e2 100644 --- a/public/index.html +++ b/public/index.html @@ -61,6 +61,8 @@

    Go by Example

  • Pointers
  • +
  • Strings and Runes
  • +
  • Structs
  • Methods
  • diff --git a/public/pointers b/public/pointers index 908cd5f4a..c1a9d48d9 100644 --- a/public/pointers +++ b/public/pointers @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'structs'; + window.location.href = 'strings-and-runes'; } } @@ -179,7 +179,7 @@ the memory address for that variable.

    - Next example: Structs. + Next example: Strings and Runes.

    diff --git a/public/strings-and-runes b/public/strings-and-runes new file mode 100644 index 000000000..689669de0 --- /dev/null +++ b/public/strings-and-runes @@ -0,0 +1,287 @@ + + + + + Go by Example: Strings and Runes + + + + +
    +

    Go by Example: Strings and Runes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    A Go string is a read-only slice of bytes. The language +and the standard library treat strings specially - as +containers of text encoded in UTF-8. +In other languages, strings are made of “characters”. +In Go, the concept of a character is called a rune - it’s +an integer that represents a Unicode code point. +This Go blog post is a good +introduction to the topic.

    + +
    + + +
    + + + +
    package main
    +
    +
    + + + +
    import (
    +    "fmt"
    +    "unicode/utf8"
    +)
    +
    +
    + + + +
    func main() {
    +
    +
    +

    s is a string assigned a literal value +representing the world “hello” in the Thai +language. Go string literals are UTF-8 +encoded text.

    + +
    + +
    +    const s = "สวัสดี"
    +
    +
    +

    Since strings are equivalent to []byte, this +will produce the length of the raw bytes stored within.

    + +
    + +
    +    fmt.Println("Len:", len(s))
    +
    +
    +

    Indexing into a string produces the raw byte values at +each index. This loop generates the hex values of all +the bytes that constitute the code points in s.

    + +
    + +
    +    for i := 0; i < len(s); i++ {
    +        fmt.Printf("%x ", s[i])
    +    }
    +    fmt.Println()
    +
    +
    +

    To count how many runes are in a string, we can use +the utf8 package. Note that the run-time of +RuneCountInString dependes on the size of the string, +because it has to decode each UTF-8 rune sequentially. +Some Thai characters are represented by multiple UTF-8 +code points, so the result of this count may be surprising.

    + +
    + +
    +    fmt.Println("Rune count:", utf8.RuneCountInString(s))
    +
    +
    +

    A range loop handles strings specially and decodes +each rune along with its offset in the string.

    + +
    + +
    +    for idx, runeValue := range s {
    +        fmt.Printf("%#U starts at %d\n", runeValue, idx)
    +    }
    +
    +
    +

    We can achieve the same iteration by using the +utf8.DecodeRuneInString function explicitly.

    + +
    + +
    +    fmt.Println("\nUsing DecodeRuneInString")
    +    for i, w := 0, 0; i < len(s); i += w {
    +        runeValue, width := utf8.DecodeRuneInString(s[i:])
    +        fmt.Printf("%#U starts at %d\n", runeValue, i)
    +        w = width
    +
    +
    +

    This demonstrates passing a rune value to a function.

    + +
    + +
    +        examineRune(runeValue)
    +    }
    +}
    +
    +
    + + + +
    func examineRune(r rune) {
    +
    +
    +

    Values enclosed in single quotes are rune literals. We +can compare a rune value to a rune literal directly.

    + +
    + +
    +    if r == 't' {
    +        fmt.Println("found tee")
    +    } else if r == 'ส' {
    +        fmt.Println("found so sua")
    +    }
    +}
    +
    +
    + + + + + + + + + + + + + +
    + + + +
    $ go run strings-and-runes.go
    +Len: 18
    +e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5 
    +Rune count: 6
    +U+0E2A 'ส' starts at 0
    +U+0E27 'ว' starts at 3
    +U+0E31 'ั' starts at 6
    +U+0E2A 'ส' starts at 9
    +U+0E14 'ด' starts at 12
    +U+0E35 'ี' starts at 15
    +
    + + + +
    Using DecodeRuneInString
    +U+0E2A 'ส' starts at 0
    +found so sua
    +U+0E27 'ว' starts at 3
    +U+0E31 'ั' starts at 6
    +U+0E2A 'ส' starts at 9
    +found so sua
    +U+0E14 'ด' starts at 12
    +U+0E35 'ี' starts at 15
    +
    + + +

    + Next example: Structs. +

    + + + + +
    + + + + diff --git a/public/structs b/public/structs index d74abeb9f..cbc34615c 100644 --- a/public/structs +++ b/public/structs @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'pointers'; + window.location.href = 'strings-and-runes'; } From e604254e38118bc4d46d55d0351ef07b2887a7d5 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 5 Feb 2022 07:11:37 -0800 Subject: [PATCH 121/283] Tweaks to other samples to accommodate strings-and-runes Add a link to the range sample, and remove partial mentions of this topic in string-functions since it's now covered well in strings-and-runes --- examples/range/range.go | 2 + examples/range/range.hash | 4 +- examples/string-functions/string-functions.go | 13 ----- .../string-functions/string-functions.hash | 4 +- examples/string-functions/string-functions.sh | 3 -- public/range | 6 ++- public/string-functions | 51 ++----------------- 7 files changed, 14 insertions(+), 69 deletions(-) diff --git a/examples/range/range.go b/examples/range/range.go index 011af674e..ec44c3fa0 100644 --- a/examples/range/range.go +++ b/examples/range/range.go @@ -42,6 +42,8 @@ func main() { // `range` on strings iterates over Unicode code // points. The first value is the starting byte index // of the `rune` and the second the `rune` itself. + // See [Strings and Runes](strings-and-runes) for more + // details. for i, c := range "go" { fmt.Println(i, c) } diff --git a/examples/range/range.hash b/examples/range/range.hash index f6e5a86ab..f2e2c7bc8 100644 --- a/examples/range/range.hash +++ b/examples/range/range.hash @@ -1,2 +1,2 @@ -c7d9ae9ed081fb4bbf27ef45242fbb39bbae3d4c -pdZOtv4g-7J +c8da490660d234fc420f39d9b8a4aba27f8aba46 +kRsyWNmLFLz diff --git a/examples/string-functions/string-functions.go b/examples/string-functions/string-functions.go index 676e904e5..5686f711c 100644 --- a/examples/string-functions/string-functions.go +++ b/examples/string-functions/string-functions.go @@ -35,17 +35,4 @@ func main() { p("ToLower: ", s.ToLower("TEST")) p("ToUpper: ", s.ToUpper("test")) p() - - // Not part of `strings`, but worth mentioning here, are - // the mechanisms for getting the length of a string in - // bytes and getting a byte by index. - p("Len: ", len("hello")) - p("Char:", "hello"[1]) } - -// Note that `len` and indexing above work at the byte level. -// Go uses UTF-8 encoded strings, so this is often useful -// as-is. If you're working with potentially multi-byte -// characters you'll want to use encoding-aware operations. -// See [strings, bytes, runes and characters in Go](https://blog.golang.org/strings) -// for more information. diff --git a/examples/string-functions/string-functions.hash b/examples/string-functions/string-functions.hash index 68fb9a490..5f8521251 100644 --- a/examples/string-functions/string-functions.hash +++ b/examples/string-functions/string-functions.hash @@ -1,2 +1,2 @@ -33b15b8c999ba65564b965b96cbfeadac0d1637d -fZ_FqN5WlSz +2201eba7e3b9339a6e700a4faa9b085c43dd1ed2 +pE_KNt12Zv9 diff --git a/examples/string-functions/string-functions.sh b/examples/string-functions/string-functions.sh index b83688dea..a38da5e7e 100644 --- a/examples/string-functions/string-functions.sh +++ b/examples/string-functions/string-functions.sh @@ -11,6 +11,3 @@ Replace: f0o Split: [a b c d e] ToLower: test ToUpper: TEST - -Len: 5 -Char: 101 diff --git a/public/range b/public/range index c151ca215..f1fb5b42a 100644 --- a/public/range +++ b/public/range @@ -43,7 +43,7 @@ of the data structures we’ve already learned.

    - +
    package main
     
    @@ -146,7 +146,9 @@ the indexes though.

    range on strings iterates over Unicode code points. The first value is the starting byte index -of the rune and the second the rune itself.

    +of the rune and the second the rune itself. +See Strings and Runes for more +details.

    diff --git a/public/string-functions b/public/string-functions index bb363ac88..19849cd4d 100644 --- a/public/string-functions +++ b/public/string-functions @@ -43,7 +43,7 @@ to give you a sense of the package.

    - +
    package main
     
    @@ -99,7 +99,7 @@ functions in the strings - +
         p("Contains:  ", s.Contains("test", "es"))
    @@ -115,43 +115,11 @@ package docs.

    p("ToLower: ", s.ToLower("TEST")) p("ToUpper: ", s.ToUpper("test")) p() -
    - - - - - -

    Not part of strings, but worth mentioning here, are -the mechanisms for getting the length of a string in -bytes and getting a byte by index.

    - - - - -
    -    p("Len: ", len("hello"))
    -    p("Char:", "hello"[1])
     }
     
    - - -

    Note that len and indexing above work at the byte level. -Go uses UTF-8 encoded strings, so this is often useful -as-is. If you’re working with potentially multi-byte -characters you’ll want to use encoding-aware operations. -See strings, bytes, runes and characters in Go -for more information.

    - - - - - - - - @@ -160,7 +128,7 @@ for more information.

    - - - - - -
    +
    $ go run string-functions.go
     Contains:   true
    @@ -178,17 +146,6 @@ for more information.

    - - - -
    Len:  5
    -Char: 101
    -
    @@ -204,7 +161,7 @@ for more information.

    From 35018ab3c9237d05fdb45c57d6587b0660cb9f15 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 5 Feb 2022 07:20:06 -0800 Subject: [PATCH 122/283] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 37eeefb38..e38618fb0 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,12 @@ inspired this project. ### FAQ +#### I found a problem with the examples; what do I do? + +We're very happy to fix problem reports and accept contributions! Please submit +[an issue](https://github.com/mmcgrana/gobyexample/issues) or send a Pull Request. +See `CONTRIBUTING.md` for more details. + #### What version of Go is required to run these examples? Given Go's strong [backwards compatibility guarantees](https://go.dev/doc/go1compat), From 2c7b3846695e7dd20bd7de3d7011239e4e0b158b Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 5 Feb 2022 07:22:56 -0800 Subject: [PATCH 123/283] Clean up last printout in string-functions It's unnecessary now --- examples/string-functions/string-functions.go | 1 - examples/string-functions/string-functions.hash | 4 ++-- public/string-functions | 5 ++--- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/examples/string-functions/string-functions.go b/examples/string-functions/string-functions.go index 5686f711c..7a26e2860 100644 --- a/examples/string-functions/string-functions.go +++ b/examples/string-functions/string-functions.go @@ -34,5 +34,4 @@ func main() { p("Split: ", s.Split("a-b-c-d-e", "-")) p("ToLower: ", s.ToLower("TEST")) p("ToUpper: ", s.ToUpper("test")) - p() } diff --git a/examples/string-functions/string-functions.hash b/examples/string-functions/string-functions.hash index 5f8521251..81e3bf005 100644 --- a/examples/string-functions/string-functions.hash +++ b/examples/string-functions/string-functions.hash @@ -1,2 +1,2 @@ -2201eba7e3b9339a6e700a4faa9b085c43dd1ed2 -pE_KNt12Zv9 +e52d4023b8102ba47f3f97e67e47da1bfe393e6c +mdta6dlNB6e diff --git a/public/string-functions b/public/string-functions index 19849cd4d..aae6f68dd 100644 --- a/public/string-functions +++ b/public/string-functions @@ -43,7 +43,7 @@ to give you a sense of the package.

    - +
    package main
     
    @@ -114,7 +114,6 @@ package docs.

    p("Split: ", s.Split("a-b-c-d-e", "-")) p("ToLower: ", s.ToLower("TEST")) p("ToUpper: ", s.ToUpper("test")) - p() }
    @@ -161,7 +160,7 @@ package docs.

    From 0f801fd5f377a065b1c5050fe15f631d7975d7f5 Mon Sep 17 00:00:00 2001 From: Konstantin Kovshenin Date: Thu, 10 Feb 2022 16:25:18 +0300 Subject: [PATCH 124/283] Fix typo in strings-and-runes (#414) --- examples/strings-and-runes/strings-and-runes.go | 2 +- public/strings-and-runes | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/strings-and-runes/strings-and-runes.go b/examples/strings-and-runes/strings-and-runes.go index d46b99ae3..36974819d 100644 --- a/examples/strings-and-runes/strings-and-runes.go +++ b/examples/strings-and-runes/strings-and-runes.go @@ -17,7 +17,7 @@ import ( func main() { // `s` is a `string` assigned a literal value - // representing the world "hello" in the Thai + // representing the word "hello" in the Thai // language. Go string literals are UTF-8 // encoded text. const s = "สวัสดี" diff --git a/public/strings-and-runes b/public/strings-and-runes index 689669de0..028ca7b86 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -82,7 +82,7 @@ introduction to the topic.

    s is a string assigned a literal value -representing the world “hello” in the Thai +representing the word “hello” in the Thai language. Go string literals are UTF-8 encoded text.

    From 5fa0d40cdbb004a26676cc82348d0944d8e93dd2 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 10 Feb 2022 05:27:34 -0800 Subject: [PATCH 125/283] Re-generate output after #414 --- examples/strings-and-runes/strings-and-runes.hash | 4 ++-- public/strings-and-runes | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/strings-and-runes/strings-and-runes.hash b/examples/strings-and-runes/strings-and-runes.hash index 47b900602..299528cdb 100644 --- a/examples/strings-and-runes/strings-and-runes.hash +++ b/examples/strings-and-runes/strings-and-runes.hash @@ -1,2 +1,2 @@ -c96321f2951af50985c648779a3a41d0b48007a7 -jDBFShEYIwP +766c486b73701deb5af9a3f5249d4febc3beda89 +y9AcFzz3UJn diff --git a/public/strings-and-runes b/public/strings-and-runes index 028ca7b86..25a0f5d28 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -48,7 +48,7 @@ introduction to the topic.

    - +
    package main
     
    From ccfd710f2ba4f28593f86902af100fff629688ed Mon Sep 17 00:00:00 2001 From: Arash Sameni <74505991+ArashSameni@users.noreply.github.com> Date: Fri, 11 Feb 2022 00:16:38 +0330 Subject: [PATCH 126/283] Templates: added comments, output and listed in examples (#413) --- examples.txt | 1 + examples/text-templates/text-templates.go | 115 ++++++ examples/text-templates/text-templates.hash | 2 + examples/text-templates/text-templates.sh | 24 ++ public/index.html | 2 + public/json | 2 +- public/regular-expressions | 4 +- public/text-templates | 402 ++++++++++++++++++++ 8 files changed, 549 insertions(+), 3 deletions(-) create mode 100644 examples/text-templates/text-templates.go create mode 100644 examples/text-templates/text-templates.hash create mode 100644 examples/text-templates/text-templates.sh create mode 100644 public/text-templates diff --git a/examples.txt b/examples.txt index 961eea23a..c0b749838 100644 --- a/examples.txt +++ b/examples.txt @@ -48,6 +48,7 @@ Collection Functions String Functions String Formatting Regular Expressions +Text Templates JSON XML Time diff --git a/examples/text-templates/text-templates.go b/examples/text-templates/text-templates.go new file mode 100644 index 000000000..cd0d9a015 --- /dev/null +++ b/examples/text-templates/text-templates.go @@ -0,0 +1,115 @@ +// Go offers built-in support for creating +// dynamic content or showing customized output to the user called Template. + +package main + +// Go has two template packages. one is "text/template" for +// regular text manipulation, and another one is "html/template" +// which has the same API as "text/template" but has additional security features. +// It should be used when generating HTML. +import ( + "log" + "os" + "text/template" +) + +func main() { + + // New creates a template with a specific name and returns a pointer to it. + t1 := template.New("t1") + + // Parse parses its parameter as template body. + // We use {{.}} to access the value passed to the template when it's getting executed. + t1, err := t1.Parse("Value is {{.}}\n") + if err != nil { + log.Fatal(err) + } + + // If we want to ignore the errors we can use Must function. + // It will panic if an error occurs when parsing the template. + t1 = template.Must(t1.Parse("Value is {{.}}\n")) + + // Execute applies parsed template to the data we pass to it and writes the output to the io.Writer. + t1.Execute(os.Stdout, t1.Name()) + t1.Execute(os.Stdout, "some text") + t1.Execute(os.Stdout, true) + t1.Execute(os.Stdout, 5) + t1.Execute(os.Stdout, []string{ + "Go", + "Rust", + "C++", + "C#", + }) + t1.Execute(os.Stdout, struct{ name string }{ + name: "Jane Doe", + }) + + // If the data is a struct we can use the {{.FieldName}} action to access its fields. + // The fields should be exported to be accessible when template is executing. + t2, _ := template. + New("t2"). + Parse("Fullname: {{.Fullname}}\n") + + t2.Execute(os.Stdout, struct { + Fullname string + }{ + Fullname: "Jane Doe", + }) + + // The same applies to maps; with maps there is no restriction on the case of key names. + t2.Execute(os.Stdout, map[string]string{ + "Fullname": "Mickey Mouse", + }) + + // You can use if control structure to show data conditionally. + // The data between if block will be shown if the field is truthy. + // Means it is not false boolean, empty string, nil or zero length slice, nil map/pointer. + t3, _ := template. + New("t3"). + Parse(`{{if .Field1}} + If block => {{.Field1}} + {{ else if .Field2}} + Else if block => {{.Field2}} + {{ else }} + Else block + {{ end }}`) + + s := struct { + Field1 string + Field2 []string + }{} + + s.Field1 = "" + s.Field2 = []string{} + t3.Execute(os.Stdout, s) + + s.Field1 = "Some text" + s.Field2 = nil + t3.Execute(os.Stdout, s) + + // Using a range action you can loop through a slice. + // Each time the range block is getting executed dot will be set + // to current item of slice. + t4, _ := template. + New("t4"). + Parse(`Range: {{ range . }} + {{.}} + {{ end }}`) + t4.Execute(os.Stdout, + []string{ + "Go", + "Rust", + "C++", + "C#", + }) + + // You can assign and reassign a value to a variable in templates. + t5, _ := template. + New("t5"). + Parse(`Variables: + {{ $language := "go" }} + {{ $language }} + {{ $language = "C" }} + {{ $language }}`) + t5.Execute(os.Stdout, nil) +} diff --git a/examples/text-templates/text-templates.hash b/examples/text-templates/text-templates.hash new file mode 100644 index 000000000..d0418a680 --- /dev/null +++ b/examples/text-templates/text-templates.hash @@ -0,0 +1,2 @@ +69a28314f7ebd877b184b35a8166e2fcaab56754 +-mRr-NuSB6f diff --git a/examples/text-templates/text-templates.sh b/examples/text-templates/text-templates.sh new file mode 100644 index 000000000..3cf70b938 --- /dev/null +++ b/examples/text-templates/text-templates.sh @@ -0,0 +1,24 @@ +$ go run templates.go +Value is t1 +Value is some text +Value is true +Value is 5 +Value is [Go Rust C++ C#] +Value is {Jane Doe} +Fullname: Jane Doe +Fullname: Mickey Mouse + + Else block + + Else if block => Some text +Range: + Go + + Rust + + C++ + + C# +Variables: +go +C diff --git a/public/index.html b/public/index.html index 4ec3917e2..5dbce3413 100644 --- a/public/index.html +++ b/public/index.html @@ -127,6 +127,8 @@

    Go by Example

  • Regular Expressions
  • +
  • Text Templates
  • +
  • JSON
  • XML
  • diff --git a/public/json b/public/json index e8cb478bb..c437bd119 100644 --- a/public/json +++ b/public/json @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'regular-expressions'; + window.location.href = 'text-templates'; } diff --git a/public/regular-expressions b/public/regular-expressions index e6592eaf3..806d67f3a 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'json'; + window.location.href = 'text-templates'; } } @@ -329,7 +329,7 @@ the regexp package docs

    - Next example: JSON. + Next example: Text Templates.

    diff --git a/public/text-templates b/public/text-templates new file mode 100644 index 000000000..1f03b49c9 --- /dev/null +++ b/public/text-templates @@ -0,0 +1,402 @@ + + + + + Go by Example: Text Templates + + + + +
    +

    Go by Example: Text Templates

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Go offers built-in support for creating +dynamic content or showing customized output to the user called Template.

    + +
    + + +
    + + + +
    package main
    +
    +
    +

    Go has two template packages. one is “text/template” for +regular text manipulation, and another one is “html/template” +which has the same API as “text/template” but has additional security features. +It should be used when generating HTML.

    + +
    + +
    +import (
    +    "log"
    +    "os"
    +    "text/template"
    +)
    +
    +
    + + + +
    func main() {
    +
    +
    +

    New creates a template with a specific name and returns a pointer to it.

    + +
    + +
    +    t1 := template.New("t1")
    +
    +
    +

    Parse parses its parameter as template body. +We use {{.}} to access the value passed to the template when it’s getting executed.

    + +
    + +
    +    t1, err := t1.Parse("Value is {{.}}\n")
    +    if err != nil {
    +        log.Fatal(err)
    +    }
    +
    +
    +

    If we want to ignore the errors we can use Must function. +It will panic if an error occurs when parsing the template.

    + +
    + +
    +    t1 = template.Must(t1.Parse("Value is {{.}}\n"))
    +
    +
    +

    Execute applies parsed template to the data we pass to it and writes the output to the io.Writer.

    + +
    + +
    +    t1.Execute(os.Stdout, t1.Name())
    +    t1.Execute(os.Stdout, "some text")
    +    t1.Execute(os.Stdout, true)
    +    t1.Execute(os.Stdout, 5)
    +    t1.Execute(os.Stdout, []string{
    +        "Go",
    +        "Rust",
    +        "C++",
    +        "C#",
    +    })
    +    t1.Execute(os.Stdout, struct{ name string }{
    +        name: "Jane Doe",
    +    })
    +
    +
    +

    If the data is a struct we can use the {{.FieldName}} action to access its fields. +The fields should be exported to be accessible when template is executing.

    + +
    + +
    +    t2, _ := template.
    +        New("t2").
    +        Parse("Fullname: {{.Fullname}}\n")
    +
    +
    + + + +
        t2.Execute(os.Stdout, struct {
    +        Fullname string
    +    }{
    +        Fullname: "Jane Doe",
    +    })
    +
    +
    +

    The same applies to maps; with maps there is no restriction on the case of key names.

    + +
    + +
    +    t2.Execute(os.Stdout, map[string]string{
    +        "Fullname": "Mickey Mouse",
    +    })
    +
    +
    +

    You can use if control structure to show data conditionally. +The data between if block will be shown if the field is truthy. +Means it is not false boolean, empty string, nil or zero length slice, nil map/pointer.

    + +
    + +
    +    t3, _ := template.
    +        New("t3").
    +        Parse(`{{if .Field1}}
    +                    If block => {{.Field1}}
    +                {{ else if .Field2}}
    +                    Else if block => {{.Field2}}
    +                {{ else }}
    +                    Else block
    +                {{ end }}`)
    +
    +
    + + + +
        s := struct {
    +        Field1 string
    +        Field2 []string
    +    }{}
    +
    +
    + + + +
        s.Field1 = ""
    +    s.Field2 = []string{}
    +    t3.Execute(os.Stdout, s)
    +
    +
    + + + +
        s.Field1 = "Some text"
    +    s.Field2 = nil
    +    t3.Execute(os.Stdout, s)
    +
    +
    +

    Using a range action you can loop through a slice. +Each time the range block is getting executed dot will be set +to current item of slice.

    + +
    + +
    +    t4, _ := template.
    +        New("t4").
    +        Parse(`Range: {{ range . }}
    +                        {{.}}
    +                      {{ end }}`)
    +    t4.Execute(os.Stdout,
    +        []string{
    +            "Go",
    +            "Rust",
    +            "C++",
    +            "C#",
    +        })
    +
    +
    +

    You can assign and reassign a value to a variable in templates.

    + +
    + +
    +    t5, _ := template.
    +        New("t5").
    +        Parse(`Variables: {{ $language := "go" }}
    +                    {{ $language }}
    +                    {{ $language = "C" }}
    +                    {{ $language }}`)
    +    t5.Execute(os.Stdout, nil)
    +}
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    $ go run templates.go 
    +Value is my-template
    +Value is some text
    +Value is true
    +Value is 5
    +Value is [Go Rust C++ C#]
    +Value is {Jane Doe}
    +Fullname: Jane Doe
    +Fullname: Mickey Mouse
    +
    + + + +
            Else block
    +
    + + + +
            Else if block => Some text
    +Range: 
    +        Go
    +
    + + + +
            Rust
    +
    + + + +
            C++
    +
    + + + +
            C#
    +Variables: 
    +go
    +C
    +
    + + +

    + Next example: JSON. +

    + + + + +
    + + + + From 0751f43b3ae30c0361f13466ff1e7cd934c4b86d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 10 Feb 2022 13:54:06 -0800 Subject: [PATCH 127/283] Round of fixes for the new text-template example Making it a bit cleaner and easier to understand --- examples/text-templates/text-templates.go | 120 ++++------ examples/text-templates/text-templates.hash | 4 +- examples/text-templates/text-templates.sh | 31 +-- public/text-templates | 250 +++++--------------- 4 files changed, 117 insertions(+), 288 deletions(-) diff --git a/examples/text-templates/text-templates.go b/examples/text-templates/text-templates.go index cd0d9a015..ec391fde9 100644 --- a/examples/text-templates/text-templates.go +++ b/examples/text-templates/text-templates.go @@ -1,38 +1,36 @@ -// Go offers built-in support for creating -// dynamic content or showing customized output to the user called Template. +// Go offers built-in support for creating dynamic content or showing customized +// output to the user with the `text/template` package. A sibling package +// named `html/template` provides the same API but has additional security +// features and should be used for generating HTML. package main -// Go has two template packages. one is "text/template" for -// regular text manipulation, and another one is "html/template" -// which has the same API as "text/template" but has additional security features. -// It should be used when generating HTML. import ( - "log" "os" "text/template" ) func main() { - // New creates a template with a specific name and returns a pointer to it. + // We can create a new template and parse its body from + // a string. + // Templates are a mix of static text and "actions" enclosed in + // `{{...}}` that are used to dynamically insert content. t1 := template.New("t1") - - // Parse parses its parameter as template body. - // We use {{.}} to access the value passed to the template when it's getting executed. t1, err := t1.Parse("Value is {{.}}\n") if err != nil { - log.Fatal(err) + panic(err) } - // If we want to ignore the errors we can use Must function. - // It will panic if an error occurs when parsing the template. - t1 = template.Must(t1.Parse("Value is {{.}}\n")) + // Alternatively, we can use the `template.Must` function to + // panic in case `Parse` returns an error. This is especially + // useful for templates initialized in the global scope. + t1 = template.Must(t1.Parse("Value: {{.}}\n")) - // Execute applies parsed template to the data we pass to it and writes the output to the io.Writer. - t1.Execute(os.Stdout, t1.Name()) + // By "executing" the template we generate its text with + // specific values for its actions. The `{{.}}` action is + // replaced by the value passed as a parameter to `Execute`. t1.Execute(os.Stdout, "some text") - t1.Execute(os.Stdout, true) t1.Execute(os.Stdout, 5) t1.Execute(os.Stdout, []string{ "Go", @@ -40,61 +38,41 @@ func main() { "C++", "C#", }) - t1.Execute(os.Stdout, struct{ name string }{ - name: "Jane Doe", - }) - // If the data is a struct we can use the {{.FieldName}} action to access its fields. - // The fields should be exported to be accessible when template is executing. - t2, _ := template. - New("t2"). - Parse("Fullname: {{.Fullname}}\n") + // Helper function we'll use below. + Create := func(name, t string) *template.Template { + return template.Must(template.New(name).Parse(t)) + } + + // If the data is a struct we can use the `{{.FieldName}}` action to access + // its fields. The fields should be exported to be accessible when a + // template is executing. + t2 := Create("t2", "Name: {{.Name}}\n") t2.Execute(os.Stdout, struct { - Fullname string - }{ - Fullname: "Jane Doe", - }) + Name string + }{"Jane Doe"}) - // The same applies to maps; with maps there is no restriction on the case of key names. + // The same applies to maps; with maps there is no restriction on the + // case of key names. t2.Execute(os.Stdout, map[string]string{ - "Fullname": "Mickey Mouse", + "Name": "Mickey Mouse", }) - // You can use if control structure to show data conditionally. - // The data between if block will be shown if the field is truthy. - // Means it is not false boolean, empty string, nil or zero length slice, nil map/pointer. - t3, _ := template. - New("t3"). - Parse(`{{if .Field1}} - If block => {{.Field1}} - {{ else if .Field2}} - Else if block => {{.Field2}} - {{ else }} - Else block - {{ end }}`) - - s := struct { - Field1 string - Field2 []string - }{} - - s.Field1 = "" - s.Field2 = []string{} - t3.Execute(os.Stdout, s) - - s.Field1 = "Some text" - s.Field2 = nil - t3.Execute(os.Stdout, s) - - // Using a range action you can loop through a slice. - // Each time the range block is getting executed dot will be set - // to current item of slice. - t4, _ := template. - New("t4"). - Parse(`Range: {{ range . }} - {{.}} - {{ end }}`) + // if/else provide conditional execution for templates. A value is considered + // false if it's the default value of a type, such as 0, an empty string, + // nil pointer, etc. + // This sample demonstrates another + // feature of templates: using `-` in actions to trim whitespace. + t3 := Create("t3", + "{{if . -}} yes {{else -}} no {{end}}\n") + t3.Execute(os.Stdout, "not empty") + t3.Execute(os.Stdout, "") + + // range blocks let us loop through slices, arrays, maps or channels. Inside + // the range block `{{.}}` is set to the current item of the iteration. + t4 := Create("t4", + "Range: {{range .}}{{.}} {{end}}\n") t4.Execute(os.Stdout, []string{ "Go", @@ -102,14 +80,4 @@ func main() { "C++", "C#", }) - - // You can assign and reassign a value to a variable in templates. - t5, _ := template. - New("t5"). - Parse(`Variables: - {{ $language := "go" }} - {{ $language }} - {{ $language = "C" }} - {{ $language }}`) - t5.Execute(os.Stdout, nil) } diff --git a/examples/text-templates/text-templates.hash b/examples/text-templates/text-templates.hash index d0418a680..859241b2f 100644 --- a/examples/text-templates/text-templates.hash +++ b/examples/text-templates/text-templates.hash @@ -1,2 +1,2 @@ -69a28314f7ebd877b184b35a8166e2fcaab56754 --mRr-NuSB6f +c29676a83f4832a77b7a9e300d3fb5fe315de7b8 +pDwkw1iMACF diff --git a/examples/text-templates/text-templates.sh b/examples/text-templates/text-templates.sh index 3cf70b938..4c951f1b9 100644 --- a/examples/text-templates/text-templates.sh +++ b/examples/text-templates/text-templates.sh @@ -1,24 +1,9 @@ $ go run templates.go -Value is t1 -Value is some text -Value is true -Value is 5 -Value is [Go Rust C++ C#] -Value is {Jane Doe} -Fullname: Jane Doe -Fullname: Mickey Mouse - - Else block - - Else if block => Some text -Range: - Go - - Rust - - C++ - - C# -Variables: -go -C +Value: some text +Value: 5 +Value: [Go Rust C++ C#] +Name: Jane Doe +Name: Mickey Mouse +yes +no +Range: Go Rust C++ C# diff --git a/public/text-templates b/public/text-templates index 1f03b49c9..2b97618a8 100644 --- a/public/text-templates +++ b/public/text-templates @@ -27,8 +27,10 @@ -

    Go offers built-in support for creating -dynamic content or showing customized output to the user called Template.

    +

    Go offers built-in support for creating dynamic content or showing customized +output to the user with the text/template package. A sibling package +named html/template provides the same API but has additional security +features and should be used for generating HTML.

    @@ -42,7 +44,7 @@ dynamic content or showing customized output to the user called Template.

    - +
    package main
     
    @@ -50,17 +52,11 @@ dynamic content or showing customized output to the user called Template.

    -

    Go has two template packages. one is “text/template” for -regular text manipulation, and another one is “html/template” -which has the same API as “text/template” but has additional security features. -It should be used when generating HTML.

    - + -
    -import (
    -    "log"
    +          
    import (
         "os"
         "text/template"
     )
    @@ -81,29 +77,19 @@ It should be used when generating HTML.

    -

    New creates a template with a specific name and returns a pointer to it.

    +

    We can create a new template and parse its body from +a string. +Templates are a mix of static text and “actions” enclosed in +{{...}} that are used to dynamically insert content.

         t1 := template.New("t1")
    -
    - - - - - -

    Parse parses its parameter as template body. -We use {{.}} to access the value passed to the template when it’s getting executed.

    - - - - -
         t1, err := t1.Parse("Value is {{.}}\n")
         if err != nil {
    -        log.Fatal(err)
    +        panic(err)
         }
     
    @@ -111,29 +97,30 @@ We use {{.}} to access the value passed to the template when it’s getting -

    If we want to ignore the errors we can use Must function. -It will panic if an error occurs when parsing the template.

    +

    Alternatively, we can use the template.Must function to +panic in case Parse returns an error. This is especially +useful for templates initialized in the global scope.

    -    t1 = template.Must(t1.Parse("Value is {{.}}\n"))
    +    t1 = template.Must(t1.Parse("Value: {{.}}\n"))
     
    -

    Execute applies parsed template to the data we pass to it and writes the output to the io.Writer.

    +

    By “executing” the template we generate its text with +specific values for its actions. The {{.}} action is +replaced by the value passed as a parameter to Execute.

    -    t1.Execute(os.Stdout, t1.Name())
         t1.Execute(os.Stdout, "some text")
    -    t1.Execute(os.Stdout, true)
         t1.Execute(os.Stdout, 5)
         t1.Execute(os.Stdout, []string{
             "Go",
    @@ -141,78 +128,36 @@ It will panic if an error occurs when parsing the template.

    "C++", "C#", }) - t1.Execute(os.Stdout, struct{ name string }{ - name: "Jane Doe", - })
    -

    If the data is a struct we can use the {{.FieldName}} action to access its fields. -The fields should be exported to be accessible when template is executing.

    +

    Helper function we’ll use below.

    -    t2, _ := template.
    -        New("t2").
    -        Parse("Fullname: {{.Fullname}}\n")
    -
    - - - - - - - - - -
        t2.Execute(os.Stdout, struct {
    -        Fullname string
    -    }{
    -        Fullname: "Jane Doe",
    -    })
    -
    - - - - - -

    The same applies to maps; with maps there is no restriction on the case of key names.

    - - - - -
    -    t2.Execute(os.Stdout, map[string]string{
    -        "Fullname": "Mickey Mouse",
    -    })
    +    Create := func(name, t string) *template.Template {
    +        return template.Must(template.New(name).Parse(t))
    +    }
     
    -

    You can use if control structure to show data conditionally. -The data between if block will be shown if the field is truthy. -Means it is not false boolean, empty string, nil or zero length slice, nil map/pointer.

    +

    If the data is a struct we can use the {{.FieldName}} action to access +its fields. The fields should be exported to be accessible when a +template is executing.

    -    t3, _ := template.
    -        New("t3").
    -        Parse(`{{if .Field1}}
    -                    If block => {{.Field1}}
    -                {{ else if .Field2}}
    -                    Else if block => {{.Field2}}
    -                {{ else }}
    -                    Else block
    -                {{ end }}`)
    +    t2 := Create("t2", "Name: {{.Name}}\n")
     
    @@ -223,55 +168,60 @@ Means it is not false boolean, empty string, nil or zero length slice, nil map/ -
        s := struct {
    -        Field1 string
    -        Field2 []string
    -    }{}
    +          
        t2.Execute(os.Stdout, struct {
    +        Name string
    +    }{"Jane Doe"})
     
    - +

    The same applies to maps; with maps there is no restriction on the +case of key names.

    + -
        s.Field1 = ""
    -    s.Field2 = []string{}
    -    t3.Execute(os.Stdout, s)
    +          
    +    t2.Execute(os.Stdout, map[string]string{
    +        "Name": "Mickey Mouse",
    +    })
     
    - +

    if/else provide conditional execution for templates. A value is considered +false if it’s the default value of a type, such as 0, an empty string, +nil pointer, etc. +This sample demonstrates another +feature of templates: using - in actions to trim whitespace.

    + -
        s.Field1 = "Some text"
    -    s.Field2 = nil
    -    t3.Execute(os.Stdout, s)
    +          
    +    t3 := Create("t3",
    +        "{{if . -}} yes {{else -}} no {{end}}\n")
    +    t3.Execute(os.Stdout, "not empty")
    +    t3.Execute(os.Stdout, "")
     
    -

    Using a range action you can loop through a slice. -Each time the range block is getting executed dot will be set -to current item of slice.

    +

    range blocks let us loop through slices, arrays, maps or channels. Inside +the range block {{.}} is set to the current item of the iteration.

    - +
    -    t4, _ := template.
    -        New("t4").
    -        Parse(`Range: {{ range . }}
    -                        {{.}}
    -                      {{ end }}`)
    +    t4 := Create("t4",
    +        "Range: {{range .}}{{.}} {{end}}\n")
         t4.Execute(os.Stdout,
             []string{
                 "Go",
    @@ -279,25 +229,6 @@ to current item of slice.

    "C++", "C#", }) -
    - - - - - -

    You can assign and reassign a value to a variable in templates.

    - - - - -
    -    t5, _ := template.
    -        New("t5").
    -        Parse(`Variables: {{ $language := "go" }}
    -                    {{ $language }}
    -                    {{ $language = "C" }}
    -                    {{ $language }}`)
    -    t5.Execute(os.Stdout, nil)
     }
     
    @@ -307,76 +238,21 @@ to current item of slice.

    - - - - - - - - - - - - - - - - - - - - - - - - - @@ -395,7 +271,7 @@ to current item of slice.

    From 1fa5cff95ced866de11a69189c02b4155b2ffd40 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 11 Feb 2022 06:19:37 -0800 Subject: [PATCH 128/283] Reorder examples slightly Text Templates should come right after String Formatting --- examples.txt | 2 +- public/index.html | 4 ++-- public/json | 2 +- public/regular-expressions | 6 +++--- public/string-formatting | 4 ++-- public/text-templates | 6 +++--- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/examples.txt b/examples.txt index c0b749838..c30951101 100644 --- a/examples.txt +++ b/examples.txt @@ -47,8 +47,8 @@ Recover Collection Functions String Functions String Formatting -Regular Expressions Text Templates +Regular Expressions JSON XML Time diff --git a/public/index.html b/public/index.html index 5dbce3413..14d1d60f5 100644 --- a/public/index.html +++ b/public/index.html @@ -125,10 +125,10 @@

    Go by Example

  • String Formatting
  • -
  • Regular Expressions
  • -
  • Text Templates
  • +
  • Regular Expressions
  • +
  • JSON
  • XML
  • diff --git a/public/json b/public/json index c437bd119..e8cb478bb 100644 --- a/public/json +++ b/public/json @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'text-templates'; + window.location.href = 'regular-expressions'; } diff --git a/public/regular-expressions b/public/regular-expressions index 806d67f3a..76a0d56c0 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -9,12 +9,12 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'string-formatting'; + window.location.href = 'text-templates'; } if (e.key == "ArrowRight") { - window.location.href = 'text-templates'; + window.location.href = 'json'; } } @@ -329,7 +329,7 @@ the regexp package docs

    - Next example: Text Templates. + Next example: JSON.

    diff --git a/public/string-formatting b/public/string-formatting index 8bd5dd210..43618a1d0 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'regular-expressions'; + window.location.href = 'text-templates'; } } @@ -442,7 +442,7 @@ and returns a string without printing it anywhere.

    - Next example: Regular Expressions. + Next example: Text Templates.

    diff --git a/public/text-templates b/public/text-templates index 2b97618a8..665eb5bd3 100644 --- a/public/text-templates +++ b/public/text-templates @@ -9,12 +9,12 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'regular-expressions'; + window.location.href = 'string-formatting'; } if (e.key == "ArrowRight") { - window.location.href = 'json'; + window.location.href = 'regular-expressions'; } } @@ -260,7 +260,7 @@ the range block {{.}} is set to the current item of the iteration.<

    - Next example: JSON. + Next example: Regular Expressions.

    From 5c36a19ea85beadd72204e0c446fc769795c9162 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 14 Mar 2022 05:52:39 -0700 Subject: [PATCH 129/283] Try rc1 1.18 version for go testing --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b49f3d46c..45e8e8744 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,14 +12,14 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.17.x] + go-version: [1.17.x, 1.18.0-rc.1] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} From 3c2447b2d17245be129fdae0646b8954735b620d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 15 Mar 2022 10:53:49 -0700 Subject: [PATCH 130/283] Add example of Go generics (#415) * Add example of Go generics Fixes #349 * Remove TODO * Update public link * Update GitHub action to only build with 1.18-rc1 1.17 won't successfully build the generics example --- .github/workflows/test.yml | 2 +- examples.txt | 1 + examples/generics/generics.go | 74 ++++++++++ examples/generics/generics.hash | 2 + examples/generics/generics.sh | 2 + public/embedding | 4 +- public/errors | 2 +- public/generics | 250 ++++++++++++++++++++++++++++++++ public/index.html | 2 + 9 files changed, 335 insertions(+), 4 deletions(-) create mode 100644 examples/generics/generics.go create mode 100644 examples/generics/generics.hash create mode 100644 examples/generics/generics.sh create mode 100644 public/generics diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 45e8e8744..2dfed23fb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.17.x, 1.18.0-rc.1] + go-version: [1.18.0-rc.1] runs-on: ${{ matrix.os }} steps: diff --git a/examples.txt b/examples.txt index c30951101..a1e4ef36f 100644 --- a/examples.txt +++ b/examples.txt @@ -20,6 +20,7 @@ Structs Methods Interfaces Embedding +Generics Errors Goroutines Channels diff --git a/examples/generics/generics.go b/examples/generics/generics.go new file mode 100644 index 000000000..de20e28a5 --- /dev/null +++ b/examples/generics/generics.go @@ -0,0 +1,74 @@ +// Starting with version 1.18, Go has added support for +// _generics_, also known as _type parameters_. + +package main + +import "fmt" + +// As an example of a generic function, `MapKeys` takes +// a map of any type and returns a slice of its keys. +// This function has two type parameters - `K` and `V`; +// `K` has the `comparable` _constraint_, meaning that +// we can compare values of this type with the `==` and +// `!=` operators. This is required for map keys in Go. +// `V` has the `any` constraint, meaning that it's not +// restricted in any way (`any` is an alias for `interface{}`). +func MapKeys[K comparable, V any](m map[K]V) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + return r +} + +// As an example of a generic type, `List` is a +// singly-linked list with values of any type. +type List[T any] struct { + head, tail *element[T] +} + +type element[T any] struct { + next *element[T] + val T +} + +// We can define methods on generic types just like we +// do on regular types, but we have to keep the type +// parameters in place. The type is `List[T]`, not `List`. +func (lst *List[T]) Push(v T) { + if lst.tail == nil { + lst.head = &element[T]{val: v} + lst.tail = lst.head + } else { + lst.tail.next = &element[T]{val: v} + lst.tail = lst.tail.next + } +} + +func (lst *List[T]) GetAll() []T { + var elems []T + for e := lst.head; e != nil; e = e.next { + elems = append(elems, e.val) + } + return elems +} + +func main() { + var m = map[int]string{1: "2", 2: "4", 4: "8"} + + // When invoking generic functions, we can often rely + // on _type inference_. Note that we don't have to + // specify the types for `K` and `V` when + // calling `MapKeys` - the compiler infers them + // automatically. + fmt.Println("keys m:", MapKeys(m)) + + // ... though we could also specify them explicitly. + _ = MapKeys[int, string](m) + + lst := List[int]{} + lst.Push(10) + lst.Push(13) + lst.Push(23) + fmt.Println("list:", lst.GetAll()) +} diff --git a/examples/generics/generics.hash b/examples/generics/generics.hash new file mode 100644 index 000000000..77ce621d5 --- /dev/null +++ b/examples/generics/generics.hash @@ -0,0 +1,2 @@ +6219a4dadc2685ab1b61dc8e95799fd683ccb761 +YulcAofh266 diff --git a/examples/generics/generics.sh b/examples/generics/generics.sh new file mode 100644 index 000000000..4e59904c5 --- /dev/null +++ b/examples/generics/generics.sh @@ -0,0 +1,2 @@ +keys: [4 1 2] +list: [10 13 23] diff --git a/public/embedding b/public/embedding index 7e089e121..7630a2ca8 100644 --- a/public/embedding +++ b/public/embedding @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'errors'; + window.location.href = 'generics'; } } @@ -230,7 +230,7 @@ we see that a container now implements the

    - Next example: Errors. + Next example: Generics.

    diff --git a/public/errors b/public/errors index 4ac669ad1..e7340a705 100644 --- a/public/errors +++ b/public/errors @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'embedding'; + window.location.href = 'generics'; } diff --git a/public/generics b/public/generics new file mode 100644 index 000000000..bddca503c --- /dev/null +++ b/public/generics @@ -0,0 +1,250 @@ + + + + + Go by Example: Generics + + + + +
    +

    Go by Example: Generics

    + +
    - - - -
    $ go run templates.go 
    -Value is my-template
    -Value is some text
    -Value is true
    -Value is 5
    -Value is [Go Rust C++ C#]
    -Value is {Jane Doe}
    -Fullname: Jane Doe
    -Fullname: Mickey Mouse
    -
    - - - -
            Else block
    -
    - - - -
            Else if block => Some text
    -Range: 
    -        Go
    -
    - - - -
            Rust
    -
    - - - -
            C++
    -
    -
            C#
    -Variables: 
    -go
    -C
    +
    $ go run templates.go 
    +Value: some text
    +Value: 5
    +Value: [Go Rust C++ C#]
    +Name: Jane Doe
    +Name: Mickey Mouse
    +yes 
    +no 
    +Range: Go Rust C++ C# 
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Starting with version 1.18, Go has added support for +generics, also known as type parameters.

    + +
    + + +
    + + + +
    package main
    +
    +
    + + + +
    import "fmt"
    +
    +
    +

    As an example of a generic function, MapKeys takes +a map of any type and returns a slice of its keys. +This function has two type parameters - K and V; +K has the comparable constraint, meaning that +we can compare values of this type with the == and +!= operators. This is required for map keys in Go. +V has the any constraint, meaning that it’s not +restricted in any way (any is an alias for interface{}).

    + +
    + +
    +func MapKeys[K comparable, V any](m map[K]V) []K {
    +    r := make([]K, 0, len(m))
    +    for k := range m {
    +        r = append(r, k)
    +    }
    +    return r
    +}
    +
    +
    +

    As an example of a generic type, List is a +singly-linked list with values of any type.

    + +
    + +
    +type List[T any] struct {
    +    head, tail *element[T]
    +}
    +
    +
    + + + +
    type element[T any] struct {
    +    next *element[T]
    +    val  T
    +}
    +
    +
    +

    We can define methods on generic types just like we +do on regular types, but we have to keep the type +parameters in place. The type is List[T], not List.

    + +
    + +
    +func (lst *List[T]) Push(v T) {
    +    if lst.tail == nil {
    +        lst.head = &element[T]{val: v}
    +        lst.tail = lst.head
    +    } else {
    +        lst.tail.next = &element[T]{val: v}
    +        lst.tail = lst.tail.next
    +    }
    +}
    +
    +
    + + + +
    func (lst *List[T]) GetAll() []T {
    +    var elems []T
    +    for e := lst.head; e != nil; e = e.next {
    +        elems = append(elems, e.val)
    +    }
    +    return elems
    +}
    +
    +
    + + + +
    func main() {
    +    var m = map[int]string{1: "2", 2: "4", 4: "8"}
    +
    +
    +

    When invoking generic functions, we can often rely +on type inference. Note that we don’t have to +specify the types for K and V when +calling MapKeys - the compiler infers them +automatically.

    + +
    + +
    +    fmt.Println("keys m:", MapKeys(m))
    +
    +
    +

    … though we could also specify them explicitly.

    + +
    + +
    +    _ = MapKeys[int, string](m)
    +
    +
    + + + +
        lst := List[int]{}
    +    lst.Push(10)
    +    lst.Push(13)
    +    lst.Push(23)
    +    fmt.Println("list:", lst.GetAll())
    +}
    +
    +
    + + + + + + + + +
    + + + +
    keys: [4 1 2]
    +list: [10 13 23]
    +
    + + +

    + Next example: Errors. +

    + + + + + + + + + diff --git a/public/index.html b/public/index.html index 14d1d60f5..c7ef0c4a9 100644 --- a/public/index.html +++ b/public/index.html @@ -71,6 +71,8 @@

    Go by Example

  • Embedding
  • +
  • Generics
  • +
  • Errors
  • Goroutines
  • From 881bb5d41ca723a2437304351d910a2612f1c066 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 15 Mar 2022 10:55:33 -0700 Subject: [PATCH 131/283] Remove collection-functions Now that we have generics, this example is not relevant. Updates #349 --- examples.txt | 1 - .../collection-functions.go | 113 ------------------ .../collection-functions.hash | 2 - .../collection-functions.sh | 7 -- public/index.html | 2 - public/recover | 4 +- public/string-functions | 2 +- 7 files changed, 3 insertions(+), 128 deletions(-) delete mode 100644 examples/collection-functions/collection-functions.go delete mode 100644 examples/collection-functions/collection-functions.hash delete mode 100644 examples/collection-functions/collection-functions.sh diff --git a/examples.txt b/examples.txt index a1e4ef36f..6772826d6 100644 --- a/examples.txt +++ b/examples.txt @@ -45,7 +45,6 @@ Sorting by Functions Panic Defer Recover -Collection Functions String Functions String Formatting Text Templates diff --git a/examples/collection-functions/collection-functions.go b/examples/collection-functions/collection-functions.go deleted file mode 100644 index 730644c57..000000000 --- a/examples/collection-functions/collection-functions.go +++ /dev/null @@ -1,113 +0,0 @@ -// We often need our programs to perform operations on -// collections of data, like selecting all items that -// satisfy a given predicate or mapping all items to a new -// collection with a custom function. - -// In some languages it's idiomatic to use [generic](http://en.wikipedia.org/wiki/Generic_programming) -// data structures and algorithms. Go does not support -// generics; in Go it's common to provide collection -// functions if and when they are specifically needed for -// your program and data types. - -// Here are some example collection functions for slices -// of `strings`. You can use these examples to build your -// own functions. Note that in some cases it may be -// clearest to just inline the collection-manipulating -// code directly, instead of creating and calling a -// helper function. - -package main - -import ( - "fmt" - "strings" -) - -// Index returns the first index of the target string `t`, or -// -1 if no match is found. -func Index(vs []string, t string) int { - for i, v := range vs { - if v == t { - return i - } - } - return -1 -} - -// Include returns `true` if the target string t is in the -// slice. -func Include(vs []string, t string) bool { - return Index(vs, t) >= 0 -} - -// Any returns `true` if one of the strings in the slice -// satisfies the predicate `f`. -func Any(vs []string, f func(string) bool) bool { - for _, v := range vs { - if f(v) { - return true - } - } - return false -} - -// All returns `true` if all of the strings in the slice -// satisfy the predicate `f`. -func All(vs []string, f func(string) bool) bool { - for _, v := range vs { - if !f(v) { - return false - } - } - return true -} - -// Filter returns a new slice containing all strings in the -// slice that satisfy the predicate `f`. -func Filter(vs []string, f func(string) bool) []string { - vsf := make([]string, 0) - for _, v := range vs { - if f(v) { - vsf = append(vsf, v) - } - } - return vsf -} - -// Map returns a new slice containing the results of applying -// the function `f` to each string in the original slice. -func Map(vs []string, f func(string) string) []string { - vsm := make([]string, len(vs)) - for i, v := range vs { - vsm[i] = f(v) - } - return vsm -} - -func main() { - - // Here we try out our various collection functions. - var strs = []string{"peach", "apple", "pear", "plum"} - - fmt.Println(Index(strs, "pear")) - - fmt.Println(Include(strs, "grape")) - - fmt.Println(Any(strs, func(v string) bool { - return strings.HasPrefix(v, "p") - })) - - fmt.Println(All(strs, func(v string) bool { - return strings.HasPrefix(v, "p") - })) - - fmt.Println(Filter(strs, func(v string) bool { - return strings.Contains(v, "e") - })) - - // The above examples all used anonymous functions, - // but you can also use named functions of the correct - // type. - fmt.Println(Map(strs, strings.ToUpper)) - -} diff --git a/examples/collection-functions/collection-functions.hash b/examples/collection-functions/collection-functions.hash deleted file mode 100644 index 27465b8db..000000000 --- a/examples/collection-functions/collection-functions.hash +++ /dev/null @@ -1,2 +0,0 @@ -002b2ee17f1111c7607a7b7742753af1b5a3c8c1 -uKnePZM91WV diff --git a/examples/collection-functions/collection-functions.sh b/examples/collection-functions/collection-functions.sh deleted file mode 100644 index 95dc0ee45..000000000 --- a/examples/collection-functions/collection-functions.sh +++ /dev/null @@ -1,7 +0,0 @@ -$ go run collection-functions.go -2 -false -true -false -[peach apple pear] -[PEACH APPLE PEAR PLUM] diff --git a/public/index.html b/public/index.html index c7ef0c4a9..5085e455b 100644 --- a/public/index.html +++ b/public/index.html @@ -121,8 +121,6 @@

    Go by Example

  • Recover
  • -
  • Collection Functions
  • -
  • String Functions
  • String Formatting
  • diff --git a/public/recover b/public/recover index 699c93569..3bda174ce 100644 --- a/public/recover +++ b/public/recover @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'collection-functions'; + window.location.href = 'string-functions'; } } @@ -180,7 +180,7 @@ panic and resumes in the deferred closure.

    - Next example: Collection Functions. + Next example: String Functions.

    diff --git a/public/string-functions b/public/string-functions index aae6f68dd..32a757d42 100644 --- a/public/string-functions +++ b/public/string-functions @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'collection-functions'; + window.location.href = 'recover'; } From 9a8d0aa5dae54deae1f7ff66009820eb3e64fba9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 15 Mar 2022 10:58:15 -0700 Subject: [PATCH 132/283] Remove collection-functions from public/ as well --- public/collection-functions | 369 ------------------------------------ 1 file changed, 369 deletions(-) delete mode 100644 public/collection-functions diff --git a/public/collection-functions b/public/collection-functions deleted file mode 100644 index 638293ff1..000000000 --- a/public/collection-functions +++ /dev/null @@ -1,369 +0,0 @@ - - - - - Go by Example: Collection Functions - - - - -
    -

    Go by Example: Collection Functions

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    We often need our programs to perform operations on -collections of data, like selecting all items that -satisfy a given predicate or mapping all items to a new -collection with a custom function.

    - -
    - - -
    -

    In some languages it’s idiomatic to use generic -data structures and algorithms. Go does not support -generics; in Go it’s common to provide collection -functions if and when they are specifically needed for -your program and data types.

    - -
    - - -
    -

    Here are some example collection functions for slices -of strings. You can use these examples to build your -own functions. Note that in some cases it may be -clearest to just inline the collection-manipulating -code directly, instead of creating and calling a -helper function.

    - -
    - - -
    - - - -
    package main
    -
    -
    - - - -
    import (
    -    "fmt"
    -    "strings"
    -)
    -
    -
    -

    Index returns the first index of the target string t, or --1 if no match is found.

    - -
    - -
    -func Index(vs []string, t string) int {
    -    for i, v := range vs {
    -        if v == t {
    -            return i
    -        }
    -    }
    -    return -1
    -}
    -
    -
    -

    Include returns true if the target string t is in the -slice.

    - -
    - -
    -func Include(vs []string, t string) bool {
    -    return Index(vs, t) >= 0
    -}
    -
    -
    -

    Any returns true if one of the strings in the slice -satisfies the predicate f.

    - -
    - -
    -func Any(vs []string, f func(string) bool) bool {
    -    for _, v := range vs {
    -        if f(v) {
    -            return true
    -        }
    -    }
    -    return false
    -}
    -
    -
    -

    All returns true if all of the strings in the slice -satisfy the predicate f.

    - -
    - -
    -func All(vs []string, f func(string) bool) bool {
    -    for _, v := range vs {
    -        if !f(v) {
    -            return false
    -        }
    -    }
    -    return true
    -}
    -
    -
    -

    Filter returns a new slice containing all strings in the -slice that satisfy the predicate f.

    - -
    - -
    -func Filter(vs []string, f func(string) bool) []string {
    -    vsf := make([]string, 0)
    -    for _, v := range vs {
    -        if f(v) {
    -            vsf = append(vsf, v)
    -        }
    -    }
    -    return vsf
    -}
    -
    -
    -

    Map returns a new slice containing the results of applying -the function f to each string in the original slice.

    - -
    - -
    -func Map(vs []string, f func(string) string) []string {
    -    vsm := make([]string, len(vs))
    -    for i, v := range vs {
    -        vsm[i] = f(v)
    -    }
    -    return vsm
    -}
    -
    -
    - - - -
    func main() {
    -
    -
    -

    Here we try out our various collection functions.

    - -
    - -
    -    var strs = []string{"peach", "apple", "pear", "plum"}
    -
    -
    - - - -
        fmt.Println(Index(strs, "pear"))
    -
    -
    - - - -
        fmt.Println(Include(strs, "grape"))
    -
    -
    - - - -
        fmt.Println(Any(strs, func(v string) bool {
    -        return strings.HasPrefix(v, "p")
    -    }))
    -
    -
    - - - -
        fmt.Println(All(strs, func(v string) bool {
    -        return strings.HasPrefix(v, "p")
    -    }))
    -
    -
    - - - -
        fmt.Println(Filter(strs, func(v string) bool {
    -        return strings.Contains(v, "e")
    -    }))
    -
    -
    -

    The above examples all used anonymous functions, -but you can also use named functions of the correct -type.

    - -
    - -
    -    fmt.Println(Map(strs, strings.ToUpper))
    -
    -
    - - - -
    }
    -
    -
    - - - - - - - - -
    - - - -
    $ go run collection-functions.go 
    -2
    -false
    -true
    -false
    -[peach apple pear]
    -[PEACH APPLE PEAR PLUM]
    -
    - - -

    - Next example: String Functions. -

    - - - - -
    - - - - From 1eba71e8f3e1efc701e785c1dbb9d18bab82ea48 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 15 Mar 2022 20:02:06 -0700 Subject: [PATCH 133/283] Set go-version to 1.18.0 in the builder (#416) --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2dfed23fb..e79402cc4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.18.0-rc.1] + go-version: [1.18.0] runs-on: ${{ matrix.os }} steps: From e6da67918c7a9e0e8b8573cd0d4db31f4ab1d130 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 17 Mar 2022 13:58:27 -0700 Subject: [PATCH 134/283] Update GH actions workflow badge in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e38618fb0..538bfd5d8 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ CloudFront, for example. ### Building -[![Build Status](https://github.com/mmcgrana/gobyexample/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/mmcgrana/gobyexample/actions) +[![test](https://github.com/mmcgrana/gobyexample/actions/workflows/test.yml/badge.svg)](https://github.com/mmcgrana/gobyexample/actions/workflows/test.yml) To build the site you'll need Go installed. Run: From ac01d2d4bb2315a24dcba1f735634c89e026deec Mon Sep 17 00:00:00 2001 From: Hayden B Date: Thu, 31 Mar 2022 05:41:58 -0700 Subject: [PATCH 135/283] Update SHA1 example to SHA256 (#418) This encourages the use of stronger cryptographic hashes. Tools such as securego/gosec will show errors when SHA1/MD5 hashes are used. --- examples.txt | 2 +- examples/sha1-hashes/sha1-hashes.hash | 2 - examples/sha1-hashes/sha1-hashes.sh | 14 ------ .../sha256-hashes.go} | 19 ++++---- examples/sha256-hashes/sha256-hashes.hash | 2 + examples/sha256-hashes/sha256-hashes.sh | 15 +++++++ public/base64-encoding | 2 +- public/index.html | 2 +- public/{sha1-hashes => sha256-hashes} | 44 +++++++++---------- public/url-parsing | 4 +- 10 files changed, 51 insertions(+), 55 deletions(-) delete mode 100644 examples/sha1-hashes/sha1-hashes.hash delete mode 100644 examples/sha1-hashes/sha1-hashes.sh rename examples/{sha1-hashes/sha1-hashes.go => sha256-hashes/sha256-hashes.go} (57%) create mode 100644 examples/sha256-hashes/sha256-hashes.hash create mode 100644 examples/sha256-hashes/sha256-hashes.sh rename public/{sha1-hashes => sha256-hashes} (74%) diff --git a/examples.txt b/examples.txt index 6772826d6..d83f7f799 100644 --- a/examples.txt +++ b/examples.txt @@ -57,7 +57,7 @@ Time Formatting / Parsing Random Numbers Number Parsing URL Parsing -SHA1 Hashes +SHA256 Hashes Base64 Encoding Reading Files Writing Files diff --git a/examples/sha1-hashes/sha1-hashes.hash b/examples/sha1-hashes/sha1-hashes.hash deleted file mode 100644 index 6313184a6..000000000 --- a/examples/sha1-hashes/sha1-hashes.hash +++ /dev/null @@ -1,2 +0,0 @@ -fc2de63b58865a6761749490ee217a94b4e343d1 -XLftf8Gvj4y diff --git a/examples/sha1-hashes/sha1-hashes.sh b/examples/sha1-hashes/sha1-hashes.sh deleted file mode 100644 index 3ed62c95e..000000000 --- a/examples/sha1-hashes/sha1-hashes.sh +++ /dev/null @@ -1,14 +0,0 @@ -# Running the program computes the hash and prints it in -# a human-readable hex format. -$ go run sha1-hashes.go -sha1 this string -cf23df2207d99a74fbe169e3eba035e633b65d94 - - -# You can compute other hashes using a similar pattern to -# the one shown above. For example, to compute MD5 hashes -# import `crypto/md5` and use `md5.New()`. - -# Note that if you need cryptographically secure hashes, -# you should carefully research -# [hash strength](http://en.wikipedia.org/wiki/Cryptographic_hash_function)! diff --git a/examples/sha1-hashes/sha1-hashes.go b/examples/sha256-hashes/sha256-hashes.go similarity index 57% rename from examples/sha1-hashes/sha1-hashes.go rename to examples/sha256-hashes/sha256-hashes.go index 24e59210b..eb437639f 100644 --- a/examples/sha1-hashes/sha1-hashes.go +++ b/examples/sha256-hashes/sha256-hashes.go @@ -1,26 +1,23 @@ -// [_SHA1 hashes_](http://en.wikipedia.org/wiki/SHA-1) are +// [_SHA256 hashes_](https://en.wikipedia.org/wiki/SHA-2) are // frequently used to compute short identities for binary -// or text blobs. For example, the [git revision control -// system](http://git-scm.com/) uses SHA1s extensively to -// identify versioned files and directories. Here's how to -// compute SHA1 hashes in Go. +// or text blobs. For example, TLS/SSL certificates use SHA256 +// to compute a certificate's signature. Here's how to compute +// SHA256 hashes in Go. package main // Go implements several hash functions in various // `crypto/*` packages. import ( - "crypto/sha1" + "crypto/sha256" "fmt" ) func main() { - s := "sha1 this string" + s := "sha256 this string" - // The pattern for generating a hash is `sha1.New()`, - // `sha1.Write(bytes)`, then `sha1.Sum([]byte{})`. // Here we start with a new hash. - h := sha1.New() + h := sha256.New() // `Write` expects bytes. If you have a string `s`, // use `[]byte(s)` to coerce it to bytes. @@ -31,7 +28,7 @@ func main() { // to an existing byte slice: it usually isn't needed. bs := h.Sum(nil) - // SHA1 values are often printed in hex, for example + // SHA256 values are often printed in hex, for example // in git commits. Use the `%x` format verb to convert // a hash results to a hex string. fmt.Println(s) diff --git a/examples/sha256-hashes/sha256-hashes.hash b/examples/sha256-hashes/sha256-hashes.hash new file mode 100644 index 000000000..79757591e --- /dev/null +++ b/examples/sha256-hashes/sha256-hashes.hash @@ -0,0 +1,2 @@ +21f16c864c11958f29949c491a9684bcb885831f +jIQtrUxWLvq diff --git a/examples/sha256-hashes/sha256-hashes.sh b/examples/sha256-hashes/sha256-hashes.sh new file mode 100644 index 000000000..bb7a81641 --- /dev/null +++ b/examples/sha256-hashes/sha256-hashes.sh @@ -0,0 +1,15 @@ +# Running the program computes the hash and prints it in +# a human-readable hex format. +$ go run sha256-hashes.go +sha256 this string +1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a... + + +# You can compute other hashes using a similar pattern to +# the one shown above. For example, to compute +# SHA512 hashes import `crypto/sha512` and use +# `sha512.New()`. + +# Note that if you need cryptographically secure hashes, +# you should carefully research +# [hash strength](https://en.wikipedia.org/wiki/Cryptographic_hash_function)! diff --git a/public/base64-encoding b/public/base64-encoding index e54904fb2..3a5c44e82 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'sha1-hashes'; + window.location.href = 'sha256-hashes'; } diff --git a/public/index.html b/public/index.html index 5085e455b..d4d26479e 100644 --- a/public/index.html +++ b/public/index.html @@ -145,7 +145,7 @@

    Go by Example

  • URL Parsing
  • -
  • SHA1 Hashes
  • +
  • SHA256 Hashes
  • Base64 Encoding
  • diff --git a/public/sha1-hashes b/public/sha256-hashes similarity index 74% rename from public/sha1-hashes rename to public/sha256-hashes index 053eedb53..48894ca0f 100644 --- a/public/sha1-hashes +++ b/public/sha256-hashes @@ -2,7 +2,7 @@ - Go by Example: SHA1 Hashes + Go by Example: SHA256 Hashes -
    -

    Go by Example: SHA1 Hashes

    +
    +

    Go by Example: SHA256 Hashes

    @@ -62,7 +61,7 @@ compute SHA1 hashes in Go.

     import (
    -    "crypto/sha1"
    +    "crypto/sha256"
         "fmt"
     )
     
    @@ -76,22 +75,20 @@ compute SHA1 hashes in Go.

    @@ -127,7 +124,7 @@ to an existing byte slice: it usually isn’t needed.

    @@ -124,15 +124,11 @@ to an existing byte slice: it usually isn’t needed.

    @@ -42,7 +42,7 @@ to express a more seamless composition of types.

    From 9deadb76aeb735445a4bcb36e465d16e12b758e7 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 6 May 2022 10:16:02 -0700 Subject: [PATCH 139/283] Improve spawning-process example with error-checking --- .../spawning-processes/spawning-processes.go | 25 ++++++++-- .../spawning-processes.hash | 4 +- .../spawning-processes/spawning-processes.sh | 5 +- public/spawning-processes | 49 +++++++++++++++---- 4 files changed, 67 insertions(+), 16 deletions(-) diff --git a/examples/spawning-processes/spawning-processes.go b/examples/spawning-processes/spawning-processes.go index 908fad391..891c21f3e 100644 --- a/examples/spawning-processes/spawning-processes.go +++ b/examples/spawning-processes/spawning-processes.go @@ -17,10 +17,10 @@ func main() { // to represent this external process. dateCmd := exec.Command("date") - // `.Output` is another helper that handles the common - // case of running a command, waiting for it to finish, - // and collecting its output. If there were no errors, - // `dateOut` will hold bytes with the date info. + // The `Output` method runs the command, waits for it + // to finish and collects its standard output. + // If there were no errors, `dateOut` will hold bytes + // with the date info. dateOut, err := dateCmd.Output() if err != nil { panic(err) @@ -28,6 +28,23 @@ func main() { fmt.Println("> date") fmt.Println(string(dateOut)) + // `Output` and other methods of `Command` will return + // `*exec.Error` if there was a problem executing the + // command (e.g. wrong path), and `*exec.ExitError` + // if the command ran but exited with a non-zero return + // code. + _, err = exec.Command("date", "-x").Output() + if err != nil { + switch e := err.(type) { + case *exec.Error: + fmt.Println("failed executing:", err) + case *exec.ExitError: + fmt.Println("command exit rc =", e.ExitCode()) + default: + panic(err) + } + } + // Next we'll look at a slightly more involved case // where we pipe data to the external process on its // `stdin` and collect the results from its `stdout`. diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index 9721992f4..011964455 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -aaedc48f74409cef2b8e9ad624aa1c4639ce630d -s-T7gxeD7hH +5303cfb969de556a875db17972b4107b6f70ba10 +rmnQdR-dMWU diff --git a/examples/spawning-processes/spawning-processes.sh b/examples/spawning-processes/spawning-processes.sh index a297f5bce..5a3202eb3 100644 --- a/examples/spawning-processes/spawning-processes.sh +++ b/examples/spawning-processes/spawning-processes.sh @@ -2,8 +2,11 @@ # as if we had run them directly from the command-line. $ go run spawning-processes.go > date -Wed Oct 10 09:53:11 PDT 2012 +Thu 05 May 2022 10:10:12 PM PDT +# date doesn't have a `-x` flag so it will exit with +# an error message and non-zero return code. +command exited with rc = 1 > grep hello hello grep diff --git a/public/spawning-processes b/public/spawning-processes index 14f405e6d..d96b37633 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -42,7 +42,7 @@ processes.

    @@ -92,10 +92,10 @@ to represent this external process.

    + + + + + @@ -249,7 +280,7 @@ as if we had run them directly from the command-line.

    From a19c5b87e6f8f946064b2a73af1619e415f04634 Mon Sep 17 00:00:00 2001 From: peterzhu1992 <35495810+peterzhu1992@users.noreply.github.com> Date: Tue, 17 May 2022 13:59:35 -0400 Subject: [PATCH 140/283] Rename embedding to struct embedding to be separated from //go:embed directive (#424) Signed-off-by: peterzhu1992 --- examples.txt | 2 +- examples/embedding/embedding.hash | 2 -- .../struct-embedding.go} | 3 +++ examples/struct-embedding/struct-embedding.hash | 2 ++ .../struct-embedding.sh} | 2 +- public/generics | 2 +- public/index.html | 2 +- public/interfaces | 4 ++-- public/{embedding => struct-embedding} | 15 +++++++++------ 9 files changed, 20 insertions(+), 14 deletions(-) delete mode 100644 examples/embedding/embedding.hash rename examples/{embedding/embedding.go => struct-embedding/struct-embedding.go} (89%) create mode 100644 examples/struct-embedding/struct-embedding.hash rename examples/{embedding/embedding.sh => struct-embedding/struct-embedding.sh} (76%) rename public/{embedding => struct-embedding} (94%) diff --git a/examples.txt b/examples.txt index d83f7f799..1c62e0138 100644 --- a/examples.txt +++ b/examples.txt @@ -19,7 +19,7 @@ Strings and Runes Structs Methods Interfaces -Embedding +Struct Embedding Generics Errors Goroutines diff --git a/examples/embedding/embedding.hash b/examples/embedding/embedding.hash deleted file mode 100644 index 4d55e33ce..000000000 --- a/examples/embedding/embedding.hash +++ /dev/null @@ -1,2 +0,0 @@ -316e334f61f03d59c8a45889a057903a786534ba -k5Z_CnP8DK9 diff --git a/examples/embedding/embedding.go b/examples/struct-embedding/struct-embedding.go similarity index 89% rename from examples/embedding/embedding.go rename to examples/struct-embedding/struct-embedding.go index 6bd021efe..856e5deac 100644 --- a/examples/embedding/embedding.go +++ b/examples/struct-embedding/struct-embedding.go @@ -1,5 +1,8 @@ // Go supports _embedding_ of structs and interfaces // to express a more seamless _composition_ of types. +// This is not to be confused with `//go:embed` which is +// a go directive introduced in Go version 1.16+ to embed +// files and folders into the application binary. package main diff --git a/examples/struct-embedding/struct-embedding.hash b/examples/struct-embedding/struct-embedding.hash new file mode 100644 index 000000000..388294848 --- /dev/null +++ b/examples/struct-embedding/struct-embedding.hash @@ -0,0 +1,2 @@ +a246237126303fb110186ac2598bca15d36e8366 +TqMui3hJuX7 diff --git a/examples/embedding/embedding.sh b/examples/struct-embedding/struct-embedding.sh similarity index 76% rename from examples/embedding/embedding.sh rename to examples/struct-embedding/struct-embedding.sh index 316095e55..02c90b36f 100644 --- a/examples/embedding/embedding.sh +++ b/examples/struct-embedding/struct-embedding.sh @@ -1,4 +1,4 @@ -$ go run embedding.go +$ go run struct-embedding.go co={num: 1, str: some name} also num: 1 describe: base with num=1 diff --git a/public/generics b/public/generics index bddca503c..2a2109315 100644 --- a/public/generics +++ b/public/generics @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'embedding'; + window.location.href = 'struct-embedding'; } diff --git a/public/index.html b/public/index.html index d4d26479e..a0c2e15fe 100644 --- a/public/index.html +++ b/public/index.html @@ -69,7 +69,7 @@

    Go by Example

  • Interfaces
  • -
  • Embedding
  • +
  • Struct Embedding
  • Generics
  • diff --git a/public/interfaces b/public/interfaces index 578bfabd9..a540bafe4 100644 --- a/public/interfaces +++ b/public/interfaces @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'embedding'; + window.location.href = 'struct-embedding'; } } @@ -222,7 +222,7 @@ these structs as arguments to measure.

    - Next example: Embedding. + Next example: Struct Embedding.

    diff --git a/public/embedding b/public/struct-embedding similarity index 94% rename from public/embedding rename to public/struct-embedding index 8ca4b7f60..176a97450 100644 --- a/public/embedding +++ b/public/struct-embedding @@ -2,7 +2,7 @@ - Go by Example: Embedding + Go by Example: Struct Embedding -
    -

    Go by Example: Embedding

    +
    +

    Go by Example: Struct Embedding

    -

    SHA1 hashes are +

    SHA256 hashes are frequently used to compute short identities for binary -or text blobs. For example, the git revision control -system uses SHA1s extensively to -identify versioned files and directories. Here’s how to -compute SHA1 hashes in Go.

    +or text blobs. For example, TLS/SSL certificates use SHA256 +to compute a certificate’s signature. Here’s how to compute +SHA256 hashes in Go.

    @@ -46,7 +45,7 @@ compute SHA1 hashes in Go.

    - +
    package main
     
    func main() {
    -    s := "sha1 this string"
    +    s := "sha256 this string"
     
    -

    The pattern for generating a hash is sha1.New(), -sha1.Write(bytes), then sha1.Sum([]byte{}). -Here we start with a new hash.

    +

    Here we start with a new hash.

    -    h := sha1.New()
    +    h := sha256.New()
     
    -

    SHA1 values are often printed in hex, for example +

    SHA256 values are often printed in hex, for example in git commits. Use the %x format verb to convert a hash results to a hex string.

    @@ -155,17 +152,18 @@ a human-readable hex format.

    -$ go run sha1-hashes.go
    -sha1 this string
    -cf23df2207d99a74fbe169e3eba035e633b65d94
    +$ go run sha256-hashes.go +sha256 this string +1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

    You can compute other hashes using a similar pattern to -the one shown above. For example, to compute MD5 hashes -import crypto/md5 and use md5.New().

    +the one shown above. For example, to compute +SHA512 hashes import crypto/sha512 and use +sha512.New().

    @@ -178,7 +176,7 @@ import crypto/md5 and use md5.New().

    Note that if you need cryptographically secure hashes, you should carefully research -hash strength!

    +hash strength!

    @@ -202,7 +200,7 @@ you should carefully research diff --git a/public/url-parsing b/public/url-parsing index 5c4916559..a60e14685 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'sha1-hashes'; + window.location.href = 'sha256-hashes'; } } @@ -222,7 +222,7 @@ pieces that we extracted.

    - Next example: SHA1 Hashes. + Next example: SHA256 Hashes.

    From ed7a09366216d64ca21d10ea3c13e1e57078b61f Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 31 Mar 2022 05:45:19 -0700 Subject: [PATCH 136/283] Clean up description in SHA256 example --- examples/sha256-hashes/sha256-hashes.go | 3 --- examples/sha256-hashes/sha256-hashes.hash | 4 ++-- public/sha256-hashes | 10 +++------- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/examples/sha256-hashes/sha256-hashes.go b/examples/sha256-hashes/sha256-hashes.go index eb437639f..0576060ed 100644 --- a/examples/sha256-hashes/sha256-hashes.go +++ b/examples/sha256-hashes/sha256-hashes.go @@ -28,9 +28,6 @@ func main() { // to an existing byte slice: it usually isn't needed. bs := h.Sum(nil) - // SHA256 values are often printed in hex, for example - // in git commits. Use the `%x` format verb to convert - // a hash results to a hex string. fmt.Println(s) fmt.Printf("%x\n", bs) } diff --git a/examples/sha256-hashes/sha256-hashes.hash b/examples/sha256-hashes/sha256-hashes.hash index 79757591e..87f56010f 100644 --- a/examples/sha256-hashes/sha256-hashes.hash +++ b/examples/sha256-hashes/sha256-hashes.hash @@ -1,2 +1,2 @@ -21f16c864c11958f29949c491a9684bcb885831f -jIQtrUxWLvq +66d0faf25cd171218b0fc0fc341836a4f0069932 +IHM1lZVm_Jm diff --git a/public/sha256-hashes b/public/sha256-hashes index 48894ca0f..28412cf13 100644 --- a/public/sha256-hashes +++ b/public/sha256-hashes @@ -45,7 +45,7 @@ SHA256 hashes in Go.

    - +
    package main
     
    -

    SHA256 values are often printed in hex, for example -in git commits. Use the %x format verb to convert -a hash results to a hex string.

    - +
    -
    -    fmt.Println(s)
    +          
        fmt.Println(s)
         fmt.Printf("%x\n", bs)
     }
     
    From e6c5a8fb2f22be5894c396d2229db8435d603fb1 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 2 May 2022 10:29:44 -0700 Subject: [PATCH 137/283] Fix typo in embedding example's comment Based on #420 by @smottt --- examples/embedding/embedding.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/embedding/embedding.go b/examples/embedding/embedding.go index f198dafef..6bd021efe 100644 --- a/examples/embedding/embedding.go +++ b/examples/embedding/embedding.go @@ -1,4 +1,4 @@ -// Go support _embedding_ of structs and interfaces +// Go supports _embedding_ of structs and interfaces // to express a more seamless _composition_ of types. package main From 6b91c38bb30d2a69c1b97309501aac9638c982e0 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 2 May 2022 10:30:17 -0700 Subject: [PATCH 138/283] Rebuild embedding example and publish public/ Closes #420 --- examples/embedding/embedding.hash | 4 ++-- public/embedding | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/embedding/embedding.hash b/examples/embedding/embedding.hash index fb9c19510..4d55e33ce 100644 --- a/examples/embedding/embedding.hash +++ b/examples/embedding/embedding.hash @@ -1,2 +1,2 @@ -8a15291c6e82b9c6873002e2aa5cef65907a3405 -Xtg07j06zBv +316e334f61f03d59c8a45889a057903a786534ba +k5Z_CnP8DK9 diff --git a/public/embedding b/public/embedding index 7630a2ca8..8ca4b7f60 100644 --- a/public/embedding +++ b/public/embedding @@ -27,7 +27,7 @@
    -

    Go support embedding of structs and interfaces +

    Go supports embedding of structs and interfaces to express a more seamless composition of types.

    - +
    package main
     
    - +
    package main
     
    -

    .Output is another helper that handles the common -case of running a command, waiting for it to finish, -and collecting its output. If there were no errors, -dateOut will hold bytes with the date info.

    +

    The Output method runs the command, waits for it +to finish and collects its standard output. + If there were no errors, dateOut will hold bytes +with the date info.

    @@ -111,6 +111,33 @@ and collecting its output. If there were no errors,
    +

    Output and other methods of Command will return +*exec.Error if there was a problem executing the +command (e.g. wrong path), and *exec.ExitError +if the command ran but exited with a non-zero return +code.

    + +
    + +
    +    _, err = exec.Command("date", "-x").Output()
    +    if err != nil {
    +        switch e := err.(type) {
    +        case *exec.Error:
    +            fmt.Println("failed executing:", err)
    +        case *exec.ExitError:
    +            fmt.Println("command exit rc =", e.ExitCode())
    +        default:
    +            panic(err)
    +        }
    +    }
    +
    +

    Next we’ll look at a slightly more involved case @@ -206,17 +233,21 @@ as if we had run them directly from the command-line.

     $ go run spawning-processes.go 
     > date
    -Wed Oct 10 09:53:11 PDT 2012
    +Thu 05 May 2022 10:10:12 PM PDT
    - +

    date doesn’t have a -x flag so it will exit with +an error message and non-zero return code.

    +
    -
    > grep hello
    +          
    +command exited with rc = 1
    +> grep hello
     hello grep
    @@ -218,7 +221,7 @@ we see that a container now implements the @@ -60,44 +59,47 @@ import it as we need to use the embed.FS type from the package.

    @@ -115,45 +117,28 @@ this single file, followed by variable single_file_string to access - - - - - @@ -164,7 +149,9 @@ then print out.

    @@ -183,10 +170,10 @@ this example can only be run on your local machine.)

    @@ -219,7 +206,7 @@ this example can only be run on your local machine.)

    From 5f2ab6c8a2112ed15b291954ab7ed5c4ed412bea Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 24 May 2022 06:28:18 -0700 Subject: [PATCH 144/283] More comment tweaks to the new embed-directive --- examples/embed-directive/embed-directive.go | 15 ++++++++------- examples/embed-directive/embed-directive.hash | 4 ++-- public/embed-directive | 19 ++++++++++--------- 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/examples/embed-directive/embed-directive.go b/examples/embed-directive/embed-directive.go index bd3a976bd..3cbbb0e67 100644 --- a/examples/embed-directive/embed-directive.go +++ b/examples/embed-directive/embed-directive.go @@ -1,7 +1,8 @@ -// `//go:embed` is a compiler directive that allows programs to include -// arbitrary files/folders in the binary at build time. Read more about go -// directives [here](https://pkg.go.dev/cmd/compile#hdr-Compiler_Directives) -// and about the embed directive [here](https://pkg.go.dev/embed). +// `//go:embed` is a [compiler +// directive](https://pkg.go.dev/cmd/compile#hdr-Compiler_Directives) that +// allows programs to include arbitrary files and folders in the Go binary at +// build time. Read more about the embed directive +// [here](https://pkg.go.dev/embed). package main // Import the `embed` package; if you don't use any exported @@ -10,9 +11,9 @@ import ( "embed" ) -// embed directives accept paths relative to the directory containing the -// Go source file. This directive embeds the contents of the file into a -// `string` variable. +// `embed` directives accept paths relative to the directory containing the +// Go source file. This directive embeds the contents of the file into the +// `string` variable immediately following it. //go:embed folder/single_file.txt var fileString string diff --git a/examples/embed-directive/embed-directive.hash b/examples/embed-directive/embed-directive.hash index 170913f8c..da30d5a9f 100644 --- a/examples/embed-directive/embed-directive.hash +++ b/examples/embed-directive/embed-directive.hash @@ -1,2 +1,2 @@ -82ad92029645b4fd1b5ef0cd9df3fecdf0a6764e -myu7kywm7oI +53a5e68182be7308ddb35cc209e6b905c5b9c713 +p6JB_5z1IBJ diff --git a/public/embed-directive b/public/embed-directive index 2743d7d6f..4735bc64a 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -27,14 +27,15 @@ diff --git a/public/atomic-counters b/public/atomic-counters index 04a30940b..6548101eb 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -46,7 +46,7 @@ counters accessed by multiple goroutines.

    diff --git a/public/base64-encoding b/public/base64-encoding index 3a5c44e82..c2db003ad 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -27,7 +27,7 @@ @@ -42,7 +42,7 @@ encoding/decoding.

    diff --git a/public/channel-buffering b/public/channel-buffering index 46b8c3fe4..3975022dd 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -46,7 +46,7 @@ those values.

    diff --git a/public/channel-directions b/public/channel-directions index c13ade243..5695a28f6 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -44,7 +44,7 @@ the program.

    diff --git a/public/channel-synchronization b/public/channel-synchronization index 055ab8347..9061590f4 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -45,7 +45,7 @@ you may prefer to use a WaitGroup.

    diff --git a/public/channels b/public/channels index 9c90f483f..3b161a72e 100644 --- a/public/channels +++ b/public/channels @@ -44,7 +44,7 @@ goroutine.

    diff --git a/public/closing-channels b/public/closing-channels index e4c94f599..d1fad4f3a 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -43,7 +43,7 @@ completion to the channel’s receivers.

    diff --git a/public/closures b/public/closures index 65fec27a7..8b8edd0aa 100644 --- a/public/closures +++ b/public/closures @@ -27,8 +27,8 @@ diff --git a/public/command-line-arguments b/public/command-line-arguments index 76324164d..b0d532205 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -27,7 +27,7 @@ diff --git a/public/command-line-flags b/public/command-line-flags index 6e5b46e43..92e2f2e15 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -27,7 +27,7 @@ diff --git a/public/command-line-subcommands b/public/command-line-subcommands index 81999bac8..9ea0cbaf5 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -46,7 +46,7 @@ subcommands that have their own flags.

    diff --git a/public/constants b/public/constants index 3123a0025..01884737d 100644 --- a/public/constants +++ b/public/constants @@ -42,7 +42,7 @@ and numeric values.

    diff --git a/public/context b/public/context index 227dfb8b4..59213e68f 100644 --- a/public/context +++ b/public/context @@ -36,7 +36,7 @@ across API boundaries and goroutines.

    diff --git a/public/directories b/public/directories index 8d5ce65ad..bef7856d9 100644 --- a/public/directories +++ b/public/directories @@ -42,7 +42,7 @@ diff --git a/public/embed-directive b/public/embed-directive index 4735bc64a..7b417808a 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -35,7 +35,7 @@ build time. Read more about the embed directive diff --git a/public/epoch b/public/epoch index c0943c6fc..890b66e76 100644 --- a/public/epoch +++ b/public/epoch @@ -29,7 +29,7 @@ @@ -44,7 +44,7 @@ Here’s how to do it in Go.

    diff --git a/public/errors b/public/errors index e7340a705..9444171a7 100644 --- a/public/errors +++ b/public/errors @@ -48,7 +48,7 @@ non-error tasks.

    @@ -268,7 +268,7 @@ assertion.

    diff --git a/public/execing-processes b/public/execing-processes index d8b7707fd..6e9c5a3d5 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -34,7 +34,7 @@ a running Go process. Sometimes we just want to completely replace the current Go process with another (perhaps non-Go) one. To do this we’ll use Go’s implementation of the classic -exec +exec function.

    @@ -49,7 +49,7 @@ function.

    diff --git a/public/exit b/public/exit index c7bedc21c..902ba7811 100644 --- a/public/exit +++ b/public/exit @@ -38,7 +38,7 @@ status.

    diff --git a/public/file-paths b/public/file-paths index 6fc44c51c..d129bde39 100644 --- a/public/file-paths +++ b/public/file-paths @@ -34,7 +34,7 @@ between operating systems; dir/file on Linux vs. diff --git a/public/functions b/public/functions index edfa0537f..74e730246 100644 --- a/public/functions +++ b/public/functions @@ -42,7 +42,7 @@ functions with a few different examples.

    diff --git a/public/generics b/public/generics index 2a2109315..6b4e6ec92 100644 --- a/public/generics +++ b/public/generics @@ -42,7 +42,7 @@ diff --git a/public/goroutines b/public/goroutines index c560f3ee0..957edc6bd 100644 --- a/public/goroutines +++ b/public/goroutines @@ -41,7 +41,7 @@ diff --git a/public/hello-world b/public/hello-world index e580e04d9..6f28be427 100644 --- a/public/hello-world +++ b/public/hello-world @@ -28,7 +28,7 @@ message. Here’s the full source code.

    @@ -155,7 +155,7 @@ in Go, but that the braces are required.

    @@ -209,7 +209,7 @@ these structs as arguments to measure.

    @@ -383,8 +383,8 @@ stream JSON encodings directly to os.Writers like diff --git a/public/line-filters b/public/line-filters index d6112e243..3fcb704a1 100644 --- a/public/line-filters +++ b/public/line-filters @@ -47,7 +47,7 @@ pattern to write your own Go line filters.

    @@ -42,7 +42,7 @@ diff --git a/public/methods b/public/methods index 7b7ea9c3b..b04b06334 100644 --- a/public/methods +++ b/public/methods @@ -41,7 +41,7 @@ diff --git a/public/multiple-return-values b/public/multiple-return-values index 8ca810f55..9fbc33d09 100644 --- a/public/multiple-return-values +++ b/public/multiple-return-values @@ -43,7 +43,7 @@ to return both result and error values from a function.

    diff --git a/public/mutexes b/public/mutexes index 9abb3ada3..8e42a7612 100644 --- a/public/mutexes +++ b/public/mutexes @@ -29,7 +29,7 @@ @@ -44,7 +44,7 @@ to safely access data across multiple goroutines.

    diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations index a19aae22f..08d4bd627 100644 --- a/public/non-blocking-channel-operations +++ b/public/non-blocking-channel-operations @@ -44,7 +44,7 @@ non-blocking multi-way selects.

    diff --git a/public/number-parsing b/public/number-parsing index 8a85221d1..af3d1d405 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -42,7 +42,7 @@ in many programs; here’s how to do it in Go.

    diff --git a/public/panic b/public/panic index a32e00c40..a93770ccd 100644 --- a/public/panic +++ b/public/panic @@ -44,7 +44,7 @@ aren’t prepared to handle gracefully.

    diff --git a/public/pointers b/public/pointers index c1a9d48d9..b57507ada 100644 --- a/public/pointers +++ b/public/pointers @@ -27,7 +27,7 @@ diff --git a/public/random-numbers b/public/random-numbers index 5ac6cf289..488191dc4 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -28,7 +28,7 @@ @@ -43,7 +43,7 @@ generation.

    @@ -200,7 +200,7 @@ produces the same sequence of random numbers.

    diff --git a/public/range-over-channels b/public/range-over-channels index 58a7ec1dd..bc4b71e71 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -44,7 +44,7 @@ values received from a channel.

    diff --git a/public/rate-limiting b/public/rate-limiting index b0f27fd94..ceb2a71ed 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -27,7 +27,7 @@ diff --git a/public/reading-files b/public/reading-files index b4199573c..58fc5bce8 100644 --- a/public/reading-files +++ b/public/reading-files @@ -43,7 +43,7 @@ reading files.

    diff --git a/public/recover b/public/recover index 3bda174ce..dda8527d2 100644 --- a/public/recover +++ b/public/recover @@ -60,7 +60,7 @@ does by default for HTTP servers.

    diff --git a/public/recursion b/public/recursion index 1ead8266c..413b684e4 100644 --- a/public/recursion +++ b/public/recursion @@ -28,7 +28,7 @@ @@ -43,7 +43,7 @@ Here’s a classic example.

    diff --git a/public/regular-expressions b/public/regular-expressions index 76a0d56c0..9f830f070 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -27,7 +27,7 @@ @@ -316,7 +316,7 @@ text with a given function.

    diff --git a/public/sha256-hashes b/public/sha256-hashes index 28412cf13..e1e1846ae 100644 --- a/public/sha256-hashes +++ b/public/sha256-hashes @@ -45,7 +45,7 @@ SHA256 hashes in Go.

    diff --git a/public/signals b/public/signals index c2ae6e265..42710f26b 100644 --- a/public/signals +++ b/public/signals @@ -28,7 +28,7 @@ diff --git a/public/site.css b/public/site.css index 2e9841569..7f95c8769 100644 --- a/public/site.css +++ b/public/site.css @@ -1,4 +1,4 @@ -/* CSS reset: http://meyerweb.com/eric/tools/css/reset/ */ +/* CSS reset: https://meyerweb.com/eric/tools/css/reset/ */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, diff --git a/public/slices b/public/slices index 99fcdb445..3780b5997 100644 --- a/public/slices +++ b/public/slices @@ -42,7 +42,7 @@ powerful interface to sequences than arrays.

    @@ -268,7 +268,7 @@ they are rendered similarly by fmt.Println.

    diff --git a/public/sorting-by-functions b/public/sorting-by-functions index f890eea49..1607ffa70 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -45,7 +45,7 @@ in Go.

    diff --git a/public/spawning-processes b/public/spawning-processes index d96b37633..d013fc14f 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -42,7 +42,7 @@ processes.

    diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 5f2ea79fc..9a135a2fb 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -48,7 +48,7 @@ by exactly 1 goroutine.

    diff --git a/public/string-formatting b/public/string-formatting index 43618a1d0..eb6b45b65 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -43,7 +43,7 @@ common string formatting tasks.

    diff --git a/public/string-functions b/public/string-functions index 32a757d42..0b38f93e6 100644 --- a/public/string-functions +++ b/public/string-functions @@ -43,7 +43,7 @@ to give you a sense of the package.

    @@ -95,7 +95,7 @@ it a lot below.

    package, not methods on the string object itself, we need pass the string in question as the first argument to the function. You can find more -functions in the strings +functions in the strings package docs.

    diff --git a/public/strings-and-runes b/public/strings-and-runes index 25a0f5d28..a7fc03e77 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -48,7 +48,7 @@ introduction to the topic.

    diff --git a/public/struct-embedding b/public/struct-embedding index 176a97450..c70b5b98c 100644 --- a/public/struct-embedding +++ b/public/struct-embedding @@ -45,7 +45,7 @@ files and folders into the application binary.

    diff --git a/public/structs b/public/structs index cbc34615c..84de85f88 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.

    diff --git a/public/switch b/public/switch index cfdb9eb36..aaab93d07 100644 --- a/public/switch +++ b/public/switch @@ -42,7 +42,7 @@ branches.

    diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 2e8cd85ba..fc173a71d 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -45,7 +45,7 @@ time.

    diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking index 84918d87d..176b37f50 100644 --- a/public/testing-and-benchmarking +++ b/public/testing-and-benchmarking @@ -47,7 +47,7 @@ typically lives in the same package as the code it tests.

    diff --git a/public/tickers b/public/tickers index 28592ef02..97ca3b53e 100644 --- a/public/tickers +++ b/public/tickers @@ -45,7 +45,7 @@ periodically until we stop it.

    diff --git a/public/time b/public/time index 05205f5ab..c8a2d52c9 100644 --- a/public/time +++ b/public/time @@ -42,7 +42,7 @@ here are some examples.

    diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index ec0623860..799989089 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -42,7 +42,7 @@ pattern-based layouts.

    diff --git a/public/timeouts b/public/timeouts index 3c981b8b7..db72edf10 100644 --- a/public/timeouts +++ b/public/timeouts @@ -44,7 +44,7 @@ elegant thanks to channels and select.

    diff --git a/public/timers b/public/timers index 386a5c662..2f1f1c967 100644 --- a/public/timers +++ b/public/timers @@ -45,7 +45,7 @@ at tickers.

    diff --git a/public/url-parsing b/public/url-parsing index a60e14685..61989e409 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -42,7 +42,7 @@ Here’s how to parse URLs in Go.

    diff --git a/public/values b/public/values index ed9e26f84..1f04b3776 100644 --- a/public/values +++ b/public/values @@ -43,7 +43,7 @@ basic examples.

    diff --git a/public/variables b/public/variables index 7b99c7510..736c7c4bc 100644 --- a/public/variables +++ b/public/variables @@ -43,7 +43,7 @@ calls.

    diff --git a/public/variadic-functions b/public/variadic-functions index 16d545673..32dbe0cf9 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -27,7 +27,7 @@ diff --git a/public/waitgroups b/public/waitgroups index 6b0da369d..38870e6fd 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    diff --git a/public/worker-pools b/public/worker-pools index 76e069e83..601a84f89 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -42,7 +42,7 @@ a worker pool using goroutines and channels.

    diff --git a/public/writing-files b/public/writing-files index d02732b3f..c9864b048 100644 --- a/public/writing-files +++ b/public/writing-files @@ -42,7 +42,7 @@ ones we saw earlier for reading.

    diff --git a/public/xml b/public/xml index 7cdec2e23..30f84ad58 100644 --- a/public/xml +++ b/public/xml @@ -42,7 +42,7 @@ formats with the encoding.xml package.

    diff --git a/templates/example.tmpl b/templates/example.tmpl index 228b90831..29b185c30 100644 --- a/templates/example.tmpl +++ b/templates/example.tmpl @@ -30,7 +30,7 @@ {{.DocsRendered}} diff --git a/templates/index.tmpl b/templates/index.tmpl index a7f39d56b..520f68bc0 100644 --- a/templates/index.tmpl +++ b/templates/index.tmpl @@ -9,7 +9,7 @@

    Go by Example

    - Go is an + Go is an open source programming language designed for building simple, fast, and reliable software. Please read the official diff --git a/templates/site.css b/templates/site.css index 2e9841569..7f95c8769 100644 --- a/templates/site.css +++ b/templates/site.css @@ -1,4 +1,4 @@ -/* CSS reset: http://meyerweb.com/eric/tools/css/reset/ */ +/* CSS reset: https://meyerweb.com/eric/tools/css/reset/ */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, From c662818d233c87cf91f1e5ab31347b6df228316b Mon Sep 17 00:00:00 2001 From: Ashish Gaur Date: Tue, 7 Jun 2022 17:53:40 +0530 Subject: [PATCH 151/283] Changes 'the' to 'then' in stateful goroutine example (#427) * Changes 'the' to 'then' in stateful goroutine example * Run tools/build to update HTML --- examples/stateful-goroutines/stateful-goroutines.go | 2 +- examples/stateful-goroutines/stateful-goroutines.hash | 4 ++-- public/stateful-goroutines | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/stateful-goroutines/stateful-goroutines.go b/examples/stateful-goroutines/stateful-goroutines.go index cb8b3474f..11a6f088d 100644 --- a/examples/stateful-goroutines/stateful-goroutines.go +++ b/examples/stateful-goroutines/stateful-goroutines.go @@ -71,7 +71,7 @@ func main() { // This starts 100 goroutines to issue reads to the // state-owning goroutine via the `reads` channel. // Each read requires constructing a `readOp`, sending - // it over the `reads` channel, and the receiving the + // it over the `reads` channel, and then receiving the // result over the provided `resp` channel. for r := 0; r < 100; r++ { go func() { diff --git a/examples/stateful-goroutines/stateful-goroutines.hash b/examples/stateful-goroutines/stateful-goroutines.hash index a5b475c08..0ed448fc6 100644 --- a/examples/stateful-goroutines/stateful-goroutines.hash +++ b/examples/stateful-goroutines/stateful-goroutines.hash @@ -1,2 +1,2 @@ -9c73569ad2e16252b04fe171618db4c5fd09efb7 -5mf_P9xqBzk +04a59d09868df58e9edf5930d38efd25cbb92861 +TBcWd-OfnaA diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 9a135a2fb..119f08b8b 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -48,7 +48,7 @@ by exactly 1 goroutine.

    @@ -176,7 +176,7 @@ value in the case of reads).

    This starts 100 goroutines to issue reads to the state-owning goroutine via the reads channel. Each read requires constructing a readOp, sending -it over the reads channel, and the receiving the +it over the reads channel, and then receiving the result over the provided resp channel.

    From f197dfc6e19a7e689ed9bb91169d18a29eeaa6f5 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 24 Jun 2022 12:43:35 -0700 Subject: [PATCH 152/283] Clarify the type of variadic params with a comment --- .../variadic-functions/variadic-functions.go | 3 +++ .../variadic-functions/variadic-functions.hash | 4 ++-- public/variadic-functions | 18 ++++++++++++++++-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/examples/variadic-functions/variadic-functions.go b/examples/variadic-functions/variadic-functions.go index 68ffe0b26..f2c88ce98 100644 --- a/examples/variadic-functions/variadic-functions.go +++ b/examples/variadic-functions/variadic-functions.go @@ -12,6 +12,9 @@ import "fmt" func sum(nums ...int) { fmt.Print(nums, " ") total := 0 + // Within the function, the type of `nums` is + // equivalent to `[]int`. We can call `len(nums)`, + // iterate over it with `range`, etc. for _, num := range nums { total += num } diff --git a/examples/variadic-functions/variadic-functions.hash b/examples/variadic-functions/variadic-functions.hash index 3c29574fd..36f5ad22e 100644 --- a/examples/variadic-functions/variadic-functions.hash +++ b/examples/variadic-functions/variadic-functions.hash @@ -1,2 +1,2 @@ -dd2e819d49c1110c7eb7dc198b62e0994e0ba93e -7_-i75JEsmM +561184169a1b4c3d4970d496b282cc81016583d6 +glNdE8aKPNq diff --git a/public/variadic-functions b/public/variadic-functions index 32dbe0cf9..8b8679334 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -44,7 +44,7 @@ function.

    @@ -73,6 +73,20 @@ of ints as arguments.

    funcsum(nums...int){fmt.Print(nums," ")total:=0 + + + + + + + @@ -145,7 +145,7 @@ it explicitly.

    @@ -179,7 +179,7 @@ automatically.

    @@ -243,7 +243,7 @@ automatically.

    From 279163e3b057ed01c08184b6517ad5355bcbb215 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 22 Aug 2022 05:58:10 -0700 Subject: [PATCH 155/283] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 1bf00e9e6..0402abdcd 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,11 @@ Some of the examples demonstrate concurrent code which has a non-deterministic execution order. It depends on how the Go runtime schedules its goroutines and may vary by operating system, CPU architecture, or even Go version. +Similarly, examples that iterate over maps may produce items in a different order +from what you're getting on your machine. This is because the order of iteration +over maps in Go is [not specified and is not guaranteed to be the same from one +iteration to the next.](https://go.dev/ref/spec#RangeClause). + It doesn't mean anything is wrong with the example. Typically the code in these examples will be insensitive to the actual order of the output; if the code is sensitive to the order - that's probably a bug - so feel free to report it. From abfc2c2cadfa82e87a71aa56fbe4cdb2089f56de Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 22 Aug 2022 05:58:44 -0700 Subject: [PATCH 156/283] Remove superfluous punctuation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0402abdcd..96cf2c02d 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ may vary by operating system, CPU architecture, or even Go version. Similarly, examples that iterate over maps may produce items in a different order from what you're getting on your machine. This is because the order of iteration over maps in Go is [not specified and is not guaranteed to be the same from one -iteration to the next.](https://go.dev/ref/spec#RangeClause). +iteration to the next](https://go.dev/ref/spec#RangeClause). It doesn't mean anything is wrong with the example. Typically the code in these examples will be insensitive to the actual order of the output; if the code is From 1b4dac72d3ae007ce1e6da06b00f79177232e19c Mon Sep 17 00:00:00 2001 From: Andreas Sommer Date: Mon, 22 Aug 2022 14:59:10 +0200 Subject: [PATCH 157/283] Mention that environment variable set by program is also listed by `os.Environ()` (#436) Co-authored-by: Andreas Sommer --- examples/environment-variables/environment-variables.sh | 1 + public/environment-variables | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/environment-variables/environment-variables.sh b/examples/environment-variables/environment-variables.sh index 09693132b..1c2e0a310 100644 --- a/examples/environment-variables/environment-variables.sh +++ b/examples/environment-variables/environment-variables.sh @@ -11,6 +11,7 @@ TERM_PROGRAM PATH SHELL ... +FOO # If we set `BAR` in the environment first, the running # program picks that value up. diff --git a/public/environment-variables b/public/environment-variables index fb6a4a167..28595958e 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -147,7 +147,8 @@ particular machine.

    TERM_PROGRAM PATH SHELL -... +... +FOO From 742fab3f1c0579c6110882172360c4698698de0d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 8 Sep 2022 05:37:20 -0700 Subject: [PATCH 158/283] Clarify slices vs. arrays a bit Highlight slices in the opening description of the arrays example, to grab attention of new users --- examples/arrays/arrays.go | 4 +++- examples/arrays/arrays.hash | 4 ++-- examples/arrays/arrays.sh | 3 --- examples/slices/slices.go | 4 ++-- examples/slices/slices.hash | 4 ++-- public/arrays | 22 ++++++---------------- public/slices | 6 +++--- 7 files changed, 18 insertions(+), 29 deletions(-) diff --git a/examples/arrays/arrays.go b/examples/arrays/arrays.go index 54bff09f0..010a7e564 100644 --- a/examples/arrays/arrays.go +++ b/examples/arrays/arrays.go @@ -1,5 +1,7 @@ // In Go, an _array_ is a numbered sequence of elements of a -// specific length. +// specific length. In typical Go code, [slices](slices) are +// much more common; arrays are useful in some special +// scenarios. package main diff --git a/examples/arrays/arrays.hash b/examples/arrays/arrays.hash index c04751e96..8e1c671d9 100644 --- a/examples/arrays/arrays.hash +++ b/examples/arrays/arrays.hash @@ -1,2 +1,2 @@ -e71f2d3763eb2950727faa39b90cf1bc037d85fa -TaahifSGSwU +e2bdc11af83f9c6964cfa0e06e4642943b3055ae +bBVikSoZ1Z7 diff --git a/examples/arrays/arrays.sh b/examples/arrays/arrays.sh index 61e30194f..76c43f6c3 100644 --- a/examples/arrays/arrays.sh +++ b/examples/arrays/arrays.sh @@ -7,6 +7,3 @@ get: 100 len: 5 dcl: [1 2 3 4 5] 2d: [[0 1 2] [1 2 3]] - -# You'll see _slices_ much more often than arrays in -# typical Go. We'll look at slices next. diff --git a/examples/slices/slices.go b/examples/slices/slices.go index 914a327ae..c9335e1e1 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -1,5 +1,5 @@ -// _Slices_ are a key data type in Go, giving a more -// powerful interface to sequences than arrays. +// _Slices_ are an important data type in Go, giving +// a more powerful interface to sequences than arrays. package main diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index 24199a58e..e23e052df 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -02c5330eb3ef32a88ca22a5adbded9bd356f89f3 -iLnoIEIxeQ1 +13835b88336e031808f2f3887cd43d0b9d85cad0 +76f4Jif5Z8o diff --git a/public/arrays b/public/arrays index 7a0b707ad..b333813d4 100644 --- a/public/arrays +++ b/public/arrays @@ -28,7 +28,9 @@
    @@ -164,7 +166,7 @@ structures.

    when printed with fmt.Println.

    - - - - - -

    Go supports embedding of structs and interfaces -to express a more seamless composition of types.

    +to express a more seamless composition of types. +This is not to be confused with //go:embed which is +a go directive introduced in Go version 1.16+ to embed +files and folders into the application binary.

    @@ -42,7 +45,7 @@ to express a more seamless composition of types.

    - +
    package main
     
    -
    $ go run embedding.go
    +          
    $ go run struct-embedding.go
     co={num: 1, str: some name}
     also num: 1
     describe: base with num=1
    
    From 7e4533640baedc98213a85c13cfb2745f58164e6 Mon Sep 17 00:00:00 2001
    From: peterzhu1992 <35495810+peterzhu1992@users.noreply.github.com>
    Date: Tue, 24 May 2022 08:31:13 -0400
    Subject: [PATCH 141/283] Add embed-directive example (#423)
    
    * Add embed-directive example and rename embedding to struct-embedding
    
    Signed-off-by: peterzhu1992 
    
    * Minor tweaks
    
    Signed-off-by: peterzhu1992 
    
    * Add some improvements
    
    Signed-off-by: peterzhu1992 
    
    * Add isDir() checks for measure.go and generate.go in tools
    
    Signed-off-by: peterzhu1992 
    ---
     examples.txt                                  |   1 +
     examples/embed-directive/embed-directive.go   |  45 ++++
     examples/embed-directive/embed-directive.hash |   2 +
     examples/embed-directive/embed-directive.sh   |  14 ++
     .../example_folder/multi_file1.hash           |   1 +
     .../example_folder/multi_file2.hash           |   1 +
     .../example_folder/single_file.txt            |   1 +
     public/embed-directive                        | 226 ++++++++++++++++++
     public/index.html                             |   2 +
     public/temporary-files-and-directories        |   4 +-
     public/testing-and-benchmarking               |   2 +-
     tools/generate.go                             |  21 +-
     tools/measure.go                              |  25 +-
     13 files changed, 326 insertions(+), 19 deletions(-)
     create mode 100644 examples/embed-directive/embed-directive.go
     create mode 100644 examples/embed-directive/embed-directive.hash
     create mode 100644 examples/embed-directive/embed-directive.sh
     create mode 100644 examples/embed-directive/example_folder/multi_file1.hash
     create mode 100644 examples/embed-directive/example_folder/multi_file2.hash
     create mode 100644 examples/embed-directive/example_folder/single_file.txt
     create mode 100644 public/embed-directive
    
    diff --git a/examples.txt b/examples.txt
    index 1c62e0138..5c22a2a73 100644
    --- a/examples.txt
    +++ b/examples.txt
    @@ -65,6 +65,7 @@ Line Filters
     File Paths
     Directories
     Temporary Files and Directories
    +Embed Directive
     Testing and Benchmarking
     Command-Line Arguments
     Command-Line Flags
    diff --git a/examples/embed-directive/embed-directive.go b/examples/embed-directive/embed-directive.go
    new file mode 100644
    index 000000000..d7b1c13bf
    --- /dev/null
    +++ b/examples/embed-directive/embed-directive.go
    @@ -0,0 +1,45 @@
    +// `//go:embed` is a compiler directive that allows programs to include arbitrary
    +// files/folders in the binary. Read more about go directive
    +// [here](https://dave.cheney.net/2018/01/08/gos-hidden-pragmas).
    +package main
    +
    +// If no exported identifiers is directly used from `embed` package,
    +// you can add an underscore `_` before the package name. In this example, we simply
    +// import it as we need to use the `embed.FS` type from the package.
    +import (
    +	//_ "embed"
    +	"embed"
    +)
    +
    +// Since one file is defined after the directive, the compiler will only include
    +// this single file, followed by variable `single_file_string` to access as `string` type.
    +//go:embed example_folder/single_file.txt
    +var single_file_string string
    +
    +// Here is a similar example but include single file as `[]byte`.
    +//go:embed example_folder/single_file.txt
    +var single_file_byte []byte
    +
    +// We can also embed multiple files or even folders with wildcard.
    +//go:embed example_folder/single_file.txt
    +//go:embed example_folder/*.hash
    +var folder_FS embed.FS
    +
    +func main() {
    +
    +	// Print out content of `example_single_file.txt` as `string`.
    +	print(single_file_string)
    +
    +	// Now handle `[]byte`.
    +	print(string(single_file_byte))
    +
    +	// Retrieve file(s) matching `*.hash` pattern by reading from variable `folder_FS` first,
    +	// then print out.
    +	hash_file1 := "example_folder/multi_file1.hash"
    +	hash_file2 := "example_folder/multi_file2.hash"
    +	hash_content1, _ := folder_FS.ReadFile(hash_file1)
    +	hash_content2, _ := folder_FS.ReadFile(hash_file2)
    +	print(string(hash_content1))
    +	print(string(hash_content2))
    +
    +}
    diff --git a/examples/embed-directive/embed-directive.hash b/examples/embed-directive/embed-directive.hash
    new file mode 100644
    index 000000000..bf62e8bd9
    --- /dev/null
    +++ b/examples/embed-directive/embed-directive.hash
    @@ -0,0 +1,2 @@
    +e996755d889f01c99c353616fb2bdeac6c3be6e6
    +-EXJc75EbN-
    diff --git a/examples/embed-directive/embed-directive.sh b/examples/embed-directive/embed-directive.sh
    new file mode 100644
    index 000000000..f6937db20
    --- /dev/null
    +++ b/examples/embed-directive/embed-directive.sh
    @@ -0,0 +1,14 @@
    +# Use these commands to run the example.
    +# (Note: due to limitation on go playground,
    +# this example can only be run on your local machine.)
    +$ mkdir -p example_folder
    +$ echo "hello go" > example_folder/single_file.txt
    +$ echo "123" > example_folder/multi_file1.hash
    +$ echo "456" > example_folder/multi_file2.hash
    +
    +$ go run embed-directive.go
    +hello go
    +hello go
    +123
    +456
    +
    diff --git a/examples/embed-directive/example_folder/multi_file1.hash b/examples/embed-directive/example_folder/multi_file1.hash
    new file mode 100644
    index 000000000..190a18037
    --- /dev/null
    +++ b/examples/embed-directive/example_folder/multi_file1.hash
    @@ -0,0 +1 @@
    +123
    diff --git a/examples/embed-directive/example_folder/multi_file2.hash b/examples/embed-directive/example_folder/multi_file2.hash
    new file mode 100644
    index 000000000..8d38505c1
    --- /dev/null
    +++ b/examples/embed-directive/example_folder/multi_file2.hash
    @@ -0,0 +1 @@
    +456
    diff --git a/examples/embed-directive/example_folder/single_file.txt b/examples/embed-directive/example_folder/single_file.txt
    new file mode 100644
    index 000000000..606d5970a
    --- /dev/null
    +++ b/examples/embed-directive/example_folder/single_file.txt
    @@ -0,0 +1 @@
    +hello go
    diff --git a/public/embed-directive b/public/embed-directive
    new file mode 100644
    index 000000000..35536bb71
    --- /dev/null
    +++ b/public/embed-directive
    @@ -0,0 +1,226 @@
    +
    +
    +  
    +    
    +    Go by Example: Embed Directive
    +    
    +  
    +  
    +  
    +    
    +

    Go by Example: Embed Directive

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    //go:embed is a compiler directive that allows programs to include arbitrary +files/folders in the binary. Read more about go directive +here.

    + +
    + +
    +package main
    +
    +
    +

    If no exported identifiers is directly used from embed package, +you can add an underscore _ before the package name. In this example, we simply +import it as we need to use the embed.FS type from the package.

    + +
    + +
    +import (
    +    //_ "embed"
    +    "embed"
    +)
    +
    +
    +

    Since one file is defined after the directive, the compiler will only include +this single file, followed by variable single_file_string to access as string type.

    + +
    + +
    +//go:embed example_folder/single_file.txt
    +var single_file_string string
    +
    +
    +

    Here is a similar example but include single file as []byte.

    + +
    + +
    +//go:embed example_folder/single_file.txt
    +var single_file_byte []byte
    +
    +
    +

    We can also embed multiple files or even folders with wildcard.

    + +
    + +
    +//go:embed example_folder/single_file.txt
    +//go:embed example_folder/*.hash
    +var folder_FS embed.FS
    +
    +
    + + + +
    func main() {
    +
    +
    +

    Print out content of example_single_file.txt as string.

    + +
    + +
    +    print(single_file_string)
    +
    +
    +

    Now handle []byte.

    + +
    + +
    +    print(string(single_file_byte))
    +
    +
    +

    Retrieve file(s) matching *.hash pattern by reading from variable folder_FS first, +then print out.

    + +
    + +
    +    hash_file1 := "example_folder/multi_file1.hash"
    +    hash_file2 := "example_folder/multi_file2.hash"
    +    hash_content1, _ := folder_FS.ReadFile(hash_file1)
    +    hash_content2, _ := folder_FS.ReadFile(hash_file2)
    +    print(string(hash_content1))
    +    print(string(hash_content2))
    +
    +
    + + + +
    }
    +
    +
    + + + + + + + + + + + + + +
    +

    Use these commands to run the example. +(Note: due to limitation on go playground, +this example can only be run on your local machine.)

    + +
    + +
    +$ mkdir -p example_folder
    +$ echo "hello go" > example_folder/single_file.txt
    +$ echo "123" > example_folder/multi_file1.hash
    +$ echo "456" > example_folder/multi_file2.hash
    +
    + + + +
    $ go run embed-directive.go
    +hello go
    +hello go
    +123
    +456
    +
    + + +

    + Next example: Testing and Benchmarking. +

    + + + + +
    + + + + diff --git a/public/index.html b/public/index.html index a0c2e15fe..83f47ea54 100644 --- a/public/index.html +++ b/public/index.html @@ -161,6 +161,8 @@

    Go by Example

  • Temporary Files and Directories
  • +
  • Embed Directive
  • +
  • Testing and Benchmarking
  • Command-Line Arguments
  • diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 91ca3a659..2e8cd85ba 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'testing-and-benchmarking'; + window.location.href = 'embed-directive'; } } @@ -225,7 +225,7 @@ prefixing them with our temporary directory.

    - Next example: Testing and Benchmarking. + Next example: Embed Directive.

    diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking index 975dbb22e..84918d87d 100644 --- a/public/testing-and-benchmarking +++ b/public/testing-and-benchmarking @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'temporary-files-and-directories'; + window.location.href = 'embed-directive'; } diff --git a/tools/generate.go b/tools/generate.go index 7616c2518..fdbe7a08a 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -36,6 +36,11 @@ func check(err error) { } } +func isDir(path string) bool { + fileStat, _ := os.Stat(path) + return fileStat.IsDir() +} + func ensureDir(dir string) { err := os.MkdirAll(dir, 0755) check(err) @@ -275,14 +280,16 @@ func parseExamples() []*Example { example.Segs = make([][]*Seg, 0) sourcePaths := mustGlob("examples/" + exampleID + "/*") for _, sourcePath := range sourcePaths { - if strings.HasSuffix(sourcePath, ".hash") { - example.GoCodeHash, example.URLHash = parseHashFile(sourcePath) - } else { - sourceSegs, filecontents := parseAndRenderSegs(sourcePath) - if filecontents != "" { - example.GoCode = filecontents + if ! isDir(sourcePath) { + if strings.HasSuffix(sourcePath, ".hash") { + example.GoCodeHash, example.URLHash = parseHashFile(sourcePath) + } else { + sourceSegs, filecontents := parseAndRenderSegs(sourcePath) + if filecontents != "" { + example.GoCode = filecontents + } + example.Segs = append(example.Segs, sourceSegs) } - example.Segs = append(example.Segs, sourceSegs) } } newCodeHash := sha1Sum(example.GoCode) diff --git a/tools/measure.go b/tools/measure.go index 7c9d6beb1..8be80d7aa 100644 --- a/tools/measure.go +++ b/tools/measure.go @@ -21,6 +21,11 @@ func readLines(path string) []string { return strings.Split(string(srcBytes), "\n") } +func isDir(path string) bool { + fileStat, _ := os.Stat(path) + return fileStat.IsDir() +} + var commentPat = regexp.MustCompile("\\s*\\/\\/") func main() { @@ -29,15 +34,17 @@ func main() { foundLongFile := false for _, sourcePath := range sourcePaths { foundLongLine := false - lines := readLines(sourcePath) - for i, line := range lines { - // Convert tabs to spaces before measuring, so we get an accurate measure - // of how long the output will end up being. - line := strings.Replace(line, "\t", " ", -1) - if !foundLongLine && !commentPat.MatchString(line) && (utf8.RuneCountInString(line) > 58) { - fmt.Printf("measure: %s:%d\n", sourcePath, i+1) - foundLongLine = true - foundLongFile = true + if ! isDir(sourcePath) { + lines := readLines(sourcePath) + for i, line := range lines { + // Convert tabs to spaces before measuring, so we get an accurate measure + // of how long the output will end up being. + line := strings.Replace(line, "\t", " ", -1) + if !foundLongLine && !commentPat.MatchString(line) && (utf8.RuneCountInString(line) > 58) { + fmt.Printf("measure: %s:%d\n", sourcePath, i+1) + foundLongLine = true + foundLongFile = true + } } } } From d4bbdc258b985ca6d21568664fd95ab9f7baa96b Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 24 May 2022 05:44:45 -0700 Subject: [PATCH 142/283] Reformat tools/ files --- tools/generate.go | 6 +++--- tools/measure.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/generate.go b/tools/generate.go index fdbe7a08a..58d10c46a 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -37,8 +37,8 @@ func check(err error) { } func isDir(path string) bool { - fileStat, _ := os.Stat(path) - return fileStat.IsDir() + fileStat, _ := os.Stat(path) + return fileStat.IsDir() } func ensureDir(dir string) { @@ -280,7 +280,7 @@ func parseExamples() []*Example { example.Segs = make([][]*Seg, 0) sourcePaths := mustGlob("examples/" + exampleID + "/*") for _, sourcePath := range sourcePaths { - if ! isDir(sourcePath) { + if !isDir(sourcePath) { if strings.HasSuffix(sourcePath, ".hash") { example.GoCodeHash, example.URLHash = parseHashFile(sourcePath) } else { diff --git a/tools/measure.go b/tools/measure.go index 8be80d7aa..04c1a30bc 100644 --- a/tools/measure.go +++ b/tools/measure.go @@ -34,7 +34,7 @@ func main() { foundLongFile := false for _, sourcePath := range sourcePaths { foundLongLine := false - if ! isDir(sourcePath) { + if !isDir(sourcePath) { lines := readLines(sourcePath) for i, line := range lines { // Convert tabs to spaces before measuring, so we get an accurate measure From fc88db181411a6eb25e2b5e4083d39cd436f2cac Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 24 May 2022 06:11:22 -0700 Subject: [PATCH 143/283] Fix up embed-directive example and rename files to be shorter --- examples/embed-directive/embed-directive.go | 59 ++++++------- examples/embed-directive/embed-directive.hash | 4 +- examples/embed-directive/embed-directive.sh | 8 +- .../multi_file1.hash => folder/file1.hash} | 0 .../multi_file2.hash => folder/file2.hash} | 0 .../single_file.txt | 0 public/embed-directive | 85 ++++++++----------- 7 files changed, 70 insertions(+), 86 deletions(-) rename examples/embed-directive/{example_folder/multi_file1.hash => folder/file1.hash} (100%) rename examples/embed-directive/{example_folder/multi_file2.hash => folder/file2.hash} (100%) rename examples/embed-directive/{example_folder => folder}/single_file.txt (100%) diff --git a/examples/embed-directive/embed-directive.go b/examples/embed-directive/embed-directive.go index d7b1c13bf..bd3a976bd 100644 --- a/examples/embed-directive/embed-directive.go +++ b/examples/embed-directive/embed-directive.go @@ -1,45 +1,42 @@ -// `//go:embed` is a compiler directive that allows programs to include arbitrary -// files/folders in the binary. Read more about go directive -// [here](https://dave.cheney.net/2018/01/08/gos-hidden-pragmas). +// `//go:embed` is a compiler directive that allows programs to include +// arbitrary files/folders in the binary at build time. Read more about go +// directives [here](https://pkg.go.dev/cmd/compile#hdr-Compiler_Directives) +// and about the embed directive [here](https://pkg.go.dev/embed). package main -// If no exported identifiers is directly used from `embed` package, -// you can add an underscore `_` before the package name. In this example, we simply -// import it as we need to use the `embed.FS` type from the package. +// Import the `embed` package; if you don't use any exported +// identifiers from this package, you can do a blank import with `_ "embed"`. import ( - //_ "embed" "embed" ) -// Since one file is defined after the directive, the compiler will only include -// this single file, followed by variable `single_file_string` to access as `string` type. -//go:embed example_folder/single_file.txt -var single_file_string string +// embed directives accept paths relative to the directory containing the +// Go source file. This directive embeds the contents of the file into a +// `string` variable. +//go:embed folder/single_file.txt +var fileString string -// Here is a similar example but include single file as `[]byte`. -//go:embed example_folder/single_file.txt -var single_file_byte []byte +// Or embed the contents of the file into a `[]byte`. +//go:embed folder/single_file.txt +var fileByte []byte -// We can also embed multiple files or even folders with wildcard. -//go:embed example_folder/single_file.txt -//go:embed example_folder/*.hash -var folder_FS embed.FS +// We can also embed multiple files or even folders with wildcards. This uses +// a variable of the [embed.FS type](https://pkg.go.dev/embed#FS), which +// implements a simple virtual file system. +//go:embed folder/single_file.txt +//go:embed folder/*.hash +var folder embed.FS func main() { - // Print out content of `example_single_file.txt` as `string`. - print(single_file_string) + // Print out the contents of `single_file.txt`. + print(fileString) + print(string(fileByte)) - // Now handle `[]byte`. - print(string(single_file_byte)) - - // Retrieve file(s) matching `*.hash` pattern by reading from variable `folder_FS` first, - // then print out. - hash_file1 := "example_folder/multi_file1.hash" - hash_file2 := "example_folder/multi_file2.hash" - hash_content1, _ := folder_FS.ReadFile(hash_file1) - hash_content2, _ := folder_FS.ReadFile(hash_file2) - print(string(hash_content1)) - print(string(hash_content2)) + // Retrieve some files from the embedded folder. + content1, _ := folder.ReadFile("folder/file1.hash") + print(string(content1)) + content2, _ := folder.ReadFile("folder/file2.hash") + print(string(content2)) } diff --git a/examples/embed-directive/embed-directive.hash b/examples/embed-directive/embed-directive.hash index bf62e8bd9..170913f8c 100644 --- a/examples/embed-directive/embed-directive.hash +++ b/examples/embed-directive/embed-directive.hash @@ -1,2 +1,2 @@ -e996755d889f01c99c353616fb2bdeac6c3be6e6 --EXJc75EbN- +82ad92029645b4fd1b5ef0cd9df3fecdf0a6764e +myu7kywm7oI diff --git a/examples/embed-directive/embed-directive.sh b/examples/embed-directive/embed-directive.sh index f6937db20..cae33d8cb 100644 --- a/examples/embed-directive/embed-directive.sh +++ b/examples/embed-directive/embed-directive.sh @@ -1,10 +1,10 @@ # Use these commands to run the example. # (Note: due to limitation on go playground, # this example can only be run on your local machine.) -$ mkdir -p example_folder -$ echo "hello go" > example_folder/single_file.txt -$ echo "123" > example_folder/multi_file1.hash -$ echo "456" > example_folder/multi_file2.hash +$ mkdir -p folder +$ echo "hello go" > folder/single_file.txt +$ echo "123" > folder/file1.hash +$ echo "456" > folder/file2.hash $ go run embed-directive.go hello go diff --git a/examples/embed-directive/example_folder/multi_file1.hash b/examples/embed-directive/folder/file1.hash similarity index 100% rename from examples/embed-directive/example_folder/multi_file1.hash rename to examples/embed-directive/folder/file1.hash diff --git a/examples/embed-directive/example_folder/multi_file2.hash b/examples/embed-directive/folder/file2.hash similarity index 100% rename from examples/embed-directive/example_folder/multi_file2.hash rename to examples/embed-directive/folder/file2.hash diff --git a/examples/embed-directive/example_folder/single_file.txt b/examples/embed-directive/folder/single_file.txt similarity index 100% rename from examples/embed-directive/example_folder/single_file.txt rename to examples/embed-directive/folder/single_file.txt diff --git a/public/embed-directive b/public/embed-directive index 35536bb71..2743d7d6f 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -27,13 +27,14 @@
    -

    //go:embed is a compiler directive that allows programs to include arbitrary -files/folders in the binary. Read more about go directive -here.

    +

    //go:embed is a compiler directive that allows programs to include +arbitrary files/folders in the binary at build time. Read more about go +directives here +and about the embed directive here.

    - +
     package main
     
    @@ -42,17 +43,15 @@ files/folders in the binary. Read more about go directive
    -

    If no exported identifiers is directly used from embed package, -you can add an underscore _ before the package name. In this example, we simply -import it as we need to use the embed.FS type from the package.

    +

    Import the embed package; if you don’t use any exported +identifiers from this package, you can do a blank import with _ "embed".

     import (
    -    //_ "embed"
    -    "embed"
    +    "embed"
     )
     
    -

    Since one file is defined after the directive, the compiler will only include -this single file, followed by variable single_file_string to access as string type.

    +

    embed directives accept paths relative to the directory containing the +Go source file. This directive embeds the contents of the file into a +string variable.

    -//go:embed example_folder/single_file.txt
    -var single_file_string string
    +//go:embed folder/single_file.txt
    +var fileString string
     
    -

    Here is a similar example but include single file as []byte.

    +

    Or embed the contents of the file into a []byte.

    -//go:embed example_folder/single_file.txt
    -var single_file_byte []byte
    +//go:embed folder/single_file.txt
    +var fileByte []byte
     
    -

    We can also embed multiple files or even folders with wildcard.

    +

    We can also embed multiple files or even folders with wildcards. This uses +a variable of the embed.FS type, which +implements a simple virtual file system.

    -//go:embed example_folder/single_file.txt
    -//go:embed example_folder/*.hash
    -var folder_FS embed.FS
    +//go:embed folder/single_file.txt
    +//go:embed folder/*.hash
    +var folder embed.FS
     
    -

    Print out content of example_single_file.txt as string.

    +

    Print out contents of single_file.txt.

    -    print(single_file_string)
    +    print(fileString)
    +    print(string(fileByte))
     
    -

    Now handle []byte.

    +

    Retrieve some files from the embedded folder.

    -    print(string(single_file_byte))
    -
    -
    -

    Retrieve file(s) matching *.hash pattern by reading from variable folder_FS first, -then print out.

    - -
    - -
    -    hash_file1 := "example_folder/multi_file1.hash"
    -    hash_file2 := "example_folder/multi_file2.hash"
    -    hash_content1, _ := folder_FS.ReadFile(hash_file1)
    -    hash_content2, _ := folder_FS.ReadFile(hash_file2)
    -    print(string(hash_content1))
    -    print(string(hash_content2))
    +    content1, _ := folder.ReadFile("folder/file1.hash")
    +    print(string(content1))
     
    -
    }
    +          
        content2, _ := folder.ReadFile("folder/file2.hash")
    +    print(string(content2))
    +}
     
    -$ mkdir -p example_folder
    -$ echo "hello go" > example_folder/single_file.txt
    -$ echo "123" > example_folder/multi_file1.hash
    -$ echo "456" > example_folder/multi_file2.hash
    +$ mkdir -p folder +$ echo "hello go" > folder/single_file.txt +$ echo "123" > folder/file1.hash +$ echo "456" > folder/file2.hash
    -

    //go:embed is a compiler directive that allows programs to include -arbitrary files/folders in the binary at build time. Read more about go -directives here -and about the embed directive here.

    +

    //go:embed is a compiler +directive that +allows programs to include arbitrary files and folders in the Go binary at +build time. Read more about the embed directive +here.

    - +
     package main
     
    @@ -59,9 +60,9 @@ identifiers from this package, you can do a blank import with _ "embe
    -

    embed directives accept paths relative to the directory containing the -Go source file. This directive embeds the contents of the file into a -string variable.

    +

    embed directives accept paths relative to the directory containing the +Go source file. This directive embeds the contents of the file into the +string variable immediately following it.

    @@ -117,7 +118,7 @@ implements a simple virtual file system.

    -

    Print out contents of single_file.txt.

    +

    Print out the contents of single_file.txt.

    From 52fd882fcfba6c85ea3e3fd4a1580d3a55c094aa Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 24 May 2022 20:17:37 -0700 Subject: [PATCH 145/283] Update golang.org links to point directly to go.dev The golang.org links have been redirecting to go.dev for a while - make direct links. --- templates/index.tmpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/index.tmpl b/templates/index.tmpl index e99e1893f..a7f39d56b 100644 --- a/templates/index.tmpl +++ b/templates/index.tmpl @@ -9,11 +9,11 @@

    Go by Example

    - Go is an + Go is an open source programming language designed for building simple, fast, and reliable software. Please read the official - documentation + documentation to learn a bit about Go code, tools packages, and modules.

    From 36464854b9d06287ca501e6cdc3369ddf78f6dbe Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 24 May 2022 20:22:13 -0700 Subject: [PATCH 146/283] Rebuild to have updated index.html in public/ --- public/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/public/index.html b/public/index.html index 83f47ea54..d01f33930 100644 --- a/public/index.html +++ b/public/index.html @@ -9,11 +9,11 @@

    Go by Example

    - Go is an + Go is an open source programming language designed for building simple, fast, and reliable software. Please read the official - documentation + documentation to learn a bit about Go code, tools packages, and modules.

    From 625ea8043e9ecc7375f8db88845ee869ec1e3352 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 25 May 2022 20:41:46 -0700 Subject: [PATCH 147/283] Render 404 page with templates to reuse the footer --- public/404.html | 10 ++++++---- templates/404.html | 17 ----------------- templates/404.tmpl | 15 +++++++++++++++ tools/generate.go | 18 ++++++++++++++++-- 4 files changed, 37 insertions(+), 23 deletions(-) delete mode 100644 templates/404.html create mode 100644 templates/404.tmpl diff --git a/public/404.html b/public/404.html index 61a5dd02f..e9e842c72 100644 --- a/public/404.html +++ b/public/404.html @@ -1,7 +1,7 @@ - + Go by Example: Not Found @@ -9,9 +9,11 @@

    Go by Example

    Sorry, we couldn't find that! Check out the home page?

    - + + +
    diff --git a/templates/404.html b/templates/404.html deleted file mode 100644 index 61a5dd02f..000000000 --- a/templates/404.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Go by Example: Not Found - - - -
    -

    Go by Example

    -

    Sorry, we couldn't find that! Check out the home page?

    - -
    - - diff --git a/templates/404.tmpl b/templates/404.tmpl new file mode 100644 index 000000000..10aae1005 --- /dev/null +++ b/templates/404.tmpl @@ -0,0 +1,15 @@ + + + + + Go by Example: Not Found + + + +
    +

    Go by Example

    +

    Sorry, we couldn't find that! Check out the home page?

    +{{ template "footer" }} +
    + + diff --git a/tools/generate.go b/tools/generate.go index 58d10c46a..a7cda7c77 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -210,7 +210,6 @@ func parseSegs(sourcePath string) ([]*Seg, string) { } func chromaFormat(code, filePath string) string { - lexer := lexers.Get(filePath) if lexer == nil { lexer = lexers.Fallback @@ -340,6 +339,21 @@ func renderExamples(examples []*Example) { } } +func render404() { + if verbose() { + fmt.Println("Rendering 404") + } + tmpl := template.New("404") + _, err := tmpl.Parse(mustReadFile("templates/footer.tmpl")) + check(err) + _, err = tmpl.Parse(mustReadFile("templates/404.tmpl")) + check(err) + file, err := os.Create(siteDir + "/404.html") + check(err) + err = tmpl.Execute(file, "") + check(err) +} + func main() { if len(os.Args) > 1 { siteDir = os.Args[1] @@ -349,12 +363,12 @@ func main() { copyFile("templates/site.css", siteDir+"/site.css") copyFile("templates/site.js", siteDir+"/site.js") copyFile("templates/favicon.ico", siteDir+"/favicon.ico") - copyFile("templates/404.html", siteDir+"/404.html") copyFile("templates/play.png", siteDir+"/play.png") copyFile("templates/clipboard.png", siteDir+"/clipboard.png") examples := parseExamples() renderIndex(examples) renderExamples(examples) + render404() } var SimpleShellOutputLexer = chroma.MustNewLexer( From d9439333fe4ae672d002b34e3952a782f9cbcd50 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 25 May 2022 20:54:05 -0700 Subject: [PATCH 148/283] Clean up template rendering code Use template.Must(...) to simplify code defer close the files we open --- tools/generate.go | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/tools/generate.go b/tools/generate.go index a7cda7c77..9ed53958f 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -313,14 +313,12 @@ func renderIndex(examples []*Example) { fmt.Println("Rendering index") } indexTmpl := template.New("index") - _, err := indexTmpl.Parse(mustReadFile("templates/footer.tmpl")) - check(err) - _, err = indexTmpl.Parse(mustReadFile("templates/index.tmpl")) - check(err) + template.Must(indexTmpl.Parse(mustReadFile("templates/footer.tmpl"))) + template.Must(indexTmpl.Parse(mustReadFile("templates/index.tmpl"))) indexF, err := os.Create(siteDir + "/index.html") check(err) - err = indexTmpl.Execute(indexF, examples) - check(err) + defer indexF.Close() + check(indexTmpl.Execute(indexF, examples)) } func renderExamples(examples []*Example) { @@ -328,14 +326,13 @@ func renderExamples(examples []*Example) { fmt.Println("Rendering examples") } exampleTmpl := template.New("example") - _, err := exampleTmpl.Parse(mustReadFile("templates/footer.tmpl")) - check(err) - _, err = exampleTmpl.Parse(mustReadFile("templates/example.tmpl")) - check(err) + template.Must(exampleTmpl.Parse(mustReadFile("templates/footer.tmpl"))) + template.Must(exampleTmpl.Parse(mustReadFile("templates/example.tmpl"))) for _, example := range examples { exampleF, err := os.Create(siteDir + "/" + example.ID) check(err) - exampleTmpl.Execute(exampleF, example) + defer exampleF.Close() + check(exampleTmpl.Execute(exampleF, example)) } } @@ -344,14 +341,12 @@ func render404() { fmt.Println("Rendering 404") } tmpl := template.New("404") - _, err := tmpl.Parse(mustReadFile("templates/footer.tmpl")) - check(err) - _, err = tmpl.Parse(mustReadFile("templates/404.tmpl")) - check(err) + template.Must(tmpl.Parse(mustReadFile("templates/footer.tmpl"))) + template.Must(tmpl.Parse(mustReadFile("templates/404.tmpl"))) file, err := os.Create(siteDir + "/404.html") check(err) - err = tmpl.Execute(file, "") - check(err) + defer file.Close() + check(tmpl.Execute(file, "")) } func main() { From 25d2811293a37b16183b0023fef1343ce12ca452 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 25 May 2022 20:59:29 -0700 Subject: [PATCH 149/283] Remove unused code --- tools/generate.go | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/tools/generate.go b/tools/generate.go index 9ed53958f..f8341c6d6 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -7,7 +7,6 @@ import ( "io" "net/http" "os" - "os/exec" "path/filepath" "regexp" "strings" @@ -53,25 +52,6 @@ func copyFile(src, dst string) { check(err) } -func pipe(bin string, arg []string, src string) []byte { - cmd := exec.Command(bin, arg...) - in, err := cmd.StdinPipe() - check(err) - out, err := cmd.StdoutPipe() - check(err) - err = cmd.Start() - check(err) - _, err = in.Write([]byte(src)) - check(err) - err = in.Close() - check(err) - bytes, err := io.ReadAll(out) - check(err) - err = cmd.Wait() - check(err) - return bytes -} - func sha1Sum(s string) string { h := sha1.New() h.Write([]byte(s)) From da13e2fbe7df715782f4cdb5d96ae5e8f1ca1d6a Mon Sep 17 00:00:00 2001 From: Andreas Deininger Date: Mon, 6 Jun 2022 20:31:46 +0200 Subject: [PATCH 150/283] Improving links (http -> https) (#425) --- .github/workflows/test.yml | 2 +- README.md | 6 +++--- examples/base64-encoding/base64-encoding.go | 2 +- examples/base64-encoding/base64-encoding.hash | 4 ++-- examples/closures/closures.go | 4 ++-- examples/closures/closures.hash | 4 ++-- examples/command-line-arguments/command-line-arguments.go | 2 +- examples/command-line-arguments/command-line-arguments.hash | 4 ++-- examples/command-line-flags/command-line-flags.go | 2 +- examples/command-line-flags/command-line-flags.hash | 4 ++-- examples/environment-variables/environment-variables.go | 4 ++-- examples/environment-variables/environment-variables.hash | 4 ++-- examples/epoch/epoch.go | 2 +- examples/epoch/epoch.hash | 4 ++-- examples/errors/errors.sh | 2 +- examples/execing-processes/execing-processes.go | 2 +- examples/execing-processes/execing-processes.hash | 4 ++-- examples/http-clients/http-clients.go | 2 +- examples/http-clients/http-clients.hash | 4 ++-- examples/if-else/if-else.sh | 2 +- examples/interfaces/interfaces.sh | 2 +- examples/json/json.sh | 4 ++-- examples/maps/maps.go | 2 +- examples/maps/maps.hash | 4 ++-- examples/mutexes/mutexes.go | 2 +- examples/mutexes/mutexes.hash | 4 ++-- examples/pointers/pointers.go | 2 +- examples/pointers/pointers.hash | 4 ++-- examples/random-numbers/random-numbers.go | 2 +- examples/random-numbers/random-numbers.hash | 4 ++-- examples/random-numbers/random-numbers.sh | 2 +- examples/rate-limiting/rate-limiting.go | 2 +- examples/rate-limiting/rate-limiting.hash | 4 ++-- examples/recursion/recursion.go | 2 +- examples/recursion/recursion.hash | 4 ++-- examples/regular-expressions/regular-expressions.go | 2 +- examples/regular-expressions/regular-expressions.hash | 4 ++-- examples/regular-expressions/regular-expressions.sh | 2 +- examples/signals/signals.go | 2 +- examples/signals/signals.hash | 4 ++-- examples/slices/slices.sh | 2 +- examples/string-functions/string-functions.go | 2 +- examples/string-functions/string-functions.hash | 4 ++-- examples/variadic-functions/variadic-functions.go | 2 +- examples/variadic-functions/variadic-functions.hash | 4 ++-- public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 4 ++-- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 6 +++--- public/command-line-arguments | 4 ++-- public/command-line-flags | 4 ++-- public/command-line-subcommands | 2 +- public/constants | 2 +- public/context | 2 +- public/defer | 2 +- public/directories | 2 +- public/embed-directive | 2 +- public/environment-variables | 6 +++--- public/epoch | 4 ++-- public/errors | 4 ++-- public/execing-processes | 4 ++-- public/exit | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/generics | 2 +- public/goroutines | 2 +- public/hello-world | 2 +- public/http-clients | 6 +++--- public/http-servers | 2 +- public/if-else | 4 ++-- public/index.html | 2 +- public/interfaces | 4 ++-- public/json | 6 +++--- public/line-filters | 2 +- public/maps | 4 ++-- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 4 ++-- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 4 ++-- public/random-numbers | 6 +++--- public/range | 2 +- public/range-over-channels | 2 +- public/rate-limiting | 4 ++-- public/reading-files | 2 +- public/recover | 2 +- public/recursion | 4 ++-- public/regular-expressions | 6 +++--- public/select | 2 +- public/sha256-hashes | 2 +- public/signals | 4 ++-- public/site.css | 2 +- public/slices | 4 ++-- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 4 ++-- public/strings-and-runes | 2 +- public/struct-embedding | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing-and-benchmarking | 2 +- public/text-templates | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 4 ++-- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- templates/example.tmpl | 2 +- templates/index.tmpl | 2 +- templates/site.css | 2 +- 130 files changed, 182 insertions(+), 182 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e79402cc4..ae898415c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.18.0] + go-version: [1.18.3] runs-on: ${{ matrix.os }} steps: diff --git a/README.md b/README.md index 538bfd5d8..1bf00e9e6 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ $ tools/upload This work is copyright Mark McGranaghan and licensed under a [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/). -The Go Gopher is copyright [Renée French](http://reneefrench.blogspot.com/) and licensed under a +The Go Gopher is copyright [Renée French](https://reneefrench.blogspot.com/) and licensed under a [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/). @@ -66,12 +66,12 @@ Contributor translations of the Go by Example site are available in: * [Chinese](https://gobyexample-cn.github.io/) by [gobyexample-cn](https://github.com/gobyexample-cn) * [Czech](http://gobyexamples.sweb.cz/) by [martinkunc](https://github.com/martinkunc/gobyexample-cz) * [French](http://le-go-par-l-exemple.keiruaprod.fr) by [keirua](https://github.com/keirua/gobyexample) -* [Italian](http://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) +* [Italian](https://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) -* [Ukrainian](http://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) +* [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) ### Thanks diff --git a/examples/base64-encoding/base64-encoding.go b/examples/base64-encoding/base64-encoding.go index 09e94fd28..d5a0b9b1f 100644 --- a/examples/base64-encoding/base64-encoding.go +++ b/examples/base64-encoding/base64-encoding.go @@ -1,5 +1,5 @@ // Go provides built-in support for [base64 -// encoding/decoding](http://en.wikipedia.org/wiki/Base64). +// encoding/decoding](https://en.wikipedia.org/wiki/Base64). package main diff --git a/examples/base64-encoding/base64-encoding.hash b/examples/base64-encoding/base64-encoding.hash index 09e2b2a41..e2b8debfc 100644 --- a/examples/base64-encoding/base64-encoding.hash +++ b/examples/base64-encoding/base64-encoding.hash @@ -1,2 +1,2 @@ -cd00d89ad0a31e48d6a2e2adc2e8d65b0f70dc73 -S7ff3UgzNlG +47f0317643bc5107af6fae64cb0fdad1260ead37 +yztzkirFEvv diff --git a/examples/closures/closures.go b/examples/closures/closures.go index 90dc2ebce..27def721d 100644 --- a/examples/closures/closures.go +++ b/examples/closures/closures.go @@ -1,5 +1,5 @@ -// Go supports [_anonymous functions_](http://en.wikipedia.org/wiki/Anonymous_function), -// which can form closures. +// Go supports [_anonymous functions_](https://en.wikipedia.org/wiki/Anonymous_function), +// which can form closures. // Anonymous functions are useful when you want to define // a function inline without having to name it. diff --git a/examples/closures/closures.hash b/examples/closures/closures.hash index df8a22b03..7dafe7d3d 100644 --- a/examples/closures/closures.hash +++ b/examples/closures/closures.hash @@ -1,2 +1,2 @@ -6713bdbb6de0d7d484422517dd77316c8b9f0a7a -66Lgw9iIIch +6514e124c8127250a2eecfadc9708181e51f9603 +NpgpzS8ZG8y diff --git a/examples/command-line-arguments/command-line-arguments.go b/examples/command-line-arguments/command-line-arguments.go index 110411329..a3fb3e68f 100644 --- a/examples/command-line-arguments/command-line-arguments.go +++ b/examples/command-line-arguments/command-line-arguments.go @@ -1,4 +1,4 @@ -// [_Command-line arguments_](http://en.wikipedia.org/wiki/Command-line_interface#Arguments) +// [_Command-line arguments_](https://en.wikipedia.org/wiki/Command-line_interface#Arguments) // are a common way to parameterize execution of programs. // For example, `go run hello.go` uses `run` and // `hello.go` arguments to the `go` program. diff --git a/examples/command-line-arguments/command-line-arguments.hash b/examples/command-line-arguments/command-line-arguments.hash index 658742928..c099ea10b 100644 --- a/examples/command-line-arguments/command-line-arguments.hash +++ b/examples/command-line-arguments/command-line-arguments.hash @@ -1,2 +1,2 @@ -d60d1c9cb5dbbb748cf3b692334076951cea7d59 -oSxtj7v_v1K +ad871e829d1457d97d0f1c1af77e39f6942ac5a5 +UYCEvh9d2Zb diff --git a/examples/command-line-flags/command-line-flags.go b/examples/command-line-flags/command-line-flags.go index 886de077f..16412cd0d 100644 --- a/examples/command-line-flags/command-line-flags.go +++ b/examples/command-line-flags/command-line-flags.go @@ -1,4 +1,4 @@ -// [_Command-line flags_](http://en.wikipedia.org/wiki/Command-line_interface#Command-line_option) +// [_Command-line flags_](https://en.wikipedia.org/wiki/Command-line_interface#Command-line_option) // are a common way to specify options for command-line // programs. For example, in `wc -l` the `-l` is a // command-line flag. diff --git a/examples/command-line-flags/command-line-flags.hash b/examples/command-line-flags/command-line-flags.hash index 5c128dac6..4b5c04958 100644 --- a/examples/command-line-flags/command-line-flags.hash +++ b/examples/command-line-flags/command-line-flags.hash @@ -1,2 +1,2 @@ -08e716a5ee3b5f74ef826d7b5ce157cb3b44c4f7 --zzqphwtdJq +9cca50e58f488570cc8e92dde37582ea5ee04bf3 +IUPZlYSigc3 diff --git a/examples/environment-variables/environment-variables.go b/examples/environment-variables/environment-variables.go index e3e42a5de..f1d3dc163 100644 --- a/examples/environment-variables/environment-variables.go +++ b/examples/environment-variables/environment-variables.go @@ -1,6 +1,6 @@ -// [Environment variables](http://en.wikipedia.org/wiki/Environment_variable) +// [Environment variables](https://en.wikipedia.org/wiki/Environment_variable) // are a universal mechanism for [conveying configuration -// information to Unix programs](http://www.12factor.net/config). +// information to Unix programs](https://www.12factor.net/config). // Let's look at how to set, get, and list environment variables. package main diff --git a/examples/environment-variables/environment-variables.hash b/examples/environment-variables/environment-variables.hash index bf640457e..02c7a2503 100644 --- a/examples/environment-variables/environment-variables.hash +++ b/examples/environment-variables/environment-variables.hash @@ -1,2 +1,2 @@ -bee983e7820d64dec5331dc706c08f6135b5c632 -KuD8tDyB4lQ +f480d3803659977183a4bc5c14da26c80b1d31fe +2jmwXM264NC diff --git a/examples/epoch/epoch.go b/examples/epoch/epoch.go index a48ece968..f77ab3030 100644 --- a/examples/epoch/epoch.go +++ b/examples/epoch/epoch.go @@ -1,6 +1,6 @@ // A common requirement in programs is getting the number // of seconds, milliseconds, or nanoseconds since the -// [Unix epoch](http://en.wikipedia.org/wiki/Unix_time). +// [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). // Here's how to do it in Go. package main diff --git a/examples/epoch/epoch.hash b/examples/epoch/epoch.hash index 7248790a8..579635a81 100644 --- a/examples/epoch/epoch.hash +++ b/examples/epoch/epoch.hash @@ -1,2 +1,2 @@ -54e66c2e84334f2adbf87aaeb62065111c5644ea -iG_EcjJp4ss +a67ae165a1f00c205a344327d9d638f4eb931b5c +lRmD1EWHHPz diff --git a/examples/errors/errors.sh b/examples/errors/errors.sh index 068d606fa..54315ae7d 100644 --- a/examples/errors/errors.sh +++ b/examples/errors/errors.sh @@ -6,5 +6,5 @@ f2 failed: 42 - can't work with it 42 can't work with it -# See this [great post](http://blog.golang.org/2011/07/error-handling-and-go.html) +# See this [great post](https://go.dev/blog/error-handling-and-go) # on the Go blog for more on error handling. diff --git a/examples/execing-processes/execing-processes.go b/examples/execing-processes/execing-processes.go index 04f5816d0..7ac83008c 100644 --- a/examples/execing-processes/execing-processes.go +++ b/examples/execing-processes/execing-processes.go @@ -5,7 +5,7 @@ // completely replace the current Go process with another // (perhaps non-Go) one. To do this we'll use Go's // implementation of the classic -// exec +// exec // function. package main diff --git a/examples/execing-processes/execing-processes.hash b/examples/execing-processes/execing-processes.hash index 8ba56375f..90bd32578 100644 --- a/examples/execing-processes/execing-processes.hash +++ b/examples/execing-processes/execing-processes.hash @@ -1,2 +1,2 @@ -18867a0e743aaadb2aba0a0c7b1ca8098a1aa95c -nI-HMuCI2lG +568ae983493addff02d2ce8df57f41daf537f077 +s9qg7olf1dM diff --git a/examples/http-clients/http-clients.go b/examples/http-clients/http-clients.go index 7cd71ef73..57b22f24c 100644 --- a/examples/http-clients/http-clients.go +++ b/examples/http-clients/http-clients.go @@ -17,7 +17,7 @@ func main() { // object and calling its `Get` method; it uses the // `http.DefaultClient` object which has useful default // settings. - resp, err := http.Get("http://gobyexample.com") + resp, err := http.Get("https://gobyexample.com") if err != nil { panic(err) } diff --git a/examples/http-clients/http-clients.hash b/examples/http-clients/http-clients.hash index b36a4b2da..81933641e 100644 --- a/examples/http-clients/http-clients.hash +++ b/examples/http-clients/http-clients.hash @@ -1,2 +1,2 @@ -fbc80f8cfcd34e9daa3c52c23f6720f6ef7019dc -kHCcVLoz7nd +1497e193431e4740f593039f613773daaf97772e +vFW_el7oHMk diff --git a/examples/if-else/if-else.sh b/examples/if-else/if-else.sh index 13c363f30..52ccc1101 100644 --- a/examples/if-else/if-else.sh +++ b/examples/if-else/if-else.sh @@ -3,6 +3,6 @@ $ go run if-else.go 8 is divisible by 4 9 has 1 digit -# There is no [ternary if](http://en.wikipedia.org/wiki/%3F:) +# There is no [ternary if](https://en.wikipedia.org/wiki/%3F:) # in Go, so you'll need to use a full `if` statement even # for basic conditions. diff --git a/examples/interfaces/interfaces.sh b/examples/interfaces/interfaces.sh index f800e3a30..b71147638 100644 --- a/examples/interfaces/interfaces.sh +++ b/examples/interfaces/interfaces.sh @@ -7,4 +7,4 @@ $ go run interfaces.go 31.41592653589793 # To learn more about Go's interfaces, check out this -# [great blog post](http://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go). +# [great blog post](https://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go). diff --git a/examples/json/json.sh b/examples/json/json.sh index e9d0c9fe9..a21ef9dd3 100644 --- a/examples/json/json.sh +++ b/examples/json/json.sh @@ -16,6 +16,6 @@ apple # We've covered the basic of JSON in Go here, but check -# out the [JSON and Go](http://blog.golang.org/2011/01/json-and-go.html) -# blog post and [JSON package docs](http://golang.org/pkg/encoding/json/) +# out the [JSON and Go](https://go.dev/blog/json) +# blog post and [JSON package docs](https://pkg.go.dev/encoding/json) # for more. diff --git a/examples/maps/maps.go b/examples/maps/maps.go index 334627002..8a40d3578 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -1,4 +1,4 @@ -// _Maps_ are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array) +// _Maps_ are Go's built-in [associative data type](https://en.wikipedia.org/wiki/Associative_array) // (sometimes called _hashes_ or _dicts_ in other languages). package main diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index 79caf58c9..2c0cd818c 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -9e0e4535c99668b460c7175f8ff2edc2ccf58bec -agK2Ro2i-Lu +22d147fe9402f9ff210f12b9810811c07f4d64ca +ulCzODwCde_0 diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index 448eb6c73..9569ba554 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -1,6 +1,6 @@ // In the previous example we saw how to manage simple // counter state using [atomic operations](atomic-counters). -// For more complex state we can use a [_mutex_](http://en.wikipedia.org/wiki/Mutual_exclusion) +// For more complex state we can use a [_mutex_](https://en.wikipedia.org/wiki/Mutual_exclusion) // to safely access data across multiple goroutines. package main diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 974d7272a..8c57af1d7 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -3688453f408d8c7cc6db91ab7fd5e0ac06ade7ea -tDqeib2-yZA +a437476f37f1f797e1bab491b3f2ac9b386f6700 +Kr_cdza5vyz diff --git a/examples/pointers/pointers.go b/examples/pointers/pointers.go index 55749978f..1a24906ce 100644 --- a/examples/pointers/pointers.go +++ b/examples/pointers/pointers.go @@ -1,4 +1,4 @@ -// Go supports pointers, +// Go supports pointers, // allowing you to pass references to values and records // within your program. diff --git a/examples/pointers/pointers.hash b/examples/pointers/pointers.hash index 455774fb3..b67064b00 100644 --- a/examples/pointers/pointers.hash +++ b/examples/pointers/pointers.hash @@ -1,2 +1,2 @@ -c727916063ddc3e99199cd24bfbde37ff301c0b4 -oimmXypnAcs +7f9855cfb983efc07415117e2be734f55a6bb64b +OlWCLpxAyBz diff --git a/examples/random-numbers/random-numbers.go b/examples/random-numbers/random-numbers.go index ebb6a8ccd..3bd5d548f 100644 --- a/examples/random-numbers/random-numbers.go +++ b/examples/random-numbers/random-numbers.go @@ -1,5 +1,5 @@ // Go's `math/rand` package provides -// [pseudorandom number](http://en.wikipedia.org/wiki/Pseudorandom_number_generator) +// [pseudorandom number](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) // generation. package main diff --git a/examples/random-numbers/random-numbers.hash b/examples/random-numbers/random-numbers.hash index 907e93b44..338e52228 100644 --- a/examples/random-numbers/random-numbers.hash +++ b/examples/random-numbers/random-numbers.hash @@ -1,2 +1,2 @@ -102041ca421268afbd4b4e7687386bb65a8c7965 -PGklfJzErTN +f0f88939692a32975d902c94066537a6ba5ab96f +RaoKyUd9tgC diff --git a/examples/random-numbers/random-numbers.sh b/examples/random-numbers/random-numbers.sh index 67c37a8ec..3cd78b480 100644 --- a/examples/random-numbers/random-numbers.sh +++ b/examples/random-numbers/random-numbers.sh @@ -7,6 +7,6 @@ $ go run random-numbers.go 5,87 -# See the [`math/rand`](http://golang.org/pkg/math/rand/) +# See the [`math/rand`](https://pkg.go.dev/math/rand) # package docs for references on other random quantities # that Go can provide. diff --git a/examples/rate-limiting/rate-limiting.go b/examples/rate-limiting/rate-limiting.go index d890e7fa7..f1e84c1c1 100644 --- a/examples/rate-limiting/rate-limiting.go +++ b/examples/rate-limiting/rate-limiting.go @@ -1,4 +1,4 @@ -// [_Rate limiting_](http://en.wikipedia.org/wiki/Rate_limiting) +// [_Rate limiting_](https://en.wikipedia.org/wiki/Rate_limiting) // is an important mechanism for controlling resource // utilization and maintaining quality of service. Go // elegantly supports rate limiting with goroutines, diff --git a/examples/rate-limiting/rate-limiting.hash b/examples/rate-limiting/rate-limiting.hash index adb0bfc72..3b6573225 100644 --- a/examples/rate-limiting/rate-limiting.hash +++ b/examples/rate-limiting/rate-limiting.hash @@ -1,2 +1,2 @@ -c7063265708287744ea172ed9ed1390043140718 -GXjXHfnKFXg +4f327f5bd5ac199ae5590652563ea6ca4ce7eff5 +lqf7pC2FUeT diff --git a/examples/recursion/recursion.go b/examples/recursion/recursion.go index f0ce4e1ea..b85deb882 100644 --- a/examples/recursion/recursion.go +++ b/examples/recursion/recursion.go @@ -1,5 +1,5 @@ // Go supports -// recursive functions. +// recursive functions. // Here's a classic example. package main diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index 026010039..7237c6a7b 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -9ac9b5af828c33eb20dd322fd1a991334242c4b3 -7hD-3-bIuSp +cdbd1a6957b3e2d7d9baa9efe4581ba4f8f3e753 +MBTKk9VpAiK diff --git a/examples/regular-expressions/regular-expressions.go b/examples/regular-expressions/regular-expressions.go index e10e934a4..aa7bf75b8 100644 --- a/examples/regular-expressions/regular-expressions.go +++ b/examples/regular-expressions/regular-expressions.go @@ -1,4 +1,4 @@ -// Go offers built-in support for [regular expressions](http://en.wikipedia.org/wiki/Regular_expression). +// Go offers built-in support for [regular expressions](https://en.wikipedia.org/wiki/Regular_expression). // Here are some examples of common regexp-related tasks // in Go. diff --git a/examples/regular-expressions/regular-expressions.hash b/examples/regular-expressions/regular-expressions.hash index 63ee8ef17..8650e3bf2 100644 --- a/examples/regular-expressions/regular-expressions.hash +++ b/examples/regular-expressions/regular-expressions.hash @@ -1,2 +1,2 @@ -5c3bcf9f8c61fc074143f766c4517e445a6d9b0f -htCqJrLdh9Q +7fd60a9497546cb5c84242276ed79aecbde7e950 +fI2YIfYsCaL diff --git a/examples/regular-expressions/regular-expressions.sh b/examples/regular-expressions/regular-expressions.sh index ec4f20145..afdab0d68 100644 --- a/examples/regular-expressions/regular-expressions.sh +++ b/examples/regular-expressions/regular-expressions.sh @@ -14,4 +14,4 @@ a a PEACH # For a complete reference on Go regular expressions check -# the [`regexp`](http://golang.org/pkg/regexp/) package docs. +# the [`regexp`](https://pkg.go.dev/regexp) package docs. diff --git a/examples/signals/signals.go b/examples/signals/signals.go index 1fd225b5b..54e8789d4 100644 --- a/examples/signals/signals.go +++ b/examples/signals/signals.go @@ -1,5 +1,5 @@ // Sometimes we'd like our Go programs to intelligently -// handle [Unix signals](http://en.wikipedia.org/wiki/Unix_signal). +// handle [Unix signals](https://en.wikipedia.org/wiki/Unix_signal). // For example, we might want a server to gracefully // shutdown when it receives a `SIGTERM`, or a command-line // tool to stop processing input if it receives a `SIGINT`. diff --git a/examples/signals/signals.hash b/examples/signals/signals.hash index 3735e8ff5..4f7a77927 100644 --- a/examples/signals/signals.hash +++ b/examples/signals/signals.hash @@ -1,2 +1,2 @@ -cd15508731199185f3205692af0f80cbdee4fcd7 -LauPuRo3v9l +739d6c0e33656817de5701412fe266c51730b532 +RKLAbvblJMQ diff --git a/examples/slices/slices.sh b/examples/slices/slices.sh index 9d40831f2..f29dd36a5 100644 --- a/examples/slices/slices.sh +++ b/examples/slices/slices.sh @@ -13,7 +13,7 @@ sl3: [c d e f] dcl: [g h i] 2d: [[0] [1 2] [2 3 4]] -# Check out this [great blog post](http://blog.golang.org/2011/01/go-slices-usage-and-internals.html) +# Check out this [great blog post](https://go.dev/blog/slices-intro) # by the Go team for more details on the design and # implementation of slices in Go. diff --git a/examples/string-functions/string-functions.go b/examples/string-functions/string-functions.go index 7a26e2860..739b5473c 100644 --- a/examples/string-functions/string-functions.go +++ b/examples/string-functions/string-functions.go @@ -20,7 +20,7 @@ func main() { // package, not methods on the string object itself, // we need pass the string in question as the first // argument to the function. You can find more - // functions in the [`strings`](http://golang.org/pkg/strings/) + // functions in the [`strings`](https://pkg.go.dev/strings) // package docs. p("Contains: ", s.Contains("test", "es")) p("Count: ", s.Count("test", "t")) diff --git a/examples/string-functions/string-functions.hash b/examples/string-functions/string-functions.hash index 81e3bf005..7a51d460b 100644 --- a/examples/string-functions/string-functions.hash +++ b/examples/string-functions/string-functions.hash @@ -1,2 +1,2 @@ -e52d4023b8102ba47f3f97e67e47da1bfe393e6c -mdta6dlNB6e +a8fc7e03fd17f6d432adf2f0e991461630ce4350 +DSKkoyx9Rcy diff --git a/examples/variadic-functions/variadic-functions.go b/examples/variadic-functions/variadic-functions.go index 02c67a5d4..68ffe0b26 100644 --- a/examples/variadic-functions/variadic-functions.go +++ b/examples/variadic-functions/variadic-functions.go @@ -1,4 +1,4 @@ -// [_Variadic functions_](http://en.wikipedia.org/wiki/Variadic_function) +// [_Variadic functions_](https://en.wikipedia.org/wiki/Variadic_function) // can be called with any number of trailing arguments. // For example, `fmt.Println` is a common variadic // function. diff --git a/examples/variadic-functions/variadic-functions.hash b/examples/variadic-functions/variadic-functions.hash index 850311a8d..3c29574fd 100644 --- a/examples/variadic-functions/variadic-functions.hash +++ b/examples/variadic-functions/variadic-functions.hash @@ -1,2 +1,2 @@ -560aaef6ce8867710f3ef609b1bb2317377a71bf -Ua6kZOMabBp +dd2e819d49c1110c7eb7dc198b62e0994e0ba93e +7_-i75JEsmM diff --git a/public/arrays b/public/arrays index f361bac76..7a0b707ad 100644 --- a/public/arrays +++ b/public/arrays @@ -42,7 +42,7 @@ specific length.

    - +
    package main
     
    - +
    package main
     
    -

    Go provides built-in support for base64 +

    Go provides built-in support for base64 encoding/decoding.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    -

    Go supports anonymous functions, -which can form closures. +

    Go supports anonymous functions, +which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

    @@ -44,7 +44,7 @@ a function inline without having to name it.

    - +
    package main
     
    -

    Command-line arguments +

    Command-line arguments are a common way to parameterize execution of programs. For example, go run hello.go uses run and hello.go arguments to the go program.

    @@ -44,7 +44,7 @@ For example, go run hello.go uses run and
    - +
    package main
     
    -

    Command-line flags +

    Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

    @@ -44,7 +44,7 @@ command-line flag.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
     package main
     
    diff --git a/public/defer b/public/defer index 2ba790bc3..2e48c9e2e 100644 --- a/public/defer +++ b/public/defer @@ -44,7 +44,7 @@ purposes of cleanup. defer is often used where e.g.
    - +
    package main
     
    - +
    package main
     
    - +
     package main
     
    diff --git a/public/environment-variables b/public/environment-variables index a15776f6e..fb6a4a167 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -27,8 +27,8 @@
    -

    Environment variables -are a universal mechanism for conveying configuration +

    Environment variables +are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.

    @@ -44,7 +44,7 @@ Let’s look at how to set, get, and list environment variables.

    - +
    package main
     

    A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the -Unix epoch. +Unix epoch. Here’s how to do it in Go.

    - +
    package main
     
    - +
    package main
     
    -

    See this great post +

    See this great post on the Go blog for more on error handling.

    - +
    package main
     
    - +
    package main
     
    - +
     package main
     
    diff --git a/public/for b/public/for index 903caba01..e5b9674be 100644 --- a/public/for +++ b/public/for @@ -42,7 +42,7 @@ some basic types of for loops.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
     package main
     
    diff --git a/public/http-clients b/public/http-clients index 1d1614843..596bba3c9 100644 --- a/public/http-clients +++ b/public/http-clients @@ -34,7 +34,7 @@ HTTP requests.

    - +
     package main
     
    @@ -79,7 +79,7 @@ settings.

    -    resp, err := http.Get("http://gobyexample.com")
    +    resp, err := http.Get("https://gobyexample.com")
         if err != nil {
             panic(err)
         }
    @@ -166,7 +166,7 @@ settings.

    diff --git a/public/http-servers b/public/http-servers index 54873d5f8..dfde83deb 100644 --- a/public/http-servers +++ b/public/http-servers @@ -32,7 +32,7 @@
    - +
     package main
     
    diff --git a/public/if-else b/public/if-else index 5bbe3fd5c..b05329e59 100644 --- a/public/if-else +++ b/public/if-else @@ -42,7 +42,7 @@ straight-forward.

    - +
    package main
     
    -

    There is no ternary if +

    There is no ternary if in Go, so you’ll need to use a full if statement even for basic conditions.

    diff --git a/public/index.html b/public/index.html index d01f33930..23d073159 100644 --- a/public/index.html +++ b/public/index.html @@ -9,7 +9,7 @@

    Go by Example

    - Go is an + Go is an open source programming language designed for building simple, fast, and reliable software. Please read the official diff --git a/public/interfaces b/public/interfaces index a540bafe4..36cef1b21 100644 --- a/public/interfaces +++ b/public/interfaces @@ -42,7 +42,7 @@ signatures.

    - +
    package main
     

    To learn more about Go’s interfaces, check out this -great blog post.

    +great blog post.

    diff --git a/public/json b/public/json index e8cb478bb..f1d7040e3 100644 --- a/public/json +++ b/public/json @@ -43,7 +43,7 @@ data types.

    - +
    package main
     

    We’ve covered the basic of JSON in Go here, but check -out the JSON and Go -blog post and JSON package docs +out the JSON and Go +blog post and JSON package docs for more.

    - +
     package main
     
    diff --git a/public/maps b/public/maps index c6b41c58e..bf99e933b 100644 --- a/public/maps +++ b/public/maps @@ -27,7 +27,7 @@
    -

    Maps are Go’s built-in associative data type +

    Maps are Go’s built-in associative data type (sometimes called hashes or dicts in other languages).

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     

    In the previous example we saw how to manage simple counter state using atomic operations. -For more complex state we can use a mutex +For more complex state we can use a mutex to safely access data across multiple goroutines.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    -

    Go supports pointers, +

    Go supports pointers, allowing you to pass references to values and records within your program.

    @@ -43,7 +43,7 @@ within your program.

    - +
    package main
     

    Go’s math/rand package provides -pseudorandom number +pseudorandom number generation.

    - +
    package main
     
    -

    See the math/rand +

    See the math/rand package docs for references on other random quantities that Go can provide.

    diff --git a/public/range b/public/range index f1fb5b42a..5259ac7f3 100644 --- a/public/range +++ b/public/range @@ -43,7 +43,7 @@ of the data structures we’ve already learned.

    - +
    package main
     
    - +
    package main
     
    -

    Rate limiting +

    Rate limiting is an important mechanism for controlling resource utilization and maintaining quality of service. Go elegantly supports rate limiting with goroutines, @@ -45,7 +45,7 @@ channels, and tickers.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     

    Go supports -recursive functions. +recursive functions. Here’s a classic example.

    - +
    package main
     
    -

    Go offers built-in support for regular expressions. +

    Go offers built-in support for regular expressions. Here are some examples of common regexp-related tasks in Go.

    @@ -43,7 +43,7 @@ in Go.

    - +
    package main
     

    For a complete reference on Go regular expressions check -the regexp package docs.

    +the regexp package docs.

    diff --git a/public/select b/public/select index be8d05dab..81326663a 100644 --- a/public/select +++ b/public/select @@ -43,7 +43,7 @@ select is a powerful feature of Go.

    - +
    package main
     
    - +
    package main
     

    Sometimes we’d like our Go programs to intelligently -handle Unix signals. +handle Unix signals. For example, we might want a server to gracefully shutdown when it receives a SIGTERM, or a command-line tool to stop processing input if it receives a SIGINT. @@ -46,7 +46,7 @@ Here’s how to handle signals in Go with channels.

    - +
    package main
     
    - +
    package main
     
    -

    Check out this great blog post +

    Check out this great blog post by the Go team for more details on the design and implementation of slices in Go.

    diff --git a/public/sorting b/public/sorting index e4c7d39f3..e3c3508db 100644 --- a/public/sorting +++ b/public/sorting @@ -43,7 +43,7 @@ builtins first.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
     package main
     
    diff --git a/public/text-templates b/public/text-templates index 665eb5bd3..df0d536f2 100644 --- a/public/text-templates +++ b/public/text-templates @@ -44,7 +44,7 @@ features and should be used for generating HTML.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    -

    Variadic functions +

    Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

    @@ -44,7 +44,7 @@ function.

    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - +
    package main
     
    - {{if .CodeRun}}{{end}} + {{if .CodeRun}}{{end}} {{.CodeRendered}}
    - +
    package main
     
    - +
    package main
     
    +

    Within the function, the type of nums is +equivalent to []int. We can call len(nums), +iterate over it with range, etc.

    + +
    + +
         for _, num := range nums {
             total += num
         }
    @@ -169,7 +183,7 @@ to form closures, which we’ll look at next.

    From 0eaaca29eff7930d5bd8264e054637afcb835351 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 27 Jun 2022 20:48:50 -0700 Subject: [PATCH 153/283] Fix typo in xml example This was noticed by @deining in #428 Closes #428 --- examples/xml/xml.go | 2 +- examples/xml/xml.hash | 4 ++-- public/xml | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/xml/xml.go b/examples/xml/xml.go index 9870377bd..4affc12cd 100644 --- a/examples/xml/xml.go +++ b/examples/xml/xml.go @@ -41,7 +41,7 @@ func main() { // it explicitly. fmt.Println(xml.Header + string(out)) - // Use `Unmarhshal` to parse a stream of bytes with XML + // Use `Unmarshal` to parse a stream of bytes with XML // into a data structure. If the XML is malformed or // cannot be mapped onto Plant, a descriptive error // will be returned. diff --git a/examples/xml/xml.hash b/examples/xml/xml.hash index b9354ae78..56c0a9aae 100644 --- a/examples/xml/xml.hash +++ b/examples/xml/xml.hash @@ -1,2 +1,2 @@ -d5da1784f3aa0bbba452d21c70833621a62159f4 -RsNLhMBazeX +4b9dfaf797591099f6fcb762241289b1662a9250 +OVq7kNMk0GR diff --git a/public/xml b/public/xml index 30f84ad58..26752fecb 100644 --- a/public/xml +++ b/public/xml @@ -42,7 +42,7 @@ formats with the encoding.xml package.

    - +
    package main
     
    -

    Use Unmarhshal to parse a stream of bytes with XML +

    Use Unmarshal to parse a stream of bytes with XML into a data structure. If the XML is malformed or cannot be mapped onto Plant, a descriptive error will be returned.

    From 73cd7a73bb69c2772f2c4c676912519d5ac1abc6 Mon Sep 17 00:00:00 2001 From: Ben McNicholl Date: Mon, 11 Jul 2022 22:42:26 +1000 Subject: [PATCH 154/283] Fix typo in Println statement (#432) * Fix typo in Println statement * Generate HTML for public files. --- examples/generics/generics.go | 2 +- examples/generics/generics.hash | 4 ++-- public/generics | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/generics/generics.go b/examples/generics/generics.go index de20e28a5..c6fa91afd 100644 --- a/examples/generics/generics.go +++ b/examples/generics/generics.go @@ -61,7 +61,7 @@ func main() { // specify the types for `K` and `V` when // calling `MapKeys` - the compiler infers them // automatically. - fmt.Println("keys m:", MapKeys(m)) + fmt.Println("keys:", MapKeys(m)) // ... though we could also specify them explicitly. _ = MapKeys[int, string](m) diff --git a/examples/generics/generics.hash b/examples/generics/generics.hash index 77ce621d5..2b23af56f 100644 --- a/examples/generics/generics.hash +++ b/examples/generics/generics.hash @@ -1,2 +1,2 @@ -6219a4dadc2685ab1b61dc8e95799fd683ccb761 -YulcAofh266 +91465956a90881ec8b4cca3968b9aa1f6d9f1447 +uXlb-AyeYmQ diff --git a/public/generics b/public/generics index 6b4e6ec92..0ca662e08 100644 --- a/public/generics +++ b/public/generics @@ -42,7 +42,7 @@
    - +
    package main
     
    -    fmt.Println("keys m:", MapKeys(m))
    +    fmt.Println("keys:", MapKeys(m))
     

    In Go, an array is a numbered sequence of elements of a -specific length.

    +specific length. In typical Go code, slices are +much more common; arrays are useful in some special +scenarios.

    @@ -42,7 +44,7 @@ specific length.

    - +
    package main
     
    +
     $ go run arrays.go
    @@ -177,18 +179,6 @@ when printed with fmt.Println.

    -

    You’ll see slices much more often than arrays in -typical Go. We’ll look at slices next.

    - -
    - - -
    @@ -204,7 +194,7 @@ typical Go. We’ll look at slices next.

    diff --git a/public/slices b/public/slices index 3780b5997..78c327a9d 100644 --- a/public/slices +++ b/public/slices @@ -27,8 +27,8 @@ -

    Slices are a key data type in Go, giving a more -powerful interface to sequences than arrays.

    +

    Slices are an important data type in Go, giving +a more powerful interface to sequences than arrays.

    @@ -42,7 +42,7 @@ powerful interface to sequences than arrays.

    - +
    package main
     
    From b4f289fe92bbaf6472958f96f72874bde21a33f5 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 8 Sep 2022 05:55:05 -0700 Subject: [PATCH 159/283] Adjust for gofmt changes in 1.19 In 1.19, gofmt slightly changes how comments are formatted; a blank `//` is inserted before `//go:embed` directives. To accommodate for that in generate.go, treat empty comment lines as part of docs segments. --- examples/embed-directive/embed-directive.go | 3 +++ examples/embed-directive/embed-directive.hash | 4 ++-- public/embed-directive | 2 +- tools/generate.go | 4 ++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/examples/embed-directive/embed-directive.go b/examples/embed-directive/embed-directive.go index 3cbbb0e67..2350138f2 100644 --- a/examples/embed-directive/embed-directive.go +++ b/examples/embed-directive/embed-directive.go @@ -14,16 +14,19 @@ import ( // `embed` directives accept paths relative to the directory containing the // Go source file. This directive embeds the contents of the file into the // `string` variable immediately following it. +// //go:embed folder/single_file.txt var fileString string // Or embed the contents of the file into a `[]byte`. +// //go:embed folder/single_file.txt var fileByte []byte // We can also embed multiple files or even folders with wildcards. This uses // a variable of the [embed.FS type](https://pkg.go.dev/embed#FS), which // implements a simple virtual file system. +// //go:embed folder/single_file.txt //go:embed folder/*.hash var folder embed.FS diff --git a/examples/embed-directive/embed-directive.hash b/examples/embed-directive/embed-directive.hash index da30d5a9f..f81e31743 100644 --- a/examples/embed-directive/embed-directive.hash +++ b/examples/embed-directive/embed-directive.hash @@ -1,2 +1,2 @@ -53a5e68182be7308ddb35cc209e6b905c5b9c713 -p6JB_5z1IBJ +69526bd78ac861c85bb12b96e9f1273e8aecc5a6 +6m2ll-D52BB diff --git a/public/embed-directive b/public/embed-directive index 7b417808a..906bece5a 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -35,7 +35,7 @@ build time. Read more about the embed directive - +
     package main
     
    diff --git a/tools/generate.go b/tools/generate.go index f8341c6d6..9362c743a 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -95,8 +95,8 @@ func debug(msg string) { } } -var docsPat = regexp.MustCompile("^\\s*(\\/\\/|#)\\s") -var dashPat = regexp.MustCompile("\\-+") +var docsPat = regexp.MustCompile(`^(\s*(\/\/|#)\s|\s*\/\/$)`) +var dashPat = regexp.MustCompile(`\-+`) // Seg is a segment of an example type Seg struct { From 00543ca6f793bf756047b20b44b9948099cbf9b1 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 8 Sep 2022 06:30:01 -0700 Subject: [PATCH 160/283] Update Go version to 1.19 in go.mod and GH actions --- .github/workflows/test.yml | 2 +- go.mod | 10 ++++++---- go.sum | 5 ++--- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ae898415c..29df4730b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.18.3] + go-version: [1.19.1] runs-on: ${{ matrix.os }} steps: diff --git a/go.mod b/go.mod index 908809f02..7efb899a8 100644 --- a/go.mod +++ b/go.mod @@ -1,23 +1,25 @@ module github.com/mmcgrana/gobyexample -go 1.17 +go 1.19 require ( github.com/alecthomas/chroma v0.8.2 + github.com/aws/aws-sdk-go-v2 v1.9.0 + github.com/aws/aws-sdk-go-v2/config v1.7.0 + github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 github.com/russross/blackfriday/v2 v2.1.0 ) require ( - github.com/aws/aws-sdk-go-v2 v1.9.0 // indirect - github.com/aws/aws-sdk-go-v2/config v1.7.0 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.4.0 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0 // indirect - github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 // indirect github.com/aws/smithy-go v1.8.0 // indirect + github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect + github.com/dlclark/regexp2 v1.2.0 // indirect ) diff --git a/go.sum b/go.sum index a2bcae3b7..a395d871a 100644 --- a/go.sum +++ b/go.sum @@ -34,11 +34,11 @@ github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAm github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= @@ -47,7 +47,6 @@ github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHX github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -55,12 +54,12 @@ github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200413165638-669c56c373c4 h1:opSr2sbRXk5X5/givKrrKj9HXxFpW2sdCiP8MJSKLQY= golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= From cc804d764b09e4851f52097b99d7eac26ce119c0 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 22 Sep 2022 07:05:32 -0700 Subject: [PATCH 161/283] Clarify determinism of Go playground w.r.t. random numbers Fixes #443 --- examples/random-numbers/random-numbers.go | 2 +- examples/random-numbers/random-numbers.hash | 4 ++-- examples/random-numbers/random-numbers.sh | 5 +++++ public/random-numbers | 14 ++++++++++---- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/examples/random-numbers/random-numbers.go b/examples/random-numbers/random-numbers.go index 3bd5d548f..53d0f381c 100644 --- a/examples/random-numbers/random-numbers.go +++ b/examples/random-numbers/random-numbers.go @@ -32,7 +32,7 @@ func main() { // produce the same sequence of numbers each time by default. // To produce varying sequences, give it a seed that changes. // Note that this is not safe to use for random numbers you - // intend to be secret, use `crypto/rand` for those. + // intend to be secret; use `crypto/rand` for those. s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) diff --git a/examples/random-numbers/random-numbers.hash b/examples/random-numbers/random-numbers.hash index 338e52228..e099cc460 100644 --- a/examples/random-numbers/random-numbers.hash +++ b/examples/random-numbers/random-numbers.hash @@ -1,2 +1,2 @@ -f0f88939692a32975d902c94066537a6ba5ab96f -RaoKyUd9tgC +ea6a386e4e5602247b2203fa433d4419ff5a9489 +Enb5uJEx0Bt diff --git a/examples/random-numbers/random-numbers.sh b/examples/random-numbers/random-numbers.sh index 3cd78b480..f9f2b5ba4 100644 --- a/examples/random-numbers/random-numbers.sh +++ b/examples/random-numbers/random-numbers.sh @@ -1,3 +1,8 @@ +# Depending on where you run this sample, some of the +# generated numbers may be different. Note that on +# the Go playground seeding with `time.Now()` still +# produces deterministic results due to the way the +# playground is implemented. $ go run random-numbers.go 81,87 0.6645600532184904 diff --git a/public/random-numbers b/public/random-numbers index 488191dc4..c1571e271 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -43,7 +43,7 @@ generation.

    - +
    package main
     
    @@ -127,7 +127,7 @@ other ranges, for example 5.0 <= f' < 10.0.

    produce the same sequence of numbers each time by default. To produce varying sequences, give it a seed that changes. Note that this is not safe to use for random numbers you -intend to be secret, use crypto/rand for those.

    +intend to be secret; use crypto/rand for those.

    @@ -184,11 +184,17 @@ produces the same sequence of random numbers.

    - +

    Depending on where you run this sample, some of the +generated numbers may be different. Note that on +the Go playground seeding with time.Now() still +produces deterministic results due to the way the +playground is implemented.

    + -
    $ go run random-numbers.go
    +          
    +$ go run random-numbers.go
     81,87
     0.6645600532184904
     7.123187485356329,8.434115364335547
    
    From 840541a6bd850dbb54af36e0b88a8f3ab6b6830a Mon Sep 17 00:00:00 2001
    From: Eli Bendersky 
    Date: Thu, 22 Sep 2022 13:44:25 -0700
    Subject: [PATCH 162/283] Rename http clients/servers to singular language:
     client/server
    
    ---
     examples.txt                                  |   4 +-
     .../http-client.go}                           |   0
     .../http-client.sh}                           |   0
     .../http-clients.hash                         |   0
     .../http-server.go}                           |   0
     .../http-server.sh}                           |   0
     .../http-servers.hash                         |   0
     public/context                                |   2 +-
     public/environment-variables                  |   4 +-
     public/http-client                            | 173 ++++++++++++++
     public/http-clients                           | 132 +----------
     public/http-server                            | 214 ++++++++++++++++++
     public/http-servers                           | 173 +-------------
     public/index.html                             |   4 +-
     14 files changed, 396 insertions(+), 310 deletions(-)
     rename examples/{http-clients/http-clients.go => http-client/http-client.go} (100%)
     rename examples/{http-clients/http-clients.sh => http-client/http-client.sh} (100%)
     rename examples/{http-clients => http-client}/http-clients.hash (100%)
     rename examples/{http-servers/http-servers.go => http-server/http-server.go} (100%)
     rename examples/{http-servers/http-servers.sh => http-server/http-server.sh} (100%)
     rename examples/{http-servers => http-server}/http-servers.hash (100%)
     create mode 100644 public/http-client
     create mode 100644 public/http-server
    
    diff --git a/examples.txt b/examples.txt
    index 5c22a2a73..de7120784 100644
    --- a/examples.txt
    +++ b/examples.txt
    @@ -71,8 +71,8 @@ Command-Line Arguments
     Command-Line Flags
     Command-Line Subcommands
     Environment Variables
    -HTTP Clients
    -HTTP Servers
    +HTTP Client
    +HTTP Server
     Context
     Spawning Processes
     Exec'ing Processes
    diff --git a/examples/http-clients/http-clients.go b/examples/http-client/http-client.go
    similarity index 100%
    rename from examples/http-clients/http-clients.go
    rename to examples/http-client/http-client.go
    diff --git a/examples/http-clients/http-clients.sh b/examples/http-client/http-client.sh
    similarity index 100%
    rename from examples/http-clients/http-clients.sh
    rename to examples/http-client/http-client.sh
    diff --git a/examples/http-clients/http-clients.hash b/examples/http-client/http-clients.hash
    similarity index 100%
    rename from examples/http-clients/http-clients.hash
    rename to examples/http-client/http-clients.hash
    diff --git a/examples/http-servers/http-servers.go b/examples/http-server/http-server.go
    similarity index 100%
    rename from examples/http-servers/http-servers.go
    rename to examples/http-server/http-server.go
    diff --git a/examples/http-servers/http-servers.sh b/examples/http-server/http-server.sh
    similarity index 100%
    rename from examples/http-servers/http-servers.sh
    rename to examples/http-server/http-server.sh
    diff --git a/examples/http-servers/http-servers.hash b/examples/http-server/http-servers.hash
    similarity index 100%
    rename from examples/http-servers/http-servers.hash
    rename to examples/http-server/http-servers.hash
    diff --git a/public/context b/public/context
    index 59213e68f..576162faf 100644
    --- a/public/context
    +++ b/public/context
    @@ -9,7 +9,7 @@
           onkeydown = (e) => {
               
               if (e.key == "ArrowLeft") {
    -              window.location.href = 'http-servers';
    +              window.location.href = 'http-server';
               }
               
               
    diff --git a/public/environment-variables b/public/environment-variables
    index 28595958e..f0d0e5ed9 100644
    --- a/public/environment-variables
    +++ b/public/environment-variables
    @@ -14,7 +14,7 @@
               
               
               if (e.key == "ArrowRight") {
    -              window.location.href = 'http-clients';
    +              window.location.href = 'http-client';
               }
               
           }
    @@ -172,7 +172,7 @@ program picks that value up.

    - Next example: HTTP Clients. + Next example: HTTP Client.

    diff --git a/public/http-client b/public/http-client new file mode 100644 index 000000000..763290b15 --- /dev/null +++ b/public/http-client @@ -0,0 +1,173 @@ + + + + + Go by Example: HTTP Client + + + + +
    +

    Go by Example: HTTP Client

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    The Go standard library comes with excellent support +for HTTP clients and servers in the net/http +package. In this example we’ll use it to issue simple +HTTP requests.

    + +
    + +
    +package main
    +
    +
    + + + +
    import (
    +    "bufio"
    +    "fmt"
    +    "net/http"
    +)
    +
    +
    + + + +
    func main() {
    +
    +
    +

    Issue an HTTP GET request to a server. http.Get is a +convenient shortcut around creating an http.Client +object and calling its Get method; it uses the +http.DefaultClient object which has useful default +settings.

    + +
    + +
    +    resp, err := http.Get("https://gobyexample.com")
    +    if err != nil {
    +        panic(err)
    +    }
    +    defer resp.Body.Close()
    +
    +
    +

    Print the HTTP response status.

    + +
    + +
    +    fmt.Println("Response status:", resp.Status)
    +
    +
    +

    Print the first 5 lines of the response body.

    + +
    + +
    +    scanner := bufio.NewScanner(resp.Body)
    +    for i := 0; scanner.Scan() && i < 5; i++ {
    +        fmt.Println(scanner.Text())
    +    }
    +
    +
    + + + +
        if err := scanner.Err(); err != nil {
    +        panic(err)
    +    }
    +}
    +
    +
    + + + + + + + + +
    + + + +
    $ go run http-clients.go
    +Response status: 200 OK
    +<!DOCTYPE html>
    +<html>
    +  <head>
    +    <meta charset="utf-8">
    +    <title>Go by Example</title>
    +
    + + +

    + Next example: HTTP Server. +

    + + + + +
    + + + + diff --git a/public/http-clients b/public/http-clients index 596bba3c9..4437bbcc0 100644 --- a/public/http-clients +++ b/public/http-clients @@ -23,136 +23,6 @@

    Go by Example: HTTP Clients

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    The Go standard library comes with excellent support -for HTTP clients and servers in the net/http -package. In this example we’ll use it to issue simple -HTTP requests.

    - -
    - -
    -package main
    -
    -
    - - - -
    import (
    -    "bufio"
    -    "fmt"
    -    "net/http"
    -)
    -
    -
    - - - -
    func main() {
    -
    -
    -

    Issue an HTTP GET request to a server. http.Get is a -convenient shortcut around creating an http.Client -object and calling its Get method; it uses the -http.DefaultClient object which has useful default -settings.

    - -
    - -
    -    resp, err := http.Get("https://gobyexample.com")
    -    if err != nil {
    -        panic(err)
    -    }
    -    defer resp.Body.Close()
    -
    -
    -

    Print the HTTP response status.

    - -
    - -
    -    fmt.Println("Response status:", resp.Status)
    -
    -
    -

    Print the first 5 lines of the response body.

    - -
    - -
    -    scanner := bufio.NewScanner(resp.Body)
    -    for i := 0; scanner.Scan() && i < 5; i++ {
    -        fmt.Println(scanner.Text())
    -    }
    -
    -
    - - - -
        if err := scanner.Err(); err != nil {
    -        panic(err)
    -    }
    -}
    -
    -
    - - - - - - - - -
    - - - -
    $ go run http-clients.go
    -Response status: 200 OK
    -<!DOCTYPE html>
    -<html>
    -  <head>
    -    <meta charset="utf-8">
    -    <title>Go by Example</title>
    -
    -

    Next example: HTTP Servers. @@ -166,7 +36,7 @@ settings.

    diff --git a/public/http-server b/public/http-server new file mode 100644 index 000000000..70cdb544f --- /dev/null +++ b/public/http-server @@ -0,0 +1,214 @@ + + + + + Go by Example: HTTP Server + + + + +
    +

    Go by Example: HTTP Server

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Writing a basic HTTP server is easy using the +net/http package.

    + +
    + +
    +package main
    +
    +
    + + + +
    import (
    +    "fmt"
    +    "net/http"
    +)
    +
    +
    +

    A fundamental concept in net/http servers is +handlers. A handler is an object implementing the +http.Handler interface. A common way to write +a handler is by using the http.HandlerFunc adapter +on functions with the appropriate signature.

    + +
    + +
    +func hello(w http.ResponseWriter, req *http.Request) {
    +
    +
    +

    Functions serving as handlers take a +http.ResponseWriter and a http.Request as +arguments. The response writer is used to fill in the +HTTP response. Here our simple response is just +“hello\n”.

    + +
    + +
    +    fmt.Fprintf(w, "hello\n")
    +}
    +
    +
    + + + +
    func headers(w http.ResponseWriter, req *http.Request) {
    +
    +
    +

    This handler does something a little more +sophisticated by reading all the HTTP request +headers and echoing them into the response body.

    + +
    + +
    +    for name, headers := range req.Header {
    +        for _, h := range headers {
    +            fmt.Fprintf(w, "%v: %v\n", name, h)
    +        }
    +    }
    +}
    +
    +
    + + + +
    func main() {
    +
    +
    +

    We register our handlers on server routes using the +http.HandleFunc convenience function. It sets up +the default router in the net/http package and +takes a function as an argument.

    + +
    + +
    +    http.HandleFunc("/hello", hello)
    +    http.HandleFunc("/headers", headers)
    +
    +
    +

    Finally, we call the ListenAndServe with the port +and a handler. nil tells it to use the default +router we’ve just set up.

    + +
    + +
    +    http.ListenAndServe(":8090", nil)
    +}
    +
    +
    + + + + + + + + + + + + + +
    +

    Run the server in the background.

    + +
    + +
    +$ go run http-servers.go &
    +
    +

    Access the /hello route.

    + +
    + +
    +$ curl localhost:8090/hello
    +hello
    +
    + + +

    + Next example: Context. +

    + + + + +
    + + + + diff --git a/public/http-servers b/public/http-servers index dfde83deb..df7ce3f0f 100644 --- a/public/http-servers +++ b/public/http-servers @@ -23,177 +23,6 @@

    Go by Example: HTTP Servers

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    Writing a basic HTTP server is easy using the -net/http package.

    - -
    - -
    -package main
    -
    -
    - - - -
    import (
    -    "fmt"
    -    "net/http"
    -)
    -
    -
    -

    A fundamental concept in net/http servers is -handlers. A handler is an object implementing the -http.Handler interface. A common way to write -a handler is by using the http.HandlerFunc adapter -on functions with the appropriate signature.

    - -
    - -
    -func hello(w http.ResponseWriter, req *http.Request) {
    -
    -
    -

    Functions serving as handlers take a -http.ResponseWriter and a http.Request as -arguments. The response writer is used to fill in the -HTTP response. Here our simple response is just -“hello\n”.

    - -
    - -
    -    fmt.Fprintf(w, "hello\n")
    -}
    -
    -
    - - - -
    func headers(w http.ResponseWriter, req *http.Request) {
    -
    -
    -

    This handler does something a little more -sophisticated by reading all the HTTP request -headers and echoing them into the response body.

    - -
    - -
    -    for name, headers := range req.Header {
    -        for _, h := range headers {
    -            fmt.Fprintf(w, "%v: %v\n", name, h)
    -        }
    -    }
    -}
    -
    -
    - - - -
    func main() {
    -
    -
    -

    We register our handlers on server routes using the -http.HandleFunc convenience function. It sets up -the default router in the net/http package and -takes a function as an argument.

    - -
    - -
    -    http.HandleFunc("/hello", hello)
    -    http.HandleFunc("/headers", headers)
    -
    -
    -

    Finally, we call the ListenAndServe with the port -and a handler. nil tells it to use the default -router we’ve just set up.

    - -
    - -
    -    http.ListenAndServe(":8090", nil)
    -}
    -
    -
    - - - - - - - - - - - - - -
    -

    Run the server in the background.

    - -
    - -
    -$ go run http-servers.go &
    -
    -

    Access the /hello route.

    - -
    - -
    -$ curl localhost:8090/hello
    -hello
    -
    -

    Next example: Context. @@ -207,7 +36,7 @@ router we’ve just set up.

    diff --git a/public/index.html b/public/index.html index 23d073159..98549d651 100644 --- a/public/index.html +++ b/public/index.html @@ -173,9 +173,9 @@

    Go by Example

  • Environment Variables
  • -
  • HTTP Clients
  • +
  • HTTP Client
  • -
  • HTTP Servers
  • +
  • HTTP Server
  • Context
  • From 2f242db0125a6b377cfccb10efe6b81ddd5a228c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 22 Sep 2022 13:45:14 -0700 Subject: [PATCH 163/283] Remove old public html --- public/http-clients | 43 ------------------------------------------- public/http-servers | 43 ------------------------------------------- 2 files changed, 86 deletions(-) delete mode 100644 public/http-clients delete mode 100644 public/http-servers diff --git a/public/http-clients b/public/http-clients deleted file mode 100644 index 4437bbcc0..000000000 --- a/public/http-clients +++ /dev/null @@ -1,43 +0,0 @@ - - - - - Go by Example: HTTP Clients - - - - -
    -

    Go by Example: HTTP Clients

    - - -

    - Next example: HTTP Servers. -

    - - - - -
    - - - - diff --git a/public/http-servers b/public/http-servers deleted file mode 100644 index df7ce3f0f..000000000 --- a/public/http-servers +++ /dev/null @@ -1,43 +0,0 @@ - - - - - Go by Example: HTTP Servers - - - - -
    -

    Go by Example: HTTP Servers

    - - -

    - Next example: Context. -

    - - - - -
    - - - - From c40fcde81fc8b2fe5b0a704d46c371985924e990 Mon Sep 17 00:00:00 2001 From: Naoya Ueda Date: Fri, 23 Sep 2022 22:12:58 +0900 Subject: [PATCH 164/283] Add missing command line example for recover.sh (#444) --- examples/recover/recover.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/recover/recover.sh b/examples/recover/recover.sh index df26fc4f4..686e75990 100644 --- a/examples/recover/recover.sh +++ b/examples/recover/recover.sh @@ -1,2 +1,3 @@ +$ go run recover.go Recovered. Error: a problem From 4f668ee955e647ae5af4122f32c0afd9b04e2234 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 23 Sep 2022 06:13:30 -0700 Subject: [PATCH 165/283] Re-generate output following previous change updating recover.go --- public/recover | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/public/recover b/public/recover index dda8527d2..903dbf8ea 100644 --- a/public/recover +++ b/public/recover @@ -171,7 +171,8 @@ panic and resumes in the deferred closure.

    -
    Recovered. Error:
    +          
    $ go run recover.go
    +Recovered. Error:
      a problem
    From 9ba0fd08dec193255b32d0d925552c9232df3a4c Mon Sep 17 00:00:00 2001 From: Aditya Sood Date: Tue, 25 Oct 2022 18:30:36 +0530 Subject: [PATCH 166/283] Minor addition to if-else text on declarations (#450) * Minor addition to if-else text on declarations Extremely minor addition to if-else text on declarations preceding conditionals, by explicitly clarifying that variables declared are only available in branches succeeding the declaration, not all the branches in the if-else ladder (i.e. preceding branches will not have it in their scope) This edit might be redundant since variables in Golang can only be used after declaration, but to a complete novice the original wording of "...any variables declared in this statement are available in *all* branches..." might be a little misleading and appear to say that the variable is in-scope for the preceding branches as well (as this seems to be a very Golang-specific semantic that other high-level languages like C/C++, Java, Scala, Kotlin etc don't support; and so it will be a brand new paradigm for developers coming from such languages). Thanks! * Increment: Include changes in source .go file for #450 --- examples/if-else/if-else.go | 4 ++-- examples/if-else/if-else.hash | 4 ++-- public/if-else | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/if-else/if-else.go b/examples/if-else/if-else.go index 1f2a4038f..d326b9083 100644 --- a/examples/if-else/if-else.go +++ b/examples/if-else/if-else.go @@ -20,8 +20,8 @@ func main() { } // A statement can precede conditionals; any variables - // declared in this statement are available in all - // branches. + // declared in this statement are available in the current + // and all the succeeding branches. if num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { diff --git a/examples/if-else/if-else.hash b/examples/if-else/if-else.hash index 8f1ebb5de..a0aa4b6b1 100644 --- a/examples/if-else/if-else.hash +++ b/examples/if-else/if-else.hash @@ -1,2 +1,2 @@ -ae7f289ac1b2b1f152cd1952b93769209eed8e1d -QlMkcwHvmns +bbac731541876062076e3dea9a2b536988d7739d +_5PfTs6dNhr diff --git a/public/if-else b/public/if-else index b05329e59..1523e8d65 100644 --- a/public/if-else +++ b/public/if-else @@ -42,7 +42,7 @@ straight-forward.

    - +
    package main
     
    @@ -105,8 +105,8 @@ straight-forward.

    A statement can precede conditionals; any variables -declared in this statement are available in all -branches.

    +declared in this statement are available in the current +and all the succeeding branches.

    From 0650d746783ee55f19e904df8996804131f3cc7d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 25 Oct 2022 06:02:53 -0700 Subject: [PATCH 167/283] Slight rewording --- examples/if-else/if-else.go | 2 +- examples/if-else/if-else.hash | 4 ++-- public/if-else | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/if-else/if-else.go b/examples/if-else/if-else.go index d326b9083..4de7c47bb 100644 --- a/examples/if-else/if-else.go +++ b/examples/if-else/if-else.go @@ -21,7 +21,7 @@ func main() { // A statement can precede conditionals; any variables // declared in this statement are available in the current - // and all the succeeding branches. + // and all subsequent branches. if num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { diff --git a/examples/if-else/if-else.hash b/examples/if-else/if-else.hash index a0aa4b6b1..37363db36 100644 --- a/examples/if-else/if-else.hash +++ b/examples/if-else/if-else.hash @@ -1,2 +1,2 @@ -bbac731541876062076e3dea9a2b536988d7739d -_5PfTs6dNhr +d6a962236fc1296684cd1ffb2d95d131ed84abde +U7xcpdutgCJ diff --git a/public/if-else b/public/if-else index 1523e8d65..ec12be9e1 100644 --- a/public/if-else +++ b/public/if-else @@ -42,7 +42,7 @@ straight-forward.

    - +
    package main
     
    @@ -106,7 +106,7 @@ straight-forward.

    A statement can precede conditionals; any variables declared in this statement are available in the current -and all the succeeding branches.

    +and all subsequent branches.

    From bc9700aab38bc25d6fc3253c88a83ca3ccb0014e Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 3 Nov 2022 06:03:54 -0700 Subject: [PATCH 168/283] Add missing `$ go run ...` line on top of generics.sh Fixes #452 --- examples/generics/generics.sh | 1 + public/generics | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/generics/generics.sh b/examples/generics/generics.sh index 4e59904c5..4aa2d0729 100644 --- a/examples/generics/generics.sh +++ b/examples/generics/generics.sh @@ -1,2 +1,3 @@ +$ go run generics.go keys: [4 1 2] list: [10 13 23] diff --git a/public/generics b/public/generics index 0ca662e08..721f0f7fa 100644 --- a/public/generics +++ b/public/generics @@ -223,7 +223,8 @@ automatically.

    -
    keys: [4 1 2]
    +          
    $ go run generics.go
    +keys: [4 1 2]
     list: [10 13 23]
    From 7b502fa0ec75f0936ce6c5426b6c15e1b91d020b Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 12 Dec 2022 05:48:06 -0800 Subject: [PATCH 169/283] Update CONTRIBUTING.md --- CONTRIBUTING.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5a135481e..051c6d638 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,10 +3,12 @@ Thanks for your interest in contributing to Go by Example! * When sending a PR that affects the displayed contents of the site, run - `tools/build` locally and include the generated HTML in the PR. If you - only want to submit a simple typo suggestion (for example, through the - Github website), feel free to send a PR anyway - we'll regenerate the - HTML and merge with your commit. + `tools/build` locally and include the generated HTML in the PR. Note that + updating the HTML in the `public` directory by itself is insufficient, since + the source of truth for the website is in the `examples` directory. + + If you don't want to deal with getting a proper PR in, feel free to just + open an issue an point out the change you suggest. * We're open to adding more examples to the site. They should be on things used by many programmers and only require the standard library. If you're From f783c4169886b5cc40ee62e35a9fa378b907592f Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 12 Dec 2022 05:49:47 -0800 Subject: [PATCH 170/283] Update CONTRIBUTING.md --- CONTRIBUTING.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 051c6d638..770268b1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,13 +2,16 @@ Thanks for your interest in contributing to Go by Example! -* When sending a PR that affects the displayed contents of the site, run - `tools/build` locally and include the generated HTML in the PR. Note that +* When sending a PR that affects the displayed contents of the site, updating the HTML in the `public` directory by itself is insufficient, since the source of truth for the website is in the `examples` directory. + Instead, update the proper source file(s) in the `examples` directory and + run `tools/build` locally to regenerate the HTML; include both changes in + your PR. + If you don't want to deal with getting a proper PR in, feel free to just - open an issue an point out the change you suggest. + open an issue and point out the change you suggest. * We're open to adding more examples to the site. They should be on things used by many programmers and only require the standard library. If you're From 30a235b65508d1b76961f74fc908f69395fba0cc Mon Sep 17 00:00:00 2001 From: Javier Pacareu Date: Mon, 12 Dec 2022 11:21:16 -0300 Subject: [PATCH 171/283] docs: remove typo (#454) * docs: remove typo * Update mutexes.go * feat: add changes Co-authored-by: Javier Pacareu --- examples/mutexes/mutexes.go | 2 +- examples/mutexes/mutexes.hash | 4 ++-- public/mutexes | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index 9569ba554..5992881fb 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -56,7 +56,7 @@ func main() { go doIncrement("a", 10000) go doIncrement("b", 10000) - // Wait a for the goroutines to finish + // Wait for the goroutines to finish wg.Wait() fmt.Println(c.counters) } diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 8c57af1d7..043180976 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -a437476f37f1f797e1bab491b3f2ac9b386f6700 -Kr_cdza5vyz +d858d466e806a9dcb5992c8c2a3c6dc377a7a904 +JU735qy2UmB diff --git a/public/mutexes b/public/mutexes index 8e42a7612..9dc784d41 100644 --- a/public/mutexes +++ b/public/mutexes @@ -44,7 +44,7 @@ to safely access data across multiple goroutines.

    - +
    package main
     
    @@ -189,7 +189,7 @@ and two of them access the same counter.

    -

    Wait a for the goroutines to finish

    +

    Wait for the goroutines to finish

    From 4944c3bc7bd7647f88ce0e120d728c061cb922be Mon Sep 17 00:00:00 2001 From: Grejo Joby <51746129+grejojoby@users.noreply.github.com> Date: Wed, 21 Dec 2022 02:23:58 +0530 Subject: [PATCH 172/283] Added more information about shorthand variable declaration (#457) --- examples/variables/variables.go | 1 + examples/variables/variables.hash | 4 ++-- public/variables | 5 +++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/examples/variables/variables.go b/examples/variables/variables.go index 8e0912f56..5fa61d4b7 100644 --- a/examples/variables/variables.go +++ b/examples/variables/variables.go @@ -29,6 +29,7 @@ func main() { // The `:=` syntax is shorthand for declaring and // initializing a variable, e.g. for // `var f string = "apple"` in this case. + // This syntax is only available inside functions. f := "apple" fmt.Println(f) } diff --git a/examples/variables/variables.hash b/examples/variables/variables.hash index 040888bcc..2665b92e5 100644 --- a/examples/variables/variables.hash +++ b/examples/variables/variables.hash @@ -1,2 +1,2 @@ -736ce4018f275bb8d12e5232349bae93611506b2 -iYyAIilyBRf +9aeef52b289d7ad9b9ac79f129d4e49f956c60ef +N5rWndIliJW diff --git a/public/variables b/public/variables index 736c7c4bc..11c6fee8f 100644 --- a/public/variables +++ b/public/variables @@ -43,7 +43,7 @@ calls.

    - +
    package main
     
    @@ -133,7 +133,8 @@ zero value for an int is 0.

    The := syntax is shorthand for declaring and initializing a variable, e.g. for -var f string = "apple" in this case.

    +var f string = "apple" in this case. +This syntax is only available inside functions.

    From b6baa3bb2521481abe5105913da99ff3337e3bfe Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 9 Jan 2023 05:58:04 -0800 Subject: [PATCH 173/283] Minor README tweaks --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 96cf2c02d..6f1e15e65 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ a site that teaches Go via annotated example programs. The Go by Example site is built by extracting code and comments from source files in `examples` and rendering -them via the `templates` into a static `public` +them using `templates` into a static `public` directory. The programs implementing this build process are in `tools`, along with dependencies specified in the `go.mod`file. @@ -93,7 +93,7 @@ Given Go's strong [backwards compatibility guarantees](https://go.dev/doc/go1com we expect the vast majority of examples to work on the latest released version of Go as well as many older releases going back years. -That said, some examples show off new features added in the latest release; therefore, +That said, some examples show off new features added in recent releases; therefore, it's recommended to try running examples with the latest officially released Go version (see Go's [release history](https://go.dev/doc/devel/release) for details). From 24b5e9a1ef07bd4b23b5b58e06041f290645faa2 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 31 Jan 2023 05:40:48 -0800 Subject: [PATCH 174/283] Tweak CSS to decrease the font size in the footer This should prevent wrapping on some screens --- public/site.css | 1 + templates/site.css | 1 + 2 files changed, 2 insertions(+) diff --git a/public/site.css b/public/site.css index 7f95c8769..f74c733c1 100644 --- a/public/site.css +++ b/public/site.css @@ -80,6 +80,7 @@ p.next { } p.footer { color: grey; + font-size: 75%; } p.footer a, p.footer a:visited { color: grey; diff --git a/templates/site.css b/templates/site.css index 7f95c8769..f74c733c1 100644 --- a/templates/site.css +++ b/templates/site.css @@ -80,6 +80,7 @@ p.next { } p.footer { color: grey; + font-size: 75%; } p.footer a, p.footer a:visited { color: grey; From 38eb2236cae44e0b8628c3feb84b7ac30559b866 Mon Sep 17 00:00:00 2001 From: siiky <12852780+siiky@users.noreply.github.com> Date: Sat, 4 Feb 2023 00:36:22 +0000 Subject: [PATCH 175/283] `dependes` -> `depends` (#462) --- examples/strings-and-runes/strings-and-runes.go | 2 +- examples/strings-and-runes/strings-and-runes.hash | 4 ++-- public/strings-and-runes | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/strings-and-runes/strings-and-runes.go b/examples/strings-and-runes/strings-and-runes.go index 36974819d..acbd0cc66 100644 --- a/examples/strings-and-runes/strings-and-runes.go +++ b/examples/strings-and-runes/strings-and-runes.go @@ -36,7 +36,7 @@ func main() { // To count how many _runes_ are in a string, we can use // the `utf8` package. Note that the run-time of - // `RuneCountInString` dependes on the size of the string, + // `RuneCountInString` depends on the size of the string, // because it has to decode each UTF-8 rune sequentially. // Some Thai characters are represented by multiple UTF-8 // code points, so the result of this count may be surprising. diff --git a/examples/strings-and-runes/strings-and-runes.hash b/examples/strings-and-runes/strings-and-runes.hash index 299528cdb..99cc716e1 100644 --- a/examples/strings-and-runes/strings-and-runes.hash +++ b/examples/strings-and-runes/strings-and-runes.hash @@ -1,2 +1,2 @@ -766c486b73701deb5af9a3f5249d4febc3beda89 -y9AcFzz3UJn +45a1127788eb4c0acfef48efee9ca386e06d4c58 +39BpTLf6BAz diff --git a/public/strings-and-runes b/public/strings-and-runes index a7fc03e77..9fe20ec53 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -48,7 +48,7 @@ introduction to the topic.

    - +
    package main
     
    @@ -131,7 +131,7 @@ the bytes that constitute the code points in s.

    To count how many runes are in a string, we can use the utf8 package. Note that the run-time of -RuneCountInString dependes on the size of the string, +RuneCountInString depends on the size of the string, because it has to decode each UTF-8 rune sequentially. Some Thai characters are represented by multiple UTF-8 code points, so the result of this count may be surprising.

    From 0812429584978a95f3d4475011695608a2d95d88 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 20 Mar 2023 05:59:53 -0700 Subject: [PATCH 176/283] Clarify zero value for map values when keys don't exist --- examples/maps/maps.go | 8 +++++++- examples/maps/maps.hash | 4 ++-- examples/maps/maps.sh | 3 ++- public/maps | 25 +++++++++++++++++++++---- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/examples/maps/maps.go b/examples/maps/maps.go index 8a40d3578..441e2a356 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -22,7 +22,13 @@ func main() { // Get a value for a key with `name[key]`. v1 := m["k1"] - fmt.Println("v1: ", v1) + fmt.Println("v1:", v1) + + // If the key doesn't exist, the + // [zero value](https://go.dev/ref/spec#The_zero_value) of the + // value type is returned. + v3 := m["k3"] + fmt.Println("v3:", v3) // The builtin `len` returns the number of key/value // pairs when called on a map. diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index 2c0cd818c..9dcd6b8d9 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -22d147fe9402f9ff210f12b9810811c07f4d64ca -ulCzODwCde_0 +0d764945481b4960c573e67f7d303166b750413e +xl_teZEVqbo diff --git a/examples/maps/maps.sh b/examples/maps/maps.sh index da7a841b3..56f3be16d 100644 --- a/examples/maps/maps.sh +++ b/examples/maps/maps.sh @@ -2,7 +2,8 @@ # printed with `fmt.Println`. $ go run maps.go map: map[k1:7 k2:13] -v1: 7 +v1: 7 +v3: 0 len: 2 map: map[k1:7] prs: false diff --git a/public/maps b/public/maps index bf99e933b..8e64a8480 100644 --- a/public/maps +++ b/public/maps @@ -42,7 +42,7 @@ - +
    package main
     
    @@ -122,7 +122,23 @@ its key/value pairs.

         v1 := m["k1"]
    -    fmt.Println("v1: ", v1)
    +    fmt.Println("v1:", v1)
    +
    + + + + + +

    If the key doesn’t exist, the +zero value of the +value type is returned.

    + + + + +
    +    v3 := m["k3"]
    +    fmt.Println("v3:", v3)
     
    @@ -207,7 +223,8 @@ printed with fmt.Println.

     $ go run maps.go 
     map: map[k1:7 k2:13]
    -v1:  7
    +v1: 7
    +v3: 0
     len: 2
     map: map[k1:7]
     prs: false
    @@ -230,7 +247,7 @@ printed with fmt.Println.

    From 4280f948d30b29e11487590feeff16ebfb83464e Mon Sep 17 00:00:00 2001 From: Lucas <58364540+lucassauro@users.noreply.github.com> Date: Mon, 27 Mar 2023 16:51:05 -0300 Subject: [PATCH 177/283] Added Brazilian portuguese (PT-BR) to translations list. (#467) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 6f1e15e65..8edc564d8 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ Contributor translations of the Go by Example site are available in: * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) +* [Brazilian Portuguese](https://lucassauro.github.io/GoEmExemplos/) by [lucassauro](https://github.com/lucassauro) ### Thanks From ea61a8431a65fa45dd7c04714306fddad1eaf009 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 3 Apr 2023 05:41:00 -0700 Subject: [PATCH 178/283] Revert "Added Brazilian portuguese (PT-BR) to translations list. (#467)" The link to the translation is dead This reverts commit 4280f948d30b29e11487590feeff16ebfb83464e. --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 8edc564d8..6f1e15e65 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,6 @@ Contributor translations of the Go by Example site are available in: * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) -* [Brazilian Portuguese](https://lucassauro.github.io/GoEmExemplos/) by [lucassauro](https://github.com/lucassauro) ### Thanks From 4b9ed3f43a2b14b676c67d27fc6670ac23a3a63d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 3 Apr 2023 05:51:01 -0700 Subject: [PATCH 179/283] Remove dead links to translations in README --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 6f1e15e65..0c6960d37 100644 --- a/README.md +++ b/README.md @@ -64,13 +64,11 @@ The Go Gopher is copyright [Renée French](https://reneefrench.blogspot.com/) an Contributor translations of the Go by Example site are available in: * [Chinese](https://gobyexample-cn.github.io/) by [gobyexample-cn](https://github.com/gobyexample-cn) -* [Czech](http://gobyexamples.sweb.cz/) by [martinkunc](https://github.com/martinkunc/gobyexample-cz) * [French](http://le-go-par-l-exemple.keiruaprod.fr) by [keirua](https://github.com/keirua/gobyexample) * [Italian](https://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) -* [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) ### Thanks From 0a1da7e32d9c2e05e7cfa067fb4b21c1f8dca69e Mon Sep 17 00:00:00 2001 From: Lucas <58364540+LCSLITX@users.noreply.github.com> Date: Mon, 3 Apr 2023 09:52:38 -0300 Subject: [PATCH 180/283] Added Brazilian portuguese (PT-BR) to translations list, updated link. (#468) * Added Brazilian portuguese (PT-BR) to translations list. * Updated translation list --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0c6960d37..958652e52 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ Contributor translations of the Go by Example site are available in: * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) +* [Brazilian Portuguese](https://lcslitx.github.io/GoEmExemplos/) by [lcslitx](https://github.com/LCSLITX) ### Thanks From 363849f9e3b859c4448b7c469125e2edb225d422 Mon Sep 17 00:00:00 2001 From: Hossein Naghdbishi <42994241+niyumard@users.noreply.github.com> Date: Wed, 19 Apr 2023 23:25:27 +0000 Subject: [PATCH 181/283] link embed directive (#469) --- examples/struct-embedding/struct-embedding.go | 2 +- examples/struct-embedding/struct-embedding.hash | 4 ++-- public/struct-embedding | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/struct-embedding/struct-embedding.go b/examples/struct-embedding/struct-embedding.go index 856e5deac..d86709e28 100644 --- a/examples/struct-embedding/struct-embedding.go +++ b/examples/struct-embedding/struct-embedding.go @@ -1,6 +1,6 @@ // Go supports _embedding_ of structs and interfaces // to express a more seamless _composition_ of types. -// This is not to be confused with `//go:embed` which is +// This is not to be confused with [`//go:embed`](embed-directive) which is // a go directive introduced in Go version 1.16+ to embed // files and folders into the application binary. diff --git a/examples/struct-embedding/struct-embedding.hash b/examples/struct-embedding/struct-embedding.hash index 388294848..3450e9642 100644 --- a/examples/struct-embedding/struct-embedding.hash +++ b/examples/struct-embedding/struct-embedding.hash @@ -1,2 +1,2 @@ -a246237126303fb110186ac2598bca15d36e8366 -TqMui3hJuX7 +7ac6d1889bfc68e8f3f931014c87e05db2ecda95 +-LOu1L0i2tR diff --git a/public/struct-embedding b/public/struct-embedding index c70b5b98c..e10cd67a8 100644 --- a/public/struct-embedding +++ b/public/struct-embedding @@ -29,7 +29,7 @@

    Go supports embedding of structs and interfaces to express a more seamless composition of types. -This is not to be confused with //go:embed which is +This is not to be confused with //go:embed which is a go directive introduced in Go version 1.16+ to embed files and folders into the application binary.

    @@ -45,7 +45,7 @@ files and folders into the application binary.

    - +
    package main
     
    From cb2d0d95558f40a8c140c7c09df5bf98384c757b Mon Sep 17 00:00:00 2001 From: Hossein Naghdbishi <42994241+niyumard@users.noreply.github.com> Date: Wed, 19 Apr 2023 23:25:41 +0000 Subject: [PATCH 182/283] /bin/bash -> /usr/bin/env bash (#471) Using env offers better portability --- tools/build | 2 +- tools/build-loop | 2 +- tools/format | 2 +- tools/generate | 2 +- tools/measure | 2 +- tools/serve | 2 +- tools/test | 2 +- tools/upload | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tools/build b/tools/build index 4f669021c..1aca25b14 100755 --- a/tools/build +++ b/tools/build @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash set -e diff --git a/tools/build-loop b/tools/build-loop index 53847018c..02d70d577 100755 --- a/tools/build-loop +++ b/tools/build-loop @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash TRAPPING=0 trap "{ echo finishing; TRAPPING=1; }" SIGINT diff --git a/tools/format b/tools/format index 457b13fe3..c10452579 100755 --- a/tools/format +++ b/tools/format @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash set -eo pipefail diff --git a/tools/generate b/tools/generate index af897e5b7..be41375a6 100755 --- a/tools/generate +++ b/tools/generate @@ -1,3 +1,3 @@ -#!/bin/bash +#!/usr/bin/env bash exec go run tools/generate.go $@ diff --git a/tools/measure b/tools/measure index f62c57834..39d583b5d 100755 --- a/tools/measure +++ b/tools/measure @@ -1,3 +1,3 @@ -#!/bin/bash +#!/usr/bin/env bash exec go run tools/measure.go diff --git a/tools/serve b/tools/serve index baf68d12f..1d4b594b0 100755 --- a/tools/serve +++ b/tools/serve @@ -1,3 +1,3 @@ -#!/bin/bash +#!/usr/bin/env bash exec go run tools/serve.go diff --git a/tools/test b/tools/test index c0c9c5518..c3805156d 100755 --- a/tools/test +++ b/tools/test @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # Sanity testing of the examples. diff --git a/tools/upload b/tools/upload index 5ca34efbe..c00a2ab42 100755 --- a/tools/upload +++ b/tools/upload @@ -1,3 +1,3 @@ -#!/bin/bash +#!/usr/bin/env bash exec go run tools/upload.go -region us-east-1 -bucket gobyexample.com From fcc06e2fe19d7367622ed8ecd8d9e0d76ddcd646 Mon Sep 17 00:00:00 2001 From: Ha Quang Phuoc <107381046+hqphuoc@users.noreply.github.com> Date: Wed, 26 Apr 2023 19:27:18 +0700 Subject: [PATCH 183/283] Add Vietnamese version translation (#472) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 958652e52..9b433df35 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ Contributor translations of the Go by Example site are available in: * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) * [Brazilian Portuguese](https://lcslitx.github.io/GoEmExemplos/) by [lcslitx](https://github.com/LCSLITX) +* [Vietnamese](https://gobyexample.vn/) by [s6k Gopher](https://github.com/s6k-gopher/gobyexample-vn) ### Thanks From fd4d72bccfff63e1f10ce8c36de80ec09e718e44 Mon Sep 17 00:00:00 2001 From: jiangbo Date: Wed, 17 May 2023 02:04:20 +0800 Subject: [PATCH 184/283] add unassigned slice example (#475) --- examples/slices/slices.go | 9 +++++++-- examples/slices/slices.hash | 4 ++-- examples/slices/slices.sh | 3 ++- public/slices | 30 +++++++++++++++++++++++------- 4 files changed, 34 insertions(+), 12 deletions(-) diff --git a/examples/slices/slices.go b/examples/slices/slices.go index c9335e1e1..08916ef7a 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -9,11 +9,16 @@ func main() { // Unlike arrays, slices are typed only by the // elements they contain (not the number of elements). + // unassigned slice equal to nil and has a length of `0` + var s []string + fmt.Println("unassigned:", s, s == nil, len(s) == 0) + // To create an empty slice with non-zero length, use // the builtin `make`. Here we make a slice of // `string`s of length `3` (initially zero-valued). - s := make([]string, 3) - fmt.Println("emp:", s) + // `string`s of capacity `5`. + s = make([]string, 3, 5) + fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s)) // We can set and get just like with arrays. s[0] = "a" diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index e23e052df..5844a3d38 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -13835b88336e031808f2f3887cd43d0b9d85cad0 -76f4Jif5Z8o +d255a550fe04d6a6d31c7256a1d980e675db0619 +ryiklDqjbId diff --git a/examples/slices/slices.sh b/examples/slices/slices.sh index f29dd36a5..925ed8252 100644 --- a/examples/slices/slices.sh +++ b/examples/slices/slices.sh @@ -1,7 +1,8 @@ # Note that while slices are different types than arrays, # they are rendered similarly by `fmt.Println`. $ go run slices.go -emp: [ ] +unassigned: [] true true +emp: [ ] len: 3 cap: 5 set: [a b c] get: c len: 3 diff --git a/public/slices b/public/slices index 78c327a9d..a6efec528 100644 --- a/public/slices +++ b/public/slices @@ -42,7 +42,7 @@ a more powerful interface to sequences than arrays.

    - +
    package main
     
    @@ -74,16 +74,31 @@ a more powerful interface to sequences than arrays.

    Unlike arrays, slices are typed only by the elements they contain (not the number of elements). -To create an empty slice with non-zero length, use +unassigned slice equal to nil and has a length of 0

    + + + + +
    +    var s []string
    +    fmt.Println("unassigned:", s, s == nil, len(s) == 0)
    +
    + + + + + +

    To create an empty slice with non-zero length, use the builtin make. Here we make a slice of -strings of length 3 (initially zero-valued).

    +strings of length 3 (initially zero-valued). +strings of capacity 5.

    -    s := make([]string, 3)
    -    fmt.Println("emp:", s)
    +    s = make([]string, 3, 5)
    +    fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
     
    @@ -252,7 +267,8 @@ they are rendered similarly by fmt.Println.

     $ go run slices.go
    -emp: [  ]
    +unassigned: [] true true
    +emp: [  ] len: 3 cap: 5
     set: [a b c]
     get: c
     len: 3
    @@ -306,7 +322,7 @@ Go’s other key builtin data structure: maps.

    From 1512fb00944288898e6dbf62e2b383a8cad010c8 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 16 May 2023 11:10:16 -0700 Subject: [PATCH 185/283] slices: tweak the recent changes for clarity and grammar --- examples/slices/slices.go | 12 ++++++++---- examples/slices/slices.hash | 4 ++-- examples/slices/slices.sh | 4 ++-- public/slices | 20 ++++++++++++-------- 4 files changed, 24 insertions(+), 16 deletions(-) diff --git a/examples/slices/slices.go b/examples/slices/slices.go index 08916ef7a..07343d6f1 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -9,15 +9,19 @@ func main() { // Unlike arrays, slices are typed only by the // elements they contain (not the number of elements). - // unassigned slice equal to nil and has a length of `0` + // An uninitialized slice equals to nil and has + // length 0. var s []string - fmt.Println("unassigned:", s, s == nil, len(s) == 0) + fmt.Println("uninit:", s, s == nil, len(s) == 0) // To create an empty slice with non-zero length, use // the builtin `make`. Here we make a slice of // `string`s of length `3` (initially zero-valued). - // `string`s of capacity `5`. - s = make([]string, 3, 5) + // By default a new slice's capacity is equal to its + // length; if we know the slice is going to grow ahead + // of time, it's possible to pass a capacity explicitly + // as an additional parameter ot `make`. + s = make([]string, 3) fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s)) // We can set and get just like with arrays. diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index 5844a3d38..163b77f62 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -d255a550fe04d6a6d31c7256a1d980e675db0619 -ryiklDqjbId +cbb10033e4e5d2f26e4b57895313a907072a75d9 +bqMChdRGpcl diff --git a/examples/slices/slices.sh b/examples/slices/slices.sh index 925ed8252..8f5d1d4aa 100644 --- a/examples/slices/slices.sh +++ b/examples/slices/slices.sh @@ -1,8 +1,8 @@ # Note that while slices are different types than arrays, # they are rendered similarly by `fmt.Println`. $ go run slices.go -unassigned: [] true true -emp: [ ] len: 3 cap: 5 +uninit: [] true true +emp: [ ] len: 3 cap: 3 set: [a b c] get: c len: 3 diff --git a/public/slices b/public/slices index a6efec528..26a256ddc 100644 --- a/public/slices +++ b/public/slices @@ -42,7 +42,7 @@ a more powerful interface to sequences than arrays.

    - +
    package main
     
    @@ -74,14 +74,15 @@ a more powerful interface to sequences than arrays.

    Unlike arrays, slices are typed only by the elements they contain (not the number of elements). -unassigned slice equal to nil and has a length of 0

    +An uninitialized slice equals to nil and has +length 0.

         var s []string
    -    fmt.Println("unassigned:", s, s == nil, len(s) == 0)
    +    fmt.Println("uninit:", s, s == nil, len(s) == 0)
     
    @@ -91,13 +92,16 @@ unassigned slice equal to nil and has a length of 0

    To create an empty slice with non-zero length, use the builtin make. Here we make a slice of strings of length 3 (initially zero-valued). -strings of capacity 5.

    +By default a new slice’s capacity is equal to its +length; if we know the slice is going to grow ahead +of time, it’s possible to pass a capacity explicitly +as an additional parameter ot make.

    -    s = make([]string, 3, 5)
    +    s = make([]string, 3)
         fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
     
    @@ -267,8 +271,8 @@ they are rendered similarly by fmt.Println.

     $ go run slices.go
    -unassigned: [] true true
    -emp: [  ] len: 3 cap: 5
    +uninit: [] true true
    +emp: [  ] len: 3 cap: 3
     set: [a b c]
     get: c
     len: 3
    @@ -322,7 +326,7 @@ Go’s other key builtin data structure: maps.

    From 4b9411514fb34ab00fa9c8b7c914f3f2ad947ad5 Mon Sep 17 00:00:00 2001 From: Hossein Naghdbishi <42994241+niyumard@users.noreply.github.com> Date: Mon, 5 Jun 2023 12:40:49 +0000 Subject: [PATCH 186/283] Introduce anonymous structs (#474) --- examples/structs/structs.go | 11 +++++++++++ examples/structs/structs.hash | 4 ++-- examples/structs/structs.sh | 3 ++- public/structs | 30 ++++++++++++++++++++++++++---- 4 files changed, 41 insertions(+), 7 deletions(-) diff --git a/examples/structs/structs.go b/examples/structs/structs.go index 268f65f1e..62d7cac0e 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -50,4 +50,15 @@ func main() { // Structs are mutable. sp.age = 51 fmt.Println(sp.age) + + // Structs don't always have to be defined as instances of types, + // you can define a struct anonymously. + dog := struct { + name string + isGood bool + }{ + "Rex", + true, + } + fmt.Println(dog) } diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index fe4d3671d..493e5b301 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -f1dcc357b5e20c3aa3a97df8245efe4aea7940d6 -n7jt1x3iw4Z +5a15014159c5c98fe5f829c483ded3914db77053 +D9lW-Dd6XQP diff --git a/examples/structs/structs.sh b/examples/structs/structs.sh index 039fd000b..350433006 100644 --- a/examples/structs/structs.sh +++ b/examples/structs/structs.sh @@ -6,4 +6,5 @@ $ go run structs.go &{Jon 42} Sean 50 -51 \ No newline at end of file +51 +{Rex true} diff --git a/public/structs b/public/structs index 84de85f88..f57905fb7 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.

    - +
    package main
     
    @@ -216,11 +216,32 @@ pointers are automatically dereferenced.

    Structs are mutable.

    - +
         sp.age = 51
         fmt.Println(sp.age)
    +
    + + + + + +

    Structs don’t always have to be defined as instances of types, +you can define a struct anonymously.

    + + + + +
    +    dog := struct {
    +        name   string
    +        isGood bool
    +    }{
    +        "Rex",
    +        true,
    +    }
    +    fmt.Println(dog)
     }
     
    @@ -244,7 +265,8 @@ pointers are automatically dereferenced.

    &{Jon 42} Sean 50 -51
    +
    51 +{Rex true}
    @@ -263,7 +285,7 @@ pointers are automatically dereferenced.

    From 6bd761536630d243bfe66369136b14b88006fad6 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 5 Jun 2023 05:47:05 -0700 Subject: [PATCH 187/283] Reword comment in new anon struct sample --- examples/structs/structs.go | 5 +++-- examples/structs/structs.hash | 4 ++-- public/structs | 7 ++++--- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/examples/structs/structs.go b/examples/structs/structs.go index 62d7cac0e..9f387008f 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -51,8 +51,9 @@ func main() { sp.age = 51 fmt.Println(sp.age) - // Structs don't always have to be defined as instances of types, - // you can define a struct anonymously. + // If a struct type is only used for a single value, we don't + // have to give it a name. The value can have an anonymous + // struct type. dog := struct { name string isGood bool diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index 493e5b301..9da9321b3 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -5a15014159c5c98fe5f829c483ded3914db77053 -D9lW-Dd6XQP +2676ffa99a3a14bc99332fc498e5d658c7988612 +EzGgwrfM-yD diff --git a/public/structs b/public/structs index f57905fb7..9c340774c 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.

    - +
    package main
     
    @@ -227,8 +227,9 @@ pointers are automatically dereferenced.

    -

    Structs don’t always have to be defined as instances of types, -you can define a struct anonymously.

    +

    If a struct type is only used for a single value, we don’t +have to give it a name. The value can have an anonymous +struct type.

    From ef81b2a729cfcfc152b765c0be4115ae799ec1f5 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 5 Jun 2023 05:48:59 -0700 Subject: [PATCH 188/283] Fix typo in a comment This was suggeste in #477 by @mnm364 Fixes #477 --- examples/slices/slices.go | 2 +- examples/slices/slices.hash | 4 ++-- public/slices | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/slices/slices.go b/examples/slices/slices.go index 07343d6f1..ac97a6b0f 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -20,7 +20,7 @@ func main() { // By default a new slice's capacity is equal to its // length; if we know the slice is going to grow ahead // of time, it's possible to pass a capacity explicitly - // as an additional parameter ot `make`. + // as an additional parameter to `make`. s = make([]string, 3) fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s)) diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index 163b77f62..eb3c4ced7 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -cbb10033e4e5d2f26e4b57895313a907072a75d9 -bqMChdRGpcl +9f1302a9c3cf79e5144c4818ea09465ff8d6da57 +553_cYPVlPH diff --git a/public/slices b/public/slices index 26a256ddc..cee1ef50d 100644 --- a/public/slices +++ b/public/slices @@ -42,7 +42,7 @@ a more powerful interface to sequences than arrays.

    - +
    package main
     
    @@ -95,7 +95,7 @@ the builtin make. Here we make a slice of By default a new slice’s capacity is equal to its length; if we know the slice is going to grow ahead of time, it’s possible to pass a capacity explicitly -as an additional parameter ot make.

    +as an additional parameter to make.

    From 1ee3369f02ae0ff8c4b1cc91a1fdb2b6128580e7 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 5 Jun 2023 13:42:02 -0700 Subject: [PATCH 189/283] Add link from structs-->testing-and-benchmarking --- examples/structs/structs.go | 3 ++- examples/structs/structs.hash | 4 ++-- public/structs | 5 +++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/examples/structs/structs.go b/examples/structs/structs.go index 9f387008f..d56c0aa60 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -53,7 +53,8 @@ func main() { // If a struct type is only used for a single value, we don't // have to give it a name. The value can have an anonymous - // struct type. + // struct type. This technique is commonly used for + // [table-driven tests](testing-and-benchmarking). dog := struct { name string isGood bool diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index 9da9321b3..372123828 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -2676ffa99a3a14bc99332fc498e5d658c7988612 -EzGgwrfM-yD +80344041b9268370bb6c73190afb1269e26f52fe +ex1J3oieEeo diff --git a/public/structs b/public/structs index 9c340774c..40e92dfaf 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.

    - +
    package main
     
    @@ -229,7 +229,8 @@ pointers are automatically dereferenced.

    If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous -struct type.

    +struct type. This technique is commonly used for +table-driven tests.

    From d51586e6bf10785d300f847aa63c52913fea6924 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 21 Aug 2023 06:15:47 -0700 Subject: [PATCH 190/283] Add example of the new clear() builtin for maps in 1.21 updates #481 Also bump go.mod to 1.21 --- examples/maps/maps.go | 5 +++++ examples/maps/maps.hash | 4 ++-- examples/maps/maps.sh | 1 + go.mod | 2 +- public/maps | 20 ++++++++++++++++++-- 5 files changed, 27 insertions(+), 5 deletions(-) diff --git a/examples/maps/maps.go b/examples/maps/maps.go index 441e2a356..79db9013c 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -39,6 +39,11 @@ func main() { delete(m, "k2") fmt.Println("map:", m) + // To remove *all* key/value pairs from a map, use + // the `clear` builtin. + clear(m) + fmt.Println("map:", m) + // The optional second return value when getting a // value from a map indicates if the key was present // in the map. This can be used to disambiguate diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index 9dcd6b8d9..d6abb5d57 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -0d764945481b4960c573e67f7d303166b750413e -xl_teZEVqbo +b976324013ef31370d1605d1834c5dd6f0db0ea1 +6gcPOX9Mm1R diff --git a/examples/maps/maps.sh b/examples/maps/maps.sh index 56f3be16d..2b24dbb89 100644 --- a/examples/maps/maps.sh +++ b/examples/maps/maps.sh @@ -6,5 +6,6 @@ v1: 7 v3: 0 len: 2 map: map[k1:7] +map: map[] prs: false map: map[bar:2 foo:1] diff --git a/go.mod b/go.mod index 7efb899a8..08c82c07c 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mmcgrana/gobyexample -go 1.19 +go 1.21 require ( github.com/alecthomas/chroma v0.8.2 diff --git a/public/maps b/public/maps index 8e64a8480..b3e0fe8ea 100644 --- a/public/maps +++ b/public/maps @@ -42,7 +42,7 @@ - +
    package main
     
    @@ -172,6 +172,21 @@ a map.

    + + +

    To remove all key/value pairs from a map, use +the clear builtin.

    + + + + +
    +    clear(m)
    +    fmt.Println("map:", m)
    +
    + + +

    The optional second return value when getting a @@ -227,6 +242,7 @@ printed with fmt.Println.

    v3: 0 len: 2 map: map[k1:7] +map: map[] prs: false map: map[bar:2 foo:1]
    @@ -247,7 +263,7 @@ printed with fmt.Println.

    From 4dc83f3ccc22e7bdf7b4ba2842ad63d7f8ae0e97 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 21 Aug 2023 07:05:01 -0700 Subject: [PATCH 191/283] Update chroma from v0.8 to v2 (v2.8.0) and fix up formatting --- go.mod | 5 +- go.sum | 37 ++--- public/arrays | 66 ++++----- public/atomic-counters | 62 ++++----- public/base64-encoding | 57 +++----- public/channel-buffering | 33 ++--- public/channel-directions | 43 +++--- public/channel-synchronization | 47 +++---- public/channels | 30 ++-- public/closing-channels | 78 +++++------ public/closures | 55 +++----- public/command-line-arguments | 45 +++--- public/command-line-flags | 123 +++++++---------- public/command-line-subcommands | 112 +++++++-------- public/constants | 51 +++---- public/context | 75 ++++------ public/defer | 80 +++++------ public/directories | 160 +++++++++------------- public/embed-directive | 73 ++++------ public/environment-variables | 66 ++++----- public/epoch | 50 +++---- public/errors | 124 +++++++---------- public/execing-processes | 58 ++++---- public/exit | 39 ++---- public/file-paths | 104 ++++++-------- public/for | 77 +++++------ public/functions | 46 +++---- public/generics | 106 ++++++--------- public/goroutines | 69 ++++------ public/hello-world | 31 ++--- public/http-client | 67 ++++----- public/http-server | 63 ++++----- public/if-else | 55 ++++---- public/interfaces | 105 ++++++-------- public/json | 181 ++++++++++--------------- public/line-filters | 60 ++++---- public/maps | 84 ++++-------- public/methods | 60 ++++---- public/multiple-return-values | 41 +++--- public/mutexes | 84 +++++------- public/non-blocking-channel-operations | 71 +++++----- public/number-parsing | 68 ++++------ public/panic | 40 +++--- public/pointers | 57 +++----- public/random-numbers | 88 +++++------- public/range | 81 +++++------ public/range-over-channels | 35 ++--- public/rate-limiting | 111 +++++++-------- public/reading-files | 125 +++++++---------- public/recover | 44 +++--- public/recursion | 55 +++----- public/regular-expressions | 113 ++++++--------- public/select | 69 ++++------ public/sha256-hashes | 44 +++--- public/signals | 66 ++++----- public/slices | 126 +++++++---------- public/sorting | 48 +++---- public/sorting-by-functions | 53 +++----- public/spawning-processes | 125 ++++++++--------- public/stateful-goroutines | 158 ++++++++++----------- public/string-formatting | 166 ++++++++--------------- public/string-functions | 73 +++++----- public/strings-and-runes | 120 +++++++--------- public/struct-embedding | 84 +++++------- public/structs | 111 ++++++--------- public/switch | 111 +++++++-------- public/temporary-files-and-directories | 75 ++++------ public/testing-and-benchmarking | 153 +++++++++------------ public/text-templates | 126 ++++++++--------- public/tickers | 65 ++++----- public/time | 129 ++++++++---------- public/time-formatting-parsing | 83 +++++------- public/timeouts | 74 +++++----- public/timers | 58 ++++---- public/url-parsing | 100 ++++++-------- public/values | 43 +++--- public/variables | 53 +++----- public/variadic-functions | 51 +++---- public/waitgroups | 87 +++++------- public/worker-pools | 94 ++++++------- public/writing-files | 109 ++++++--------- public/xml | 149 +++++++++----------- tools/generate.go | 66 +++++---- 83 files changed, 2675 insertions(+), 3884 deletions(-) diff --git a/go.mod b/go.mod index 08c82c07c..1f29711f4 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/mmcgrana/gobyexample go 1.21 require ( - github.com/alecthomas/chroma v0.8.2 + github.com/alecthomas/chroma/v2 v2.8.0 github.com/aws/aws-sdk-go-v2 v1.9.0 github.com/aws/aws-sdk-go-v2/config v1.7.0 github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 @@ -20,6 +20,5 @@ require ( github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 // indirect github.com/aws/smithy-go v1.8.0 // indirect - github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect - github.com/dlclark/regexp2 v1.2.0 // indirect + github.com/dlclark/regexp2 v1.10.0 // indirect ) diff --git a/go.sum b/go.sum index a395d871a..4917b6426 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,9 @@ -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U= -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= -github.com/alecthomas/chroma v0.8.2 h1:x3zkuE2lUk/RIekyAJ3XRqSCP4zwWDfcw/YJCuCAACg= -github.com/alecthomas/chroma v0.8.2/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721 h1:JHZL0hZKJ1VENNfmXvHbgYlbUOvpzYzvy2aZU5gXVeo= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= -github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= +github.com/alecthomas/assert/v2 v2.2.1 h1:XivOgYcduV98QCahG8T5XTezV5bylXe+lBxLG2K2ink= +github.com/alecthomas/assert/v2 v2.2.1/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= +github.com/alecthomas/chroma/v2 v2.8.0 h1:w9WJUjFFmHHB2e8mRpL9jjy3alYDlU0QLDezj1xE264= +github.com/alecthomas/chroma/v2 v2.8.0/go.mod h1:yrkMI9807G1ROx13fhe1v6PN2DDeaR73L3d+1nmYQtw= +github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= +github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/aws/aws-sdk-go-v2 v1.9.0 h1:+S+dSqQCN3MSU5vJRu1HqHrq00cJn6heIMU7X9hcsoo= github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= github.com/aws/aws-sdk-go-v2/config v1.7.0 h1:J2cZ7qe+3IpqBEXnHUrFrOjoB9BlsXg7j53vxcl5IVg= @@ -31,34 +28,20 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 h1:1at4e5P+lvHNl2nUktdM2/v+rpICg github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= github.com/aws/smithy-go v1.8.0 h1:AEwwwXQZtUwP5Mz506FeXXrKBe0jA8gVM+1gEcSRooc= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= -github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= -github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= -github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0= +github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200413165638-669c56c373c4 h1:opSr2sbRXk5X5/givKrrKj9HXxFpW2sdCiP8MJSKLQY= -golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/public/arrays b/public/arrays index b333813d4..675a3f3b9 100644 --- a/public/arrays +++ b/public/arrays @@ -45,8 +45,7 @@ scenarios.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ scenarios.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -67,8 +65,7 @@ scenarios.

    -
    func main() {
    -
    +
    func main() {
    @@ -82,10 +79,8 @@ zero-valued, which for ints means 0s.

    -
    -    var a [5]int
    -    fmt.Println("emp:", a)
    -
    +
        var a [5]int
    +    fmt.Println("emp:", a)
    @@ -98,11 +93,9 @@ zero-valued, which for ints means 0s.

    -
    -    a[4] = 100
    -    fmt.Println("set:", a)
    -    fmt.Println("get:", a[4])
    -
    +
        a[4] = 100
    +    fmt.Println("set:", a)
    +    fmt.Println("get:", a[4])
    @@ -113,9 +106,7 @@ zero-valued, which for ints means 0s.

    -
    -    fmt.Println("len:", len(a))
    -
    +
        fmt.Println("len:", len(a))
    @@ -127,10 +118,8 @@ in one line.

    -
    -    b := [5]int{1, 2, 3, 4, 5}
    -    fmt.Println("dcl:", b)
    -
    +
        b := [5]int{1, 2, 3, 4, 5}
    +    fmt.Println("dcl:", b)
    @@ -143,16 +132,14 @@ structures.

    -
    -    var twoD [2][3]int
    -    for i := 0; i < 2; i++ {
    -        for j := 0; j < 3; j++ {
    -            twoD[i][j] = i + j
    -        }
    -    }
    -    fmt.Println("2d: ", twoD)
    -}
    -
    +
        var twoD [2][3]int
    +    for i := 0; i < 2; i++ {
    +        for j := 0; j < 3; j++ {
    +            twoD[i][j] = i + j
    +        }
    +    }
    +    fmt.Println("2d: ", twoD)
    +}
    @@ -168,14 +155,13 @@ when printed with fmt.Println.

    -
    -$ go run arrays.go
    -emp: [0 0 0 0 0]
    -set: [0 0 0 0 100]
    -get: 100
    -len: 5
    -dcl: [1 2 3 4 5]
    -2d:  [[0 1 2] [1 2 3]]
    +
    $ go run arrays.go
    +emp: [0 0 0 0 0]
    +set: [0 0 0 0 100]
    +get: 100
    +len: 5
    +dcl: [1 2 3 4 5]
    +2d:  [[0 1 2] [1 2 3]]
    diff --git a/public/atomic-counters b/public/atomic-counters index 6548101eb..fccef500f 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -47,8 +47,7 @@ counters accessed by multiple goroutines.

    -
    package main
    -
    +
    package main
    @@ -58,12 +57,11 @@ counters accessed by multiple goroutines.

    -
    import (
    -    "fmt"
    -    "sync"
    -    "sync/atomic"
    -)
    -
    +
    import (
    +    "fmt"
    +    "sync"
    +    "sync/atomic"
    +)
    @@ -73,8 +71,7 @@ counters accessed by multiple goroutines.

    -
    func main() {
    -
    +
    func main() {
    @@ -86,9 +83,7 @@ counters accessed by multiple goroutines.

    -
    -    var ops uint64
    -
    +
        var ops uint64
    @@ -100,9 +95,7 @@ to finish their work.

    -
    -    var wg sync.WaitGroup
    -
    +
        var wg sync.WaitGroup
    @@ -114,10 +107,8 @@ counter exactly 1000 times.

    -
    -    for i := 0; i < 50; i++ {
    -        wg.Add(1)
    -
    +
        for i := 0; i < 50; i++ {
    +        wg.Add(1)
    @@ -131,9 +122,8 @@ address of our ops counter with the -
            go func() {
    -            for c := 0; c < 1000; c++ {
    -
    +
            go func() {
    +            for c := 0; c < 1000; c++ {
    @@ -143,12 +133,11 @@ address of our ops counter with the -
                    atomic.AddUint64(&ops, 1)
    -            }
    -            wg.Done()
    -        }()
    -    }
    -
    +
                    atomic.AddUint64(&ops, 1)
    +            }
    +            wg.Done()
    +        }()
    +    }
    @@ -159,9 +148,7 @@ address of our ops counter with the -
    -    wg.Wait()
    -
    +
        wg.Wait()
    @@ -176,10 +163,8 @@ also possible, using functions like -
    -    fmt.Println("ops:", ops)
    -}
    -
    +
        fmt.Println("ops:", ops)
    +}
    @@ -199,9 +184,8 @@ when running with the -race flag.

    -
    -$ go run atomic-counters.go
    -ops: 50000
    +
    $ go run atomic-counters.go
    +ops: 50000
    diff --git a/public/base64-encoding b/public/base64-encoding index c2db003ad..94812e28b 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -43,8 +43,7 @@ encoding/decoding.

    -
    package main
    -
    +
    package main
    @@ -57,12 +56,10 @@ save us some space below.

    -
    -import (
    -    b64 "encoding/base64"
    -    "fmt"
    -)
    -
    +
    import (
    +    b64 "encoding/base64"
    +    "fmt"
    +)
    @@ -72,8 +69,7 @@ save us some space below.

    -
    func main() {
    -
    +
    func main() {
    @@ -84,9 +80,7 @@ save us some space below.

    -
    -    data := "abc123!?$*&()'-=@~"
    -
    +
        data := "abc123!?$*&()'-=@~"
    @@ -100,10 +94,8 @@ convert our string to that type.

    -
    -    sEnc := b64.StdEncoding.EncodeToString([]byte(data))
    -    fmt.Println(sEnc)
    -
    +
        sEnc := b64.StdEncoding.EncodeToString([]byte(data))
    +    fmt.Println(sEnc)
    @@ -116,11 +108,9 @@ well-formed.

    -
    -    sDec, _ := b64.StdEncoding.DecodeString(sEnc)
    -    fmt.Println(string(sDec))
    -    fmt.Println()
    -
    +
        sDec, _ := b64.StdEncoding.DecodeString(sEnc)
    +    fmt.Println(string(sDec))
    +    fmt.Println()
    @@ -132,13 +122,11 @@ format.

    -
    -    uEnc := b64.URLEncoding.EncodeToString([]byte(data))
    -    fmt.Println(uEnc)
    -    uDec, _ := b64.URLEncoding.DecodeString(uEnc)
    -    fmt.Println(string(uDec))
    -}
    -
    +
        uEnc := b64.URLEncoding.EncodeToString([]byte(data))
    +    fmt.Println(uEnc)
    +    uDec, _ := b64.URLEncoding.DecodeString(uEnc)
    +    fmt.Println(string(uDec))
    +}
    @@ -155,10 +143,9 @@ but they both decode to the original string as desired.

    -
    -$ go run base64-encoding.go
    -YWJjMTIzIT8kKiYoKSctPUB+
    -abc123!?$*&()'-=@~
    +
    $ go run base64-encoding.go
    +YWJjMTIzIT8kKiYoKSctPUB+
    +abc123!?$*&()'-=@~
    @@ -168,8 +155,8 @@ but they both decode to the original string as desired.

    -
    YWJjMTIzIT8kKiYoKSctPUB-
    -abc123!?$*&()'-=@~
    +
    YWJjMTIzIT8kKiYoKSctPUB-
    +abc123!?$*&()'-=@~
    diff --git a/public/channel-buffering b/public/channel-buffering index 3975022dd..bbac79dd3 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -47,8 +47,7 @@ those values.

    -
    package main
    -
    +
    package main
    @@ -58,8 +57,7 @@ those values.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -69,8 +67,7 @@ those values.

    -
    func main() {
    -
    +
    func main() {
    @@ -82,9 +79,7 @@ those values.

    -
    -    messages := make(chan string, 2)
    -
    +
        messages := make(chan string, 2)
    @@ -97,10 +92,8 @@ concurrent receive.

    -
    -    messages <- "buffered"
    -    messages <- "channel"
    -
    +
        messages <- "buffered"
    +    messages <- "channel"
    @@ -111,11 +104,9 @@ concurrent receive.

    -
    -    fmt.Println(<-messages)
    -    fmt.Println(<-messages)
    -}
    -
    +
        fmt.Println(<-messages)
    +    fmt.Println(<-messages)
    +}
    @@ -129,9 +120,9 @@ concurrent receive.

    -
    $ go run channel-buffering.go 
    -buffered
    -channel
    +
    $ go run channel-buffering.go 
    +buffered
    +channel
    diff --git a/public/channel-directions b/public/channel-directions index 5695a28f6..2f554f99c 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -45,8 +45,7 @@ the program.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ the program.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -70,11 +68,9 @@ receive on this channel.

    -
    -func ping(pings chan<- string, msg string) {
    -    pings <- msg
    -}
    -
    +
    func ping(pings chan<- string, msg string) {
    +    pings <- msg
    +}
    @@ -86,12 +82,10 @@ receive on this channel.

    -
    -func pong(pings <-chan string, pongs chan<- string) {
    -    msg := <-pings
    -    pongs <- msg
    -}
    -
    +
    func pong(pings <-chan string, pongs chan<- string) {
    +    msg := <-pings
    +    pongs <- msg
    +}
    @@ -101,14 +95,13 @@ receive on this channel.

    -
    func main() {
    -    pings := make(chan string, 1)
    -    pongs := make(chan string, 1)
    -    ping(pings, "passed message")
    -    pong(pings, pongs)
    -    fmt.Println(<-pongs)
    -}
    -
    +
    func main() {
    +    pings := make(chan string, 1)
    +    pongs := make(chan string, 1)
    +    ping(pings, "passed message")
    +    pong(pings, pongs)
    +    fmt.Println(<-pongs)
    +}
    @@ -122,8 +115,8 @@ receive on this channel.

    -
    $ go run channel-directions.go
    -passed message
    +
    $ go run channel-directions.go
    +passed message
    diff --git a/public/channel-synchronization b/public/channel-synchronization index 9061590f4..f9ce9501c 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -46,8 +46,7 @@ you may prefer to use a WaitGroup.

    -
    package main
    -
    +
    package main
    @@ -57,11 +56,10 @@ you may prefer to use a WaitGroup.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -74,12 +72,10 @@ goroutine that this function’s work is done.

    -
    -func worker(done chan bool) {
    -    fmt.Print("working...")
    -    time.Sleep(time.Second)
    -    fmt.Println("done")
    -
    +
    func worker(done chan bool) {
    +    fmt.Print("working...")
    +    time.Sleep(time.Second)
    +    fmt.Println("done")
    @@ -90,10 +86,8 @@ goroutine that this function’s work is done.

    -
    -    done <- true
    -}
    -
    +
        done <- true
    +}
    @@ -103,8 +97,7 @@ goroutine that this function’s work is done.

    -
    func main() {
    -
    +
    func main() {
    @@ -116,10 +109,8 @@ notify on.

    -
    -    done := make(chan bool, 1)
    -    go worker(done)
    -
    +
        done := make(chan bool, 1)
    +    go worker(done)
    @@ -131,10 +122,8 @@ worker on the channel.

    -
    -    <-done
    -}
    -
    +
        <-done
    +}
    @@ -148,8 +137,8 @@ worker on the channel.

    -
    $ go run channel-synchronization.go      
    -working...done                  
    +
    $ go run channel-synchronization.go      
    +working...done                  
    diff --git a/public/channels b/public/channels index 3b161a72e..2ad6de039 100644 --- a/public/channels +++ b/public/channels @@ -45,8 +45,7 @@ goroutine.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ goroutine.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -67,8 +65,7 @@ goroutine.

    -
    func main() {
    -
    +
    func main() {
    @@ -80,9 +77,7 @@ Channels are typed by the values they convey.

    -
    -    messages := make(chan string)
    -
    +
        messages := make(chan string)
    @@ -95,9 +90,7 @@ channel we made above, from a new goroutine.

    -
    -    go func() { messages <- "ping" }()
    -
    +
        go func() { messages <- "ping" }()
    @@ -110,11 +103,9 @@ we sent above and print it out.

    -
    -    msg := <-messages
    -    fmt.Println(msg)
    -}
    -
    +
        msg := <-messages
    +    fmt.Println(msg)
    +}
    @@ -131,9 +122,8 @@ our channel.

    -
    -$ go run channels.go 
    -ping
    +
    $ go run channels.go 
    +ping
    diff --git a/public/closing-channels b/public/closing-channels index d1fad4f3a..a6310979d 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -44,8 +44,7 @@ completion to the channel’s receivers.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ completion to the channel’s receivers.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -70,11 +68,9 @@ the worker we’ll close the jobs channel.

    -
    -func main() {
    -    jobs := make(chan int, 5)
    -    done := make(chan bool)
    -
    +
    func main() {
    +    jobs := make(chan int, 5)
    +    done := make(chan bool)
    @@ -91,20 +87,18 @@ all our jobs.

    -
    -    go func() {
    -        for {
    -            j, more := <-jobs
    -            if more {
    -                fmt.Println("received job", j)
    -            } else {
    -                fmt.Println("received all jobs")
    -                done <- true
    -                return
    -            }
    -        }
    -    }()
    -
    +
        go func() {
    +        for {
    +            j, more := <-jobs
    +            if more {
    +                fmt.Println("received job", j)
    +            } else {
    +                fmt.Println("received all jobs")
    +                done <- true
    +                return
    +            }
    +        }
    +    }()
    @@ -116,14 +110,12 @@ channel, then closes it.

    -
    -    for j := 1; j <= 3; j++ {
    -        jobs <- j
    -        fmt.Println("sent job", j)
    -    }
    -    close(jobs)
    -    fmt.Println("sent all jobs")
    -
    +
        for j := 1; j <= 3; j++ {
    +        jobs <- j
    +        fmt.Println("sent job", j)
    +    }
    +    close(jobs)
    +    fmt.Println("sent all jobs")
    @@ -136,10 +128,8 @@ we saw earlier.

    -
    -    <-done
    -}
    -
    +
        <-done
    +}
    @@ -153,15 +143,15 @@ we saw earlier.

    -
    $ go run closing-channels.go 
    -sent job 1
    -received job 1
    -sent job 2
    -received job 2
    -sent job 3
    -received job 3
    -sent all jobs
    -received all jobs
    +
    $ go run closing-channels.go 
    +sent job 1
    +received job 1
    +sent job 2
    +received job 2
    +sent job 3
    +received job 3
    +sent all jobs
    +received all jobs
    diff --git a/public/closures b/public/closures index 8b8edd0aa..399acd31d 100644 --- a/public/closures +++ b/public/closures @@ -45,8 +45,7 @@ a function inline without having to name it.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ a function inline without having to name it.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -71,15 +69,13 @@ form a closure.

    -
    -func intSeq() func() int {
    -    i := 0
    -    return func() int {
    -        i++
    -        return i
    -    }
    -}
    -
    +
    func intSeq() func() int {
    +    i := 0
    +    return func() int {
    +        i++
    +        return i
    +    }
    +}
    @@ -89,8 +85,7 @@ form a closure.

    -
    func main() {
    -
    +
    func main() {
    @@ -104,9 +99,7 @@ we call nextInt.

    -
    -    nextInt := intSeq()
    -
    +
        nextInt := intSeq()
    @@ -118,11 +111,9 @@ a few times.

    -
    -    fmt.Println(nextInt())
    -    fmt.Println(nextInt())
    -    fmt.Println(nextInt())
    -
    +
        fmt.Println(nextInt())
    +    fmt.Println(nextInt())
    +    fmt.Println(nextInt())
    @@ -134,11 +125,9 @@ particular function, create and test a new one.

    -
    -    newInts := intSeq()
    -    fmt.Println(newInts())
    -}
    -
    +
        newInts := intSeq()
    +    fmt.Println(newInts())
    +}
    @@ -152,11 +141,11 @@ particular function, create and test a new one.

    -
    $ go run closures.go
    -1
    -2
    -3
    -1
    +
    $ go run closures.go
    +1
    +2
    +3
    +1
    diff --git a/public/command-line-arguments b/public/command-line-arguments index b0d532205..132a57d2e 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -45,8 +45,7 @@ For example, go run hello.go uses run and -
    package main
    -
    +
    package main
    @@ -56,11 +55,10 @@ For example, go run hello.go uses run and -
    import (
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +)
    @@ -70,8 +68,7 @@ For example, go run hello.go uses run and -
    func main() {
    -
    +
    func main() {
    @@ -85,10 +82,8 @@ holds the arguments to the program.

    -
    -    argsWithProg := os.Args
    -    argsWithoutProg := os.Args[1:]
    -
    +
        argsWithProg := os.Args
    +    argsWithoutProg := os.Args[1:]
    @@ -99,9 +94,7 @@ holds the arguments to the program.

    -
    -    arg := os.Args[3]
    -
    +
        arg := os.Args[3]
    @@ -111,11 +104,10 @@ holds the arguments to the program.

    -
        fmt.Println(argsWithProg)
    -    fmt.Println(argsWithoutProg)
    -    fmt.Println(arg)
    -}
    -
    +
        fmt.Println(argsWithProg)
    +    fmt.Println(argsWithoutProg)
    +    fmt.Println(arg)
    +}
    @@ -131,12 +123,11 @@ build a binary with go build first.

    -
    -$ go build command-line-arguments.go
    -$ ./command-line-arguments a b c d
    -[./command-line-arguments a b c d]       
    -[a b c d]
    -c
    +
    $ go build command-line-arguments.go
    +$ ./command-line-arguments a b c d
    +[./command-line-arguments a b c d]       
    +[a b c d]
    +c
    diff --git a/public/command-line-flags b/public/command-line-flags index 92e2f2e15..e58d90942 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -45,8 +45,7 @@ command-line flag.

    -
    package main
    -
    +
    package main
    @@ -59,12 +58,10 @@ implement our example command-line program.

    -
    -import (
    -    "flag"
    -    "fmt"
    -)
    -
    +
    import (
    +    "flag"
    +    "fmt"
    +)
    @@ -74,8 +71,7 @@ implement our example command-line program.

    -
    func main() {
    -
    +
    func main() {
    @@ -91,9 +87,7 @@ we’ll see how to use this pointer below.

    -
    -    wordPtr := flag.String("word", "foo", "a string")
    -
    +
        wordPtr := flag.String("word", "foo", "a string")
    @@ -105,10 +99,8 @@ similar approach to the word flag.

    -
    -    numbPtr := flag.Int("numb", 42, "an int")
    -    forkPtr := flag.Bool("fork", false, "a bool")
    -
    +
        numbPtr := flag.Int("numb", 42, "an int")
    +    forkPtr := flag.Bool("fork", false, "a bool")
    @@ -122,10 +114,8 @@ declaration function.

    -
    -    var svar string
    -    flag.StringVar(&svar, "svar", "bar", "a string var")
    -
    +
        var svar string
    +    flag.StringVar(&svar, "svar", "bar", "a string var")
    @@ -137,9 +127,7 @@ to execute the command-line parsing.

    -
    -    flag.Parse()
    -
    +
        flag.Parse()
    @@ -153,14 +141,12 @@ to get the actual option values.

    -
    -    fmt.Println("word:", *wordPtr)
    -    fmt.Println("numb:", *numbPtr)
    -    fmt.Println("fork:", *forkPtr)
    -    fmt.Println("svar:", svar)
    -    fmt.Println("tail:", flag.Args())
    -}
    -
    +
        fmt.Println("word:", *wordPtr)
    +    fmt.Println("numb:", *numbPtr)
    +    fmt.Println("fork:", *forkPtr)
    +    fmt.Println("svar:", svar)
    +    fmt.Println("tail:", flag.Args())
    +}
    @@ -177,8 +163,7 @@ binary directly.

    -
    -$ go build command-line-flags.go
    +
    $ go build command-line-flags.go
    @@ -190,13 +175,12 @@ all flags.

    -
    -$ ./command-line-flags -word=opt -numb=7 -fork -svar=flag
    -word: opt
    -numb: 7
    -fork: true
    -svar: flag
    -tail: []
    +
    $ ./command-line-flags -word=opt -numb=7 -fork -svar=flag
    +word: opt
    +numb: 7
    +fork: true
    +svar: flag
    +tail: []
    @@ -208,13 +192,12 @@ their default values.

    -
    -$ ./command-line-flags -word=opt
    -word: opt
    -numb: 42
    -fork: false
    -svar: bar
    -tail: []
    +
    $ ./command-line-flags -word=opt
    +word: opt
    +numb: 42
    +fork: false
    +svar: bar
    +tail: []
    @@ -226,11 +209,10 @@ any flags.

    -
    -$ ./command-line-flags -word=opt a1 a2 a3
    -word: opt
    -...
    -tail: [a1 a2 a3]
    +
    $ ./command-line-flags -word=opt a1 a2 a3
    +word: opt
    +...
    +tail: [a1 a2 a3]
    @@ -243,13 +225,12 @@ will be interpreted as positional arguments).

    -
    -$ ./command-line-flags -word=opt a1 a2 a3 -numb=7
    -word: opt
    -numb: 42
    -fork: false
    -svar: bar
    -tail: [a1 a2 a3 -numb=7]
    +
    $ ./command-line-flags -word=opt a1 a2 a3 -numb=7
    +word: opt
    +numb: 42
    +fork: false
    +svar: bar
    +tail: [a1 a2 a3 -numb=7]
    @@ -261,13 +242,12 @@ generated help text for the command-line program.

    -
    -$ ./command-line-flags -h
    -Usage of ./command-line-flags:
    -  -fork=false: a bool
    -  -numb=42: an int
    -  -svar="bar": a string var
    -  -word="foo": a string
    +
    $ ./command-line-flags -h
    +Usage of ./command-line-flags:
    +  -fork=false: a bool
    +  -numb=42: an int
    +  -svar="bar": a string var
    +  -word="foo": a string
    @@ -280,11 +260,10 @@ and show the help text again.

    -
    -$ ./command-line-flags -wat
    -flag provided but not defined: -wat
    -Usage of ./command-line-flags:
    -...
    +
    $ ./command-line-flags -wat
    +flag provided but not defined: -wat
    +Usage of ./command-line-flags:
    +...
    diff --git a/public/command-line-subcommands b/public/command-line-subcommands index 9ea0cbaf5..cc95b27bb 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -47,8 +47,7 @@ subcommands that have their own flags.

    -
    package main
    -
    +
    package main
    @@ -58,12 +57,11 @@ subcommands that have their own flags.

    -
    import (
    -    "flag"
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "flag"
    +    "fmt"
    +    "os"
    +)
    @@ -73,8 +71,7 @@ subcommands that have their own flags.

    -
    func main() {
    -
    +
    func main() {
    @@ -87,11 +84,9 @@ for this subcommand.

    -
    -    fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
    -    fooEnable := fooCmd.Bool("enable", false, "enable")
    -    fooName := fooCmd.String("name", "", "name")
    -
    +
        fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
    +    fooEnable := fooCmd.Bool("enable", false, "enable")
    +    fooName := fooCmd.String("name", "", "name")
    @@ -103,10 +98,8 @@ supported flags.

    -
    -    barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
    -    barLevel := barCmd.Int("level", 0, "level")
    -
    +
        barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
    +    barLevel := barCmd.Int("level", 0, "level")
    @@ -118,12 +111,10 @@ to the program.

    -
    -    if len(os.Args) < 2 {
    -        fmt.Println("expected 'foo' or 'bar' subcommands")
    -        os.Exit(1)
    -    }
    -
    +
        if len(os.Args) < 2 {
    +        fmt.Println("expected 'foo' or 'bar' subcommands")
    +        os.Exit(1)
    +    }
    @@ -134,9 +125,7 @@ to the program.

    -
    -    switch os.Args[1] {
    -
    +
        switch os.Args[1] {
    @@ -148,24 +137,22 @@ have access to trailing positional arguments.

    -
    -    case "foo":
    -        fooCmd.Parse(os.Args[2:])
    -        fmt.Println("subcommand 'foo'")
    -        fmt.Println("  enable:", *fooEnable)
    -        fmt.Println("  name:", *fooName)
    -        fmt.Println("  tail:", fooCmd.Args())
    -    case "bar":
    -        barCmd.Parse(os.Args[2:])
    -        fmt.Println("subcommand 'bar'")
    -        fmt.Println("  level:", *barLevel)
    -        fmt.Println("  tail:", barCmd.Args())
    -    default:
    -        fmt.Println("expected 'foo' or 'bar' subcommands")
    -        os.Exit(1)
    -    }
    -}
    -
    +
        case "foo":
    +        fooCmd.Parse(os.Args[2:])
    +        fmt.Println("subcommand 'foo'")
    +        fmt.Println("  enable:", *fooEnable)
    +        fmt.Println("  name:", *fooName)
    +        fmt.Println("  tail:", fooCmd.Args())
    +    case "bar":
    +        barCmd.Parse(os.Args[2:])
    +        fmt.Println("subcommand 'bar'")
    +        fmt.Println("  level:", *barLevel)
    +        fmt.Println("  tail:", barCmd.Args())
    +    default:
    +        fmt.Println("expected 'foo' or 'bar' subcommands")
    +        os.Exit(1)
    +    }
    +}
    @@ -179,7 +166,7 @@ have access to trailing positional arguments.

    -
    $ go build command-line-subcommands.go 
    +
    $ go build command-line-subcommands.go 
    @@ -190,12 +177,11 @@ have access to trailing positional arguments.

    -
    -$ ./command-line-subcommands foo -enable -name=joe a1 a2
    -subcommand 'foo'
    -  enable: true
    -  name: joe
    -  tail: [a1 a2]
    +
    $ ./command-line-subcommands foo -enable -name=joe a1 a2
    +subcommand 'foo'
    +  enable: true
    +  name: joe
    +  tail: [a1 a2]
    @@ -206,11 +192,10 @@ have access to trailing positional arguments.

    -
    -$ ./command-line-subcommands bar -level 8 a1
    -subcommand 'bar'
    -  level: 8
    -  tail: [a1]
    +
    $ ./command-line-subcommands bar -level 8 a1
    +subcommand 'bar'
    +  level: 8
    +  tail: [a1]
    @@ -221,12 +206,11 @@ have access to trailing positional arguments.

    -
    -$ ./command-line-subcommands bar -enable a1
    -flag provided but not defined: -enable
    -Usage of bar:
    -  -level int
    -        level
    +
    $ ./command-line-subcommands bar -enable a1
    +flag provided but not defined: -enable
    +Usage of bar:
    +  -level int
    +        level
    diff --git a/public/constants b/public/constants index 01884737d..1a5e56a17 100644 --- a/public/constants +++ b/public/constants @@ -43,8 +43,7 @@ and numeric values.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ and numeric values.

    -
    import (
    -    "fmt"
    -    "math"
    -)
    -
    +
    import (
    +    "fmt"
    +    "math"
    +)
    @@ -69,9 +67,7 @@ and numeric values.

    -
    -const s string = "constant"
    -
    +
    const s string = "constant"
    @@ -81,9 +77,8 @@ and numeric values.

    -
    func main() {
    -    fmt.Println(s)
    -
    +
    func main() {
    +    fmt.Println(s)
    @@ -95,9 +90,7 @@ statement can.

    -
    -    const n = 500000000
    -
    +
        const n = 500000000
    @@ -109,10 +102,8 @@ arbitrary precision.

    -
    -    const d = 3e20 / n
    -    fmt.Println(d)
    -
    +
        const d = 3e20 / n
    +    fmt.Println(d)
    @@ -124,9 +115,7 @@ one, such as by an explicit conversion.

    -
    -    fmt.Println(int64(d))
    -
    +
        fmt.Println(int64(d))
    @@ -140,10 +129,8 @@ assignment or function call. For example, here -
    -    fmt.Println(math.Sin(n))
    -}
    -
    +
        fmt.Println(math.Sin(n))
    +}
    @@ -157,11 +144,11 @@ assignment or function call. For example, here -
    $ go run constant.go 
    -constant
    -6e+11
    -600000000000
    --0.28470407323754404
    +
    $ go run constant.go 
    +constant
    +6e+11
    +600000000000
    +-0.28470407323754404
    diff --git a/public/context b/public/context index 576162faf..c60472df5 100644 --- a/public/context +++ b/public/context @@ -37,9 +37,7 @@ across API boundaries and goroutines.

    -
    -package main
    -
    +
    package main
    @@ -49,12 +47,11 @@ across API boundaries and goroutines.

    -
    import (
    -    "fmt"
    -    "net/http"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "net/http"
    +    "time"
    +)
    @@ -64,8 +61,7 @@ across API boundaries and goroutines.

    -
    func hello(w http.ResponseWriter, req *http.Request) {
    -
    +
    func hello(w http.ResponseWriter, req *http.Request) {
    @@ -78,11 +74,9 @@ the Context() method.

    -
    -    ctx := req.Context()
    -    fmt.Println("server: hello handler started")
    -    defer fmt.Println("server: hello handler ended")
    -
    +
        ctx := req.Context()
    +    fmt.Println("server: hello handler started")
    +    defer fmt.Println("server: hello handler ended")
    @@ -97,12 +91,10 @@ the work and return as soon as possible.

    -
    -    select {
    -    case <-time.After(10 * time.Second):
    -        fmt.Fprintf(w, "hello\n")
    -    case <-ctx.Done():
    -
    +
        select {
    +    case <-time.After(10 * time.Second):
    +        fmt.Fprintf(w, "hello\n")
    +    case <-ctx.Done():
    @@ -115,14 +107,12 @@ closed.

    -
    -        err := ctx.Err()
    -        fmt.Println("server:", err)
    -        internalError := http.StatusInternalServerError
    -        http.Error(w, err.Error(), internalError)
    -    }
    -}
    -
    +
            err := ctx.Err()
    +        fmt.Println("server:", err)
    +        internalError := http.StatusInternalServerError
    +        http.Error(w, err.Error(), internalError)
    +    }
    +}
    @@ -132,8 +122,7 @@ closed.

    -
    func main() {
    -
    +
    func main() {
    @@ -145,11 +134,9 @@ route, and start serving.

    -
    -    http.HandleFunc("/hello", hello)
    -    http.ListenAndServe(":8090", nil)
    -}
    -
    +
        http.HandleFunc("/hello", hello)
    +    http.ListenAndServe(":8090", nil)
    +}
    @@ -164,8 +151,7 @@ route, and start serving.

    -
    -$ go run context-in-http-servers.go &
    +
    $ go run context-in-http-servers.go &
    @@ -178,12 +164,11 @@ cancellation.

    -
    -$ curl localhost:8090/hello
    -server: hello handler started
    -^C
    -server: context canceled
    -server: hello handler ended
    +
    $ curl localhost:8090/hello
    +server: hello handler started
    +^C
    +server: context canceled
    +server: hello handler ended
    diff --git a/public/defer b/public/defer index 2e48c9e2e..84cb13f94 100644 --- a/public/defer +++ b/public/defer @@ -45,8 +45,7 @@ purposes of cleanup. defer is often used where e.g. -
    package main
    -
    +
    package main
    @@ -56,11 +55,10 @@ purposes of cleanup. defer is often used where e.g. -
    import (
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +)
    @@ -73,9 +71,7 @@ do that with defer.

    -
    -func main() {
    -
    +
    func main() {
    @@ -90,12 +86,10 @@ of the enclosing function (main), after -
    -    f := createFile("/tmp/defer.txt")
    -    defer closeFile(f)
    -    writeFile(f)
    -}
    -
    +
        f := createFile("/tmp/defer.txt")
    +    defer closeFile(f)
    +    writeFile(f)
    +}
    @@ -105,15 +99,14 @@ of the enclosing function (main), after -
    func createFile(p string) *os.File {
    -    fmt.Println("creating")
    -    f, err := os.Create(p)
    -    if err != nil {
    -        panic(err)
    -    }
    -    return f
    -}
    -
    +
    func createFile(p string) *os.File {
    +    fmt.Println("creating")
    +    f, err := os.Create(p)
    +    if err != nil {
    +        panic(err)
    +    }
    +    return f
    +}
    @@ -123,10 +116,9 @@ of the enclosing function (main), after -
    func writeFile(f *os.File) {
    -    fmt.Println("writing")
    -    fmt.Fprintln(f, "data")
    -
    +
    func writeFile(f *os.File) {
    +    fmt.Println("writing")
    +    fmt.Fprintln(f, "data")
    @@ -136,8 +128,7 @@ of the enclosing function (main), after -
    }
    -
    +
    }
    @@ -149,10 +140,9 @@ file, even in a deferred function.

    -
    func closeFile(f *os.File) {
    -    fmt.Println("closing")
    -    err := f.Close()
    -
    +
    func closeFile(f *os.File) {
    +    fmt.Println("closing")
    +    err := f.Close()
    @@ -162,12 +152,11 @@ file, even in a deferred function.

    -
        if err != nil {
    -        fmt.Fprintf(os.Stderr, "error: %v\n", err)
    -        os.Exit(1)
    -    }
    -}
    -
    +
        if err != nil {
    +        fmt.Fprintf(os.Stderr, "error: %v\n", err)
    +        os.Exit(1)
    +    }
    +}
    @@ -183,11 +172,10 @@ after being written.

    -
    -$ go run defer.go
    -creating
    -writing
    -closing
    +
    $ go run defer.go
    +creating
    +writing
    +closing
    diff --git a/public/directories b/public/directories index bef7856d9..5dfbd6046 100644 --- a/public/directories +++ b/public/directories @@ -43,8 +43,7 @@ -
    package main
    -
    +
    package main
    @@ -54,12 +53,11 @@ -
    import (
    -    "fmt"
    -    "os"
    -    "path/filepath"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +    "path/filepath"
    +)
    @@ -69,12 +67,11 @@ -
    func check(e error) {
    -    if e != nil {
    -        panic(e)
    -    }
    -}
    -
    +
    func check(e error) {
    +    if e != nil {
    +        panic(e)
    +    }
    +}
    @@ -84,8 +81,7 @@ -
    func main() {
    -
    +
    func main() {
    @@ -97,10 +93,8 @@ directory.

    -
    -    err := os.Mkdir("subdir", 0755)
    -    check(err)
    -
    +
        err := os.Mkdir("subdir", 0755)
    +    check(err)
    @@ -114,9 +108,7 @@ will delete a whole directory tree (similarly to -
    -    defer os.RemoveAll("subdir")
    -
    +
        defer os.RemoveAll("subdir")
    @@ -127,12 +119,10 @@ will delete a whole directory tree (similarly to -
    -    createEmptyFile := func(name string) {
    -        d := []byte("")
    -        check(os.WriteFile(name, d, 0644))
    -    }
    -
    +
        createEmptyFile := func(name string) {
    +        d := []byte("")
    +        check(os.WriteFile(name, d, 0644))
    +    }
    @@ -142,8 +132,7 @@ will delete a whole directory tree (similarly to -
        createEmptyFile("subdir/file1")
    -
    +
        createEmptyFile("subdir/file1")
    @@ -156,10 +145,8 @@ command-line mkdir -p.

    -
    -    err = os.MkdirAll("subdir/parent/child", 0755)
    -    check(err)
    -
    +
        err = os.MkdirAll("subdir/parent/child", 0755)
    +    check(err)
    @@ -169,10 +156,9 @@ command-line mkdir -p.

    -
        createEmptyFile("subdir/parent/file2")
    -    createEmptyFile("subdir/parent/file3")
    -    createEmptyFile("subdir/parent/child/file4")
    -
    +
        createEmptyFile("subdir/parent/file2")
    +    createEmptyFile("subdir/parent/file3")
    +    createEmptyFile("subdir/parent/child/file4")
    @@ -184,10 +170,8 @@ slice of os.DirEntry objects.

    -
    -    c, err := os.ReadDir("subdir/parent")
    -    check(err)
    -
    +
        c, err := os.ReadDir("subdir/parent")
    +    check(err)
    @@ -197,11 +181,10 @@ slice of os.DirEntry objects.

    -
        fmt.Println("Listing subdir/parent")
    -    for _, entry := range c {
    -        fmt.Println(" ", entry.Name(), entry.IsDir())
    -    }
    -
    +
        fmt.Println("Listing subdir/parent")
    +    for _, entry := range c {
    +        fmt.Println(" ", entry.Name(), entry.IsDir())
    +    }
    @@ -213,10 +196,8 @@ similarly to cd.

    -
    -    err = os.Chdir("subdir/parent/child")
    -    check(err)
    -
    +
        err = os.Chdir("subdir/parent/child")
    +    check(err)
    @@ -228,10 +209,8 @@ when listing the current directory.

    -
    -    c, err = os.ReadDir(".")
    -    check(err)
    -
    +
        c, err = os.ReadDir(".")
    +    check(err)
    @@ -241,11 +220,10 @@ when listing the current directory.

    -
        fmt.Println("Listing subdir/parent/child")
    -    for _, entry := range c {
    -        fmt.Println(" ", entry.Name(), entry.IsDir())
    -    }
    -
    +
        fmt.Println("Listing subdir/parent/child")
    +    for _, entry := range c {
    +        fmt.Println(" ", entry.Name(), entry.IsDir())
    +    }
    @@ -256,10 +234,8 @@ when listing the current directory.

    -
    -    err = os.Chdir("../../..")
    -    check(err)
    -
    +
        err = os.Chdir("../../..")
    +    check(err)
    @@ -273,11 +249,9 @@ directory visited.

    -
    -    fmt.Println("Visiting subdir")
    -    err = filepath.Walk("subdir", visit)
    -}
    -
    +
        fmt.Println("Visiting subdir")
    +    err = filepath.Walk("subdir", visit)
    +}
    @@ -289,15 +263,13 @@ recursively by filepath.Walk.

    -
    -func visit(p string, info os.FileInfo, err error) error {
    -    if err != nil {
    -        return err
    -    }
    -    fmt.Println(" ", p, info.IsDir())
    -    return nil
    -}
    -
    +
    func visit(p string, info os.FileInfo, err error) error {
    +    if err != nil {
    +        return err
    +    }
    +    fmt.Println(" ", p, info.IsDir())
    +    return nil
    +}
    @@ -311,21 +283,21 @@ recursively by filepath.Walk.

    -
    $ go run directories.go
    -Listing subdir/parent
    -  child true
    -  file2 false
    -  file3 false
    -Listing subdir/parent/child
    -  file4 false
    -Visiting subdir
    -  subdir true
    -  subdir/file1 false
    -  subdir/parent true
    -  subdir/parent/child true
    -  subdir/parent/child/file4 false
    -  subdir/parent/file2 false
    -  subdir/parent/file3 false
    +
    $ go run directories.go
    +Listing subdir/parent
    +  child true
    +  file2 false
    +  file3 false
    +Listing subdir/parent/child
    +  file4 false
    +Visiting subdir
    +  subdir true
    +  subdir/file1 false
    +  subdir/parent true
    +  subdir/parent/child true
    +  subdir/parent/child/file4 false
    +  subdir/parent/file2 false
    +  subdir/parent/file3 false
    diff --git a/public/embed-directive b/public/embed-directive index 906bece5a..d7d06929d 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -36,9 +36,7 @@ build time. Read more about the embed directive -
    -package main
    -
    +
    package main
    @@ -50,11 +48,9 @@ identifiers from this package, you can do a blank import with _ "embe -
    -import (
    -    "embed"
    -)
    -
    +
    import (
    +    "embed"
    +)
    @@ -67,10 +63,8 @@ Go source file. This directive embeds the contents of the file into the -
    -//go:embed folder/single_file.txt
    -var fileString string
    -
    +
    //go:embed folder/single_file.txt
    +var fileString string
    @@ -81,10 +75,8 @@ Go source file. This directive embeds the contents of the file into the -
    -//go:embed folder/single_file.txt
    -var fileByte []byte
    -
    +
    //go:embed folder/single_file.txt
    +var fileByte []byte
    @@ -97,11 +89,9 @@ implements a simple virtual file system.

    -
    -//go:embed folder/single_file.txt
    -//go:embed folder/*.hash
    -var folder embed.FS
    -
    +
    //go:embed folder/single_file.txt
    +//go:embed folder/*.hash
    +var folder embed.FS
    @@ -111,8 +101,7 @@ implements a simple virtual file system.

    -
    func main() {
    -
    +
    func main() {
    @@ -123,10 +112,8 @@ implements a simple virtual file system.

    -
    -    print(fileString)
    -    print(string(fileByte))
    -
    +
        print(fileString)
    +    print(string(fileByte))
    @@ -137,10 +124,8 @@ implements a simple virtual file system.

    -
    -    content1, _ := folder.ReadFile("folder/file1.hash")
    -    print(string(content1))
    -
    +
        content1, _ := folder.ReadFile("folder/file1.hash")
    +    print(string(content1))
    @@ -150,10 +135,9 @@ implements a simple virtual file system.

    -
        content2, _ := folder.ReadFile("folder/file2.hash")
    -    print(string(content2))
    -}
    -
    +
        content2, _ := folder.ReadFile("folder/file2.hash")
    +    print(string(content2))
    +}
    @@ -170,11 +154,10 @@ this example can only be run on your local machine.)

    -
    -$ mkdir -p folder
    -$ echo "hello go" > folder/single_file.txt
    -$ echo "123" > folder/file1.hash
    -$ echo "456" > folder/file2.hash
    +
    $ mkdir -p folder
    +$ echo "hello go" > folder/single_file.txt
    +$ echo "123" > folder/file1.hash
    +$ echo "456" > folder/file2.hash
    @@ -184,11 +167,11 @@ this example can only be run on your local machine.)

    -
    $ go run embed-directive.go
    -hello go
    -hello go
    -123
    -456
    +
    $ go run embed-directive.go
    +hello go
    +hello go
    +123
    +456
    diff --git a/public/environment-variables b/public/environment-variables index f0d0e5ed9..eb0ccb78d 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -45,8 +45,7 @@ Let’s look at how to set, get, and list environment variables.

    -
    package main
    -
    +
    package main
    @@ -56,12 +55,11 @@ Let’s look at how to set, get, and list environment variables.

    -
    import (
    -    "fmt"
    -    "os"
    -    "strings"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +    "strings"
    +)
    @@ -71,8 +69,7 @@ Let’s look at how to set, get, and list environment variables.

    -
    func main() {
    -
    +
    func main() {
    @@ -86,11 +83,9 @@ environment.

    -
    -    os.Setenv("FOO", "1")
    -    fmt.Println("FOO:", os.Getenv("FOO"))
    -    fmt.Println("BAR:", os.Getenv("BAR"))
    -
    +
        os.Setenv("FOO", "1")
    +    fmt.Println("FOO:", os.Getenv("FOO"))
    +    fmt.Println("BAR:", os.Getenv("BAR"))
    @@ -104,14 +99,12 @@ get the key and value. Here we print all the keys.

    -
    -    fmt.Println()
    -    for _, e := range os.Environ() {
    -        pair := strings.SplitN(e, "=", 2)
    -        fmt.Println(pair[0])
    -    }
    -}
    -
    +
        fmt.Println()
    +    for _, e := range os.Environ() {
    +        pair := strings.SplitN(e, "=", 2)
    +        fmt.Println(pair[0])
    +    }
    +}
    @@ -128,10 +121,9 @@ for FOO that we set in the program, but that -
    -$ go run environment-variables.go
    -FOO: 1
    -BAR: 
    +
    $ go run environment-variables.go
    +FOO: 1
    +BAR: 
    @@ -143,12 +135,11 @@ particular machine.

    -
    -TERM_PROGRAM
    -PATH
    -SHELL
    -...
    -FOO
    +
    TERM_PROGRAM
    +PATH
    +SHELL
    +...
    +FOO
    @@ -160,11 +151,10 @@ program picks that value up.

    -
    -$ BAR=2 go run environment-variables.go
    -FOO: 1
    -BAR: 2
    -...
    +
    $ BAR=2 go run environment-variables.go
    +FOO: 1
    +BAR: 2
    +...
    diff --git a/public/epoch b/public/epoch index 890b66e76..8e7d9a70a 100644 --- a/public/epoch +++ b/public/epoch @@ -45,8 +45,7 @@ Here’s how to do it in Go.

    -
    package main
    -
    +
    package main
    @@ -56,11 +55,10 @@ Here’s how to do it in Go.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -70,8 +68,7 @@ Here’s how to do it in Go.

    -
    func main() {
    -
    +
    func main() {
    @@ -84,10 +81,8 @@ milliseconds or nanoseconds, respectively.

    -
    -    now := time.Now()
    -    fmt.Println(now)
    -
    +
        now := time.Now()
    +    fmt.Println(now)
    @@ -97,10 +92,9 @@ milliseconds or nanoseconds, respectively.

    -
        fmt.Println(now.Unix())
    -    fmt.Println(now.UnixMilli())
    -    fmt.Println(now.UnixNano())
    -
    +
        fmt.Println(now.Unix())
    +    fmt.Println(now.UnixMilli())
    +    fmt.Println(now.UnixNano())
    @@ -112,11 +106,9 @@ since the epoch into the corresponding time.

    -
    -    fmt.Println(time.Unix(now.Unix(), 0))
    -    fmt.Println(time.Unix(0, now.UnixNano()))
    -}
    -
    +
        fmt.Println(time.Unix(now.Unix(), 0))
    +    fmt.Println(time.Unix(0, now.UnixNano()))
    +}
    @@ -130,13 +122,13 @@ since the epoch into the corresponding time.

    -
    $ go run epoch.go 
    -2012-10-31 16:13:58.292387 +0000 UTC
    -1351700038
    -1351700038292
    -1351700038292387000
    -2012-10-31 16:13:58 +0000 UTC
    -2012-10-31 16:13:58.292387 +0000 UTC
    +
    $ go run epoch.go 
    +2012-10-31 16:13:58.292387 +0000 UTC
    +1351700038
    +1351700038292
    +1351700038292387000
    +2012-10-31 16:13:58 +0000 UTC
    +2012-10-31 16:13:58.292387 +0000 UTC
    diff --git a/public/errors b/public/errors index 9444171a7..ab084adae 100644 --- a/public/errors +++ b/public/errors @@ -49,8 +49,7 @@ non-error tasks.

    -
    package main
    -
    +
    package main
    @@ -60,11 +59,10 @@ non-error tasks.

    -
    import (
    -    "errors"
    -    "fmt"
    -)
    -
    +
    import (
    +    "errors"
    +    "fmt"
    +)
    @@ -76,10 +74,8 @@ have type error, a built-in interface.

    -
    -func f1(arg int) (int, error) {
    -    if arg == 42 {
    -
    +
    func f1(arg int) (int, error) {
    +    if arg == 42 {
    @@ -91,9 +87,7 @@ with the given error message.

    -
    -        return -1, errors.New("can't work with 42")
    -
    +
            return -1, errors.New("can't work with 42")
    @@ -103,8 +97,7 @@ with the given error message.

    -
        }
    -
    +
        }
    @@ -116,10 +109,8 @@ there was no error.

    -
    -    return arg + 3, nil
    -}
    -
    +
        return arg + 3, nil
    +}
    @@ -133,12 +124,10 @@ to explicitly represent an argument error.

    -
    -type argError struct {
    -    arg  int
    -    prob string
    -}
    -
    +
    type argError struct {
    +    arg  int
    +    prob string
    +}
    @@ -148,10 +137,9 @@ to explicitly represent an argument error.

    -
    func (e *argError) Error() string {
    -    return fmt.Sprintf("%d - %s", e.arg, e.prob)
    -}
    -
    +
    func (e *argError) Error() string {
    +    return fmt.Sprintf("%d - %s", e.arg, e.prob)
    +}
    @@ -161,9 +149,8 @@ to explicitly represent an argument error.

    -
    func f2(arg int) (int, error) {
    -    if arg == 42 {
    -
    +
    func f2(arg int) (int, error) {
    +    if arg == 42 {
    @@ -176,12 +163,10 @@ fields arg and prob.

    -
    -        return -1, &argError{arg, "can't work with it"}
    -    }
    -    return arg + 3, nil
    -}
    -
    +
            return -1, &argError{arg, "can't work with it"}
    +    }
    +    return arg + 3, nil
    +}
    @@ -191,8 +176,7 @@ fields arg and prob.

    -
    func main() {
    -
    +
    func main() {
    @@ -206,22 +190,20 @@ idiom in Go code.

    -
    -    for _, i := range []int{7, 42} {
    -        if r, e := f1(i); e != nil {
    -            fmt.Println("f1 failed:", e)
    -        } else {
    -            fmt.Println("f1 worked:", r)
    -        }
    -    }
    -    for _, i := range []int{7, 42} {
    -        if r, e := f2(i); e != nil {
    -            fmt.Println("f2 failed:", e)
    -        } else {
    -            fmt.Println("f2 worked:", r)
    -        }
    -    }
    -
    +
        for _, i := range []int{7, 42} {
    +        if r, e := f1(i); e != nil {
    +            fmt.Println("f1 failed:", e)
    +        } else {
    +            fmt.Println("f1 worked:", r)
    +        }
    +    }
    +    for _, i := range []int{7, 42} {
    +        if r, e := f2(i); e != nil {
    +            fmt.Println("f2 failed:", e)
    +        } else {
    +            fmt.Println("f2 worked:", r)
    +        }
    +    }
    @@ -235,14 +217,12 @@ assertion.

    -
    -    _, e := f2(42)
    -    if ae, ok := e.(*argError); ok {
    -        fmt.Println(ae.arg)
    -        fmt.Println(ae.prob)
    -    }
    -}
    -
    +
        _, e := f2(42)
    +    if ae, ok := e.(*argError); ok {
    +        fmt.Println(ae.arg)
    +        fmt.Println(ae.prob)
    +    }
    +}
    @@ -256,13 +236,13 @@ assertion.

    -
    $ go run errors.go
    -f1 worked: 10
    -f1 failed: can't work with 42
    -f2 worked: 10
    -f2 failed: 42 - can't work with it
    -42
    -can't work with it
    +
    $ go run errors.go
    +f1 worked: 10
    +f1 failed: can't work with 42
    +f2 worked: 10
    +f2 failed: 42 - can't work with it
    +42
    +can't work with it
    diff --git a/public/execing-processes b/public/execing-processes index 6e9c5a3d5..083d11ec7 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -50,8 +50,7 @@ function.

    -
    package main
    -
    +
    package main
    @@ -61,12 +60,11 @@ function.

    -
    import (
    -    "os"
    -    "os/exec"
    -    "syscall"
    -)
    -
    +
    import (
    +    "os"
    +    "os/exec"
    +    "syscall"
    +)
    @@ -76,8 +74,7 @@ function.

    -
    func main() {
    -
    +
    func main() {
    @@ -91,12 +88,10 @@ we’ll use exec.LookPath to find it (probably -
    -    binary, lookErr := exec.LookPath("ls")
    -    if lookErr != nil {
    -        panic(lookErr)
    -    }
    -
    +
        binary, lookErr := exec.LookPath("ls")
    +    if lookErr != nil {
    +        panic(lookErr)
    +    }
    @@ -110,9 +105,7 @@ be the program name.

    -
    -    args := []string{"ls", "-a", "-l", "-h"}
    -
    +
        args := []string{"ls", "-a", "-l", "-h"}
    @@ -125,9 +118,7 @@ environment.

    -
    -    env := os.Environ()
    -
    +
        env := os.Environ()
    @@ -142,13 +133,11 @@ value.

    -
    -    execErr := syscall.Exec(binary, args, env)
    -    if execErr != nil {
    -        panic(execErr)
    -    }
    -}
    -
    +
        execErr := syscall.Exec(binary, args, env)
    +    if execErr != nil {
    +        panic(execErr)
    +    }
    +}
    @@ -163,12 +152,11 @@ value.

    -
    -$ go run execing-processes.go
    -total 16
    -drwxr-xr-x  4 mark 136B Oct 3 16:29 .
    -drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
    --rw-r--r--  1 mark 1.3K Oct 3 16:28 execing-processes.go
    +
    $ go run execing-processes.go
    +total 16
    +drwxr-xr-x  4 mark 136B Oct 3 16:29 .
    +drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
    +-rw-r--r--  1 mark 1.3K Oct 3 16:28 execing-processes.go
    diff --git a/public/exit b/public/exit index 902ba7811..ff7073ceb 100644 --- a/public/exit +++ b/public/exit @@ -39,8 +39,7 @@ status.

    -
    package main
    -
    +
    package main
    @@ -50,11 +49,10 @@ status.

    -
    import (
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +)
    @@ -64,8 +62,7 @@ status.

    -
    func main() {
    -
    +
    func main() {
    @@ -77,9 +74,7 @@ this fmt.Println will never be called.

    -
    -    defer fmt.Println("!")
    -
    +
        defer fmt.Println("!")
    @@ -90,10 +85,8 @@ this fmt.Println will never be called.

    -
    -    os.Exit(3)
    -}
    -
    +
        os.Exit(3)
    +}
    @@ -123,9 +116,8 @@ will be picked up by go and printed.

    -
    -$ go run exit.go
    -exit status 3
    +
    $ go run exit.go
    +exit status 3
    @@ -137,11 +129,10 @@ the status in the terminal.

    -
    -$ go build exit.go
    -$ ./exit
    -$ echo $?
    -3
    +
    $ go build exit.go
    +$ ./exit
    +$ echo $?
    +3
    diff --git a/public/file-paths b/public/file-paths index d129bde39..bfa4b61a5 100644 --- a/public/file-paths +++ b/public/file-paths @@ -35,9 +35,7 @@ between operating systems; dir/file on Linux vs. -
    -package main
    -
    +
    package main
    @@ -47,12 +45,11 @@ between operating systems; dir/file on Linux vs. -
    import (
    -    "fmt"
    -    "path/filepath"
    -    "strings"
    -)
    -
    +
    import (
    +    "fmt"
    +    "path/filepath"
    +    "strings"
    +)
    @@ -62,8 +59,7 @@ between operating systems; dir/file on Linux vs. -
    func main() {
    -
    +
    func main() {
    @@ -76,10 +72,8 @@ and constructs a hierarchical path from them.

    -
    -    p := filepath.Join("dir1", "dir2", "filename")
    -    fmt.Println("p:", p)
    -
    +
        p := filepath.Join("dir1", "dir2", "filename")
    +    fmt.Println("p:", p)
    @@ -94,10 +88,8 @@ and directory changes.

    -
    -    fmt.Println(filepath.Join("dir1//", "filename"))
    -    fmt.Println(filepath.Join("dir1/../dir1", "filename"))
    -
    +
        fmt.Println(filepath.Join("dir1//", "filename"))
    +    fmt.Println(filepath.Join("dir1/../dir1", "filename"))
    @@ -110,10 +102,8 @@ return both in the same call.

    -
    -    fmt.Println("Dir(p):", filepath.Dir(p))
    -    fmt.Println("Base(p):", filepath.Base(p))
    -
    +
        fmt.Println("Dir(p):", filepath.Dir(p))
    +    fmt.Println("Base(p):", filepath.Base(p))
    @@ -124,10 +114,8 @@ return both in the same call.

    -
    -    fmt.Println(filepath.IsAbs("dir/file"))
    -    fmt.Println(filepath.IsAbs("/dir/file"))
    -
    +
        fmt.Println(filepath.IsAbs("dir/file"))
    +    fmt.Println(filepath.IsAbs("/dir/file"))
    @@ -137,8 +125,7 @@ return both in the same call.

    -
        filename := "config.json"
    -
    +
        filename := "config.json"
    @@ -150,10 +137,8 @@ can split the extension out of such names with Ext.

    -
    -    ext := filepath.Ext(filename)
    -    fmt.Println(ext)
    -
    +
        ext := filepath.Ext(filename)
    +    fmt.Println(ext)
    @@ -165,9 +150,7 @@ use strings.TrimSuffix.

    -
    -    fmt.Println(strings.TrimSuffix(filename, ext))
    -
    +
        fmt.Println(strings.TrimSuffix(filename, ext))
    @@ -180,13 +163,11 @@ be made relative to base.

    -
    -    rel, err := filepath.Rel("a/b", "a/b/t/file")
    -    if err != nil {
    -        panic(err)
    -    }
    -    fmt.Println(rel)
    -
    +
        rel, err := filepath.Rel("a/b", "a/b/t/file")
    +    if err != nil {
    +        panic(err)
    +    }
    +    fmt.Println(rel)
    @@ -196,13 +177,12 @@ be made relative to base.

    -
        rel, err = filepath.Rel("a/b", "a/c/t/file")
    -    if err != nil {
    -        panic(err)
    -    }
    -    fmt.Println(rel)
    -}
    -
    +
        rel, err = filepath.Rel("a/b", "a/c/t/file")
    +    if err != nil {
    +        panic(err)
    +    }
    +    fmt.Println(rel)
    +}
    @@ -216,18 +196,18 @@ be made relative to base.

    -
    $ go run file-paths.go
    -p: dir1/dir2/filename
    -dir1/filename
    -dir1/filename
    -Dir(p): dir1/dir2
    -Base(p): filename
    -false
    -true
    -.json
    -config
    -t/file
    -../c/t/file
    +
    $ go run file-paths.go
    +p: dir1/dir2/filename
    +dir1/filename
    +dir1/filename
    +Dir(p): dir1/dir2
    +Base(p): filename
    +false
    +true
    +.json
    +config
    +t/file
    +../c/t/file
    diff --git a/public/for b/public/for index e5b9674be..987ade2e9 100644 --- a/public/for +++ b/public/for @@ -43,8 +43,7 @@ some basic types of for loops.

    -
    package main
    -
    +
    package main
    @@ -54,8 +53,7 @@ some basic types of for loops.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -65,8 +63,7 @@ some basic types of for loops.

    -
    func main() {
    -
    +
    func main() {
    @@ -77,13 +74,11 @@ some basic types of for loops.

    -
    -    i := 1
    -    for i <= 3 {
    -        fmt.Println(i)
    -        i = i + 1
    -    }
    -
    +
        i := 1
    +    for i <= 3 {
    +        fmt.Println(i)
    +        i = i + 1
    +    }
    @@ -94,11 +89,9 @@ some basic types of for loops.

    -
    -    for j := 7; j <= 9; j++ {
    -        fmt.Println(j)
    -    }
    -
    +
        for j := 7; j <= 9; j++ {
    +        fmt.Println(j)
    +    }
    @@ -111,12 +104,10 @@ the enclosing function.

    -
    -    for {
    -        fmt.Println("loop")
    -        break
    -    }
    -
    +
        for {
    +        fmt.Println("loop")
    +        break
    +    }
    @@ -128,15 +119,13 @@ the loop.

    -
    -    for n := 0; n <= 5; n++ {
    -        if n%2 == 0 {
    -            continue
    -        }
    -        fmt.Println(n)
    -    }
    -}
    -
    +
        for n := 0; n <= 5; n++ {
    +        if n%2 == 0 {
    +            continue
    +        }
    +        fmt.Println(n)
    +    }
    +}
    @@ -150,17 +139,17 @@ the loop.

    -
    $ go run for.go
    -1
    -2
    -3
    -7
    -8
    -9
    -loop
    -1
    -3
    -5
    +
    $ go run for.go
    +1
    +2
    +3
    +7
    +8
    +9
    +loop
    +1
    +3
    +5
    diff --git a/public/functions b/public/functions index 74e730246..87a3a044d 100644 --- a/public/functions +++ b/public/functions @@ -43,8 +43,7 @@ functions with a few different examples.

    -
    package main
    -
    +
    package main
    @@ -54,8 +53,7 @@ functions with a few different examples.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -67,9 +65,7 @@ their sum as an int.

    -
    -func plus(a int, b int) int {
    -
    +
    func plus(a int, b int) int {
    @@ -82,10 +78,8 @@ expression.

    -
    -    return a + b
    -}
    -
    +
        return a + b
    +}
    @@ -99,11 +93,9 @@ declares the type.

    -
    -func plusPlus(a, b, c int) int {
    -    return a + b + c
    -}
    -
    +
    func plusPlus(a, b, c int) int {
    +    return a + b + c
    +}
    @@ -113,8 +105,7 @@ declares the type.

    -
    func main() {
    -
    +
    func main() {
    @@ -126,10 +117,8 @@ declares the type.

    -
    -    res := plus(1, 2)
    -    fmt.Println("1+2 =", res)
    -
    +
        res := plus(1, 2)
    +    fmt.Println("1+2 =", res)
    @@ -139,10 +128,9 @@ declares the type.

    -
        res = plusPlus(1, 2, 3)
    -    fmt.Println("1+2+3 =", res)
    -}
    -
    +
        res = plusPlus(1, 2, 3)
    +    fmt.Println("1+2+3 =", res)
    +}
    @@ -156,9 +144,9 @@ declares the type.

    -
    $ go run functions.go 
    -1+2 = 3
    -1+2+3 = 6
    +
    $ go run functions.go 
    +1+2 = 3
    +1+2+3 = 6
    diff --git a/public/generics b/public/generics index 721f0f7fa..adee89770 100644 --- a/public/generics +++ b/public/generics @@ -43,8 +43,7 @@ -
    package main
    -
    +
    package main
    @@ -54,8 +53,7 @@ -
    import "fmt"
    -
    +
    import "fmt"
    @@ -73,15 +71,13 @@ restricted in any way (any is an alias for interface{} -
    -func MapKeys[K comparable, V any](m map[K]V) []K {
    -    r := make([]K, 0, len(m))
    -    for k := range m {
    -        r = append(r, k)
    -    }
    -    return r
    -}
    -
    +
    func MapKeys[K comparable, V any](m map[K]V) []K {
    +    r := make([]K, 0, len(m))
    +    for k := range m {
    +        r = append(r, k)
    +    }
    +    return r
    +}
    @@ -93,11 +89,9 @@ singly-linked list with values of any type.

    -
    -type List[T any] struct {
    -    head, tail *element[T]
    -}
    -
    +
    type List[T any] struct {
    +    head, tail *element[T]
    +}
    @@ -107,11 +101,10 @@ singly-linked list with values of any type.

    -
    type element[T any] struct {
    -    next *element[T]
    -    val  T
    -}
    -
    +
    type element[T any] struct {
    +    next *element[T]
    +    val  T
    +}
    @@ -124,17 +117,15 @@ parameters in place. The type is List[T], not List.

    -
    -func (lst *List[T]) Push(v T) {
    -    if lst.tail == nil {
    -        lst.head = &element[T]{val: v}
    -        lst.tail = lst.head
    -    } else {
    -        lst.tail.next = &element[T]{val: v}
    -        lst.tail = lst.tail.next
    -    }
    -}
    -
    +
    func (lst *List[T]) Push(v T) {
    +    if lst.tail == nil {
    +        lst.head = &element[T]{val: v}
    +        lst.tail = lst.head
    +    } else {
    +        lst.tail.next = &element[T]{val: v}
    +        lst.tail = lst.tail.next
    +    }
    +}
    @@ -144,14 +135,13 @@ parameters in place. The type is List[T], not List.

    -
    func (lst *List[T]) GetAll() []T {
    -    var elems []T
    -    for e := lst.head; e != nil; e = e.next {
    -        elems = append(elems, e.val)
    -    }
    -    return elems
    -}
    -
    +
    func (lst *List[T]) GetAll() []T {
    +    var elems []T
    +    for e := lst.head; e != nil; e = e.next {
    +        elems = append(elems, e.val)
    +    }
    +    return elems
    +}
    @@ -161,9 +151,8 @@ parameters in place. The type is List[T], not List.

    -
    func main() {
    -    var m = map[int]string{1: "2", 2: "4", 4: "8"}
    -
    +
    func main() {
    +    var m = map[int]string{1: "2", 2: "4", 4: "8"}
    @@ -178,9 +167,7 @@ automatically.

    -
    -    fmt.Println("keys:", MapKeys(m))
    -
    +
        fmt.Println("keys:", MapKeys(m))
    @@ -191,9 +178,7 @@ automatically.

    -
    -    _ = MapKeys[int, string](m)
    -
    +
        _ = MapKeys[int, string](m)
    @@ -203,13 +188,12 @@ automatically.

    -
        lst := List[int]{}
    -    lst.Push(10)
    -    lst.Push(13)
    -    lst.Push(23)
    -    fmt.Println("list:", lst.GetAll())
    -}
    -
    +
        lst := List[int]{}
    +    lst.Push(10)
    +    lst.Push(13)
    +    lst.Push(23)
    +    fmt.Println("list:", lst.GetAll())
    +}
    @@ -223,9 +207,9 @@ automatically.

    -
    $ go run generics.go
    -keys: [4 1 2]
    -list: [10 13 23]
    +
    $ go run generics.go
    +keys: [4 1 2]
    +list: [10 13 23]
    diff --git a/public/goroutines b/public/goroutines index 957edc6bd..6b16ea9d9 100644 --- a/public/goroutines +++ b/public/goroutines @@ -42,8 +42,7 @@ -
    package main
    -
    +
    package main
    @@ -53,11 +52,10 @@ -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -67,12 +65,11 @@ -
    func f(from string) {
    -    for i := 0; i < 3; i++ {
    -        fmt.Println(from, ":", i)
    -    }
    -}
    -
    +
    func f(from string) {
    +    for i := 0; i < 3; i++ {
    +        fmt.Println(from, ":", i)
    +    }
    +}
    @@ -82,8 +79,7 @@ -
    func main() {
    -
    +
    func main() {
    @@ -96,9 +92,7 @@ synchronously.

    -
    -    f("direct")
    -
    +
        f("direct")
    @@ -111,9 +105,7 @@ concurrently with the calling one.

    -
    -    go f("goroutine")
    -
    +
        go f("goroutine")
    @@ -125,11 +117,9 @@ function call.

    -
    -    go func(msg string) {
    -        fmt.Println(msg)
    -    }("going")
    -
    +
        go func(msg string) {
    +        fmt.Println(msg)
    +    }("going")
    @@ -142,11 +132,9 @@ separate goroutines now. Wait for them to finish -
    -    time.Sleep(time.Second)
    -    fmt.Println("done")
    -}
    -
    +
        time.Sleep(time.Second)
    +    fmt.Println("done")
    +}
    @@ -165,16 +153,15 @@ Go runtime.

    -
    -$ go run goroutines.go
    -direct : 0
    -direct : 1
    -direct : 2
    -goroutine : 0
    -going
    -goroutine : 1
    -goroutine : 2
    -done
    +
    $ go run goroutines.go
    +direct : 0
    +direct : 1
    +direct : 2
    +goroutine : 0
    +going
    +goroutine : 1
    +goroutine : 2
    +done
    diff --git a/public/hello-world b/public/hello-world index 6f28be427..83c5787fb 100644 --- a/public/hello-world +++ b/public/hello-world @@ -29,9 +29,7 @@ message. Here’s the full source code.

    -
    -package main
    -
    +
    package main
    @@ -41,8 +39,7 @@ message. Here’s the full source code.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -52,10 +49,9 @@ message. Here’s the full source code.

    -
    func main() {
    -    fmt.Println("hello world")
    -}
    -
    +
    func main() {
    +    fmt.Println("hello world")
    +}
    @@ -71,9 +67,8 @@ use go run.

    -
    -$ go run hello-world.go
    -hello world
    +
    $ go run hello-world.go
    +hello world
    @@ -85,10 +80,9 @@ binaries. We can do this using go build.

    -
    -$ go build hello-world.go
    -$ ls
    -hello-world    hello-world.go
    +
    $ go build hello-world.go
    +$ ls
    +hello-world    hello-world.go
    @@ -99,9 +93,8 @@ binaries. We can do this using go build.

    -
    -$ ./hello-world
    -hello world
    +
    $ ./hello-world
    +hello world
    diff --git a/public/http-client b/public/http-client index 763290b15..b693af7c2 100644 --- a/public/http-client +++ b/public/http-client @@ -35,9 +35,7 @@ HTTP requests.

    -
    -package main
    -
    +
    package main
    @@ -47,12 +45,11 @@ HTTP requests.

    -
    import (
    -    "bufio"
    -    "fmt"
    -    "net/http"
    -)
    -
    +
    import (
    +    "bufio"
    +    "fmt"
    +    "net/http"
    +)
    @@ -62,8 +59,7 @@ HTTP requests.

    -
    func main() {
    -
    +
    func main() {
    @@ -78,13 +74,11 @@ settings.

    -
    -    resp, err := http.Get("https://gobyexample.com")
    -    if err != nil {
    -        panic(err)
    -    }
    -    defer resp.Body.Close()
    -
    +
        resp, err := http.Get("https://gobyexample.com")
    +    if err != nil {
    +        panic(err)
    +    }
    +    defer resp.Body.Close()
    @@ -95,9 +89,7 @@ settings.

    -
    -    fmt.Println("Response status:", resp.Status)
    -
    +
        fmt.Println("Response status:", resp.Status)
    @@ -108,12 +100,10 @@ settings.

    -
    -    scanner := bufio.NewScanner(resp.Body)
    -    for i := 0; scanner.Scan() && i < 5; i++ {
    -        fmt.Println(scanner.Text())
    -    }
    -
    +
        scanner := bufio.NewScanner(resp.Body)
    +    for i := 0; scanner.Scan() && i < 5; i++ {
    +        fmt.Println(scanner.Text())
    +    }
    @@ -123,11 +113,10 @@ settings.

    -
        if err := scanner.Err(); err != nil {
    -        panic(err)
    -    }
    -}
    -
    +
        if err := scanner.Err(); err != nil {
    +        panic(err)
    +    }
    +}
    @@ -141,13 +130,13 @@ settings.

    -
    $ go run http-clients.go
    -Response status: 200 OK
    -<!DOCTYPE html>
    -<html>
    -  <head>
    -    <meta charset="utf-8">
    -    <title>Go by Example</title>
    +
    $ go run http-clients.go
    +Response status: 200 OK
    +<!DOCTYPE html>
    +<html>
    +  <head>
    +    <meta charset="utf-8">
    +    <title>Go by Example</title>
    diff --git a/public/http-server b/public/http-server index 70cdb544f..e2ecdc6eb 100644 --- a/public/http-server +++ b/public/http-server @@ -33,9 +33,7 @@ -
    -package main
    -
    +
    package main
    @@ -45,11 +43,10 @@ -
    import (
    -    "fmt"
    -    "net/http"
    -)
    -
    +
    import (
    +    "fmt"
    +    "net/http"
    +)
    @@ -64,9 +61,7 @@ on functions with the appropriate signature.

    -
    -func hello(w http.ResponseWriter, req *http.Request) {
    -
    +
    func hello(w http.ResponseWriter, req *http.Request) {
    @@ -81,10 +76,8 @@ HTTP response. Here our simple response is just -
    -    fmt.Fprintf(w, "hello\n")
    -}
    -
    +
        fmt.Fprintf(w, "hello\n")
    +}
    @@ -94,8 +87,7 @@ HTTP response. Here our simple response is just -
    func headers(w http.ResponseWriter, req *http.Request) {
    -
    +
    func headers(w http.ResponseWriter, req *http.Request) {
    @@ -108,14 +100,12 @@ headers and echoing them into the response body.

    -
    -    for name, headers := range req.Header {
    -        for _, h := range headers {
    -            fmt.Fprintf(w, "%v: %v\n", name, h)
    -        }
    -    }
    -}
    -
    +
        for name, headers := range req.Header {
    +        for _, h := range headers {
    +            fmt.Fprintf(w, "%v: %v\n", name, h)
    +        }
    +    }
    +}
    @@ -125,8 +115,7 @@ headers and echoing them into the response body.

    -
    func main() {
    -
    +
    func main() {
    @@ -140,10 +129,8 @@ takes a function as an argument.

    -
    -    http.HandleFunc("/hello", hello)
    -    http.HandleFunc("/headers", headers)
    -
    +
        http.HandleFunc("/hello", hello)
    +    http.HandleFunc("/headers", headers)
    @@ -156,10 +143,8 @@ router we’ve just set up.

    -
    -    http.ListenAndServe(":8090", nil)
    -}
    -
    +
        http.ListenAndServe(":8090", nil)
    +}
    @@ -174,8 +159,7 @@ router we’ve just set up.

    -
    -$ go run http-servers.go &
    +
    $ go run http-servers.go &
    @@ -186,9 +170,8 @@ router we’ve just set up.

    -
    -$ curl localhost:8090/hello
    -hello
    +
    $ curl localhost:8090/hello
    +hello
    diff --git a/public/if-else b/public/if-else index ec12be9e1..c394864a5 100644 --- a/public/if-else +++ b/public/if-else @@ -43,8 +43,7 @@ straight-forward.

    -
    package main
    -
    +
    package main
    @@ -54,8 +53,7 @@ straight-forward.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -65,8 +63,7 @@ straight-forward.

    -
    func main() {
    -
    +
    func main() {
    @@ -77,13 +74,11 @@ straight-forward.

    -
    -    if 7%2 == 0 {
    -        fmt.Println("7 is even")
    -    } else {
    -        fmt.Println("7 is odd")
    -    }
    -
    +
        if 7%2 == 0 {
    +        fmt.Println("7 is even")
    +    } else {
    +        fmt.Println("7 is odd")
    +    }
    @@ -94,11 +89,9 @@ straight-forward.

    -
    -    if 8%4 == 0 {
    -        fmt.Println("8 is divisible by 4")
    -    }
    -
    +
        if 8%4 == 0 {
    +        fmt.Println("8 is divisible by 4")
    +    }
    @@ -111,16 +104,14 @@ and all subsequent branches.

    -
    -    if num := 9; num < 0 {
    -        fmt.Println(num, "is negative")
    -    } else if num < 10 {
    -        fmt.Println(num, "has 1 digit")
    -    } else {
    -        fmt.Println(num, "has multiple digits")
    -    }
    -}
    -
    +
        if num := 9; num < 0 {
    +        fmt.Println(num, "is negative")
    +    } else if num < 10 {
    +        fmt.Println(num, "has 1 digit")
    +    } else {
    +        fmt.Println(num, "has multiple digits")
    +    }
    +}
    @@ -146,10 +137,10 @@ in Go, but that the braces are required.

    -
    $ go run if-else.go 
    -7 is odd
    -8 is divisible by 4
    -9 has 1 digit
    +
    $ go run if-else.go 
    +7 is odd
    +8 is divisible by 4
    +9 has 1 digit
    diff --git a/public/interfaces b/public/interfaces index 36cef1b21..fd3b13166 100644 --- a/public/interfaces +++ b/public/interfaces @@ -43,8 +43,7 @@ signatures.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ signatures.

    -
    import (
    -    "fmt"
    -    "math"
    -)
    -
    +
    import (
    +    "fmt"
    +    "math"
    +)
    @@ -69,12 +67,10 @@ signatures.

    -
    -type geometry interface {
    -    area() float64
    -    perim() float64
    -}
    -
    +
    type geometry interface {
    +    area() float64
    +    perim() float64
    +}
    @@ -86,14 +82,12 @@ signatures.

    -
    -type rect struct {
    -    width, height float64
    -}
    -type circle struct {
    -    radius float64
    -}
    -
    +
    type rect struct {
    +    width, height float64
    +}
    +type circle struct {
    +    radius float64
    +}
    @@ -106,14 +100,12 @@ implement geometry on rects.

    -
    -func (r rect) area() float64 {
    -    return r.width * r.height
    -}
    -func (r rect) perim() float64 {
    -    return 2*r.width + 2*r.height
    -}
    -
    +
    func (r rect) area() float64 {
    +    return r.width * r.height
    +}
    +func (r rect) perim() float64 {
    +    return 2*r.width + 2*r.height
    +}
    @@ -124,14 +116,12 @@ implement geometry on rects.

    -
    -func (c circle) area() float64 {
    -    return math.Pi * c.radius * c.radius
    -}
    -func (c circle) perim() float64 {
    -    return 2 * math.Pi * c.radius
    -}
    -
    +
    func (c circle) area() float64 {
    +    return math.Pi * c.radius * c.radius
    +}
    +func (c circle) perim() float64 {
    +    return 2 * math.Pi * c.radius
    +}
    @@ -145,13 +135,11 @@ to work on any geometry.

    -
    -func measure(g geometry) {
    -    fmt.Println(g)
    -    fmt.Println(g.area())
    -    fmt.Println(g.perim())
    -}
    -
    +
    func measure(g geometry) {
    +    fmt.Println(g)
    +    fmt.Println(g.area())
    +    fmt.Println(g.perim())
    +}
    @@ -161,10 +149,9 @@ to work on any geometry.

    -
    func main() {
    -    r := rect{width: 3, height: 4}
    -    c := circle{radius: 5}
    -
    +
    func main() {
    +    r := rect{width: 3, height: 4}
    +    c := circle{radius: 5}
    @@ -178,11 +165,9 @@ these structs as arguments to measure.

    -
    -    measure(r)
    -    measure(c)
    -}
    -
    +
        measure(r)
    +    measure(c)
    +}
    @@ -196,13 +181,13 @@ these structs as arguments to measure.

    -
    $ go run interfaces.go
    -{3 4}
    -12
    -14
    -{5}
    -78.53981633974483
    -31.41592653589793
    +
    $ go run interfaces.go
    +{3 4}
    +12
    +14
    +{5}
    +78.53981633974483
    +31.41592653589793
    diff --git a/public/json b/public/json index f1d7040e3..e33a3ef61 100644 --- a/public/json +++ b/public/json @@ -44,8 +44,7 @@ data types.

    -
    package main
    -
    +
    package main
    @@ -55,12 +54,11 @@ data types.

    -
    import (
    -    "encoding/json"
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "encoding/json"
    +    "fmt"
    +    "os"
    +)
    @@ -72,12 +70,10 @@ decoding of custom types below.

    -
    -type response1 struct {
    -    Page   int
    -    Fruits []string
    -}
    -
    +
    type response1 struct {
    +    Page   int
    +    Fruits []string
    +}
    @@ -89,12 +85,10 @@ Fields must start with capital letters to be exported.

    -
    -type response2 struct {
    -    Page   int      `json:"page"`
    -    Fruits []string `json:"fruits"`
    -}
    -
    +
    type response2 struct {
    +    Page   int      `json:"page"`
    +    Fruits []string `json:"fruits"`
    +}
    @@ -104,8 +98,7 @@ Fields must start with capital letters to be exported.

    -
    func main() {
    -
    +
    func main() {
    @@ -118,10 +111,8 @@ values.

    -
    -    bolB, _ := json.Marshal(true)
    -    fmt.Println(string(bolB))
    -
    +
        bolB, _ := json.Marshal(true)
    +    fmt.Println(string(bolB))
    @@ -131,9 +122,8 @@ values.

    -
        intB, _ := json.Marshal(1)
    -    fmt.Println(string(intB))
    -
    +
        intB, _ := json.Marshal(1)
    +    fmt.Println(string(intB))
    @@ -143,9 +133,8 @@ values.

    -
        fltB, _ := json.Marshal(2.34)
    -    fmt.Println(string(fltB))
    -
    +
        fltB, _ := json.Marshal(2.34)
    +    fmt.Println(string(fltB))
    @@ -155,9 +144,8 @@ values.

    -
        strB, _ := json.Marshal("gopher")
    -    fmt.Println(string(strB))
    -
    +
        strB, _ := json.Marshal("gopher")
    +    fmt.Println(string(strB))
    @@ -169,11 +157,9 @@ to JSON arrays and objects as you’d expect.

    -
    -    slcD := []string{"apple", "peach", "pear"}
    -    slcB, _ := json.Marshal(slcD)
    -    fmt.Println(string(slcB))
    -
    +
        slcD := []string{"apple", "peach", "pear"}
    +    slcB, _ := json.Marshal(slcD)
    +    fmt.Println(string(slcB))
    @@ -183,10 +169,9 @@ to JSON arrays and objects as you’d expect.

    -
        mapD := map[string]int{"apple": 5, "lettuce": 7}
    -    mapB, _ := json.Marshal(mapD)
    -    fmt.Println(string(mapB))
    -
    +
        mapD := map[string]int{"apple": 5, "lettuce": 7}
    +    mapB, _ := json.Marshal(mapD)
    +    fmt.Println(string(mapB))
    @@ -200,13 +185,11 @@ use those names as the JSON keys.

    -
    -    res1D := &response1{
    -        Page:   1,
    -        Fruits: []string{"apple", "peach", "pear"}}
    -    res1B, _ := json.Marshal(res1D)
    -    fmt.Println(string(res1B))
    -
    +
        res1D := &response1{
    +        Page:   1,
    +        Fruits: []string{"apple", "peach", "pear"}}
    +    res1B, _ := json.Marshal(res1D)
    +    fmt.Println(string(res1B))
    @@ -220,13 +203,11 @@ of such tags.

    -
    -    res2D := &response2{
    -        Page:   1,
    -        Fruits: []string{"apple", "peach", "pear"}}
    -    res2B, _ := json.Marshal(res2D)
    -    fmt.Println(string(res2B))
    -
    +
        res2D := &response2{
    +        Page:   1,
    +        Fruits: []string{"apple", "peach", "pear"}}
    +    res2B, _ := json.Marshal(res2D)
    +    fmt.Println(string(res2B))
    @@ -239,9 +220,7 @@ structure.

    -
    -    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    -
    +
        byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    @@ -255,9 +234,7 @@ to arbitrary data types.

    -
    -    var dat map[string]interface{}
    -
    +
        var dat map[string]interface{}
    @@ -269,12 +246,10 @@ associated errors.

    -
    -    if err := json.Unmarshal(byt, &dat); err != nil {
    -        panic(err)
    -    }
    -    fmt.Println(dat)
    -
    +
        if err := json.Unmarshal(byt, &dat); err != nil {
    +        panic(err)
    +    }
    +    fmt.Println(dat)
    @@ -288,10 +263,8 @@ the expected float64 type.

    -
    -    num := dat["num"].(float64)
    -    fmt.Println(num)
    -
    +
        num := dat["num"].(float64)
    +    fmt.Println(num)
    @@ -303,11 +276,9 @@ conversions.

    -
    -    strs := dat["strs"].([]interface{})
    -    str1 := strs[0].(string)
    -    fmt.Println(str1)
    -
    +
        strs := dat["strs"].([]interface{})
    +    str1 := strs[0].(string)
    +    fmt.Println(str1)
    @@ -322,13 +293,11 @@ data.

    -
    -    str := `{"page": 1, "fruits": ["apple", "peach"]}`
    -    res := response2{}
    -    json.Unmarshal([]byte(str), &res)
    -    fmt.Println(res)
    -    fmt.Println(res.Fruits[0])
    -
    +
        str := `{"page": 1, "fruits": ["apple", "peach"]}`
    +    res := response2{}
    +    json.Unmarshal([]byte(str), &res)
    +    fmt.Println(res)
    +    fmt.Println(res.Fruits[0])
    @@ -343,12 +312,10 @@ stream JSON encodings directly to os.Writers like -
    -    enc := json.NewEncoder(os.Stdout)
    -    d := map[string]int{"apple": 5, "lettuce": 7}
    -    enc.Encode(d)
    -}
    -
    +
        enc := json.NewEncoder(os.Stdout)
    +    d := map[string]int{"apple": 5, "lettuce": 7}
    +    enc.Encode(d)
    +}
    @@ -362,21 +329,21 @@ stream JSON encodings directly to os.Writers like -
    $ go run json.go
    -true
    -1
    -2.34
    -"gopher"
    -["apple","peach","pear"]
    -{"apple":5,"lettuce":7}
    -{"Page":1,"Fruits":["apple","peach","pear"]}
    -{"page":1,"fruits":["apple","peach","pear"]}
    -map[num:6.13 strs:[a b]]
    -6.13
    -a
    -{1 [apple peach]}
    -apple
    -{"apple":5,"lettuce":7}
    +
    $ go run json.go
    +true
    +1
    +2.34
    +"gopher"
    +["apple","peach","pear"]
    +{"apple":5,"lettuce":7}
    +{"Page":1,"Fruits":["apple","peach","pear"]}
    +{"page":1,"fruits":["apple","peach","pear"]}
    +map[num:6.13 strs:[a b]]
    +6.13
    +a
    +{1 [apple peach]}
    +apple
    +{"apple":5,"lettuce":7}
    diff --git a/public/line-filters b/public/line-filters index 3fcb704a1..4dc0a8714 100644 --- a/public/line-filters +++ b/public/line-filters @@ -48,9 +48,7 @@ pattern to write your own Go line filters.

    -
    -package main
    -
    +
    package main
    @@ -60,13 +58,12 @@ pattern to write your own Go line filters.

    -
    import (
    -    "bufio"
    -    "fmt"
    -    "os"
    -    "strings"
    -)
    -
    +
    import (
    +    "bufio"
    +    "fmt"
    +    "os"
    +    "strings"
    +)
    @@ -76,8 +73,7 @@ pattern to write your own Go line filters.

    -
    func main() {
    -
    +
    func main() {
    @@ -91,9 +87,7 @@ the next line in the default scanner.

    -
    -    scanner := bufio.NewScanner(os.Stdin)
    -
    +
        scanner := bufio.NewScanner(os.Stdin)
    @@ -105,8 +99,7 @@ from the input.

    -
        for scanner.Scan() {
    -
    +
        for scanner.Scan() {
    @@ -116,8 +109,7 @@ from the input.

    -
            ucl := strings.ToUpper(scanner.Text())
    -
    +
            ucl := strings.ToUpper(scanner.Text())
    @@ -128,10 +120,8 @@ from the input.

    -
    -        fmt.Println(ucl)
    -    }
    -
    +
            fmt.Println(ucl)
    +    }
    @@ -143,13 +133,11 @@ expected and not reported by Scan as an error.

    -
    -    if err := scanner.Err(); err != nil {
    -        fmt.Fprintln(os.Stderr, "error:", err)
    -        os.Exit(1)
    -    }
    -}
    -
    +
        if err := scanner.Err(); err != nil {
    +        fmt.Fprintln(os.Stderr, "error:", err)
    +        os.Exit(1)
    +    }
    +}
    @@ -165,9 +153,8 @@ lowercase lines.

    -
    -$ echo 'hello'   > /tmp/lines
    -$ echo 'filter' >> /tmp/lines
    +
    $ echo 'hello'   > /tmp/lines
    +$ echo 'filter' >> /tmp/lines
    @@ -178,10 +165,9 @@ lowercase lines.

    -
    -$ cat /tmp/lines | go run line-filters.go
    -HELLO
    -FILTER
    +
    $ cat /tmp/lines | go run line-filters.go
    +HELLO
    +FILTER
    diff --git a/public/maps b/public/maps index b3e0fe8ea..94427d5f3 100644 --- a/public/maps +++ b/public/maps @@ -43,8 +43,7 @@ -
    package main
    -
    +
    package main
    @@ -54,8 +53,7 @@ -
    import "fmt"
    -
    +
    import "fmt"
    @@ -65,8 +63,7 @@ -
    func main() {
    -
    +
    func main() {
    @@ -78,9 +75,7 @@ -
    -    m := make(map[string]int)
    -
    +
        m := make(map[string]int)
    @@ -92,10 +87,8 @@ syntax.

    -
    -    m["k1"] = 7
    -    m["k2"] = 13
    -
    +
        m["k1"] = 7
    +    m["k2"] = 13
    @@ -107,9 +100,7 @@ its key/value pairs.

    -
    -    fmt.Println("map:", m)
    -
    +
        fmt.Println("map:", m)
    @@ -120,10 +111,8 @@ its key/value pairs.

    -
    -    v1 := m["k1"]
    -    fmt.Println("v1:", v1)
    -
    +
        v1 := m["k1"]
    +    fmt.Println("v1:", v1)
    @@ -136,10 +125,8 @@ value type is returned.

    -
    -    v3 := m["k3"]
    -    fmt.Println("v3:", v3)
    -
    +
        v3 := m["k3"]
    +    fmt.Println("v3:", v3)
    @@ -151,9 +138,7 @@ pairs when called on a map.

    -
    -    fmt.Println("len:", len(m))
    -
    +
        fmt.Println("len:", len(m))
    @@ -165,10 +150,8 @@ a map.

    -
    -    delete(m, "k2")
    -    fmt.Println("map:", m)
    -
    +
        delete(m, "k2")
    +    fmt.Println("map:", m)
    @@ -180,10 +163,8 @@ the clear builtin.

    -
    -    clear(m)
    -    fmt.Println("map:", m)
    -
    +
        clear(m)
    +    fmt.Println("map:", m)
    @@ -200,10 +181,8 @@ itself, so we ignored it with the blank identifier -
    -    _, prs := m["k2"]
    -    fmt.Println("prs:", prs)
    -
    +
        _, prs := m["k2"]
    +    fmt.Println("prs:", prs)
    @@ -215,11 +194,9 @@ the same line with this syntax.

    -
    -    n := map[string]int{"foo": 1, "bar": 2}
    -    fmt.Println("map:", n)
    -}
    -
    +
        n := map[string]int{"foo": 1, "bar": 2}
    +    fmt.Println("map:", n)
    +}
    @@ -235,16 +212,15 @@ printed with fmt.Println.

    -
    -$ go run maps.go 
    -map: map[k1:7 k2:13]
    -v1: 7
    -v3: 0
    -len: 2
    -map: map[k1:7]
    -map: map[]
    -prs: false
    -map: map[bar:2 foo:1]
    +
    $ go run maps.go 
    +map: map[k1:7 k2:13]
    +v1: 7
    +v3: 0
    +len: 2
    +map: map[k1:7]
    +map: map[]
    +prs: false
    +map: map[bar:2 foo:1]
    diff --git a/public/methods b/public/methods index b04b06334..70d36d037 100644 --- a/public/methods +++ b/public/methods @@ -42,8 +42,7 @@ -
    package main
    -
    +
    package main
    @@ -53,8 +52,7 @@ -
    import "fmt"
    -
    +
    import "fmt"
    @@ -64,10 +62,9 @@ -
    type rect struct {
    -    width, height int
    -}
    -
    +
    type rect struct {
    +    width, height int
    +}
    @@ -78,11 +75,9 @@ -
    -func (r *rect) area() int {
    -    return r.width * r.height
    -}
    -
    +
    func (r *rect) area() int {
    +    return r.width * r.height
    +}
    @@ -94,11 +89,9 @@ receiver types. Here’s an example of a value receiver.

    -
    -func (r rect) perim() int {
    -    return 2*r.width + 2*r.height
    -}
    -
    +
    func (r rect) perim() int {
    +    return 2*r.width + 2*r.height
    +}
    @@ -108,9 +101,8 @@ receiver types. Here’s an example of a value receiver.

    -
    func main() {
    -    r := rect{width: 10, height: 5}
    -
    +
    func main() {
    +    r := rect{width: 10, height: 5}
    @@ -121,10 +113,8 @@ receiver types. Here’s an example of a value receiver.

    -
    -    fmt.Println("area: ", r.area())
    -    fmt.Println("perim:", r.perim())
    -
    +
        fmt.Println("area: ", r.area())
    +    fmt.Println("perim:", r.perim())
    @@ -139,12 +129,10 @@ receiving struct.

    -
    -    rp := &r
    -    fmt.Println("area: ", rp.area())
    -    fmt.Println("perim:", rp.perim())
    -}
    -
    +
        rp := &r
    +    fmt.Println("area: ", rp.area())
    +    fmt.Println("perim:", rp.perim())
    +}
    @@ -158,11 +146,11 @@ receiving struct.

    -
    $ go run methods.go 
    -area:  50
    -perim: 30
    -area:  50
    -perim: 30
    +
    $ go run methods.go 
    +area:  50
    +perim: 30
    +area:  50
    +perim: 30
    diff --git a/public/multiple-return-values b/public/multiple-return-values index 9fbc33d09..7f6d6d4bd 100644 --- a/public/multiple-return-values +++ b/public/multiple-return-values @@ -44,8 +44,7 @@ to return both result and error values from a function.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ to return both result and error values from a function.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -68,11 +66,9 @@ the function returns 2 ints.

    -
    -func vals() (int, int) {
    -    return 3, 7
    -}
    -
    +
    func vals() (int, int) {
    +    return 3, 7
    +}
    @@ -82,8 +78,7 @@ the function returns 2 ints.

    -
    func main() {
    -
    +
    func main() {
    @@ -95,11 +90,9 @@ call with multiple assignment.

    -
    -    a, b := vals()
    -    fmt.Println(a)
    -    fmt.Println(b)
    -
    +
        a, b := vals()
    +    fmt.Println(a)
    +    fmt.Println(b)
    @@ -111,11 +104,9 @@ use the blank identifier _.

    -
    -    _, c := vals()
    -    fmt.Println(c)
    -}
    -
    +
        _, c := vals()
    +    fmt.Println(c)
    +}
    @@ -129,10 +120,10 @@ use the blank identifier _.

    -
    $ go run multiple-return-values.go
    -3
    -7
    -7
    +
    $ go run multiple-return-values.go
    +3
    +7
    +7
    diff --git a/public/mutexes b/public/mutexes index 9dc784d41..b88885672 100644 --- a/public/mutexes +++ b/public/mutexes @@ -45,8 +45,7 @@ to safely access data across multiple goroutines.

    -
    package main
    -
    +
    package main
    @@ -56,11 +55,10 @@ to safely access data across multiple goroutines.

    -
    import (
    -    "fmt"
    -    "sync"
    -)
    -
    +
    import (
    +    "fmt"
    +    "sync"
    +)
    @@ -76,12 +74,10 @@ pointer.

    -
    -type Container struct {
    -    mu       sync.Mutex
    -    counters map[string]int
    -}
    -
    +
    type Container struct {
    +    mu       sync.Mutex
    +    counters map[string]int
    +}
    @@ -94,8 +90,7 @@ statement.

    -
    func (c *Container) inc(name string) {
    -
    +
    func (c *Container) inc(name string) {
    @@ -105,11 +100,10 @@ statement.

    -
        c.mu.Lock()
    -    defer c.mu.Unlock()
    -    c.counters[name]++
    -}
    -
    +
        c.mu.Lock()
    +    defer c.mu.Unlock()
    +    c.counters[name]++
    +}
    @@ -121,9 +115,8 @@ initialization is required here.

    -
    func main() {
    -    c := Container{
    -
    +
    func main() {
    +    c := Container{
    @@ -133,9 +126,8 @@ initialization is required here.

    -
            counters: map[string]int{"a": 0, "b": 0},
    -    }
    -
    +
            counters: map[string]int{"a": 0, "b": 0},
    +    }
    @@ -145,8 +137,7 @@ initialization is required here.

    -
        var wg sync.WaitGroup
    -
    +
        var wg sync.WaitGroup
    @@ -158,14 +149,12 @@ in a loop.

    -
    -    doIncrement := func(name string, n int) {
    -        for i := 0; i < n; i++ {
    -            c.inc(name)
    -        }
    -        wg.Done()
    -    }
    -
    +
        doIncrement := func(name string, n int) {
    +        for i := 0; i < n; i++ {
    +            c.inc(name)
    +        }
    +        wg.Done()
    +    }
    @@ -178,12 +167,10 @@ and two of them access the same counter.

    -
    -    wg.Add(3)
    -    go doIncrement("a", 10000)
    -    go doIncrement("a", 10000)
    -    go doIncrement("b", 10000)
    -
    +
        wg.Add(3)
    +    go doIncrement("a", 10000)
    +    go doIncrement("a", 10000)
    +    go doIncrement("b", 10000)
    @@ -194,11 +181,9 @@ and two of them access the same counter.

    -
    -    wg.Wait()
    -    fmt.Println(c.counters)
    -}
    -
    +
        wg.Wait()
    +    fmt.Println(c.counters)
    +}
    @@ -214,9 +199,8 @@ updated as expected.

    -
    -$ go run mutexes.go
    -map[a:20000 b:10000]
    +
    $ go run mutexes.go
    +map[a:20000 b:10000]
    diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations index 08d4bd627..4e70d05b6 100644 --- a/public/non-blocking-channel-operations +++ b/public/non-blocking-channel-operations @@ -45,8 +45,7 @@ non-blocking multi-way selects.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ non-blocking multi-way selects.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -67,10 +65,9 @@ non-blocking multi-way selects.

    -
    func main() {
    -    messages := make(chan string)
    -    signals := make(chan bool)
    -
    +
    func main() {
    +    messages := make(chan string)
    +    signals := make(chan bool)
    @@ -84,14 +81,12 @@ it will immediately take the default case.

    -
    -    select {
    -    case msg := <-messages:
    -        fmt.Println("received message", msg)
    -    default:
    -        fmt.Println("no message received")
    -    }
    -
    +
        select {
    +    case msg := <-messages:
    +        fmt.Println("received message", msg)
    +    default:
    +        fmt.Println("no message received")
    +    }
    @@ -105,15 +100,13 @@ Therefore the default case is selected.

    -
    -    msg := "hi"
    -    select {
    -    case messages <- msg:
    -        fmt.Println("sent message", msg)
    -    default:
    -        fmt.Println("no message sent")
    -    }
    -
    +
        msg := "hi"
    +    select {
    +    case messages <- msg:
    +        fmt.Println("sent message", msg)
    +    default:
    +        fmt.Println("no message sent")
    +    }
    @@ -127,17 +120,15 @@ on both messages and signals.

    -
    -    select {
    -    case msg := <-messages:
    -        fmt.Println("received message", msg)
    -    case sig := <-signals:
    -        fmt.Println("received signal", sig)
    -    default:
    -        fmt.Println("no activity")
    -    }
    -}
    -
    +
        select {
    +    case msg := <-messages:
    +        fmt.Println("received message", msg)
    +    case sig := <-signals:
    +        fmt.Println("received signal", sig)
    +    default:
    +        fmt.Println("no activity")
    +    }
    +}
    @@ -151,10 +142,10 @@ on both messages and signals.

    -
    $ go run non-blocking-channel-operations.go 
    -no message received
    -no message sent
    -no activity
    +
    $ go run non-blocking-channel-operations.go 
    +no message received
    +no message sent
    +no activity
    diff --git a/public/number-parsing b/public/number-parsing index af3d1d405..9bebcd3ec 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -43,8 +43,7 @@ in many programs; here’s how to do it in Go.

    -
    package main
    -
    +
    package main
    @@ -56,12 +55,10 @@ parsing.

    -
    -import (
    -    "fmt"
    -    "strconv"
    -)
    -
    +
    import (
    +    "fmt"
    +    "strconv"
    +)
    @@ -71,8 +68,7 @@ parsing.

    -
    func main() {
    -
    +
    func main() {
    @@ -84,10 +80,8 @@ precision to parse.

    -
    -    f, _ := strconv.ParseFloat("1.234", 64)
    -    fmt.Println(f)
    -
    +
        f, _ := strconv.ParseFloat("1.234", 64)
    +    fmt.Println(f)
    @@ -100,10 +94,8 @@ bits.

    -
    -    i, _ := strconv.ParseInt("123", 0, 64)
    -    fmt.Println(i)
    -
    +
        i, _ := strconv.ParseInt("123", 0, 64)
    +    fmt.Println(i)
    @@ -114,10 +106,8 @@ bits.

    -
    -    d, _ := strconv.ParseInt("0x1c8", 0, 64)
    -    fmt.Println(d)
    -
    +
        d, _ := strconv.ParseInt("0x1c8", 0, 64)
    +    fmt.Println(d)
    @@ -128,10 +118,8 @@ bits.

    -
    -    u, _ := strconv.ParseUint("789", 0, 64)
    -    fmt.Println(u)
    -
    +
        u, _ := strconv.ParseUint("789", 0, 64)
    +    fmt.Println(u)
    @@ -143,10 +131,8 @@ bits.

    -
    -    k, _ := strconv.Atoi("135")
    -    fmt.Println(k)
    -
    +
        k, _ := strconv.Atoi("135")
    +    fmt.Println(k)
    @@ -157,11 +143,9 @@ bits.

    -
    -    _, e := strconv.Atoi("wat")
    -    fmt.Println(e)
    -}
    -
    +
        _, e := strconv.Atoi("wat")
    +    fmt.Println(e)
    +}
    @@ -175,13 +159,13 @@ bits.

    -
    $ go run number-parsing.go 
    -1.234
    -123
    -456
    -789
    -135
    -strconv.ParseInt: parsing "wat": invalid syntax
    +
    $ go run number-parsing.go 
    +1.234
    +123
    +456
    +789
    +135
    +strconv.ParseInt: parsing "wat": invalid syntax
    diff --git a/public/panic b/public/panic index a93770ccd..08636d8ff 100644 --- a/public/panic +++ b/public/panic @@ -45,8 +45,7 @@ aren’t prepared to handle gracefully.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ aren’t prepared to handle gracefully.

    -
    import "os"
    -
    +
    import "os"
    @@ -67,8 +65,7 @@ aren’t prepared to handle gracefully.

    -
    func main() {
    -
    +
    func main() {
    @@ -81,9 +78,7 @@ site designed to panic.

    -
    -    panic("a problem")
    -
    +
        panic("a problem")
    @@ -97,13 +92,11 @@ returns an error value that we don’t know how to -
    -    _, err := os.Create("/tmp/file")
    -    if err != nil {
    -        panic(err)
    -    }
    -}
    -
    +
        _, err := os.Create("/tmp/file")
    +    if err != nil {
    +        panic(err)
    +    }
    +}
    @@ -134,9 +127,8 @@ the first panic out.

    -
    -$ go run panic.go
    -panic: a problem
    +
    $ go run panic.go
    +panic: a problem
    @@ -146,11 +138,11 @@ the first panic out.

    -
    goroutine 1 [running]:
    -main.main()
    -    /.../panic.go:12 +0x47
    -...
    -exit status 2
    +
    goroutine 1 [running]:
    +main.main()
    +    /.../panic.go:12 +0x47
    +...
    +exit status 2
    diff --git a/public/pointers b/public/pointers index b57507ada..cbb64a885 100644 --- a/public/pointers +++ b/public/pointers @@ -44,8 +44,7 @@ within your program.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ within your program.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -71,11 +69,9 @@ from the one in the calling function.

    -
    -func zeroval(ival int) {
    -    ival = 0
    -}
    -
    +
    func zeroval(ival int) {
    +    ival = 0
    +}
    @@ -91,11 +87,9 @@ value at the referenced address.

    -
    -func zeroptr(iptr *int) {
    -    *iptr = 0
    -}
    -
    +
    func zeroptr(iptr *int) {
    +    *iptr = 0
    +}
    @@ -105,10 +99,9 @@ value at the referenced address.

    -
    func main() {
    -    i := 1
    -    fmt.Println("initial:", i)
    -
    +
    func main() {
    +    i := 1
    +    fmt.Println("initial:", i)
    @@ -118,9 +111,8 @@ value at the referenced address.

    -
        zeroval(i)
    -    fmt.Println("zeroval:", i)
    -
    +
        zeroval(i)
    +    fmt.Println("zeroval:", i)
    @@ -132,10 +124,8 @@ i.e. a pointer to i.

    -
    -    zeroptr(&i)
    -    fmt.Println("zeroptr:", i)
    -
    +
        zeroptr(&i)
    +    fmt.Println("zeroptr:", i)
    @@ -146,10 +136,8 @@ i.e. a pointer to i.

    -
    -    fmt.Println("pointer:", &i)
    -}
    -
    +
        fmt.Println("pointer:", &i)
    +}
    @@ -166,12 +154,11 @@ the memory address for that variable.

    -
    -$ go run pointers.go
    -initial: 1
    -zeroval: 1
    -zeroptr: 0
    -pointer: 0x42131100
    +
    $ go run pointers.go
    +initial: 1
    +zeroval: 1
    +zeroptr: 0
    +pointer: 0x42131100
    diff --git a/public/random-numbers b/public/random-numbers index c1571e271..5b0a95f16 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -44,8 +44,7 @@ generation.

    -
    package main
    -
    +
    package main
    @@ -55,12 +54,11 @@ generation.

    -
    import (
    -    "fmt"
    -    "math/rand"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "math/rand"
    +    "time"
    +)
    @@ -70,8 +68,7 @@ generation.

    -
    func main() {
    -
    +
    func main() {
    @@ -83,11 +80,9 @@ generation.

    -
    -    fmt.Print(rand.Intn(100), ",")
    -    fmt.Print(rand.Intn(100))
    -    fmt.Println()
    -
    +
        fmt.Print(rand.Intn(100), ",")
    +    fmt.Print(rand.Intn(100))
    +    fmt.Println()
    @@ -99,9 +94,7 @@ generation.

    -
    -    fmt.Println(rand.Float64())
    -
    +
        fmt.Println(rand.Float64())
    @@ -113,11 +106,9 @@ other ranges, for example 5.0 <= f' < 10.0.

    -
    -    fmt.Print((rand.Float64()*5)+5, ",")
    -    fmt.Print((rand.Float64() * 5) + 5)
    -    fmt.Println()
    -
    +
        fmt.Print((rand.Float64()*5)+5, ",")
    +    fmt.Print((rand.Float64() * 5) + 5)
    +    fmt.Println()
    @@ -132,10 +123,8 @@ intend to be secret; use crypto/rand for those.

    -
    -    s1 := rand.NewSource(time.Now().UnixNano())
    -    r1 := rand.New(s1)
    -
    +
        s1 := rand.NewSource(time.Now().UnixNano())
    +    r1 := rand.New(s1)
    @@ -147,11 +136,9 @@ functions on the rand package.

    -
    -    fmt.Print(r1.Intn(100), ",")
    -    fmt.Print(r1.Intn(100))
    -    fmt.Println()
    -
    +
        fmt.Print(r1.Intn(100), ",")
    +    fmt.Print(r1.Intn(100))
    +    fmt.Println()
    @@ -163,18 +150,16 @@ produces the same sequence of random numbers.

    -
    -    s2 := rand.NewSource(42)
    -    r2 := rand.New(s2)
    -    fmt.Print(r2.Intn(100), ",")
    -    fmt.Print(r2.Intn(100))
    -    fmt.Println()
    -    s3 := rand.NewSource(42)
    -    r3 := rand.New(s3)
    -    fmt.Print(r3.Intn(100), ",")
    -    fmt.Print(r3.Intn(100))
    -}
    -
    +
        s2 := rand.NewSource(42)
    +    r2 := rand.New(s2)
    +    fmt.Print(r2.Intn(100), ",")
    +    fmt.Print(r2.Intn(100))
    +    fmt.Println()
    +    s3 := rand.NewSource(42)
    +    r3 := rand.New(s3)
    +    fmt.Print(r3.Intn(100), ",")
    +    fmt.Print(r3.Intn(100))
    +}
    @@ -193,14 +178,13 @@ playground is implemented.

    -
    -$ go run random-numbers.go
    -81,87
    -0.6645600532184904
    -7.123187485356329,8.434115364335547
    -0,28
    -5,87
    -5,87
    +
    $ go run random-numbers.go
    +81,87
    +0.6645600532184904
    +7.123187485356329,8.434115364335547
    +0,28
    +5,87
    +5,87
    diff --git a/public/range b/public/range index 5259ac7f3..3c83d606a 100644 --- a/public/range +++ b/public/range @@ -44,8 +44,7 @@ of the data structures we’ve already learned.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ of the data structures we’ve already learned.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -66,8 +64,7 @@ of the data structures we’ve already learned.

    -
    func main() {
    -
    +
    func main() {
    @@ -79,14 +76,12 @@ Arrays work like this too.

    -
    -    nums := []int{2, 3, 4}
    -    sum := 0
    -    for _, num := range nums {
    -        sum += num
    -    }
    -    fmt.Println("sum:", sum)
    -
    +
        nums := []int{2, 3, 4}
    +    sum := 0
    +    for _, num := range nums {
    +        sum += num
    +    }
    +    fmt.Println("sum:", sum)
    @@ -101,13 +96,11 @@ the indexes though.

    -
    -    for i, num := range nums {
    -        if num == 3 {
    -            fmt.Println("index:", i)
    -        }
    -    }
    -
    +
        for i, num := range nums {
    +        if num == 3 {
    +            fmt.Println("index:", i)
    +        }
    +    }
    @@ -118,12 +111,10 @@ the indexes though.

    -
    -    kvs := map[string]string{"a": "apple", "b": "banana"}
    -    for k, v := range kvs {
    -        fmt.Printf("%s -> %s\n", k, v)
    -    }
    -
    +
        kvs := map[string]string{"a": "apple", "b": "banana"}
    +    for k, v := range kvs {
    +        fmt.Printf("%s -> %s\n", k, v)
    +    }
    @@ -134,11 +125,9 @@ the indexes though.

    -
    -    for k := range kvs {
    -        fmt.Println("key:", k)
    -    }
    -
    +
        for k := range kvs {
    +        fmt.Println("key:", k)
    +    }
    @@ -153,12 +142,10 @@ details.

    -
    -    for i, c := range "go" {
    -        fmt.Println(i, c)
    -    }
    -}
    -
    +
        for i, c := range "go" {
    +        fmt.Println(i, c)
    +    }
    +}
    @@ -172,15 +159,15 @@ details.

    -
    $ go run range.go
    -sum: 9
    -index: 1
    -a -> apple
    -b -> banana
    -key: a
    -key: b
    -0 103
    -1 111
    +
    $ go run range.go
    +sum: 9
    +index: 1
    +a -> apple
    +b -> banana
    +key: a
    +key: b
    +0 103
    +1 111
    diff --git a/public/range-over-channels b/public/range-over-channels index bc4b71e71..f46006046 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -45,8 +45,7 @@ values received from a channel.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ values received from a channel.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -67,8 +65,7 @@ values received from a channel.

    -
    func main() {
    -
    +
    func main() {
    @@ -79,12 +76,10 @@ values received from a channel.

    -
    -    queue := make(chan string, 2)
    -    queue <- "one"
    -    queue <- "two"
    -    close(queue)
    -
    +
        queue := make(chan string, 2)
    +    queue <- "one"
    +    queue <- "two"
    +    close(queue)
    @@ -98,12 +93,10 @@ receiving the 2 elements.

    -
    -    for elem := range queue {
    -        fmt.Println(elem)
    -    }
    -}
    -
    +
        for elem := range queue {
    +        fmt.Println(elem)
    +    }
    +}
    @@ -117,9 +110,9 @@ receiving the 2 elements.

    -
    $ go run range-over-channels.go
    -one
    -two
    +
    $ go run range-over-channels.go
    +one
    +two
    diff --git a/public/rate-limiting b/public/rate-limiting index ceb2a71ed..4ce31db2d 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -46,8 +46,7 @@ channels, and tickers.

    -
    package main
    -
    +
    package main
    @@ -57,11 +56,10 @@ channels, and tickers.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -71,8 +69,7 @@ channels, and tickers.

    -
    func main() {
    -
    +
    func main() {
    @@ -86,13 +83,11 @@ same name.

    -
    -    requests := make(chan int, 5)
    -    for i := 1; i <= 5; i++ {
    -        requests <- i
    -    }
    -    close(requests)
    -
    +
        requests := make(chan int, 5)
    +    for i := 1; i <= 5; i++ {
    +        requests <- i
    +    }
    +    close(requests)
    @@ -105,9 +100,7 @@ our rate limiting scheme.

    -
    -    limiter := time.Tick(200 * time.Millisecond)
    -
    +
        limiter := time.Tick(200 * time.Millisecond)
    @@ -120,12 +113,10 @@ before serving each request, we limit ourselves to -
    -    for req := range requests {
    -        <-limiter
    -        fmt.Println("request", req, time.Now())
    -    }
    -
    +
        for req := range requests {
    +        <-limiter
    +        fmt.Println("request", req, time.Now())
    +    }
    @@ -140,9 +131,7 @@ channel will allow bursts of up to 3 events.

    -
    -    burstyLimiter := make(chan time.Time, 3)
    -
    +
        burstyLimiter := make(chan time.Time, 3)
    @@ -153,11 +142,9 @@ channel will allow bursts of up to 3 events.

    -
    -    for i := 0; i < 3; i++ {
    -        burstyLimiter <- time.Now()
    -    }
    -
    +
        for i := 0; i < 3; i++ {
    +        burstyLimiter <- time.Now()
    +    }
    @@ -169,13 +156,11 @@ value to burstyLimiter, up to its limit of 3.

    -
    -    go func() {
    -        for t := range time.Tick(200 * time.Millisecond) {
    -            burstyLimiter <- t
    -        }
    -    }()
    -
    +
        go func() {
    +        for t := range time.Tick(200 * time.Millisecond) {
    +            burstyLimiter <- t
    +        }
    +    }()
    @@ -188,18 +173,16 @@ of burstyLimiter.

    -
    -    burstyRequests := make(chan int, 5)
    -    for i := 1; i <= 5; i++ {
    -        burstyRequests <- i
    -    }
    -    close(burstyRequests)
    -    for req := range burstyRequests {
    -        <-burstyLimiter
    -        fmt.Println("request", req, time.Now())
    -    }
    -}
    -
    +
        burstyRequests := make(chan int, 5)
    +    for i := 1; i <= 5; i++ {
    +        burstyRequests <- i
    +    }
    +    close(burstyRequests)
    +    for req := range burstyRequests {
    +        <-burstyLimiter
    +        fmt.Println("request", req, time.Now())
    +    }
    +}
    @@ -215,13 +198,12 @@ handled once every ~200 milliseconds as desired.

    -
    -$ go run rate-limiting.go
    -request 1 2012-10-19 00:38:18.687438 +0000 UTC
    -request 2 2012-10-19 00:38:18.887471 +0000 UTC
    -request 3 2012-10-19 00:38:19.087238 +0000 UTC
    -request 4 2012-10-19 00:38:19.287338 +0000 UTC
    -request 5 2012-10-19 00:38:19.487331 +0000 UTC
    +
    $ go run rate-limiting.go
    +request 1 2012-10-19 00:38:18.687438 +0000 UTC
    +request 2 2012-10-19 00:38:18.887471 +0000 UTC
    +request 3 2012-10-19 00:38:19.087238 +0000 UTC
    +request 4 2012-10-19 00:38:19.287338 +0000 UTC
    +request 5 2012-10-19 00:38:19.487331 +0000 UTC
    @@ -234,12 +216,11 @@ then serve the remaining 2 with ~200ms delays each.

    -
    -request 1 2012-10-19 00:38:20.487578 +0000 UTC
    -request 2 2012-10-19 00:38:20.487645 +0000 UTC
    -request 3 2012-10-19 00:38:20.487676 +0000 UTC
    -request 4 2012-10-19 00:38:20.687483 +0000 UTC
    -request 5 2012-10-19 00:38:20.887542 +0000 UTC
    +
    request 1 2012-10-19 00:38:20.487578 +0000 UTC
    +request 2 2012-10-19 00:38:20.487645 +0000 UTC
    +request 3 2012-10-19 00:38:20.487676 +0000 UTC
    +request 4 2012-10-19 00:38:20.687483 +0000 UTC
    +request 5 2012-10-19 00:38:20.887542 +0000 UTC
    diff --git a/public/reading-files b/public/reading-files index 58fc5bce8..fceb4bd8a 100644 --- a/public/reading-files +++ b/public/reading-files @@ -44,8 +44,7 @@ reading files.

    -
    package main
    -
    +
    package main
    @@ -55,13 +54,12 @@ reading files.

    -
    import (
    -    "bufio"
    -    "fmt"
    -    "io"
    -    "os"
    -)
    -
    +
    import (
    +    "bufio"
    +    "fmt"
    +    "io"
    +    "os"
    +)
    @@ -73,13 +71,11 @@ This helper will streamline our error checks below.

    -
    -func check(e error) {
    -    if e != nil {
    -        panic(e)
    -    }
    -}
    -
    +
    func check(e error) {
    +    if e != nil {
    +        panic(e)
    +    }
    +}
    @@ -89,8 +85,7 @@ This helper will streamline our error checks below.

    -
    func main() {
    -
    +
    func main() {
    @@ -102,11 +97,9 @@ slurping a file’s entire contents into memory.

    -
    -    dat, err := os.ReadFile("/tmp/dat")
    -    check(err)
    -    fmt.Print(string(dat))
    -
    +
        dat, err := os.ReadFile("/tmp/dat")
    +    check(err)
    +    fmt.Print(string(dat))
    @@ -119,10 +112,8 @@ by Opening a file to obtain an os.File value.

    -
    -    f, err := os.Open("/tmp/dat")
    -    check(err)
    -
    +
        f, err := os.Open("/tmp/dat")
    +    check(err)
    @@ -135,12 +126,10 @@ actually were read.

    -
    -    b1 := make([]byte, 5)
    -    n1, err := f.Read(b1)
    -    check(err)
    -    fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
    -
    +
        b1 := make([]byte, 5)
    +    n1, err := f.Read(b1)
    +    check(err)
    +    fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
    @@ -152,15 +141,13 @@ and Read from there.

    -
    -    o2, err := f.Seek(6, 0)
    -    check(err)
    -    b2 := make([]byte, 2)
    -    n2, err := f.Read(b2)
    -    check(err)
    -    fmt.Printf("%d bytes @ %d: ", n2, o2)
    -    fmt.Printf("%v\n", string(b2[:n2]))
    -
    +
        o2, err := f.Seek(6, 0)
    +    check(err)
    +    b2 := make([]byte, 2)
    +    n2, err := f.Read(b2)
    +    check(err)
    +    fmt.Printf("%d bytes @ %d: ", n2, o2)
    +    fmt.Printf("%v\n", string(b2[:n2]))
    @@ -174,14 +161,12 @@ implemented with ReadAtLeast.

    -
    -    o3, err := f.Seek(6, 0)
    -    check(err)
    -    b3 := make([]byte, 2)
    -    n3, err := io.ReadAtLeast(f, b3, 2)
    -    check(err)
    -    fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
    -
    +
        o3, err := f.Seek(6, 0)
    +    check(err)
    +    b3 := make([]byte, 2)
    +    n3, err := io.ReadAtLeast(f, b3, 2)
    +    check(err)
    +    fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
    @@ -193,10 +178,8 @@ accomplishes this.

    -
    -    _, err = f.Seek(0, 0)
    -    check(err)
    -
    +
        _, err = f.Seek(0, 0)
    +    check(err)
    @@ -210,12 +193,10 @@ reading methods it provides.

    -
    -    r4 := bufio.NewReader(f)
    -    b4, err := r4.Peek(5)
    -    check(err)
    -    fmt.Printf("5 bytes: %s\n", string(b4))
    -
    +
        r4 := bufio.NewReader(f)
    +    b4, err := r4.Peek(5)
    +    check(err)
    +    fmt.Printf("5 bytes: %s\n", string(b4))
    @@ -228,10 +209,8 @@ be scheduled immediately after Opening with -
    -    f.Close()
    -}
    -
    +
        f.Close()
    +}
    @@ -245,15 +224,15 @@ be scheduled immediately after Opening with -
    $ echo "hello" > /tmp/dat
    -$ echo "go" >>   /tmp/dat
    -$ go run reading-files.go
    -hello
    -go
    -5 bytes: hello
    -2 bytes @ 6: go
    -2 bytes @ 6: go
    -5 bytes: hello
    +
    $ echo "hello" > /tmp/dat
    +$ echo "go" >>   /tmp/dat
    +$ go run reading-files.go
    +hello
    +go
    +5 bytes: hello
    +2 bytes @ 6: go
    +2 bytes @ 6: go
    +5 bytes: hello
    diff --git a/public/recover b/public/recover index 903dbf8ea..b0d61c946 100644 --- a/public/recover +++ b/public/recover @@ -61,8 +61,7 @@ does by default for HTTP servers.

    -
    package main
    -
    +
    package main
    @@ -72,8 +71,7 @@ does by default for HTTP servers.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -84,11 +82,9 @@ does by default for HTTP servers.

    -
    -func mayPanic() {
    -    panic("a problem")
    -}
    -
    +
    func mayPanic() {
    +    panic("a problem")
    +}
    @@ -102,8 +98,7 @@ the panic.

    -
    func main() {
    -
    +
    func main() {
    @@ -115,9 +110,8 @@ the call to panic.

    -
        defer func() {
    -        if r := recover(); r != nil {
    -
    +
        defer func() {
    +        if r := recover(); r != nil {
    @@ -127,10 +121,9 @@ the call to panic.

    -
                fmt.Println("Recovered. Error:\n", r)
    -        }
    -    }()
    -
    +
                fmt.Println("Recovered. Error:\n", r)
    +        }
    +    }()
    @@ -140,8 +133,7 @@ the call to panic.

    -
        mayPanic()
    -
    +
        mayPanic()
    @@ -154,10 +146,8 @@ panic and resumes in the deferred closure.

    -
    -    fmt.Println("After mayPanic()")
    -}
    -
    +
        fmt.Println("After mayPanic()")
    +}
    @@ -171,9 +161,9 @@ panic and resumes in the deferred closure.

    -
    $ go run recover.go
    -Recovered. Error:
    - a problem
    +
    $ go run recover.go
    +Recovered. Error:
    + a problem
    diff --git a/public/recursion b/public/recursion index 413b684e4..8b07370ff 100644 --- a/public/recursion +++ b/public/recursion @@ -44,8 +44,7 @@ Here’s a classic example.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ Here’s a classic example.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -68,14 +66,12 @@ base case of fact(0).

    -
    -func fact(n int) int {
    -    if n == 0 {
    -        return 1
    -    }
    -    return n * fact(n-1)
    -}
    -
    +
    func fact(n int) int {
    +    if n == 0 {
    +        return 1
    +    }
    +    return n * fact(n-1)
    +}
    @@ -85,9 +81,8 @@ base case of fact(0).

    -
    func main() {
    -    fmt.Println(fact(7))
    -
    +
    func main() {
    +    fmt.Println(fact(7))
    @@ -100,9 +95,7 @@ before it’s defined.

    -
    -    var fib func(n int) int
    -
    +
        var fib func(n int) int
    @@ -112,11 +105,10 @@ before it’s defined.

    -
        fib = func(n int) int {
    -        if n < 2 {
    -            return n
    -        }
    -
    +
        fib = func(n int) int {
    +        if n < 2 {
    +            return n
    +        }
    @@ -128,10 +120,8 @@ knows which function to call with fib here.

    -
    -        return fib(n-1) + fib(n-2)
    -    }
    -
    +
            return fib(n-1) + fib(n-2)
    +    }
    @@ -141,9 +131,8 @@ knows which function to call with fib here.

    -
        fmt.Println(fib(7))
    -}
    -
    +
        fmt.Println(fib(7))
    +}
    @@ -157,9 +146,9 @@ knows which function to call with fib here.

    -
    $ go run recursion.go 
    -5040
    -13
    +
    $ go run recursion.go 
    +5040
    +13
    diff --git a/public/regular-expressions b/public/regular-expressions index 9f830f070..43d6beaa8 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -44,8 +44,7 @@ in Go.

    -
    package main
    -
    +
    package main
    @@ -55,12 +54,11 @@ in Go.

    -
    import (
    -    "bytes"
    -    "fmt"
    -    "regexp"
    -)
    -
    +
    import (
    +    "bytes"
    +    "fmt"
    +    "regexp"
    +)
    @@ -70,8 +68,7 @@ in Go.

    -
    func main() {
    -
    +
    func main() {
    @@ -82,10 +79,8 @@ in Go.

    -
    -    match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
    -    fmt.Println(match)
    -
    +
        match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
    +    fmt.Println(match)
    @@ -98,9 +93,7 @@ optimized Regexp struct.

    -
    -    r, _ := regexp.Compile("p([a-z]+)ch")
    -
    +
        r, _ := regexp.Compile("p([a-z]+)ch")
    @@ -112,9 +105,7 @@ a match test like we saw earlier.

    -
    -    fmt.Println(r.MatchString("peach"))
    -
    +
        fmt.Println(r.MatchString("peach"))
    @@ -125,9 +116,7 @@ a match test like we saw earlier.

    -
    -    fmt.Println(r.FindString("peach punch"))
    -
    +
        fmt.Println(r.FindString("peach punch"))
    @@ -140,9 +129,7 @@ matching text.

    -
    -    fmt.Println("idx:", r.FindStringIndex("peach punch"))
    -
    +
        fmt.Println("idx:", r.FindStringIndex("peach punch"))
    @@ -156,9 +143,7 @@ information for both p([a-z]+)ch and ([a-z]+).

    -
    -    fmt.Println(r.FindStringSubmatch("peach punch"))
    -
    +
        fmt.Println(r.FindStringSubmatch("peach punch"))
    @@ -170,9 +155,7 @@ indexes of matches and submatches.

    -
    -    fmt.Println(r.FindStringSubmatchIndex("peach punch"))
    -
    +
        fmt.Println(r.FindStringSubmatchIndex("peach punch"))
    @@ -185,9 +168,7 @@ example to find all matches for a regexp.

    -
    -    fmt.Println(r.FindAllString("peach punch pinch", -1))
    -
    +
        fmt.Println(r.FindAllString("peach punch pinch", -1))
    @@ -199,10 +180,8 @@ functions we saw above as well.

    -
    -    fmt.Println("all:", r.FindAllStringSubmatchIndex(
    -        "peach punch pinch", -1))
    -
    +
        fmt.Println("all:", r.FindAllStringSubmatchIndex(
    +        "peach punch pinch", -1))
    @@ -215,9 +194,7 @@ of matches.

    -
    -    fmt.Println(r.FindAllString("peach punch pinch", 2))
    -
    +
        fmt.Println(r.FindAllString("peach punch pinch", 2))
    @@ -231,9 +208,7 @@ function name.

    -
    -    fmt.Println(r.Match([]byte("peach")))
    -
    +
        fmt.Println(r.Match([]byte("peach")))
    @@ -248,10 +223,8 @@ global variables.

    -
    -    r = regexp.MustCompile("p([a-z]+)ch")
    -    fmt.Println("regexp:", r)
    -
    +
        r = regexp.MustCompile("p([a-z]+)ch")
    +    fmt.Println("regexp:", r)
    @@ -263,9 +236,7 @@ subsets of strings with other values.

    -
    -    fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
    -
    +
        fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
    @@ -277,12 +248,10 @@ text with a given function.

    -
    -    in := []byte("a peach")
    -    out := r.ReplaceAllFunc(in, bytes.ToUpper)
    -    fmt.Println(string(out))
    -}
    -
    +
        in := []byte("a peach")
    +    out := r.ReplaceAllFunc(in, bytes.ToUpper)
    +    fmt.Println(string(out))
    +}
    @@ -296,20 +265,20 @@ text with a given function.

    -
    $ go run regular-expressions.go
    -true
    -true
    -peach
    -idx: [0 5]
    -[peach ea]
    -[0 5 1 3]
    -[peach punch pinch]
    -all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
    -[peach punch]
    -true
    -regexp: p([a-z]+)ch
    -a <fruit>
    -a PEACH
    +
    $ go run regular-expressions.go
    +true
    +true
    +peach
    +idx: [0 5]
    +[peach ea]
    +[0 5 1 3]
    +[peach punch pinch]
    +all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
    +[peach punch]
    +true
    +regexp: p([a-z]+)ch
    +a <fruit>
    +a PEACH
    diff --git a/public/select b/public/select index 81326663a..7b660f906 100644 --- a/public/select +++ b/public/select @@ -44,8 +44,7 @@ select is a powerful feature of Go.

    -
    package main
    -
    +
    package main
    @@ -55,11 +54,10 @@ select is a powerful feature of Go.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -69,8 +67,7 @@ select is a powerful feature of Go.

    -
    func main() {
    -
    +
    func main() {
    @@ -81,10 +78,8 @@ select is a powerful feature of Go.

    -
    -    c1 := make(chan string)
    -    c2 := make(chan string)
    -
    +
        c1 := make(chan string)
    +    c2 := make(chan string)
    @@ -97,16 +92,14 @@ executing in concurrent goroutines.

    -
    -    go func() {
    -        time.Sleep(1 * time.Second)
    -        c1 <- "one"
    -    }()
    -    go func() {
    -        time.Sleep(2 * time.Second)
    -        c2 <- "two"
    -    }()
    -
    +
        go func() {
    +        time.Sleep(1 * time.Second)
    +        c1 <- "one"
    +    }()
    +    go func() {
    +        time.Sleep(2 * time.Second)
    +        c2 <- "two"
    +    }()
    @@ -118,17 +111,15 @@ simultaneously, printing each one as it arrives.

    -
    -    for i := 0; i < 2; i++ {
    -        select {
    -        case msg1 := <-c1:
    -            fmt.Println("received", msg1)
    -        case msg2 := <-c2:
    -            fmt.Println("received", msg2)
    -        }
    -    }
    -}
    -
    +
        for i := 0; i < 2; i++ {
    +        select {
    +        case msg1 := <-c1:
    +            fmt.Println("received", msg1)
    +        case msg2 := <-c2:
    +            fmt.Println("received", msg2)
    +        }
    +    }
    +}
    @@ -144,10 +135,9 @@ expected.

    -
    -$ time go run select.go 
    -received one
    -received two
    +
    $ time go run select.go 
    +received one
    +received two
    @@ -160,8 +150,7 @@ concurrently.

    -
    -real    0m2.245s
    +
    real    0m2.245s
    diff --git a/public/sha256-hashes b/public/sha256-hashes index e1e1846ae..f05fd3cf7 100644 --- a/public/sha256-hashes +++ b/public/sha256-hashes @@ -46,8 +46,7 @@ SHA256 hashes in Go.

    -
    package main
    -
    +
    package main
    @@ -59,12 +58,10 @@ SHA256 hashes in Go.

    -
    -import (
    -    "crypto/sha256"
    -    "fmt"
    -)
    -
    +
    import (
    +    "crypto/sha256"
    +    "fmt"
    +)
    @@ -74,9 +71,8 @@ SHA256 hashes in Go.

    -
    func main() {
    -    s := "sha256 this string"
    -
    +
    func main() {
    +    s := "sha256 this string"
    @@ -87,9 +83,7 @@ SHA256 hashes in Go.

    -
    -    h := sha256.New()
    -
    +
        h := sha256.New()
    @@ -101,9 +95,7 @@ use []byte(s) to coerce it to bytes.

    -
    -    h.Write([]byte(s))
    -
    +
        h.Write([]byte(s))
    @@ -116,9 +108,7 @@ to an existing byte slice: it usually isn’t needed.

    -
    -    bs := h.Sum(nil)
    -
    +
        bs := h.Sum(nil)
    @@ -128,10 +118,9 @@ to an existing byte slice: it usually isn’t needed.

    -
        fmt.Println(s)
    -    fmt.Printf("%x\n", bs)
    -}
    -
    +
        fmt.Println(s)
    +    fmt.Printf("%x\n", bs)
    +}
    @@ -147,10 +136,9 @@ a human-readable hex format.

    -
    -$ go run sha256-hashes.go
    -sha256 this string
    -1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
    +
    $ go run sha256-hashes.go
    +sha256 this string
    +1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
    diff --git a/public/signals b/public/signals index 42710f26b..6f8e1ca78 100644 --- a/public/signals +++ b/public/signals @@ -47,8 +47,7 @@ Here’s how to handle signals in Go with channels.

    -
    package main
    -
    +
    package main
    @@ -58,13 +57,12 @@ Here’s how to handle signals in Go with channels.

    -
    import (
    -    "fmt"
    -    "os"
    -    "os/signal"
    -    "syscall"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +    "os/signal"
    +    "syscall"
    +)
    @@ -74,8 +72,7 @@ Here’s how to handle signals in Go with channels.

    -
    func main() {
    -
    +
    func main() {
    @@ -89,9 +86,7 @@ should be buffered.

    -
    -    sigs := make(chan os.Signal, 1)
    -
    +
        sigs := make(chan os.Signal, 1)
    @@ -103,9 +98,7 @@ receive notifications of the specified signals.

    -
    -    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    -
    +
        signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    @@ -119,9 +112,7 @@ a more realistic scenario of graceful shutdown.

    -
    -    done := make(chan bool, 1)
    -
    +
        done := make(chan bool, 1)
    @@ -134,8 +125,7 @@ and then notify the program that it can finish.

    -
        go func() {
    -
    +
        go func() {
    @@ -145,12 +135,11 @@ and then notify the program that it can finish.

    -
            sig := <-sigs
    -        fmt.Println()
    -        fmt.Println(sig)
    -        done <- true
    -    }()
    -
    +
            sig := <-sigs
    +        fmt.Println()
    +        fmt.Println(sig)
    +        done <- true
    +    }()
    @@ -163,12 +152,10 @@ above sending a value on done) and then exit.

    -
    -    fmt.Println("awaiting signal")
    -    <-done
    -    fmt.Println("exiting")
    -}
    -
    +
        fmt.Println("awaiting signal")
    +    <-done
    +    fmt.Println("exiting")
    +}
    @@ -186,12 +173,11 @@ causing the program to print interrupt and then exit.

    -
    -$ go run signals.go
    -awaiting signal
    -^C
    -interrupt
    -exiting
    +
    $ go run signals.go
    +awaiting signal
    +^C
    +interrupt
    +exiting
    diff --git a/public/slices b/public/slices index cee1ef50d..f26101e7c 100644 --- a/public/slices +++ b/public/slices @@ -43,8 +43,7 @@ a more powerful interface to sequences than arrays.

    -
    package main
    -
    +
    package main
    @@ -54,8 +53,7 @@ a more powerful interface to sequences than arrays.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -65,8 +63,7 @@ a more powerful interface to sequences than arrays.

    -
    func main() {
    -
    +
    func main() {
    @@ -80,10 +77,8 @@ length 0.

    -
    -    var s []string
    -    fmt.Println("uninit:", s, s == nil, len(s) == 0)
    -
    +
        var s []string
    +    fmt.Println("uninit:", s, s == nil, len(s) == 0)
    @@ -100,10 +95,8 @@ as an additional parameter to make.

    -
    -    s = make([]string, 3)
    -    fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
    -
    +
        s = make([]string, 3)
    +    fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
    @@ -114,13 +107,11 @@ as an additional parameter to make.

    -
    -    s[0] = "a"
    -    s[1] = "b"
    -    s[2] = "c"
    -    fmt.Println("set:", s)
    -    fmt.Println("get:", s[2])
    -
    +
        s[0] = "a"
    +    s[1] = "b"
    +    s[2] = "c"
    +    fmt.Println("set:", s)
    +    fmt.Println("get:", s[2])
    @@ -131,9 +122,7 @@ as an additional parameter to make.

    -
    -    fmt.Println("len:", len(s))
    -
    +
        fmt.Println("len:", len(s))
    @@ -149,11 +138,9 @@ Note that we need to accept a return value from -
    -    s = append(s, "d")
    -    s = append(s, "e", "f")
    -    fmt.Println("apd:", s)
    -
    +
        s = append(s, "d")
    +    s = append(s, "e", "f")
    +    fmt.Println("apd:", s)
    @@ -166,11 +153,9 @@ into c from s.

    -
    -    c := make([]string, len(s))
    -    copy(c, s)
    -    fmt.Println("cpy:", c)
    -
    +
        c := make([]string, len(s))
    +    copy(c, s)
    +    fmt.Println("cpy:", c)
    @@ -183,10 +168,8 @@ of the elements s[2], s[3], and s[4].

    -
    -    l := s[2:5]
    -    fmt.Println("sl1:", l)
    -
    +
        l := s[2:5]
    +    fmt.Println("sl1:", l)
    @@ -197,10 +180,8 @@ of the elements s[2], s[3], and s[4].

    -
    -    l = s[:5]
    -    fmt.Println("sl2:", l)
    -
    +
        l = s[:5]
    +    fmt.Println("sl2:", l)
    @@ -211,10 +192,8 @@ of the elements s[2], s[3], and s[4].

    -
    -    l = s[2:]
    -    fmt.Println("sl3:", l)
    -
    +
        l = s[2:]
    +    fmt.Println("sl3:", l)
    @@ -226,10 +205,8 @@ in a single line as well.

    -
    -    t := []string{"g", "h", "i"}
    -    fmt.Println("dcl:", t)
    -
    +
        t := []string{"g", "h", "i"}
    +    fmt.Println("dcl:", t)
    @@ -242,18 +219,16 @@ vary, unlike with multi-dimensional arrays.

    -
    -    twoD := make([][]int, 3)
    -    for i := 0; i < 3; i++ {
    -        innerLen := i + 1
    -        twoD[i] = make([]int, innerLen)
    -        for j := 0; j < innerLen; j++ {
    -            twoD[i][j] = i + j
    -        }
    -    }
    -    fmt.Println("2d: ", twoD)
    -}
    -
    +
        twoD := make([][]int, 3)
    +    for i := 0; i < 3; i++ {
    +        innerLen := i + 1
    +        twoD[i] = make([]int, innerLen)
    +        for j := 0; j < innerLen; j++ {
    +            twoD[i][j] = i + j
    +        }
    +    }
    +    fmt.Println("2d: ", twoD)
    +}
    @@ -269,20 +244,19 @@ they are rendered similarly by fmt.Println.

    -
    -$ go run slices.go
    -uninit: [] true true
    -emp: [  ] len: 3 cap: 3
    -set: [a b c]
    -get: c
    -len: 3
    -apd: [a b c d e f]
    -cpy: [a b c d e f]
    -sl1: [c d e]
    -sl2: [a b c d e]
    -sl3: [c d e f]
    -dcl: [g h i]
    -2d:  [[0] [1 2] [2 3 4]]
    +
    $ go run slices.go
    +uninit: [] true true
    +emp: [  ] len: 3 cap: 3
    +set: [a b c]
    +get: c
    +len: 3
    +apd: [a b c d e f]
    +cpy: [a b c d e f]
    +sl1: [c d e]
    +sl2: [a b c d e]
    +sl3: [c d e f]
    +dcl: [g h i]
    +2d:  [[0] [1 2] [2 3 4]]
    diff --git a/public/sorting b/public/sorting index e3c3508db..866ca5dec 100644 --- a/public/sorting +++ b/public/sorting @@ -44,8 +44,7 @@ builtins first.

    -
    package main
    -
    +
    package main
    @@ -55,11 +54,10 @@ builtins first.

    -
    import (
    -    "fmt"
    -    "sort"
    -)
    -
    +
    import (
    +    "fmt"
    +    "sort"
    +)
    @@ -69,8 +67,7 @@ builtins first.

    -
    func main() {
    -
    +
    func main() {
    @@ -84,11 +81,9 @@ return a new one.

    -
    -    strs := []string{"c", "a", "b"}
    -    sort.Strings(strs)
    -    fmt.Println("Strings:", strs)
    -
    +
        strs := []string{"c", "a", "b"}
    +    sort.Strings(strs)
    +    fmt.Println("Strings:", strs)
    @@ -99,11 +94,9 @@ return a new one.

    -
    -    ints := []int{7, 2, 4}
    -    sort.Ints(ints)
    -    fmt.Println("Ints:   ", ints)
    -
    +
        ints := []int{7, 2, 4}
    +    sort.Ints(ints)
    +    fmt.Println("Ints:   ", ints)
    @@ -115,11 +108,9 @@ already in sorted order.

    -
    -    s := sort.IntsAreSorted(ints)
    -    fmt.Println("Sorted: ", s)
    -}
    -
    +
        s := sort.IntsAreSorted(ints)
    +    fmt.Println("Sorted: ", s)
    +}
    @@ -135,11 +126,10 @@ slices and true as the result of our AreSorted test. -
    -$ go run sorting.go
    -Strings: [a b c]
    -Ints:    [2 4 7]
    -Sorted:  true
    +
    $ go run sorting.go
    +Strings: [a b c]
    +Ints:    [2 4 7]
    +Sorted:  true
    diff --git a/public/sorting-by-functions b/public/sorting-by-functions index 1607ffa70..77b833c04 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -46,8 +46,7 @@ in Go.

    -
    package main
    -
    +
    package main
    @@ -57,11 +56,10 @@ in Go.

    -
    import (
    -    "fmt"
    -    "sort"
    -)
    -
    +
    import (
    +    "fmt"
    +    "sort"
    +)
    @@ -75,9 +73,7 @@ type.

    -
    -type byLength []string
    -
    +
    type byLength []string
    @@ -94,17 +90,15 @@ we use len(s[i]) and len(s[j]) here.

    -
    -func (s byLength) Len() int {
    -    return len(s)
    -}
    -func (s byLength) Swap(i, j int) {
    -    s[i], s[j] = s[j], s[i]
    -}
    -func (s byLength) Less(i, j int) bool {
    -    return len(s[i]) < len(s[j])
    -}
    -
    +
    func (s byLength) Len() int {
    +    return len(s)
    +}
    +func (s byLength) Swap(i, j int) {
    +    s[i], s[j] = s[j], s[i]
    +}
    +func (s byLength) Less(i, j int) bool {
    +    return len(s[i]) < len(s[j])
    +}
    @@ -118,13 +112,11 @@ slice.

    -
    -func main() {
    -    fruits := []string{"peach", "banana", "kiwi"}
    -    sort.Sort(byLength(fruits))
    -    fmt.Println(fruits)
    -}
    -
    +
    func main() {
    +    fruits := []string{"peach", "banana", "kiwi"}
    +    sort.Sort(byLength(fruits))
    +    fmt.Println(fruits)
    +}
    @@ -140,9 +132,8 @@ length, as desired.

    -
    -$ go run sorting-by-functions.go 
    -[kiwi peach banana]
    +
    $ go run sorting-by-functions.go 
    +[kiwi peach banana]
    diff --git a/public/spawning-processes b/public/spawning-processes index d013fc14f..5c48a4317 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -43,8 +43,7 @@ processes.

    -
    package main
    -
    +
    package main
    @@ -54,12 +53,11 @@ processes.

    -
    import (
    -    "fmt"
    -    "io"
    -    "os/exec"
    -)
    -
    +
    import (
    +    "fmt"
    +    "io"
    +    "os/exec"
    +)
    @@ -69,8 +67,7 @@ processes.

    -
    func main() {
    -
    +
    func main() {
    @@ -84,9 +81,7 @@ to represent this external process.

    -
    -    dateCmd := exec.Command("date")
    -
    +
        dateCmd := exec.Command("date")
    @@ -100,14 +95,12 @@ with the date info.

    -
    -    dateOut, err := dateCmd.Output()
    -    if err != nil {
    -        panic(err)
    -    }
    -    fmt.Println("> date")
    -    fmt.Println(string(dateOut))
    -
    +
        dateOut, err := dateCmd.Output()
    +    if err != nil {
    +        panic(err)
    +    }
    +    fmt.Println("> date")
    +    fmt.Println(string(dateOut))
    @@ -122,19 +115,17 @@ code.

    -
    -    _, err = exec.Command("date", "-x").Output()
    -    if err != nil {
    -        switch e := err.(type) {
    -        case *exec.Error:
    -            fmt.Println("failed executing:", err)
    -        case *exec.ExitError:
    -            fmt.Println("command exit rc =", e.ExitCode())
    -        default:
    -            panic(err)
    -        }
    -    }
    -
    +
        _, err = exec.Command("date", "-x").Output()
    +    if err != nil {
    +        switch e := err.(type) {
    +        case *exec.Error:
    +            fmt.Println("failed executing:", err)
    +        case *exec.ExitError:
    +            fmt.Println("command exit rc =", e.ExitCode())
    +        default:
    +            panic(err)
    +        }
    +    }
    @@ -147,9 +138,7 @@ where we pipe data to the external process on its -
    -    grepCmd := exec.Command("grep", "hello")
    -
    +
        grepCmd := exec.Command("grep", "hello")
    @@ -163,15 +152,13 @@ to exit.

    -
    -    grepIn, _ := grepCmd.StdinPipe()
    -    grepOut, _ := grepCmd.StdoutPipe()
    -    grepCmd.Start()
    -    grepIn.Write([]byte("hello grep\ngoodbye grep"))
    -    grepIn.Close()
    -    grepBytes, _ := io.ReadAll(grepOut)
    -    grepCmd.Wait()
    -
    +
        grepIn, _ := grepCmd.StdinPipe()
    +    grepOut, _ := grepCmd.StdoutPipe()
    +    grepCmd.Start()
    +    grepIn.Write([]byte("hello grep\ngoodbye grep"))
    +    grepIn.Close()
    +    grepBytes, _ := io.ReadAll(grepOut)
    +    grepCmd.Wait()
    @@ -186,10 +173,8 @@ exactly the same way.

    -
    -    fmt.Println("> grep hello")
    -    fmt.Println(string(grepBytes))
    -
    +
        fmt.Println("> grep hello")
    +    fmt.Println(string(grepBytes))
    @@ -205,16 +190,14 @@ option:

    -
    -    lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
    -    lsOut, err := lsCmd.Output()
    -    if err != nil {
    -        panic(err)
    -    }
    -    fmt.Println("> ls -a -l -h")
    -    fmt.Println(string(lsOut))
    -}
    -
    +
        lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
    +    lsOut, err := lsCmd.Output()
    +    if err != nil {
    +        panic(err)
    +    }
    +    fmt.Println("> ls -a -l -h")
    +    fmt.Println(string(lsOut))
    +}
    @@ -230,10 +213,9 @@ as if we had run them directly from the command-line.

    -
    -$ go run spawning-processes.go 
    -> date
    -Thu 05 May 2022 10:10:12 PM PDT
    +
    $ go run spawning-processes.go 
    +> date
    +Thu 05 May 2022 10:10:12 PM PDT
    @@ -245,10 +227,9 @@ an error message and non-zero return code.

    -
    -command exited with rc = 1
    -> grep hello
    -hello grep
    +
    command exited with rc = 1
    +> grep hello
    +hello grep
    @@ -258,10 +239,10 @@ an error message and non-zero return code.

    -
    > ls -a -l -h
    -drwxr-xr-x  4 mark 136B Oct 3 16:29 .
    -drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
    --rw-r--r--  1 mark 1.3K Oct 3 16:28 spawning-processes.go
    +
    > ls -a -l -h
    +drwxr-xr-x  4 mark 136B Oct 3 16:29 .
    +drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
    +-rw-r--r--  1 mark 1.3K Oct 3 16:28 spawning-processes.go
    diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 119f08b8b..d4430729e 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -49,8 +49,7 @@ by exactly 1 goroutine.

    -
    package main
    -
    +
    package main
    @@ -60,13 +59,12 @@ by exactly 1 goroutine.

    -
    import (
    -    "fmt"
    -    "math/rand"
    -    "sync/atomic"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "math/rand"
    +    "sync/atomic"
    +    "time"
    +)
    @@ -84,17 +82,15 @@ goroutine to respond.

    -
    -type readOp struct {
    -    key  int
    -    resp chan int
    -}
    -type writeOp struct {
    -    key  int
    -    val  int
    -    resp chan bool
    -}
    -
    +
    type readOp struct {
    +    key  int
    +    resp chan int
    +}
    +type writeOp struct {
    +    key  int
    +    val  int
    +    resp chan bool
    +}
    @@ -104,8 +100,7 @@ goroutine to respond.

    -
    func main() {
    -
    +
    func main() {
    @@ -116,10 +111,8 @@ goroutine to respond.

    -
    -    var readOps uint64
    -    var writeOps uint64
    -
    +
        var readOps uint64
    +    var writeOps uint64
    @@ -132,10 +125,8 @@ respectively.

    -
    -    reads := make(chan readOp)
    -    writes := make(chan writeOp)
    -
    +
        reads := make(chan readOp)
    +    writes := make(chan writeOp)
    @@ -154,20 +145,18 @@ value in the case of reads).

    -
    -    go func() {
    -        var state = make(map[int]int)
    -        for {
    -            select {
    -            case read := <-reads:
    -                read.resp <- state[read.key]
    -            case write := <-writes:
    -                state[write.key] = write.val
    -                write.resp <- true
    -            }
    -        }
    -    }()
    -
    +
        go func() {
    +        var state = make(map[int]int)
    +        for {
    +            select {
    +            case read := <-reads:
    +                read.resp <- state[read.key]
    +            case write := <-writes:
    +                state[write.key] = write.val
    +                write.resp <- true
    +            }
    +        }
    +    }()
    @@ -182,21 +171,19 @@ result over the provided resp channel.

    -
    -    for r := 0; r < 100; r++ {
    -        go func() {
    -            for {
    -                read := readOp{
    -                    key:  rand.Intn(5),
    -                    resp: make(chan int)}
    -                reads <- read
    -                <-read.resp
    -                atomic.AddUint64(&readOps, 1)
    -                time.Sleep(time.Millisecond)
    -            }
    -        }()
    -    }
    -
    +
        for r := 0; r < 100; r++ {
    +        go func() {
    +            for {
    +                read := readOp{
    +                    key:  rand.Intn(5),
    +                    resp: make(chan int)}
    +                reads <- read
    +                <-read.resp
    +                atomic.AddUint64(&readOps, 1)
    +                time.Sleep(time.Millisecond)
    +            }
    +        }()
    +    }
    @@ -208,22 +195,20 @@ approach.

    -
    -    for w := 0; w < 10; w++ {
    -        go func() {
    -            for {
    -                write := writeOp{
    -                    key:  rand.Intn(5),
    -                    val:  rand.Intn(100),
    -                    resp: make(chan bool)}
    -                writes <- write
    -                <-write.resp
    -                atomic.AddUint64(&writeOps, 1)
    -                time.Sleep(time.Millisecond)
    -            }
    -        }()
    -    }
    -
    +
        for w := 0; w < 10; w++ {
    +        go func() {
    +            for {
    +                write := writeOp{
    +                    key:  rand.Intn(5),
    +                    val:  rand.Intn(100),
    +                    resp: make(chan bool)}
    +                writes <- write
    +                <-write.resp
    +                atomic.AddUint64(&writeOps, 1)
    +                time.Sleep(time.Millisecond)
    +            }
    +        }()
    +    }
    @@ -234,9 +219,7 @@ approach.

    -
    -    time.Sleep(time.Second)
    -
    +
        time.Sleep(time.Second)
    @@ -247,13 +230,11 @@ approach.

    -
    -    readOpsFinal := atomic.LoadUint64(&readOps)
    -    fmt.Println("readOps:", readOpsFinal)
    -    writeOpsFinal := atomic.LoadUint64(&writeOps)
    -    fmt.Println("writeOps:", writeOpsFinal)
    -}
    -
    +
        readOpsFinal := atomic.LoadUint64(&readOps)
    +    fmt.Println("readOps:", readOpsFinal)
    +    writeOpsFinal := atomic.LoadUint64(&writeOps)
    +    fmt.Println("writeOps:", writeOpsFinal)
    +}
    @@ -270,10 +251,9 @@ total operations.

    -
    -$ go run stateful-goroutines.go
    -readOps: 71708
    -writeOps: 7177
    +
    $ go run stateful-goroutines.go
    +readOps: 71708
    +writeOps: 7177
    diff --git a/public/string-formatting b/public/string-formatting index eb6b45b65..1d98485a8 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -44,8 +44,7 @@ common string formatting tasks.

    -
    package main
    -
    +
    package main
    @@ -55,11 +54,10 @@ common string formatting tasks.

    -
    import (
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +)
    @@ -69,10 +67,9 @@ common string formatting tasks.

    -
    type point struct {
    -    x, y int
    -}
    -
    +
    type point struct {
    +    x, y int
    +}
    @@ -82,8 +79,7 @@ common string formatting tasks.

    -
    func main() {
    -
    +
    func main() {
    @@ -96,10 +92,8 @@ an instance of our point struct.

    -
    -    p := point{1, 2}
    -    fmt.Printf("struct1: %v\n", p)
    -
    +
        p := point{1, 2}
    +    fmt.Printf("struct1: %v\n", p)
    @@ -111,9 +105,7 @@ include the struct’s field names.

    -
    -    fmt.Printf("struct2: %+v\n", p)
    -
    +
        fmt.Printf("struct2: %+v\n", p)
    @@ -126,9 +118,7 @@ would produce that value.

    -
    -    fmt.Printf("struct3: %#v\n", p)
    -
    +
        fmt.Printf("struct3: %#v\n", p)
    @@ -139,9 +129,7 @@ would produce that value.

    -
    -    fmt.Printf("type: %T\n", p)
    -
    +
        fmt.Printf("type: %T\n", p)
    @@ -152,9 +140,7 @@ would produce that value.

    -
    -    fmt.Printf("bool: %t\n", true)
    -
    +
        fmt.Printf("bool: %t\n", true)
    @@ -166,9 +152,7 @@ Use %d for standard, base-10 formatting.

    -
    -    fmt.Printf("int: %d\n", 123)
    -
    +
        fmt.Printf("int: %d\n", 123)
    @@ -179,9 +163,7 @@ Use %d for standard, base-10 formatting.

    -
    -    fmt.Printf("bin: %b\n", 14)
    -
    +
        fmt.Printf("bin: %b\n", 14)
    @@ -193,9 +175,7 @@ given integer.

    -
    -    fmt.Printf("char: %c\n", 33)
    -
    +
        fmt.Printf("char: %c\n", 33)
    @@ -206,9 +186,7 @@ given integer.

    -
    -    fmt.Printf("hex: %x\n", 456)
    -
    +
        fmt.Printf("hex: %x\n", 456)
    @@ -220,9 +198,7 @@ floats. For basic decimal formatting use %f.

    -
    -    fmt.Printf("float1: %f\n", 78.9)
    -
    +
        fmt.Printf("float1: %f\n", 78.9)
    @@ -234,10 +210,8 @@ different versions of) scientific notation.

    -
    -    fmt.Printf("float2: %e\n", 123400000.0)
    -    fmt.Printf("float3: %E\n", 123400000.0)
    -
    +
        fmt.Printf("float2: %e\n", 123400000.0)
    +    fmt.Printf("float3: %E\n", 123400000.0)
    @@ -248,9 +222,7 @@ different versions of) scientific notation.

    -
    -    fmt.Printf("str1: %s\n", "\"string\"")
    -
    +
        fmt.Printf("str1: %s\n", "\"string\"")
    @@ -261,9 +233,7 @@ different versions of) scientific notation.

    -
    -    fmt.Printf("str2: %q\n", "\"string\"")
    -
    +
        fmt.Printf("str2: %q\n", "\"string\"")
    @@ -276,9 +246,7 @@ per byte of input.

    -
    -    fmt.Printf("str3: %x\n", "hex this")
    -
    +
        fmt.Printf("str3: %x\n", "hex this")
    @@ -289,9 +257,7 @@ per byte of input.

    -
    -    fmt.Printf("pointer: %p\n", &p)
    -
    +
        fmt.Printf("pointer: %p\n", &p)
    @@ -307,9 +273,7 @@ spaces.

    -
    -    fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
    -
    +
        fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
    @@ -323,9 +287,7 @@ width.precision syntax.

    -
    -    fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
    -
    +
        fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
    @@ -336,9 +298,7 @@ width.precision syntax.

    -
    -    fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
    -
    +
        fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
    @@ -351,9 +311,7 @@ table-like output. For basic right-justified width.

    -
    -    fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
    -
    +
        fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
    @@ -364,9 +322,7 @@ table-like output. For basic right-justified width.

    -
    -    fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
    -
    +
        fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
    @@ -379,10 +335,8 @@ and returns a string without printing it anywhere.

    -
    -    s := fmt.Sprintf("sprintf: a %s", "string")
    -    fmt.Println(s)
    -
    +
        s := fmt.Sprintf("sprintf: a %s", "string")
    +    fmt.Println(s)
    @@ -394,10 +348,8 @@ and returns a string without printing it anywhere.

    -
    -    fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
    -}
    -
    +
        fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
    +}
    @@ -411,30 +363,30 @@ and returns a string without printing it anywhere.

    -
    $ go run string-formatting.go
    -struct1: {1 2}
    -struct2: {x:1 y:2}
    -struct3: main.point{x:1, y:2}
    -type: main.point
    -bool: true
    -int: 123
    -bin: 1110
    -char: !
    -hex: 1c8
    -float1: 78.900000
    -float2: 1.234000e+08
    -float3: 1.234000E+08
    -str1: "string"
    -str2: "\"string\""
    -str3: 6865782074686973
    -pointer: 0xc0000ba000
    -width1: |    12|   345|
    -width2: |  1.20|  3.45|
    -width3: |1.20  |3.45  |
    -width4: |   foo|     b|
    -width5: |foo   |b     |
    -sprintf: a string
    -io: an error
    +
    $ go run string-formatting.go
    +struct1: {1 2}
    +struct2: {x:1 y:2}
    +struct3: main.point{x:1, y:2}
    +type: main.point
    +bool: true
    +int: 123
    +bin: 1110
    +char: !
    +hex: 1c8
    +float1: 78.900000
    +float2: 1.234000e+08
    +float3: 1.234000E+08
    +str1: "string"
    +str2: "\"string\""
    +str3: 6865782074686973
    +pointer: 0xc0000ba000
    +width1: |    12|   345|
    +width2: |  1.20|  3.45|
    +width3: |1.20  |3.45  |
    +width4: |   foo|     b|
    +width5: |foo   |b     |
    +sprintf: a string
    +io: an error
    diff --git a/public/string-functions b/public/string-functions index 0b38f93e6..b5f721564 100644 --- a/public/string-functions +++ b/public/string-functions @@ -44,8 +44,7 @@ to give you a sense of the package.

    -
    package main
    -
    +
    package main
    @@ -55,11 +54,10 @@ to give you a sense of the package.

    -
    import (
    -    "fmt"
    -    s "strings"
    -)
    -
    +
    import (
    +    "fmt"
    +    s "strings"
    +)
    @@ -71,9 +69,7 @@ it a lot below.

    -
    -var p = fmt.Println
    -
    +
    var p = fmt.Println
    @@ -83,8 +79,7 @@ it a lot below.

    -
    func main() {
    -
    +
    func main() {
    @@ -101,21 +96,19 @@ package docs.

    -
    -    p("Contains:  ", s.Contains("test", "es"))
    -    p("Count:     ", s.Count("test", "t"))
    -    p("HasPrefix: ", s.HasPrefix("test", "te"))
    -    p("HasSuffix: ", s.HasSuffix("test", "st"))
    -    p("Index:     ", s.Index("test", "e"))
    -    p("Join:      ", s.Join([]string{"a", "b"}, "-"))
    -    p("Repeat:    ", s.Repeat("a", 5))
    -    p("Replace:   ", s.Replace("foo", "o", "0", -1))
    -    p("Replace:   ", s.Replace("foo", "o", "0", 1))
    -    p("Split:     ", s.Split("a-b-c-d-e", "-"))
    -    p("ToLower:   ", s.ToLower("TEST"))
    -    p("ToUpper:   ", s.ToUpper("test"))
    -}
    -
    +
        p("Contains:  ", s.Contains("test", "es"))
    +    p("Count:     ", s.Count("test", "t"))
    +    p("HasPrefix: ", s.HasPrefix("test", "te"))
    +    p("HasSuffix: ", s.HasSuffix("test", "st"))
    +    p("Index:     ", s.Index("test", "e"))
    +    p("Join:      ", s.Join([]string{"a", "b"}, "-"))
    +    p("Repeat:    ", s.Repeat("a", 5))
    +    p("Replace:   ", s.Replace("foo", "o", "0", -1))
    +    p("Replace:   ", s.Replace("foo", "o", "0", 1))
    +    p("Split:     ", s.Split("a-b-c-d-e", "-"))
    +    p("ToLower:   ", s.ToLower("TEST"))
    +    p("ToUpper:   ", s.ToUpper("test"))
    +}
    @@ -129,19 +122,19 @@ package docs.

    -
    $ go run string-functions.go
    -Contains:   true
    -Count:      2
    -HasPrefix:  true
    -HasSuffix:  true
    -Index:      1
    -Join:       a-b
    -Repeat:     aaaaa
    -Replace:    f00
    -Replace:    f0o
    -Split:      [a b c d e]
    -ToLower:    test
    -ToUpper:    TEST
    +
    $ go run string-functions.go
    +Contains:   true
    +Count:      2
    +HasPrefix:  true
    +HasSuffix:  true
    +Index:      1
    +Join:       a-b
    +Repeat:     aaaaa
    +Replace:    f00
    +Replace:    f0o
    +Split:      [a b c d e]
    +ToLower:    test
    +ToUpper:    TEST
    diff --git a/public/strings-and-runes b/public/strings-and-runes index 9fe20ec53..f5bf97e9e 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -49,8 +49,7 @@ introduction to the topic.

    -
    package main
    -
    +
    package main
    @@ -60,11 +59,10 @@ introduction to the topic.

    -
    import (
    -    "fmt"
    -    "unicode/utf8"
    -)
    -
    +
    import (
    +    "fmt"
    +    "unicode/utf8"
    +)
    @@ -74,8 +72,7 @@ introduction to the topic.

    -
    func main() {
    -
    +
    func main() {
    @@ -89,9 +86,7 @@ encoded text.

    -
    -    const s = "สวัสดี"
    -
    +
        const s = "สวัสดี"
    @@ -103,9 +98,7 @@ will produce the length of the raw bytes stored within.

    -
    -    fmt.Println("Len:", len(s))
    -
    +
        fmt.Println("Len:", len(s))
    @@ -118,12 +111,10 @@ the bytes that constitute the code points in s.

    -
    -    for i := 0; i < len(s); i++ {
    -        fmt.Printf("%x ", s[i])
    -    }
    -    fmt.Println()
    -
    +
        for i := 0; i < len(s); i++ {
    +        fmt.Printf("%x ", s[i])
    +    }
    +    fmt.Println()
    @@ -139,9 +130,7 @@ code points, so the result of this count may be surprising.

    -
    -    fmt.Println("Rune count:", utf8.RuneCountInString(s))
    -
    +
        fmt.Println("Rune count:", utf8.RuneCountInString(s))
    @@ -153,11 +142,9 @@ each rune along with its offset in the string.

    -
    -    for idx, runeValue := range s {
    -        fmt.Printf("%#U starts at %d\n", runeValue, idx)
    -    }
    -
    +
        for idx, runeValue := range s {
    +        fmt.Printf("%#U starts at %d\n", runeValue, idx)
    +    }
    @@ -169,13 +156,11 @@ each rune along with its offset in the string.

    -
    -    fmt.Println("\nUsing DecodeRuneInString")
    -    for i, w := 0, 0; i < len(s); i += w {
    -        runeValue, width := utf8.DecodeRuneInString(s[i:])
    -        fmt.Printf("%#U starts at %d\n", runeValue, i)
    -        w = width
    -
    +
        fmt.Println("\nUsing DecodeRuneInString")
    +    for i, w := 0, 0; i < len(s); i += w {
    +        runeValue, width := utf8.DecodeRuneInString(s[i:])
    +        fmt.Printf("%#U starts at %d\n", runeValue, i)
    +        w = width
    @@ -186,11 +171,9 @@ each rune along with its offset in the string.

    -
    -        examineRune(runeValue)
    -    }
    -}
    -
    +
            examineRune(runeValue)
    +    }
    +}
    @@ -200,8 +183,7 @@ each rune along with its offset in the string.

    -
    func examineRune(r rune) {
    -
    +
    func examineRune(r rune) {
    @@ -213,14 +195,12 @@ can compare a rune value to a rune literal directly.

    -
    -    if r == 't' {
    -        fmt.Println("found tee")
    -    } else if r == 'ส' {
    -        fmt.Println("found so sua")
    -    }
    -}
    -
    +
        if r == 't' {
    +        fmt.Println("found tee")
    +    } else if r == 'ส' {
    +        fmt.Println("found so sua")
    +    }
    +}
    @@ -234,16 +214,16 @@ can compare a rune value to a rune literal directly.

    -
    $ go run strings-and-runes.go
    -Len: 18
    -e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5 
    -Rune count: 6
    -U+0E2A 'ส' starts at 0
    -U+0E27 'ว' starts at 3
    -U+0E31 'ั' starts at 6
    -U+0E2A 'ส' starts at 9
    -U+0E14 'ด' starts at 12
    -U+0E35 'ี' starts at 15
    +
    $ go run strings-and-runes.go
    +Len: 18
    +e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5 
    +Rune count: 6
    +U+0E2A 'ส' starts at 0
    +U+0E27 'ว' starts at 3
    +U+0E31 'ั' starts at 6
    +U+0E2A 'ส' starts at 9
    +U+0E14 'ด' starts at 12
    +U+0E35 'ี' starts at 15
    @@ -253,15 +233,15 @@ can compare a rune value to a rune literal directly.

    -
    Using DecodeRuneInString
    -U+0E2A 'ส' starts at 0
    -found so sua
    -U+0E27 'ว' starts at 3
    -U+0E31 'ั' starts at 6
    -U+0E2A 'ส' starts at 9
    -found so sua
    -U+0E14 'ด' starts at 12
    -U+0E35 'ี' starts at 15
    +
    Using DecodeRuneInString
    +U+0E2A 'ส' starts at 0
    +found so sua
    +U+0E27 'ว' starts at 3
    +U+0E31 'ั' starts at 6
    +U+0E2A 'ส' starts at 9
    +found so sua
    +U+0E14 'ด' starts at 12
    +U+0E35 'ี' starts at 15
    diff --git a/public/struct-embedding b/public/struct-embedding index e10cd67a8..40b5fe9dc 100644 --- a/public/struct-embedding +++ b/public/struct-embedding @@ -46,8 +46,7 @@ files and folders into the application binary.

    -
    package main
    -
    +
    package main
    @@ -57,8 +56,7 @@ files and folders into the application binary.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -68,10 +66,9 @@ files and folders into the application binary.

    -
    type base struct {
    -    num int
    -}
    -
    +
    type base struct {
    +    num int
    +}
    @@ -81,10 +78,9 @@ files and folders into the application binary.

    -
    func (b base) describe() string {
    -    return fmt.Sprintf("base with num=%v", b.num)
    -}
    -
    +
    func (b base) describe() string {
    +    return fmt.Sprintf("base with num=%v", b.num)
    +}
    @@ -96,12 +92,10 @@ like a field without a name.

    -
    -type container struct {
    -    base
    -    str string
    -}
    -
    +
    type container struct {
    +    base
    +    str string
    +}
    @@ -111,8 +105,7 @@ like a field without a name.

    -
    func main() {
    -
    +
    func main() {
    @@ -125,14 +118,12 @@ embedded type serves as the field name.

    -
    -    co := container{
    -        base: base{
    -            num: 1,
    -        },
    -        str: "some name",
    -    }
    -
    +
        co := container{
    +        base: base{
    +            num: 1,
    +        },
    +        str: "some name",
    +    }
    @@ -144,9 +135,7 @@ e.g. co.num.

    -
    -    fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
    -
    +
        fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
    @@ -158,9 +147,7 @@ the embedded type name.

    -
    -    fmt.Println("also num:", co.base.num)
    -
    +
        fmt.Println("also num:", co.base.num)
    @@ -174,9 +161,7 @@ directly on co.

    -
    -    fmt.Println("describe:", co.describe())
    -
    +
        fmt.Println("describe:", co.describe())
    @@ -186,10 +171,9 @@ directly on co.

    -
        type describer interface {
    -        describe() string
    -    }
    -
    +
        type describer interface {
    +        describe() string
    +    }
    @@ -203,11 +187,9 @@ we see that a container now implements the -
    -    var d describer = co
    -    fmt.Println("describer:", d.describe())
    -}
    -
    +
        var d describer = co
    +    fmt.Println("describer:", d.describe())
    +}
    @@ -221,11 +203,11 @@ we see that a container now implements the -
    $ go run struct-embedding.go
    -co={num: 1, str: some name}
    -also num: 1
    -describe: base with num=1
    -describer: base with num=1
    +
    $ go run struct-embedding.go
    +co={num: 1, str: some name}
    +also num: 1
    +describe: base with num=1
    +describer: base with num=1
    diff --git a/public/structs b/public/structs index 40e92dfaf..15a573ae9 100644 --- a/public/structs +++ b/public/structs @@ -44,8 +44,7 @@ records.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ records.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -67,12 +65,10 @@ records.

    -
    -type person struct {
    -    name string
    -    age  int
    -}
    -
    +
    type person struct {
    +    name string
    +    age  int
    +}
    @@ -83,9 +79,7 @@ records.

    -
    -func newPerson(name string) *person {
    -
    +
    func newPerson(name string) *person {
    @@ -97,12 +91,10 @@ as a local variable will survive the scope of the function.

    -
    -    p := person{name: name}
    -    p.age = 42
    -    return &p
    -}
    -
    +
        p := person{name: name}
    +    p.age = 42
    +    return &p
    +}
    @@ -112,8 +104,7 @@ as a local variable will survive the scope of the function.

    -
    func main() {
    -
    +
    func main() {
    @@ -124,9 +115,7 @@ as a local variable will survive the scope of the function.

    -
    -    fmt.Println(person{"Bob", 20})
    -
    +
        fmt.Println(person{"Bob", 20})
    @@ -137,9 +126,7 @@ as a local variable will survive the scope of the function.

    -
    -    fmt.Println(person{name: "Alice", age: 30})
    -
    +
        fmt.Println(person{name: "Alice", age: 30})
    @@ -150,9 +137,7 @@ as a local variable will survive the scope of the function.

    -
    -    fmt.Println(person{name: "Fred"})
    -
    +
        fmt.Println(person{name: "Fred"})
    @@ -163,9 +148,7 @@ as a local variable will survive the scope of the function.

    -
    -    fmt.Println(&person{name: "Ann", age: 40})
    -
    +
        fmt.Println(&person{name: "Ann", age: 40})
    @@ -176,9 +159,7 @@ as a local variable will survive the scope of the function.

    -
    -    fmt.Println(newPerson("Jon"))
    -
    +
        fmt.Println(newPerson("Jon"))
    @@ -189,10 +170,8 @@ as a local variable will survive the scope of the function.

    -
    -    s := person{name: "Sean", age: 50}
    -    fmt.Println(s.name)
    -
    +
        s := person{name: "Sean", age: 50}
    +    fmt.Println(s.name)
    @@ -204,10 +183,8 @@ pointers are automatically dereferenced.

    -
    -    sp := &s
    -    fmt.Println(sp.age)
    -
    +
        sp := &s
    +    fmt.Println(sp.age)
    @@ -218,10 +195,8 @@ pointers are automatically dereferenced.

    -
    -    sp.age = 51
    -    fmt.Println(sp.age)
    -
    +
        sp.age = 51
    +    fmt.Println(sp.age)
    @@ -235,17 +210,15 @@ struct type. This technique is commonly used for -
    -    dog := struct {
    -        name   string
    -        isGood bool
    -    }{
    -        "Rex",
    -        true,
    -    }
    -    fmt.Println(dog)
    -}
    -
    +
        dog := struct {
    +        name   string
    +        isGood bool
    +    }{
    +        "Rex",
    +        true,
    +    }
    +    fmt.Println(dog)
    +}
    @@ -259,16 +232,16 @@ struct type. This technique is commonly used for -
    $ go run structs.go
    -{Bob 20}
    -{Alice 30}
    -{Fred 0}
    -&{Ann 40}
    -&{Jon 42}
    -Sean
    -50
    -51
    -{Rex true}
    +
    $ go run structs.go
    +{Bob 20}
    +{Alice 30}
    +{Fred 0}
    +&{Ann 40}
    +&{Jon 42}
    +Sean
    +50
    +51
    +{Rex true}
    diff --git a/public/switch b/public/switch index aaab93d07..947a66fed 100644 --- a/public/switch +++ b/public/switch @@ -43,8 +43,7 @@ branches.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ branches.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -68,8 +66,7 @@ branches.

    -
    func main() {
    -
    +
    func main() {
    @@ -80,18 +77,16 @@ branches.

    -
    -    i := 2
    -    fmt.Print("Write ", i, " as ")
    -    switch i {
    -    case 1:
    -        fmt.Println("one")
    -    case 2:
    -        fmt.Println("two")
    -    case 3:
    -        fmt.Println("three")
    -    }
    -
    +
        i := 2
    +    fmt.Print("Write ", i, " as ")
    +    switch i {
    +    case 1:
    +        fmt.Println("one")
    +    case 2:
    +        fmt.Println("two")
    +    case 3:
    +        fmt.Println("three")
    +    }
    @@ -104,14 +99,12 @@ in the same case statement. We use the optional -
    -    switch time.Now().Weekday() {
    -    case time.Saturday, time.Sunday:
    -        fmt.Println("It's the weekend")
    -    default:
    -        fmt.Println("It's a weekday")
    -    }
    -
    +
        switch time.Now().Weekday() {
    +    case time.Saturday, time.Sunday:
    +        fmt.Println("It's the weekend")
    +    default:
    +        fmt.Println("It's a weekday")
    +    }
    @@ -124,15 +117,13 @@ to express if/else logic. Here we also show how the -
    -    t := time.Now()
    -    switch {
    -    case t.Hour() < 12:
    -        fmt.Println("It's before noon")
    -    default:
    -        fmt.Println("It's after noon")
    -    }
    -
    +
        t := time.Now()
    +    switch {
    +    case t.Hour() < 12:
    +        fmt.Println("It's before noon")
    +    default:
    +        fmt.Println("It's after noon")
    +    }
    @@ -146,22 +137,20 @@ type corresponding to its clause.

    -
    -    whatAmI := func(i interface{}) {
    -        switch t := i.(type) {
    -        case bool:
    -            fmt.Println("I'm a bool")
    -        case int:
    -            fmt.Println("I'm an int")
    -        default:
    -            fmt.Printf("Don't know type %T\n", t)
    -        }
    -    }
    -    whatAmI(true)
    -    whatAmI(1)
    -    whatAmI("hey")
    -}
    -
    +
        whatAmI := func(i interface{}) {
    +        switch t := i.(type) {
    +        case bool:
    +            fmt.Println("I'm a bool")
    +        case int:
    +            fmt.Println("I'm an int")
    +        default:
    +            fmt.Printf("Don't know type %T\n", t)
    +        }
    +    }
    +    whatAmI(true)
    +    whatAmI(1)
    +    whatAmI("hey")
    +}
    @@ -175,13 +164,13 @@ type corresponding to its clause.

    -
    $ go run switch.go 
    -Write 2 as two
    -It's a weekday
    -It's after noon
    -I'm a bool
    -I'm an int
    -Don't know type string
    +
    $ go run switch.go 
    +Write 2 as two
    +It's a weekday
    +It's after noon
    +I'm a bool
    +I'm an int
    +Don't know type string
    diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index fc173a71d..bcb035452 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -46,8 +46,7 @@ time.

    -
    package main
    -
    +
    package main
    @@ -57,12 +56,11 @@ time.

    -
    import (
    -    "fmt"
    -    "os"
    -    "path/filepath"
    -)
    -
    +
    import (
    +    "fmt"
    +    "os"
    +    "path/filepath"
    +)
    @@ -72,12 +70,11 @@ time.

    -
    func check(e error) {
    -    if e != nil {
    -        panic(e)
    -    }
    -}
    -
    +
    func check(e error) {
    +    if e != nil {
    +        panic(e)
    +    }
    +}
    @@ -87,8 +84,7 @@ time.

    -
    func main() {
    -
    +
    func main() {
    @@ -103,10 +99,8 @@ create the file in the default location for our OS.

    -
    -    f, err := os.CreateTemp("", "sample")
    -    check(err)
    -
    +
        f, err := os.CreateTemp("", "sample")
    +    check(err)
    @@ -122,9 +116,7 @@ calls will always create different file names.

    -
    -    fmt.Println("Temp file name:", f.Name())
    -
    +
        fmt.Println("Temp file name:", f.Name())
    @@ -138,9 +130,7 @@ explicitly.

    -
    -    defer os.Remove(f.Name())
    -
    +
        defer os.Remove(f.Name())
    @@ -151,10 +141,8 @@ explicitly.

    -
    -    _, err = f.Write([]byte{1, 2, 3, 4})
    -    check(err)
    -
    +
        _, err = f.Write([]byte{1, 2, 3, 4})
    +    check(err)
    @@ -169,11 +157,9 @@ rather than an open file.

    -
    -    dname, err := os.MkdirTemp("", "sampledir")
    -    check(err)
    -    fmt.Println("Temp dir name:", dname)
    -
    +
        dname, err := os.MkdirTemp("", "sampledir")
    +    check(err)
    +    fmt.Println("Temp dir name:", dname)
    @@ -183,8 +169,7 @@ rather than an open file.

    -
        defer os.RemoveAll(dname)
    -
    +
        defer os.RemoveAll(dname)
    @@ -196,12 +181,10 @@ prefixing them with our temporary directory.

    -
    -    fname := filepath.Join(dname, "file1")
    -    err = os.WriteFile(fname, []byte{1, 2}, 0666)
    -    check(err)
    -}
    -
    +
        fname := filepath.Join(dname, "file1")
    +    err = os.WriteFile(fname, []byte{1, 2}, 0666)
    +    check(err)
    +}
    @@ -215,9 +198,9 @@ prefixing them with our temporary directory.

    -
    $ go run temporary-files-and-directories.go
    -Temp file name: /tmp/sample610887201
    -Temp dir name: /tmp/sampledir898854668
    +
    $ go run temporary-files-and-directories.go
    +Temp file name: /tmp/sample610887201
    +Temp dir name: /tmp/sampledir898854668
    diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking index 176b37f50..edefa47c6 100644 --- a/public/testing-and-benchmarking +++ b/public/testing-and-benchmarking @@ -48,9 +48,7 @@ typically lives in the same package as the code it tests.

    -
    -package main
    -
    +
    package main
    @@ -60,11 +58,10 @@ typically lives in the same package as the code it tests.

    -
    import (
    -    "fmt"
    -    "testing"
    -)
    -
    +
    import (
    +    "fmt"
    +    "testing"
    +)
    @@ -79,14 +76,12 @@ be named intutils_test.go.

    -
    -func IntMin(a, b int) int {
    -    if a < b {
    -        return a
    -    }
    -    return b
    -}
    -
    +
    func IntMin(a, b int) int {
    +    if a < b {
    +        return a
    +    }
    +    return b
    +}
    @@ -98,11 +93,9 @@ beginning with Test.

    -
    -func TestIntMinBasic(t *testing.T) {
    -    ans := IntMin(2, -2)
    -    if ans != -2 {
    -
    +
    func TestIntMinBasic(t *testing.T) {
    +    ans := IntMin(2, -2)
    +    if ans != -2 {
    @@ -115,11 +108,9 @@ failures and stop the test immediately.

    -
    -        t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    -    }
    -}
    -
    +
            t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    +    }
    +}
    @@ -133,19 +124,17 @@ walks over them and performs the test logic.

    -
    -func TestIntMinTableDriven(t *testing.T) {
    -    var tests = []struct {
    -        a, b int
    -        want int
    -    }{
    -        {0, 1, 0},
    -        {1, 0, 0},
    -        {2, -2, -2},
    -        {0, -1, -1},
    -        {-1, 0, -1},
    -    }
    -
    +
    func TestIntMinTableDriven(t *testing.T) {
    +    var tests = []struct {
    +        a, b int
    +        want int
    +    }{
    +        {0, 1, 0},
    +        {1, 0, 0},
    +        {2, -2, -2},
    +        {0, -1, -1},
    +        {-1, 0, -1},
    +    }
    @@ -158,8 +147,7 @@ when executing go test -v.

    -
        for _, tt := range tests {
    -
    +
        for _, tt := range tests {
    @@ -169,16 +157,15 @@ when executing go test -v.

    -
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
    -        t.Run(testname, func(t *testing.T) {
    -            ans := IntMin(tt.a, tt.b)
    -            if ans != tt.want {
    -                t.Errorf("got %d, want %d", ans, tt.want)
    -            }
    -        })
    -    }
    -}
    -
    +
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
    +        t.Run(testname, func(t *testing.T) {
    +            ans := IntMin(tt.a, tt.b)
    +            if ans != tt.want {
    +                t.Errorf("got %d, want %d", ans, tt.want)
    +            }
    +        })
    +    }
    +}
    @@ -192,9 +179,7 @@ executes each benchmark function several times, increasing -
    -func BenchmarkIntMin(b *testing.B) {
    -
    +
    func BenchmarkIntMin(b *testing.B) {
    @@ -206,12 +191,10 @@ benchmarking in a loop b.N times.

    -
    -    for i := 0; i < b.N; i++ {
    -        IntMin(1, 2)
    -    }
    -}
    -
    +
        for i := 0; i < b.N; i++ {
    +        IntMin(1, 2)
    +    }
    +}
    @@ -226,24 +209,23 @@ benchmarking in a loop b.N times.

    -
    -$ go test -v
    -== RUN   TestIntMinBasic
    ---- PASS: TestIntMinBasic (0.00s)
    -=== RUN   TestIntMinTableDriven
    -=== RUN   TestIntMinTableDriven/0,1
    -=== RUN   TestIntMinTableDriven/1,0
    -=== RUN   TestIntMinTableDriven/2,-2
    -=== RUN   TestIntMinTableDriven/0,-1
    -=== RUN   TestIntMinTableDriven/-1,0
    ---- PASS: TestIntMinTableDriven (0.00s)
    -    --- PASS: TestIntMinTableDriven/0,1 (0.00s)
    -    --- PASS: TestIntMinTableDriven/1,0 (0.00s)
    -    --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
    -    --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
    -    --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
    -PASS
    -ok      examples/testing-and-benchmarking    0.023s
    +
    $ go test -v
    +== RUN   TestIntMinBasic
    +--- PASS: TestIntMinBasic (0.00s)
    +=== RUN   TestIntMinTableDriven
    +=== RUN   TestIntMinTableDriven/0,1
    +=== RUN   TestIntMinTableDriven/1,0
    +=== RUN   TestIntMinTableDriven/2,-2
    +=== RUN   TestIntMinTableDriven/0,-1
    +=== RUN   TestIntMinTableDriven/-1,0
    +--- PASS: TestIntMinTableDriven (0.00s)
    +    --- PASS: TestIntMinTableDriven/0,1 (0.00s)
    +    --- PASS: TestIntMinTableDriven/1,0 (0.00s)
    +    --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
    +    --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
    +    --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
    +PASS
    +ok      examples/testing-and-benchmarking    0.023s
    @@ -256,14 +238,13 @@ benchmark function names with a regexp.

    -
    -$ go test -bench=.
    -goos: darwin
    -goarch: arm64
    -pkg: examples/testing
    -BenchmarkIntMin-8 1000000000 0.3136 ns/op
    -PASS
    -ok      examples/testing-and-benchmarking    0.351s
    +
    $ go test -bench=.
    +goos: darwin
    +goarch: arm64
    +pkg: examples/testing
    +BenchmarkIntMin-8 1000000000 0.3136 ns/op
    +PASS
    +ok      examples/testing-and-benchmarking    0.351s
    diff --git a/public/text-templates b/public/text-templates index df0d536f2..43b39dab3 100644 --- a/public/text-templates +++ b/public/text-templates @@ -45,8 +45,7 @@ features and should be used for generating HTML.

    -
    package main
    -
    +
    package main
    @@ -56,11 +55,10 @@ features and should be used for generating HTML.

    -
    import (
    -    "os"
    -    "text/template"
    -)
    -
    +
    import (
    +    "os"
    +    "text/template"
    +)
    @@ -70,8 +68,7 @@ features and should be used for generating HTML.

    -
    func main() {
    -
    +
    func main() {
    @@ -85,13 +82,11 @@ Templates are a mix of static text and “actions” enclosed in -
    -    t1 := template.New("t1")
    -    t1, err := t1.Parse("Value is {{.}}\n")
    -    if err != nil {
    -        panic(err)
    -    }
    -
    +
        t1 := template.New("t1")
    +    t1, err := t1.Parse("Value is {{.}}\n")
    +    if err != nil {
    +        panic(err)
    +    }
    @@ -104,9 +99,7 @@ useful for templates initialized in the global scope.

    -
    -    t1 = template.Must(t1.Parse("Value: {{.}}\n"))
    -
    +
        t1 = template.Must(t1.Parse("Value: {{.}}\n"))
    @@ -119,16 +112,14 @@ replaced by the value passed as a parameter to Execute.

    -
    -    t1.Execute(os.Stdout, "some text")
    -    t1.Execute(os.Stdout, 5)
    -    t1.Execute(os.Stdout, []string{
    -        "Go",
    -        "Rust",
    -        "C++",
    -        "C#",
    -    })
    -
    +
        t1.Execute(os.Stdout, "some text")
    +    t1.Execute(os.Stdout, 5)
    +    t1.Execute(os.Stdout, []string{
    +        "Go",
    +        "Rust",
    +        "C++",
    +        "C#",
    +    })
    @@ -139,11 +130,9 @@ replaced by the value passed as a parameter to Execute.

    -
    -    Create := func(name, t string) *template.Template {
    -        return template.Must(template.New(name).Parse(t))
    -    }
    -
    +
        Create := func(name, t string) *template.Template {
    +        return template.Must(template.New(name).Parse(t))
    +    }
    @@ -156,9 +145,7 @@ template is executing.

    -
    -    t2 := Create("t2", "Name: {{.Name}}\n")
    -
    +
        t2 := Create("t2", "Name: {{.Name}}\n")
    @@ -168,10 +155,9 @@ template is executing.

    -
        t2.Execute(os.Stdout, struct {
    -        Name string
    -    }{"Jane Doe"})
    -
    +
        t2.Execute(os.Stdout, struct {
    +        Name string
    +    }{"Jane Doe"})
    @@ -183,11 +169,9 @@ case of key names.

    -
    -    t2.Execute(os.Stdout, map[string]string{
    -        "Name": "Mickey Mouse",
    -    })
    -
    +
        t2.Execute(os.Stdout, map[string]string{
    +        "Name": "Mickey Mouse",
    +    })
    @@ -202,12 +186,10 @@ feature of templates: using - in actions to trim whitespace.

    -
    -    t3 := Create("t3",
    -        "{{if . -}} yes {{else -}} no {{end}}\n")
    -    t3.Execute(os.Stdout, "not empty")
    -    t3.Execute(os.Stdout, "")
    -
    +
        t3 := Create("t3",
    +        "{{if . -}} yes {{else -}} no {{end}}\n")
    +    t3.Execute(os.Stdout, "not empty")
    +    t3.Execute(os.Stdout, "")
    @@ -219,18 +201,16 @@ the range block {{.}} is set to the current item of the iteration.< -
    -    t4 := Create("t4",
    -        "Range: {{range .}}{{.}} {{end}}\n")
    -    t4.Execute(os.Stdout,
    -        []string{
    -            "Go",
    -            "Rust",
    -            "C++",
    -            "C#",
    -        })
    -}
    -
    +
        t4 := Create("t4",
    +        "Range: {{range .}}{{.}} {{end}}\n")
    +    t4.Execute(os.Stdout,
    +        []string{
    +            "Go",
    +            "Rust",
    +            "C++",
    +            "C#",
    +        })
    +}
    @@ -244,15 +224,15 @@ the range block {{.}} is set to the current item of the iteration.< -
    $ go run templates.go 
    -Value: some text
    -Value: 5
    -Value: [Go Rust C++ C#]
    -Name: Jane Doe
    -Name: Mickey Mouse
    -yes 
    -no 
    -Range: Go Rust C++ C# 
    +
    $ go run templates.go 
    +Value: some text
    +Value: 5
    +Value: [Go Rust C++ C#]
    +Name: Jane Doe
    +Name: Mickey Mouse
    +yes 
    +no 
    +Range: Go Rust C++ C# 
    diff --git a/public/tickers b/public/tickers index 97ca3b53e..f3702252b 100644 --- a/public/tickers +++ b/public/tickers @@ -46,8 +46,7 @@ periodically until we stop it.

    -
    package main
    -
    +
    package main
    @@ -57,11 +56,10 @@ periodically until we stop it.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -71,8 +69,7 @@ periodically until we stop it.

    -
    func main() {
    -
    +
    func main() {
    @@ -86,10 +83,8 @@ values as they arrive every 500ms.

    -
    -    ticker := time.NewTicker(500 * time.Millisecond)
    -    done := make(chan bool)
    -
    +
        ticker := time.NewTicker(500 * time.Millisecond)
    +    done := make(chan bool)
    @@ -99,17 +94,16 @@ values as they arrive every 500ms.

    -
        go func() {
    -        for {
    -            select {
    -            case <-done:
    -                return
    -            case t := <-ticker.C:
    -                fmt.Println("Tick at", t)
    -            }
    -        }
    -    }()
    -
    +
        go func() {
    +        for {
    +            select {
    +            case <-done:
    +                return
    +            case t := <-ticker.C:
    +                fmt.Println("Tick at", t)
    +            }
    +        }
    +    }()
    @@ -122,13 +116,11 @@ channel. We’ll stop ours after 1600ms.

    -
    -    time.Sleep(1600 * time.Millisecond)
    -    ticker.Stop()
    -    done <- true
    -    fmt.Println("Ticker stopped")
    -}
    -
    +
        time.Sleep(1600 * time.Millisecond)
    +    ticker.Stop()
    +    done <- true
    +    fmt.Println("Ticker stopped")
    +}
    @@ -144,12 +136,11 @@ before we stop it.

    -
    -$ go run tickers.go
    -Tick at 2012-09-23 11:29:56.487625 -0700 PDT
    -Tick at 2012-09-23 11:29:56.988063 -0700 PDT
    -Tick at 2012-09-23 11:29:57.488076 -0700 PDT
    -Ticker stopped
    +
    $ go run tickers.go
    +Tick at 2012-09-23 11:29:56.487625 -0700 PDT
    +Tick at 2012-09-23 11:29:56.988063 -0700 PDT
    +Tick at 2012-09-23 11:29:57.488076 -0700 PDT
    +Ticker stopped
    diff --git a/public/time b/public/time index c8a2d52c9..7b46e75dd 100644 --- a/public/time +++ b/public/time @@ -43,8 +43,7 @@ here are some examples.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ here are some examples.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -68,9 +66,8 @@ here are some examples.

    -
    func main() {
    -    p := fmt.Println
    -
    +
    func main() {
    +    p := fmt.Println
    @@ -81,10 +78,8 @@ here are some examples.

    -
    -    now := time.Now()
    -    p(now)
    -
    +
        now := time.Now()
    +    p(now)
    @@ -97,11 +92,9 @@ with a Location, i.e. time zone.

    -
    -    then := time.Date(
    -        2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
    -    p(then)
    -
    +
        then := time.Date(
    +        2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
    +    p(then)
    @@ -113,16 +106,14 @@ value as expected.

    -
    -    p(then.Year())
    -    p(then.Month())
    -    p(then.Day())
    -    p(then.Hour())
    -    p(then.Minute())
    -    p(then.Second())
    -    p(then.Nanosecond())
    -    p(then.Location())
    -
    +
        p(then.Year())
    +    p(then.Month())
    +    p(then.Day())
    +    p(then.Hour())
    +    p(then.Minute())
    +    p(then.Second())
    +    p(then.Nanosecond())
    +    p(then.Location())
    @@ -133,9 +124,7 @@ value as expected.

    -
    -    p(then.Weekday())
    -
    +
        p(then.Weekday())
    @@ -148,11 +137,9 @@ as the second, respectively.

    -
    -    p(then.Before(now))
    -    p(then.After(now))
    -    p(then.Equal(now))
    -
    +
        p(then.Before(now))
    +    p(then.After(now))
    +    p(then.Equal(now))
    @@ -164,10 +151,8 @@ the interval between two times.

    -
    -    diff := now.Sub(then)
    -    p(diff)
    -
    +
        diff := now.Sub(then)
    +    p(diff)
    @@ -179,12 +164,10 @@ various units.

    -
    -    p(diff.Hours())
    -    p(diff.Minutes())
    -    p(diff.Seconds())
    -    p(diff.Nanoseconds())
    -
    +
        p(diff.Hours())
    +    p(diff.Minutes())
    +    p(diff.Seconds())
    +    p(diff.Nanoseconds())
    @@ -197,11 +180,9 @@ duration.

    -
    -    p(then.Add(diff))
    -    p(then.Add(-diff))
    -}
    -
    +
        p(then.Add(diff))
    +    p(then.Add(-diff))
    +}
    @@ -215,28 +196,28 @@ duration.

    -
    $ go run time.go
    -2012-10-31 15:50:13.793654 +0000 UTC
    -2009-11-17 20:34:58.651387237 +0000 UTC
    -2009
    -November
    -17
    -20
    -34
    -58
    -651387237
    -UTC
    -Tuesday
    -true
    -false
    -false
    -25891h15m15.142266763s
    -25891.25420618521
    -1.5534752523711128e+06
    -9.320851514226677e+07
    -93208515142266763
    -2012-10-31 15:50:13.793654 +0000 UTC
    -2006-12-05 01:19:43.509120474 +0000 UTC
    +
    $ go run time.go
    +2012-10-31 15:50:13.793654 +0000 UTC
    +2009-11-17 20:34:58.651387237 +0000 UTC
    +2009
    +November
    +17
    +20
    +34
    +58
    +651387237
    +UTC
    +Tuesday
    +true
    +false
    +false
    +25891h15m15.142266763s
    +25891.25420618521
    +1.5534752523711128e+06
    +9.320851514226677e+07
    +93208515142266763
    +2012-10-31 15:50:13.793654 +0000 UTC
    +2006-12-05 01:19:43.509120474 +0000 UTC
    diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index 799989089..a82af482c 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -43,8 +43,7 @@ pattern-based layouts.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ pattern-based layouts.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -68,9 +66,8 @@ pattern-based layouts.

    -
    func main() {
    -    p := fmt.Println
    -
    +
    func main() {
    +    p := fmt.Println
    @@ -83,10 +80,8 @@ constant.

    -
    -    t := time.Now()
    -    p(t.Format(time.RFC3339))
    -
    +
        t := time.Now()
    +    p(t.Format(time.RFC3339))
    @@ -97,12 +92,10 @@ constant.

    -
    -    t1, e := time.Parse(
    -        time.RFC3339,
    -        "2012-11-01T22:08:41+00:00")
    -    p(t1)
    -
    +
        t1, e := time.Parse(
    +        time.RFC3339,
    +        "2012-11-01T22:08:41+00:00")
    +    p(t1)
    @@ -119,14 +112,12 @@ The example time must be exactly as shown: the year 2006, -
    -    p(t.Format("3:04PM"))
    -    p(t.Format("Mon Jan _2 15:04:05 2006"))
    -    p(t.Format("2006-01-02T15:04:05.999999-07:00"))
    -    form := "3 04 PM"
    -    t2, e := time.Parse(form, "8 41 PM")
    -    p(t2)
    -
    +
        p(t.Format("3:04PM"))
    +    p(t.Format("Mon Jan _2 15:04:05 2006"))
    +    p(t.Format("2006-01-02T15:04:05.999999-07:00"))
    +    form := "3 04 PM"
    +    t2, e := time.Parse(form, "8 41 PM")
    +    p(t2)
    @@ -139,11 +130,9 @@ components of the time value.

    -
    -    fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
    -        t.Year(), t.Month(), t.Day(),
    -        t.Hour(), t.Minute(), t.Second())
    -
    +
        fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
    +        t.Year(), t.Month(), t.Day(),
    +        t.Hour(), t.Minute(), t.Second())
    @@ -155,12 +144,10 @@ explaining the parsing problem.

    -
    -    ansic := "Mon Jan _2 15:04:05 2006"
    -    _, e = time.Parse(ansic, "8:41PM")
    -    p(e)
    -}
    -
    +
        ansic := "Mon Jan _2 15:04:05 2006"
    +    _, e = time.Parse(ansic, "8:41PM")
    +    p(e)
    +}
    @@ -174,15 +161,15 @@ explaining the parsing problem.

    -
    $ go run time-formatting-parsing.go 
    -2014-04-15T18:00:15-07:00
    -2012-11-01 22:08:41 +0000 +0000
    -6:00PM
    -Tue Apr 15 18:00:15 2014
    -2014-04-15T18:00:15.161182-07:00
    -0000-01-01 20:41:00 +0000 UTC
    -2014-04-15T18:00:15-00:00
    -parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": ...
    +
    $ go run time-formatting-parsing.go 
    +2014-04-15T18:00:15-07:00
    +2012-11-01 22:08:41 +0000 +0000
    +6:00PM
    +Tue Apr 15 18:00:15 2014
    +2014-04-15T18:00:15.161182-07:00
    +0000-01-01 20:41:00 +0000 UTC
    +2014-04-15T18:00:15-00:00
    +parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": ...
    diff --git a/public/timeouts b/public/timeouts index db72edf10..39e2ffd46 100644 --- a/public/timeouts +++ b/public/timeouts @@ -45,8 +45,7 @@ elegant thanks to channels and select.

    -
    package main
    -
    +
    package main
    @@ -56,11 +55,10 @@ elegant thanks to channels and select.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -70,8 +68,7 @@ elegant thanks to channels and select.

    -
    func main() {
    -
    +
    func main() {
    @@ -87,13 +84,11 @@ channel is never read.

    -
    -    c1 := make(chan string, 1)
    -    go func() {
    -        time.Sleep(2 * time.Second)
    -        c1 <- "result 1"
    -    }()
    -
    +
        c1 := make(chan string, 1)
    +    go func() {
    +        time.Sleep(2 * time.Second)
    +        c1 <- "result 1"
    +    }()
    @@ -109,14 +104,12 @@ if the operation takes more than the allowed 1s.

    -
    -    select {
    -    case res := <-c1:
    -        fmt.Println(res)
    -    case <-time.After(1 * time.Second):
    -        fmt.Println("timeout 1")
    -    }
    -
    +
        select {
    +    case res := <-c1:
    +        fmt.Println(res)
    +    case <-time.After(1 * time.Second):
    +        fmt.Println("timeout 1")
    +    }
    @@ -128,20 +121,18 @@ from c2 will succeed and we’ll print the result.

    -
    -    c2 := make(chan string, 1)
    -    go func() {
    -        time.Sleep(2 * time.Second)
    -        c2 <- "result 2"
    -    }()
    -    select {
    -    case res := <-c2:
    -        fmt.Println(res)
    -    case <-time.After(3 * time.Second):
    -        fmt.Println("timeout 2")
    -    }
    -}
    -
    +
        c2 := make(chan string, 1)
    +    go func() {
    +        time.Sleep(2 * time.Second)
    +        c2 <- "result 2"
    +    }()
    +    select {
    +    case res := <-c2:
    +        fmt.Println(res)
    +    case <-time.After(3 * time.Second):
    +        fmt.Println("timeout 2")
    +    }
    +}
    @@ -157,10 +148,9 @@ out and the second succeeding.

    -
    -$ go run timeouts.go 
    -timeout 1
    -result 2
    +
    $ go run timeouts.go 
    +timeout 1
    +result 2
    diff --git a/public/timers b/public/timers index 2f1f1c967..107d9150a 100644 --- a/public/timers +++ b/public/timers @@ -46,8 +46,7 @@ at tickers.

    -
    package main
    -
    +
    package main
    @@ -57,11 +56,10 @@ at tickers.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -71,8 +69,7 @@ at tickers.

    -
    func main() {
    -
    +
    func main() {
    @@ -86,9 +83,7 @@ time. This timer will wait 2 seconds.

    -
    -    timer1 := time.NewTimer(2 * time.Second)
    -
    +
        timer1 := time.NewTimer(2 * time.Second)
    @@ -101,10 +96,8 @@ fired.

    -
    -    <-timer1.C
    -    fmt.Println("Timer 1 fired")
    -
    +
        <-timer1.C
    +    fmt.Println("Timer 1 fired")
    @@ -118,17 +111,15 @@ Here’s an example of that.

    -
    -    timer2 := time.NewTimer(time.Second)
    -    go func() {
    -        <-timer2.C
    -        fmt.Println("Timer 2 fired")
    -    }()
    -    stop2 := timer2.Stop()
    -    if stop2 {
    -        fmt.Println("Timer 2 stopped")
    -    }
    -
    +
        timer2 := time.NewTimer(time.Second)
    +    go func() {
    +        <-timer2.C
    +        fmt.Println("Timer 2 fired")
    +    }()
    +    stop2 := timer2.Stop()
    +    if stop2 {
    +        fmt.Println("Timer 2 stopped")
    +    }
    @@ -140,10 +131,8 @@ was going to, to show it is in fact stopped.

    -
    -    time.Sleep(2 * time.Second)
    -}
    -
    +
        time.Sleep(2 * time.Second)
    +}
    @@ -160,10 +149,9 @@ a chance to fire.

    -
    -$ go run timers.go
    -Timer 1 fired
    -Timer 2 stopped
    +
    $ go run timers.go
    +Timer 1 fired
    +Timer 2 stopped
    diff --git a/public/url-parsing b/public/url-parsing index 61989e409..4b6bc03ae 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -43,8 +43,7 @@ Here’s how to parse URLs in Go.

    -
    package main
    -
    +
    package main
    @@ -54,12 +53,11 @@ Here’s how to parse URLs in Go.

    -
    import (
    -    "fmt"
    -    "net"
    -    "net/url"
    -)
    -
    +
    import (
    +    "fmt"
    +    "net"
    +    "net/url"
    +)
    @@ -69,8 +67,7 @@ Here’s how to parse URLs in Go.

    -
    func main() {
    -
    +
    func main() {
    @@ -83,9 +80,7 @@ query params, and query fragment.

    -
    -    s := "postgres://user:pass@host.com:5432/path?k=v#f"
    -
    +
        s := "postgres://user:pass@host.com:5432/path?k=v#f"
    @@ -96,12 +91,10 @@ query params, and query fragment.

    -
    -    u, err := url.Parse(s)
    -    if err != nil {
    -        panic(err)
    -    }
    -
    +
        u, err := url.Parse(s)
    +    if err != nil {
    +        panic(err)
    +    }
    @@ -112,9 +105,7 @@ query params, and query fragment.

    -
    -    fmt.Println(u.Scheme)
    -
    +
        fmt.Println(u.Scheme)
    @@ -127,12 +118,10 @@ values.

    -
    -    fmt.Println(u.User)
    -    fmt.Println(u.User.Username())
    -    p, _ := u.User.Password()
    -    fmt.Println(p)
    -
    +
        fmt.Println(u.User)
    +    fmt.Println(u.User.Username())
    +    p, _ := u.User.Password()
    +    fmt.Println(p)
    @@ -144,12 +133,10 @@ if present. Use SplitHostPort to extract them.

    -
    -    fmt.Println(u.Host)
    -    host, port, _ := net.SplitHostPort(u.Host)
    -    fmt.Println(host)
    -    fmt.Println(port)
    -
    +
        fmt.Println(u.Host)
    +    host, port, _ := net.SplitHostPort(u.Host)
    +    fmt.Println(host)
    +    fmt.Println(port)
    @@ -161,10 +148,8 @@ the #.

    -
    -    fmt.Println(u.Path)
    -    fmt.Println(u.Fragment)
    -
    +
        fmt.Println(u.Path)
    +    fmt.Println(u.Fragment)
    @@ -179,13 +164,11 @@ if you only want the first value.

    -
    -    fmt.Println(u.RawQuery)
    -    m, _ := url.ParseQuery(u.RawQuery)
    -    fmt.Println(m)
    -    fmt.Println(m["k"][0])
    -}
    -
    +
        fmt.Println(u.RawQuery)
    +    m, _ := url.ParseQuery(u.RawQuery)
    +    fmt.Println(m)
    +    fmt.Println(m["k"][0])
    +}
    @@ -201,20 +184,19 @@ pieces that we extracted.

    -
    -$ go run url-parsing.go 
    -postgres
    -user:pass
    -user
    -pass
    -host.com:5432
    -host.com
    -5432
    -/path
    -f
    -k=v
    -map[k:[v]]
    -v
    +
    $ go run url-parsing.go 
    +postgres
    +user:pass
    +user
    +pass
    +host.com:5432
    +host.com
    +5432
    +/path
    +f
    +k=v
    +map[k:[v]]
    +v
    diff --git a/public/values b/public/values index 1f04b3776..6aece1bfe 100644 --- a/public/values +++ b/public/values @@ -44,8 +44,7 @@ basic examples.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ basic examples.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -66,8 +64,7 @@ basic examples.

    -
    func main() {
    -
    +
    func main() {
    @@ -78,9 +75,7 @@ basic examples.

    -
    -    fmt.Println("go" + "lang")
    -
    +
        fmt.Println("go" + "lang")
    @@ -91,10 +86,8 @@ basic examples.

    -
    -    fmt.Println("1+1 =", 1+1)
    -    fmt.Println("7.0/3.0 =", 7.0/3.0)
    -
    +
        fmt.Println("1+1 =", 1+1)
    +    fmt.Println("7.0/3.0 =", 7.0/3.0)
    @@ -105,12 +98,10 @@ basic examples.

    -
    -    fmt.Println(true && false)
    -    fmt.Println(true || false)
    -    fmt.Println(!true)
    -}
    -
    +
        fmt.Println(true && false)
    +    fmt.Println(true || false)
    +    fmt.Println(!true)
    +}
    @@ -124,13 +115,13 @@ basic examples.

    -
    $ go run values.go
    -golang
    -1+1 = 2
    -7.0/3.0 = 2.3333333333333335
    -false
    -true
    -false
    +
    $ go run values.go
    +golang
    +1+1 = 2
    +7.0/3.0 = 2.3333333333333335
    +false
    +true
    +false
    diff --git a/public/variables b/public/variables index 11c6fee8f..5c07db665 100644 --- a/public/variables +++ b/public/variables @@ -44,8 +44,7 @@ calls.

    -
    package main
    -
    +
    package main
    @@ -55,8 +54,7 @@ calls.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -66,8 +64,7 @@ calls.

    -
    func main() {
    -
    +
    func main() {
    @@ -78,10 +75,8 @@ calls.

    -
    -    var a = "initial"
    -    fmt.Println(a)
    -
    +
        var a = "initial"
    +    fmt.Println(a)
    @@ -92,10 +87,8 @@ calls.

    -
    -    var b, c int = 1, 2
    -    fmt.Println(b, c)
    -
    +
        var b, c int = 1, 2
    +    fmt.Println(b, c)
    @@ -106,10 +99,8 @@ calls.

    -
    -    var d = true
    -    fmt.Println(d)
    -
    +
        var d = true
    +    fmt.Println(d)
    @@ -122,10 +113,8 @@ zero value for an int is 0.

    -
    -    var e int
    -    fmt.Println(e)
    -
    +
        var e int
    +    fmt.Println(e)
    @@ -139,11 +128,9 @@ This syntax is only available inside functions.

    -
    -    f := "apple"
    -    fmt.Println(f)
    -}
    -
    +
        f := "apple"
    +    fmt.Println(f)
    +}
    @@ -157,12 +144,12 @@ This syntax is only available inside functions.

    -
    $ go run variables.go
    -initial
    -1 2
    -true
    -0
    -apple
    +
    $ go run variables.go
    +initial
    +1 2
    +true
    +0
    +apple
    diff --git a/public/variadic-functions b/public/variadic-functions index 8b8679334..a07a44b78 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -45,8 +45,7 @@ function.

    -
    package main
    -
    +
    package main
    @@ -56,8 +55,7 @@ function.

    -
    import "fmt"
    -
    +
    import "fmt"
    @@ -69,11 +67,9 @@ of ints as arguments.

    -
    -func sum(nums ...int) {
    -    fmt.Print(nums, " ")
    -    total := 0
    -
    +
    func sum(nums ...int) {
    +    fmt.Print(nums, " ")
    +    total := 0
    @@ -86,13 +82,11 @@ iterate over it with range, etc.

    -
    -    for _, num := range nums {
    -        total += num
    -    }
    -    fmt.Println(total)
    -}
    -
    +
        for _, num := range nums {
    +        total += num
    +    }
    +    fmt.Println(total)
    +}
    @@ -102,8 +96,7 @@ iterate over it with range, etc.

    -
    func main() {
    -
    +
    func main() {
    @@ -115,10 +108,8 @@ with individual arguments.

    -
    -    sum(1, 2)
    -    sum(1, 2, 3)
    -
    +
        sum(1, 2)
    +    sum(1, 2, 3)
    @@ -131,11 +122,9 @@ apply them to a variadic function using -
    -    nums := []int{1, 2, 3, 4}
    -    sum(nums...)
    -}
    -
    +
        nums := []int{1, 2, 3, 4}
    +    sum(nums...)
    +}
    @@ -149,10 +138,10 @@ apply them to a variadic function using -
    $ go run variadic-functions.go 
    -[1 2] 3
    -[1 2 3] 6
    -[1 2 3 4] 10
    +
    $ go run variadic-functions.go 
    +[1 2] 3
    +[1 2 3] 6
    +[1 2 3 4] 10
    diff --git a/public/waitgroups b/public/waitgroups index 38870e6fd..6b4465f34 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -43,8 +43,7 @@ use a wait group.

    -
    package main
    -
    +
    package main
    @@ -54,12 +53,11 @@ use a wait group.

    -
    import (
    -    "fmt"
    -    "sync"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "sync"
    +    "time"
    +)
    @@ -70,10 +68,8 @@ use a wait group.

    -
    -func worker(id int) {
    -    fmt.Printf("Worker %d starting\n", id)
    -
    +
    func worker(id int) {
    +    fmt.Printf("Worker %d starting\n", id)
    @@ -84,11 +80,9 @@ use a wait group.

    -
    -    time.Sleep(time.Second)
    -    fmt.Printf("Worker %d done\n", id)
    -}
    -
    +
        time.Sleep(time.Second)
    +    fmt.Printf("Worker %d done\n", id)
    +}
    @@ -98,8 +92,7 @@ use a wait group.

    -
    func main() {
    -
    +
    func main() {
    @@ -112,9 +105,7 @@ explicitly passed into functions, it should be done by pointer.

    -
    -    var wg sync.WaitGroup
    -
    +
        var wg sync.WaitGroup
    @@ -126,10 +117,8 @@ counter for each.

    -
    -    for i := 1; i <= 5; i++ {
    -        wg.Add(1)
    -
    +
        for i := 1; i <= 5; i++ {
    +        wg.Add(1)
    @@ -142,9 +131,7 @@ for more details.

    -
    -        i := i
    -
    +
            i := i
    @@ -158,13 +145,11 @@ involved in its execution.

    -
    -        go func() {
    -            defer wg.Done()
    -            worker(i)
    -        }()
    -    }
    -
    +
            go func() {
    +            defer wg.Done()
    +            worker(i)
    +        }()
    +    }
    @@ -176,9 +161,7 @@ all the workers notified they’re done.

    -
    -    wg.Wait()
    -
    +
        wg.Wait()
    @@ -192,9 +175,7 @@ advanced use cases, consider using the -
    -}
    -
    +
    }
    @@ -208,17 +189,17 @@ advanced use cases, consider using the -
    $ go run waitgroups.go
    -Worker 5 starting
    -Worker 3 starting
    -Worker 4 starting
    -Worker 1 starting
    -Worker 2 starting
    -Worker 4 done
    -Worker 1 done
    -Worker 2 done
    -Worker 5 done
    -Worker 3 done
    +
    $ go run waitgroups.go
    +Worker 5 starting
    +Worker 3 starting
    +Worker 4 starting
    +Worker 1 starting
    +Worker 2 starting
    +Worker 4 done
    +Worker 1 done
    +Worker 2 done
    +Worker 5 done
    +Worker 3 done
    diff --git a/public/worker-pools b/public/worker-pools index 601a84f89..2a024a786 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -43,8 +43,7 @@ a worker pool using goroutines and channels.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ a worker pool using goroutines and channels.

    -
    import (
    -    "fmt"
    -    "time"
    -)
    -
    +
    import (
    +    "fmt"
    +    "time"
    +)
    @@ -73,16 +71,14 @@ simulate an expensive task.

    -
    -func worker(id int, jobs <-chan int, results chan<- int) {
    -    for j := range jobs {
    -        fmt.Println("worker", id, "started  job", j)
    -        time.Sleep(time.Second)
    -        fmt.Println("worker", id, "finished job", j)
    -        results <- j * 2
    -    }
    -}
    -
    +
    func worker(id int, jobs <-chan int, results chan<- int) {
    +    for j := range jobs {
    +        fmt.Println("worker", id, "started  job", j)
    +        time.Sleep(time.Second)
    +        fmt.Println("worker", id, "finished job", j)
    +        results <- j * 2
    +    }
    +}
    @@ -92,8 +88,7 @@ simulate an expensive task.

    -
    func main() {
    -
    +
    func main() {
    @@ -106,11 +101,9 @@ channels for this.

    -
    -    const numJobs = 5
    -    jobs := make(chan int, numJobs)
    -    results := make(chan int, numJobs)
    -
    +
        const numJobs = 5
    +    jobs := make(chan int, numJobs)
    +    results := make(chan int, numJobs)
    @@ -122,11 +115,9 @@ because there are no jobs yet.

    -
    -    for w := 1; w <= 3; w++ {
    -        go worker(w, jobs, results)
    -    }
    -
    +
        for w := 1; w <= 3; w++ {
    +        go worker(w, jobs, results)
    +    }
    @@ -138,12 +129,10 @@ channel to indicate that’s all the work we have.

    -
    -    for j := 1; j <= numJobs; j++ {
    -        jobs <- j
    -    }
    -    close(jobs)
    -
    +
        for j := 1; j <= numJobs; j++ {
    +        jobs <- j
    +    }
    +    close(jobs)
    @@ -157,12 +146,10 @@ goroutines is to use a WaitGroup.

    -
    -    for a := 1; a <= numJobs; a++ {
    -        <-results
    -    }
    -}
    -
    +
        for a := 1; a <= numJobs; a++ {
    +        <-results
    +    }
    +}
    @@ -180,18 +167,17 @@ there are 3 workers operating concurrently.

    -
    -$ time go run worker-pools.go 
    -worker 1 started  job 1
    -worker 2 started  job 2
    -worker 3 started  job 3
    -worker 1 finished job 1
    -worker 1 started  job 4
    -worker 2 finished job 2
    -worker 2 started  job 5
    -worker 3 finished job 3
    -worker 1 finished job 4
    -worker 2 finished job 5
    +
    $ time go run worker-pools.go 
    +worker 1 started  job 1
    +worker 2 started  job 2
    +worker 3 started  job 3
    +worker 1 finished job 1
    +worker 1 started  job 4
    +worker 2 finished job 2
    +worker 2 started  job 5
    +worker 3 finished job 3
    +worker 1 finished job 4
    +worker 2 finished job 5
    @@ -201,7 +187,7 @@ there are 3 workers operating concurrently.

    -
    real    0m2.358s
    +
    real    0m2.358s
    diff --git a/public/writing-files b/public/writing-files index c9864b048..75ef52246 100644 --- a/public/writing-files +++ b/public/writing-files @@ -43,8 +43,7 @@ ones we saw earlier for reading.

    -
    package main
    -
    +
    package main
    @@ -54,12 +53,11 @@ ones we saw earlier for reading.

    -
    import (
    -    "bufio"
    -    "fmt"
    -    "os"
    -)
    -
    +
    import (
    +    "bufio"
    +    "fmt"
    +    "os"
    +)
    @@ -69,12 +67,11 @@ ones we saw earlier for reading.

    -
    func check(e error) {
    -    if e != nil {
    -        panic(e)
    -    }
    -}
    -
    +
    func check(e error) {
    +    if e != nil {
    +        panic(e)
    +    }
    +}
    @@ -84,8 +81,7 @@ ones we saw earlier for reading.

    -
    func main() {
    -
    +
    func main() {
    @@ -97,11 +93,9 @@ bytes) into a file.

    -
    -    d1 := []byte("hello\ngo\n")
    -    err := os.WriteFile("/tmp/dat1", d1, 0644)
    -    check(err)
    -
    +
        d1 := []byte("hello\ngo\n")
    +    err := os.WriteFile("/tmp/dat1", d1, 0644)
    +    check(err)
    @@ -112,10 +106,8 @@ bytes) into a file.

    -
    -    f, err := os.Create("/tmp/dat2")
    -    check(err)
    -
    +
        f, err := os.Create("/tmp/dat2")
    +    check(err)
    @@ -127,9 +119,7 @@ after opening a file.

    -
    -    defer f.Close()
    -
    +
        defer f.Close()
    @@ -140,12 +130,10 @@ after opening a file.

    -
    -    d2 := []byte{115, 111, 109, 101, 10}
    -    n2, err := f.Write(d2)
    -    check(err)
    -    fmt.Printf("wrote %d bytes\n", n2)
    -
    +
        d2 := []byte{115, 111, 109, 101, 10}
    +    n2, err := f.Write(d2)
    +    check(err)
    +    fmt.Printf("wrote %d bytes\n", n2)
    @@ -156,11 +144,9 @@ after opening a file.

    -
    -    n3, err := f.WriteString("writes\n")
    -    check(err)
    -    fmt.Printf("wrote %d bytes\n", n3)
    -
    +
        n3, err := f.WriteString("writes\n")
    +    check(err)
    +    fmt.Printf("wrote %d bytes\n", n3)
    @@ -171,9 +157,7 @@ after opening a file.

    -
    -    f.Sync()
    -
    +
        f.Sync()
    @@ -185,12 +169,10 @@ to the buffered readers we saw earlier.

    -
    -    w := bufio.NewWriter(f)
    -    n4, err := w.WriteString("buffered\n")
    -    check(err)
    -    fmt.Printf("wrote %d bytes\n", n4)
    -
    +
        w := bufio.NewWriter(f)
    +    n4, err := w.WriteString("buffered\n")
    +    check(err)
    +    fmt.Printf("wrote %d bytes\n", n4)
    @@ -202,9 +184,7 @@ been applied to the underlying writer.

    -
    -    w.Flush()
    -
    +
        w.Flush()
    @@ -214,8 +194,7 @@ been applied to the underlying writer.

    -
    }
    -
    +
    }
    @@ -230,11 +209,10 @@ been applied to the underlying writer.

    -
    -$ go run writing-files.go 
    -wrote 5 bytes
    -wrote 7 bytes
    -wrote 9 bytes
    +
    $ go run writing-files.go 
    +wrote 5 bytes
    +wrote 7 bytes
    +wrote 9 bytes
    @@ -245,14 +223,13 @@ been applied to the underlying writer.

    -
    -$ cat /tmp/dat1
    -hello
    -go
    -$ cat /tmp/dat2
    -some
    -writes
    -buffered
    +
    $ cat /tmp/dat1
    +hello
    +go
    +$ cat /tmp/dat2
    +some
    +writes
    +buffered
    diff --git a/public/xml b/public/xml index 26752fecb..5ea737ac7 100644 --- a/public/xml +++ b/public/xml @@ -43,8 +43,7 @@ formats with the encoding.xml package.

    -
    package main
    -
    +
    package main
    @@ -54,11 +53,10 @@ formats with the encoding.xml package.

    -
    import (
    -    "encoding/xml"
    -    "fmt"
    -)
    -
    +
    import (
    +    "encoding/xml"
    +    "fmt"
    +)
    @@ -75,14 +73,12 @@ the name of the XML element representing this struct; -
    -type Plant struct {
    -    XMLName xml.Name `xml:"plant"`
    -    Id      int      `xml:"id,attr"`
    -    Name    string   `xml:"name"`
    -    Origin  []string `xml:"origin"`
    -}
    -
    +
    type Plant struct {
    +    XMLName xml.Name `xml:"plant"`
    +    Id      int      `xml:"id,attr"`
    +    Name    string   `xml:"name"`
    +    Origin  []string `xml:"origin"`
    +}
    @@ -92,11 +88,10 @@ the name of the XML element representing this struct; -
    func (p Plant) String() string {
    -    return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
    -        p.Id, p.Name, p.Origin)
    -}
    -
    +
    func (p Plant) String() string {
    +    return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
    +        p.Id, p.Name, p.Origin)
    +}
    @@ -106,10 +101,9 @@ the name of the XML element representing this struct; -
    func main() {
    -    coffee := &Plant{Id: 27, Name: "Coffee"}
    -    coffee.Origin = []string{"Ethiopia", "Brazil"}
    -
    +
    func main() {
    +    coffee := &Plant{Id: 27, Name: "Coffee"}
    +    coffee.Origin = []string{"Ethiopia", "Brazil"}
    @@ -122,10 +116,8 @@ human-readable output.

    -
    -    out, _ := xml.MarshalIndent(coffee, " ", "  ")
    -    fmt.Println(string(out))
    -
    +
        out, _ := xml.MarshalIndent(coffee, " ", "  ")
    +    fmt.Println(string(out))
    @@ -137,9 +129,7 @@ it explicitly.

    -
    -    fmt.Println(xml.Header + string(out))
    -
    +
        fmt.Println(xml.Header + string(out))
    @@ -153,13 +143,11 @@ will be returned.

    -
    -    var p Plant
    -    if err := xml.Unmarshal(out, &p); err != nil {
    -        panic(err)
    -    }
    -    fmt.Println(p)
    -
    +
        var p Plant
    +    if err := xml.Unmarshal(out, &p); err != nil {
    +        panic(err)
    +    }
    +    fmt.Println(p)
    @@ -169,9 +157,8 @@ will be returned.

    -
        tomato := &Plant{Id: 81, Name: "Tomato"}
    -    tomato.Origin = []string{"Mexico", "California"}
    -
    +
        tomato := &Plant{Id: 81, Name: "Tomato"}
    +    tomato.Origin = []string{"Mexico", "California"}
    @@ -183,12 +170,10 @@ to nest all plants under <parent><child>... -
    -    type Nesting struct {
    -        XMLName xml.Name `xml:"nesting"`
    -        Plants  []*Plant `xml:"parent>child>plant"`
    -    }
    -
    +
        type Nesting struct {
    +        XMLName xml.Name `xml:"nesting"`
    +        Plants  []*Plant `xml:"parent>child>plant"`
    +    }
    @@ -198,9 +183,8 @@ to nest all plants under <parent><child>... -
        nesting := &Nesting{}
    -    nesting.Plants = []*Plant{coffee, tomato}
    -
    +
        nesting := &Nesting{}
    +    nesting.Plants = []*Plant{coffee, tomato}
    @@ -210,10 +194,9 @@ to nest all plants under <parent><child>... -
        out, _ = xml.MarshalIndent(nesting, " ", "  ")
    -    fmt.Println(string(out))
    -}
    -
    +
        out, _ = xml.MarshalIndent(nesting, " ", "  ")
    +    fmt.Println(string(out))
    +}
    @@ -227,35 +210,35 @@ to nest all plants under <parent><child>... -
    $ go run xml.go
    - <plant id="27">
    -   <name>Coffee</name>
    -   <origin>Ethiopia</origin>
    -   <origin>Brazil</origin>
    - </plant>
    -<?xml version="1.0" encoding="UTF-8"?>
    - <plant id="27">
    -   <name>Coffee</name>
    -   <origin>Ethiopia</origin>
    -   <origin>Brazil</origin>
    - </plant>
    -Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
    - <nesting>
    -   <parent>
    -     <child>
    -       <plant id="27">
    -         <name>Coffee</name>
    -         <origin>Ethiopia</origin>
    -         <origin>Brazil</origin>
    -       </plant>
    -       <plant id="81">
    -         <name>Tomato</name>
    -         <origin>Mexico</origin>
    -         <origin>California</origin>
    -       </plant>
    -     </child>
    -   </parent>
    - </nesting>
    +
    $ go run xml.go
    + <plant id="27">
    +   <name>Coffee</name>
    +   <origin>Ethiopia</origin>
    +   <origin>Brazil</origin>
    + </plant>
    +<?xml version="1.0" encoding="UTF-8"?>
    + <plant id="27">
    +   <name>Coffee</name>
    +   <origin>Ethiopia</origin>
    +   <origin>Brazil</origin>
    + </plant>
    +Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
    + <nesting>
    +   <parent>
    +     <child>
    +       <plant id="27">
    +         <name>Coffee</name>
    +         <origin>Ethiopia</origin>
    +         <origin>Brazil</origin>
    +       </plant>
    +       <plant id="81">
    +         <name>Tomato</name>
    +         <origin>Mexico</origin>
    +         <origin>California</origin>
    +       </plant>
    +     </child>
    +   </parent>
    + </nesting>
    diff --git a/tools/generate.go b/tools/generate.go index 9362c743a..bc6935ef5 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -12,10 +12,10 @@ import ( "strings" "text/template" - "github.com/alecthomas/chroma" - "github.com/alecthomas/chroma/formatters/html" - "github.com/alecthomas/chroma/lexers" - "github.com/alecthomas/chroma/styles" + "github.com/alecthomas/chroma/v2" + "github.com/alecthomas/chroma/v2/formatters/html" + "github.com/alecthomas/chroma/v2/lexers" + "github.com/alecthomas/chroma/v2/styles" "github.com/russross/blackfriday/v2" ) @@ -222,6 +222,12 @@ func parseAndRenderSegs(sourcePath string) ([]*Seg, string) { seg.DocsRendered = markdown(seg.Docs) } if seg.Code != "" { + // TODO: with the update to Chroma 2.8.0 I had to change this, because the + // new chromoa would render this leading newline for all code segments, + // which would then be shifted down compared to the doc segments. Maybe + // the parsing should be modified to not produce this \n in the first + // place? + seg.Code = strings.TrimLeft(seg.Code, "\n") seg.CodeRendered = chromaFormat(seg.Code, sourcePath) // adding the content to the js code for copying to the clipboard @@ -353,30 +359,32 @@ var SimpleShellOutputLexer = chroma.MustNewLexer( Filenames: []string{"*.sh"}, MimeTypes: []string{}, }, - chroma.Rules{ - "root": { - // $ or > triggers the start of prompt formatting - {`^\$`, chroma.GenericPrompt, chroma.Push("prompt")}, - {`^>`, chroma.GenericPrompt, chroma.Push("prompt")}, - - // empty lines are just text - {`^$\n`, chroma.Text, nil}, - - // otherwise its all output - {`[^\n]+$\n?`, chroma.GenericOutput, nil}, - }, - "prompt": { - // when we find newline, do output formatting rules - {`\n`, chroma.Text, chroma.Push("output")}, - // otherwise its all text - {`[^\n]+$`, chroma.Text, nil}, - }, - "output": { - // sometimes there isn't output so we go right back to prompt - {`^\$`, chroma.GenericPrompt, chroma.Pop(1)}, - {`^>`, chroma.GenericPrompt, chroma.Pop(1)}, - // otherwise its all output - {`[^\n]+$\n?`, chroma.GenericOutput, nil}, - }, + func() chroma.Rules { + return chroma.Rules{ + "root": { + // $ or > triggers the start of prompt formatting + {`^\$`, chroma.GenericPrompt, chroma.Push("prompt")}, + {`^>`, chroma.GenericPrompt, chroma.Push("prompt")}, + + // empty lines are just text + {`^$\n`, chroma.Text, nil}, + + // otherwise its all output + {`[^\n]+$\n?`, chroma.GenericOutput, nil}, + }, + "prompt": { + // when we find newline, do output formatting rules + {`\n`, chroma.Text, chroma.Push("output")}, + // otherwise its all text + {`[^\n]+$`, chroma.Text, nil}, + }, + "output": { + // sometimes there isn't output so we go right back to prompt + {`^\$`, chroma.GenericPrompt, chroma.Pop(1)}, + {`^>`, chroma.GenericPrompt, chroma.Pop(1)}, + // otherwise its all output + {`[^\n]+$\n?`, chroma.GenericOutput, nil}, + }, + } }, ) From 83763d99d14f13493538d03fbf732bdc1e3a788c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 21 Aug 2023 07:05:34 -0700 Subject: [PATCH 192/283] Bump Go version for GH actions --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 29df4730b..fc52b39c8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.19.1] + go-version: [1.21.0] runs-on: ${{ matrix.os }} steps: From 57db236e6cf31703f5eddb3f24a65ce36bb95057 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 21 Aug 2023 09:03:37 -0700 Subject: [PATCH 193/283] Properly fix extra newline rendered at the beginning of code segments --- tools/generate.go | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/tools/generate.go b/tools/generate.go index bc6935ef5..82e20476c 100644 --- a/tools/generate.go +++ b/tools/generate.go @@ -145,7 +145,6 @@ func parseSegs(sourcePath string) ([]*Seg, string) { lines = append(lines, strings.Replace(line, "\t", " ", -1)) source = append(source, line) } - filecontent := strings.Join(source, "\n") segs := []*Seg{} lastSeen := "" for _, line := range lines { @@ -175,7 +174,12 @@ func parseSegs(sourcePath string) ([]*Seg, string) { newSeg := Seg{Docs: "", Code: line} segs = append(segs, &newSeg) } else { - segs[len(segs)-1].Code = segs[len(segs)-1].Code + "\n" + line + lastSeg := segs[len(segs)-1] + if len(lastSeg.Code) == 0 { + lastSeg.Code = line + } else { + lastSeg.Code = lastSeg.Code + "\n" + line + } } debug("CODE: " + line) lastSeen = "code" @@ -186,7 +190,7 @@ func parseSegs(sourcePath string) ([]*Seg, string) { seg.CodeLeading = (i < (len(segs) - 1)) seg.CodeRun = strings.Contains(seg.Code, "package main") } - return segs, filecontent + return segs, strings.Join(source, "\n") } func chromaFormat(code, filePath string) string { @@ -222,12 +226,6 @@ func parseAndRenderSegs(sourcePath string) ([]*Seg, string) { seg.DocsRendered = markdown(seg.Docs) } if seg.Code != "" { - // TODO: with the update to Chroma 2.8.0 I had to change this, because the - // new chromoa would render this leading newline for all code segments, - // which would then be shifted down compared to the doc segments. Maybe - // the parsing should be modified to not produce this \n in the first - // place? - seg.Code = strings.TrimLeft(seg.Code, "\n") seg.CodeRendered = chromaFormat(seg.Code, sourcePath) // adding the content to the js code for copying to the clipboard From 655a3b6a9e216972337ccab5c124142d2ad71a83 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 21 Aug 2023 12:27:51 -0700 Subject: [PATCH 194/283] Update sorting sample to use slices.Sort instead of sort package --- examples/sorting/sorting.go | 21 ++++++++++----------- examples/sorting/sorting.hash | 4 ++-- examples/sorting/sorting.sh | 2 -- public/sorting | 29 +++++++++++++---------------- 4 files changed, 25 insertions(+), 31 deletions(-) diff --git a/examples/sorting/sorting.go b/examples/sorting/sorting.go index acc67d8d7..f022982a6 100644 --- a/examples/sorting/sorting.go +++ b/examples/sorting/sorting.go @@ -1,4 +1,4 @@ -// Go's `sort` package implements sorting for builtins +// Go's `slices` package implements sorting for builtins // and user-defined types. We'll look at sorting for // builtins first. @@ -6,26 +6,25 @@ package main import ( "fmt" - "sort" + "slices" ) func main() { - // Sort methods are specific to the builtin type; - // here's an example for strings. Note that sorting is - // in-place, so it changes the given slice and doesn't - // return a new one. + // Sorting functions are generic, and work for any + // _ordered_ built-in type. For a list of ordered + // types, see [cmp.Ordered](https://pkg.go.dev/cmp#Ordered). strs := []string{"c", "a", "b"} - sort.Strings(strs) + slices.Sort(strs) fmt.Println("Strings:", strs) // An example of sorting `int`s. ints := []int{7, 2, 4} - sort.Ints(ints) + slices.Sort(ints) fmt.Println("Ints: ", ints) - // We can also use `sort` to check if a slice is - // already in sorted order. - s := sort.IntsAreSorted(ints) + // We can also use the `slices` package to check if + // a slice is already in sorted order. + s := slices.IsSorted(ints) fmt.Println("Sorted: ", s) } diff --git a/examples/sorting/sorting.hash b/examples/sorting/sorting.hash index e845bdf24..083264320 100644 --- a/examples/sorting/sorting.hash +++ b/examples/sorting/sorting.hash @@ -1,2 +1,2 @@ -c39a7498686fe1d74f729fd6b21a70bf063abf14 -_gY0tANzJ4l +2091224c8d8ac748883215c4dbe9611fb8afacc3 +X7iJcIua02T diff --git a/examples/sorting/sorting.sh b/examples/sorting/sorting.sh index c0e74620f..838724656 100644 --- a/examples/sorting/sorting.sh +++ b/examples/sorting/sorting.sh @@ -1,5 +1,3 @@ -# Running our program prints the sorted string and int -# slices and `true` as the result of our `AreSorted` test. $ go run sorting.go Strings: [a b c] Ints: [2 4 7] diff --git a/public/sorting b/public/sorting index 866ca5dec..cd946ab27 100644 --- a/public/sorting +++ b/public/sorting @@ -27,7 +27,7 @@ -

    Go’s sort package implements sorting for builtins +

    Go’s slices package implements sorting for builtins and user-defined types. We’ll look at sorting for builtins first.

    @@ -43,7 +43,7 @@ builtins first.

    - +
    package main
    @@ -56,7 +56,7 @@ builtins first.

    import (
         "fmt"
    -    "sort"
    +    "slices"
     )
    @@ -73,16 +73,15 @@ builtins first.

    -

    Sort methods are specific to the builtin type; -here’s an example for strings. Note that sorting is -in-place, so it changes the given slice and doesn’t -return a new one.

    +

    Sorting functions are generic, and work for any +ordered built-in type. For a list of ordered +types, see cmp.Ordered.

        strs := []string{"c", "a", "b"}
    -    sort.Strings(strs)
    +    slices.Sort(strs)
         fmt.Println("Strings:", strs)
    @@ -95,20 +94,20 @@ return a new one.

        ints := []int{7, 2, 4}
    -    sort.Ints(ints)
    +    slices.Sort(ints)
         fmt.Println("Ints:   ", ints)
    -

    We can also use sort to check if a slice is -already in sorted order.

    +

    We can also use the slices package to check if +a slice is already in sorted order.

    -
        s := sort.IntsAreSorted(ints)
    +          
        s := slices.IsSorted(ints)
         fmt.Println("Sorted: ", s)
     }
    @@ -120,9 +119,7 @@ already in sorted order.

    -

    Running our program prints the sorted string and int -slices and true as the result of our AreSorted test.

    - + @@ -148,7 +145,7 @@ slices and true as the result of our AreSorted test. From 2166e61181f712d4a7c8a29b019fe7d122ffc8a3 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 21 Aug 2023 12:47:17 -0700 Subject: [PATCH 195/283] Update sorting-by-functions example to use slices.SortFunc --- .../sorting-by-functions.go | 66 +++++----- .../sorting-by-functions.hash | 4 +- .../sorting-by-functions.sh | 9 +- public/sorting-by-functions | 116 ++++++++++-------- 4 files changed, 106 insertions(+), 89 deletions(-) diff --git a/examples/sorting-by-functions/sorting-by-functions.go b/examples/sorting-by-functions/sorting-by-functions.go index 8524f668a..d54d79ecd 100644 --- a/examples/sorting-by-functions/sorting-by-functions.go +++ b/examples/sorting-by-functions/sorting-by-functions.go @@ -7,39 +7,47 @@ package main import ( + "cmp" "fmt" - "sort" + "slices" ) -// In order to sort by a custom function in Go, we need a -// corresponding type. Here we've created a `byLength` -// type that is just an alias for the builtin `[]string` -// type. -type byLength []string - -// We implement `sort.Interface` - `Len`, `Less`, and -// `Swap` - on our type so we can use the `sort` package's -// generic `Sort` function. `Len` and `Swap` -// will usually be similar across types and `Less` will -// hold the actual custom sorting logic. In our case we -// want to sort in order of increasing string length, so -// we use `len(s[i])` and `len(s[j])` here. -func (s byLength) Len() int { - return len(s) -} -func (s byLength) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s byLength) Less(i, j int) bool { - return len(s[i]) < len(s[j]) -} - -// With all of this in place, we can now implement our -// custom sort by converting the original `fruits` slice -// to `byLength`, and then use `sort.Sort` on that typed -// slice. func main() { fruits := []string{"peach", "banana", "kiwi"} - sort.Sort(byLength(fruits)) + + // We implement a comparison function for string + // lengths. `cmp.Compare` is helpful for this. + lenCmp := func(a, b string) int { + return cmp.Compare(len(a), len(b)) + } + + // Now we can call `slices.SortFunc` with this custom + // comparison function to sort `fruits` by name length. + slices.SortFunc(fruits, lenCmp) fmt.Println(fruits) + + // We can use the same technique to sort a slice of + // values that aren't built-in types. + type Person struct { + name string + age int + } + + people := []Person{ + Person{name: "Jax", age: 37}, + Person{name: "TJ", age: 25}, + Person{name: "Alex", age: 72}, + } + + // Sort `people` by age using `slices.SortFunc`. + // + // Note: if the `Person` struct is large, + // you may want the slice to contain `*Person` instead + // and adjust the sorting function accordingly. If in + // doubt, [benchmark](testing-and-benchmarking)! + slices.SortFunc(people, + func(a, b Person) int { + return cmp.Compare(a.age, b.age) + }) + fmt.Println(people) } diff --git a/examples/sorting-by-functions/sorting-by-functions.hash b/examples/sorting-by-functions/sorting-by-functions.hash index ff61f8111..8413a1003 100644 --- a/examples/sorting-by-functions/sorting-by-functions.hash +++ b/examples/sorting-by-functions/sorting-by-functions.hash @@ -1,2 +1,2 @@ -e5a6006366e05ee7785eebac8ba588e4b937a197 -h4g4vaLBtkw +9902d1c5654b64d8b381ea7888c0793ac8ab4a97 +3EaTknAZHMu diff --git a/examples/sorting-by-functions/sorting-by-functions.sh b/examples/sorting-by-functions/sorting-by-functions.sh index d2a1c4c40..eb8b9b4a3 100644 --- a/examples/sorting-by-functions/sorting-by-functions.sh +++ b/examples/sorting-by-functions/sorting-by-functions.sh @@ -1,10 +1,3 @@ -# Running our program shows a list sorted by string -# length, as desired. $ go run sorting-by-functions.go [kiwi peach banana] - -# By following this same pattern of creating a custom -# type, implementing the three `Interface` methods on that -# type, and then calling sort.Sort on a collection of that -# custom type, we can sort Go slices by arbitrary -# functions. +[{TJ 25} {Jax 37} {Alex 72}] diff --git a/public/sorting-by-functions b/public/sorting-by-functions index 77b833c04..43e5f4752 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -45,7 +45,7 @@ in Go.

    - +
    package main
    @@ -57,98 +57,114 @@ in Go.

    import (
    +    "cmp"
         "fmt"
    -    "sort"
    +    "slices"
     )
    -

    In order to sort by a custom function in Go, we need a -corresponding type. Here we’ve created a byLength -type that is just an alias for the builtin []string -type.

    - + -
    type byLength []string
    +
    func main() {
    +    fruits := []string{"peach", "banana", "kiwi"}
    -

    We implement sort.Interface - Len, Less, and -Swap - on our type so we can use the sort package’s -generic Sort function. Len and Swap -will usually be similar across types and Less will -hold the actual custom sorting logic. In our case we -want to sort in order of increasing string length, so -we use len(s[i]) and len(s[j]) here.

    +

    We implement a comparison function for string +lengths. cmp.Compare is helpful for this.

    -
    func (s byLength) Len() int {
    -    return len(s)
    -}
    -func (s byLength) Swap(i, j int) {
    -    s[i], s[j] = s[j], s[i]
    -}
    -func (s byLength) Less(i, j int) bool {
    -    return len(s[i]) < len(s[j])
    -}
    +
        lenCmp := func(a, b string) int {
    +        return cmp.Compare(len(a), len(b))
    +    }
    -

    With all of this in place, we can now implement our -custom sort by converting the original fruits slice -to byLength, and then use sort.Sort on that typed -slice.

    +

    Now we can call slices.SortFunc with this custom +comparison function to sort fruits by name length.

    - + -
    func main() {
    -    fruits := []string{"peach", "banana", "kiwi"}
    -    sort.Sort(byLength(fruits))
    -    fmt.Println(fruits)
    -}
    +
        slices.SortFunc(fruits, lenCmp)
    +    fmt.Println(fruits)
    - - - - + + + + + - + + +
    -

    Running our program shows a list sorted by string -length, as desired.

    +

    We can use the same technique to sort a slice of +values that aren’t built-in types.

    -
    $ go run sorting-by-functions.go 
    -[kiwi peach banana]
    +
        type Person struct {
    +        name string
    +        age  int
    +    }
    +
    + + + +
        people := []Person{
    +        Person{name: "Jax", age: 37},
    +        Person{name: "TJ", age: 25},
    +        Person{name: "Alex", age: 72},
    +    }
    -

    By following this same pattern of creating a custom -type, implementing the three Interface methods on that -type, and then calling sort.Sort on a collection of that -custom type, we can sort Go slices by arbitrary -functions.

    +

    Sort people by age using slices.SortFunc.

    + +

    Note: if the Person struct is large, +you may want the slice to contain *Person instead +and adjust the sorting function accordingly. If in +doubt, benchmark!

    + - +
        slices.SortFunc(people,
    +        func(a, b Person) int {
    +            return cmp.Compare(a.age, b.age)
    +        })
    +    fmt.Println(people)
    +}
    +
    + + + + + + @@ -167,7 +183,7 @@ functions.

    From 146bd9cce2d3d89fac28f4f6334d9b2acbed7dee Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 22 Aug 2023 05:52:14 -0700 Subject: [PATCH 196/283] Add examples of maps/slices packages --- examples/maps/maps.go | 12 +++++++++++- examples/maps/maps.hash | 4 ++-- examples/maps/maps.sh | 1 + examples/slices/slices.go | 12 +++++++++++- examples/slices/slices.hash | 4 ++-- examples/slices/slices.sh | 1 + public/maps | 31 +++++++++++++++++++++++++------ public/slices | 25 ++++++++++++++++++++++--- 8 files changed, 75 insertions(+), 15 deletions(-) diff --git a/examples/maps/maps.go b/examples/maps/maps.go index 79db9013c..40f7c5873 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -3,7 +3,10 @@ package main -import "fmt" +import ( + "fmt" + "maps" +) func main() { @@ -58,4 +61,11 @@ func main() { // the same line with this syntax. n := map[string]int{"foo": 1, "bar": 2} fmt.Println("map:", n) + + // The `maps` package contains a number of useful + // utility functions for maps. + n2 := map[string]int{"foo": 1, "bar": 2} + if maps.Equal(n, n2) { + fmt.Println("n == n2") + } } diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index d6abb5d57..32f844afe 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -b976324013ef31370d1605d1834c5dd6f0db0ea1 -6gcPOX9Mm1R +c8435b8cc754213b70c58c9a51dfa824c6f70dd7 +5jpkxJ2T0Lv diff --git a/examples/maps/maps.sh b/examples/maps/maps.sh index 2b24dbb89..f234e9f60 100644 --- a/examples/maps/maps.sh +++ b/examples/maps/maps.sh @@ -9,3 +9,4 @@ map: map[k1:7] map: map[] prs: false map: map[bar:2 foo:1] +n == n2 diff --git a/examples/slices/slices.go b/examples/slices/slices.go index ac97a6b0f..541b582b3 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -3,7 +3,10 @@ package main -import "fmt" +import ( + "fmt" + "slices" +) func main() { @@ -70,6 +73,13 @@ func main() { t := []string{"g", "h", "i"} fmt.Println("dcl:", t) + // The `slices` package contains a number of useful + // utility functions for slices. + t2 := []string{"g", "h", "i"} + if slices.Equal(t, t2) { + fmt.Println("t == t2") + } + // Slices can be composed into multi-dimensional data // structures. The length of the inner slices can // vary, unlike with multi-dimensional arrays. diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index eb3c4ced7..e671db628 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -9f1302a9c3cf79e5144c4818ea09465ff8d6da57 -553_cYPVlPH +522c14373ae9581dd3001be32530cdf940637646 +kiy1StxorBF diff --git a/examples/slices/slices.sh b/examples/slices/slices.sh index 8f5d1d4aa..42a400514 100644 --- a/examples/slices/slices.sh +++ b/examples/slices/slices.sh @@ -12,6 +12,7 @@ sl1: [c d e] sl2: [a b c d e] sl3: [c d e f] dcl: [g h i] +t == t2 2d: [[0] [1 2] [2 3 4]] # Check out this [great blog post](https://go.dev/blog/slices-intro) diff --git a/public/maps b/public/maps index 94427d5f3..1f2146e3c 100644 --- a/public/maps +++ b/public/maps @@ -42,7 +42,7 @@ @@ -53,7 +53,10 @@ @@ -192,10 +195,25 @@ itself, so we ignored it with the blank identifier the same line with this syntax.

    - + + + + + @@ -220,7 +238,8 @@ printed with fmt.Println.

    map: map[k1:7] map: map[] prs: false -map: map[bar:2 foo:1] +map: map[bar:2 foo:1] +n == n2 @@ -239,7 +258,7 @@ printed with fmt.Println.

    diff --git a/public/slices b/public/slices index f26101e7c..dc8889d79 100644 --- a/public/slices +++ b/public/slices @@ -42,7 +42,7 @@ a more powerful interface to sequences than arrays.

    @@ -53,7 +53,10 @@ a more powerful interface to sequences than arrays.

    @@ -210,6 +213,21 @@ in a single line as well.

    + + + + + @@ -300,7 +319,7 @@ Go’s other key builtin data structure: maps.

    From 15d8fe75b82f488461a0bb219e555bfccb999b08 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 22 Aug 2023 13:45:00 -0700 Subject: [PATCH 197/283] Add new example: logging with the log and log/slog packages --- examples.txt | 1 + examples/logging/logging.go | 77 ++++++++++ examples/logging/logging.hash | 2 + examples/logging/logging.sh | 18 +++ public/environment-variables | 4 +- public/http-client | 2 +- public/index.html | 2 + public/logging | 276 ++++++++++++++++++++++++++++++++++ 8 files changed, 379 insertions(+), 3 deletions(-) create mode 100644 examples/logging/logging.go create mode 100644 examples/logging/logging.hash create mode 100644 examples/logging/logging.sh create mode 100644 public/logging diff --git a/examples.txt b/examples.txt index de7120784..b637704b8 100644 --- a/examples.txt +++ b/examples.txt @@ -71,6 +71,7 @@ Command-Line Arguments Command-Line Flags Command-Line Subcommands Environment Variables +Logging HTTP Client HTTP Server Context diff --git a/examples/logging/logging.go b/examples/logging/logging.go new file mode 100644 index 000000000..18bbaf76d --- /dev/null +++ b/examples/logging/logging.go @@ -0,0 +1,77 @@ +// The Go standard library provides straightforward +// tools for outputting logs from Go programs, with +// the [log](https://pkg.go.dev/log) package for +// free-form output and the +// [log/slog](https://pkg.go.dev/log/slog) package for +// structured output. +package main + +import ( + "bytes" + "fmt" + "log" + "os" + + "log/slog" +) + +func main() { + + // Simply invoking functions like `Println` from the + // `log` package uses the _standard_ logger, which + // is already pre-configured for reasonable logging + // output to `os.Stderr`. Additional methods like + // `Fatal*` or `Panic*` will exit the program after + // logging. + log.Println("standard logger") + + // Loggers can be configured with _flags_ to set + // their output format. By default, the standard + // logger has the `log.Ldate` and `log.Ltime` flags + // set, and these are collected in `log.LstdFlags`. + // We can change its flags to emit time with + // microsecond accuracy, for example. + log.SetFlags(log.LstdFlags | log.Lmicroseconds) + log.Println("with micro") + + // It also supports emitting the file name and + // line from which the `log` function is called. + log.SetFlags(log.LstdFlags | log.Lshortfile) + log.Println("with file/line") + + // It may be useful to create a custom logger and + // pass it around. When creating a new logger, we + // can set a _prefix_ to distinguish its output + // from other loggers. + mylog := log.New(os.Stdout, "my:", log.LstdFlags) + mylog.Println("from mylog") + + // We can set the prefix + // on existing loggers (including the standard one) + // with the `SetPrefix` method. + mylog.SetPrefix("ohmy:") + mylog.Println("from mylog") + + // Loggers can have custom output targets; + // any `io.Writer` works. + var buf bytes.Buffer + buflog := log.New(&buf, "buf:", log.LstdFlags) + + // This call writes the log output into `buf`. + buflog.Println("hello") + + // This will actually show it on standard output. + fmt.Print("from buflog:", buf.String()) + + // The `slog` package provides + // _structured_ log output. For example, logging + // in JSON format is straightforward. + jsonHandler := slog.NewJSONHandler(os.Stderr, nil) + myslog := slog.New(jsonHandler) + myslog.Info("hi there") + + // In addition to the message, `slog` output can + // contain an arbitrary number of key=value + // pairs. + myslog.Info("hello again", "key", "val", "age", 25) +} diff --git a/examples/logging/logging.hash b/examples/logging/logging.hash new file mode 100644 index 000000000..4d1c7a70e --- /dev/null +++ b/examples/logging/logging.hash @@ -0,0 +1,2 @@ +38a7ef451859bb4c163df938b3a9d0e5ac293bef +Qd0uCqBlYUn diff --git a/examples/logging/logging.sh b/examples/logging/logging.sh new file mode 100644 index 000000000..00bcc76c1 --- /dev/null +++ b/examples/logging/logging.sh @@ -0,0 +1,18 @@ +# Sample output; the date and time +# emitted will depend on when the example ran. +$ go run logging.go +2023/08/22 10:45:16 standard logger +2023/08/22 10:45:16.904141 with micro +2023/08/22 10:45:16 logging.go:40: with file/line +my:2023/08/22 10:45:16 from mylog +ohmy:2023/08/22 10:45:16 from mylog +from buflog:buf:2023/08/22 10:45:16 hello + +# These are wrapped for clarity of presentation +# on the website; in reality they are emitted +# on a single line. +{"time":"2023-08-22T10:45:16.904166391-07:00", + "level":"INFO","msg":"hi there"} +{"time":"2023-08-22T10:45:16.904178985-07:00", + "level":"INFO","msg":"hello again", + "key":"val","age":25} diff --git a/public/environment-variables b/public/environment-variables index eb0ccb78d..ad03f4a1f 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'http-client'; + window.location.href = 'logging'; } } @@ -162,7 +162,7 @@ program picks that value up.

    - Next example: HTTP Client. + Next example: Logging.

    diff --git a/public/http-client b/public/http-client index b693af7c2..c00245320 100644 --- a/public/http-client +++ b/public/http-client @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'environment-variables'; + window.location.href = 'logging'; } diff --git a/public/index.html b/public/index.html index 98549d651..54853fec8 100644 --- a/public/index.html +++ b/public/index.html @@ -173,6 +173,8 @@

    Go by Example

  • Environment Variables
  • +
  • Logging
  • +
  • HTTP Client
  • HTTP Server
  • diff --git a/public/logging b/public/logging new file mode 100644 index 000000000..b945208e4 --- /dev/null +++ b/public/logging @@ -0,0 +1,276 @@ + + + + + Go by Example: Logging + + + + +
    +

    Go by Example: Logging

    + +
    + + + +
    $ go run sorting-by-functions.go 
    +[kiwi peach banana]
    +[{TJ 25} {Jax 37} {Alex 72}]
    - +
    package main
    -
    import "fmt"
    +
    import (
    +    "fmt"
    +    "maps"
    +)
    +
        n := map[string]int{"foo": 1, "bar": 2}
    -    fmt.Println("map:", n)
    +    fmt.Println("map:", n)
    +
    +

    The maps package contains a number of useful +utility functions for maps.

    + +
    + +
        n2 := map[string]int{"foo": 1, "bar": 2}
    +    if maps.Equal(n, n2) {
    +        fmt.Println("n == n2")
    +    }
     }
    - +
    package main
    -
    import "fmt"
    +
    import (
    +    "fmt"
    +    "slices"
    +)
    +

    The slices package contains a number of useful +utility functions for slices.

    + +
    + +
        t2 := []string{"g", "h", "i"}
    +    if slices.Equal(t, t2) {
    +        fmt.Println("t == t2")
    +    }
    +

    Slices can be composed into multi-dimensional data @@ -256,6 +274,7 @@ they are rendered similarly by fmt.Println.

    sl2: [a b c d e] sl3: [c d e f] dcl: [g h i] +t == t2 2d: [[0] [1 2] [2 3 4]]
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    The Go standard library provides straightforward +tools for outputting logs from Go programs, with +the log package for +free-form output and the +log/slog package for +structured output.

    + +
    + +
    package main
    +
    + + + +
    import (
    +    "bytes"
    +    "fmt"
    +    "log"
    +    "os"
    +
    + + + +
        "log/slog"
    +)
    +
    + + + +
    func main() {
    +
    +

    Simply invoking functions like Println from the +log package uses the standard logger, which +is already pre-configured for reasonable logging +output to os.Stderr. Additional methods like +Fatal* or Panic* will exit the program after +logging.

    + +
    + +
        log.Println("standard logger")
    +
    +

    Loggers can be configured with flags to set +their output format. By default, the standard +logger has the log.Ldate and log.Ltime flags +set, and these are collected in log.LstdFlags. +We can change its flags to emit time with +microsecond accuracy, for example.

    + +
    + +
        log.SetFlags(log.LstdFlags | log.Lmicroseconds)
    +    log.Println("with micro")
    +
    +

    It also supports emitting the file name and +line from which the log function is called.

    + +
    + +
        log.SetFlags(log.LstdFlags | log.Lshortfile)
    +    log.Println("with file/line")
    +
    +

    It may be useful to create a custom logger and +pass it around. When creating a new logger, we +can set a prefix to distinguish its output +from other loggers.

    + +
    + +
        mylog := log.New(os.Stdout, "my:", log.LstdFlags)
    +    mylog.Println("from mylog")
    +
    +

    We can set the prefix +on existing loggers (including the standard one) +with the SetPrefix method.

    + +
    + +
        mylog.SetPrefix("ohmy:")
    +    mylog.Println("from mylog")
    +
    +

    Loggers can have custom output targets; +any io.Writer works.

    + +
    + +
        var buf bytes.Buffer
    +    buflog := log.New(&buf, "buf:", log.LstdFlags)
    +
    +

    This call writes the log output into buf.

    + +
    + +
        buflog.Println("hello")
    +
    +

    This will actually show it on standard output.

    + +
    + +
        fmt.Print("from buflog:", buf.String())
    +
    +

    The slog package provides +structured log output. For example, logging +in JSON format is straightforward.

    + +
    + +
        jsonHandler := slog.NewJSONHandler(os.Stderr, nil)
    +    myslog := slog.New(jsonHandler)
    +    myslog.Info("hi there")
    +
    +

    In addition to the message, slog output can +contain an arbitrary number of key=value +pairs.

    + +
    + +
        myslog.Info("hello again", "key", "val", "age", 25)
    +}
    +
    + + + + + + + + + + + + + +
    +

    Sample output; the date and time +emitted will depend on when the example ran.

    + +
    + +
    $ go run logging.go
    +2023/08/22 10:45:16 standard logger
    +2023/08/22 10:45:16.904141 with micro
    +2023/08/22 10:45:16 logging.go:40: with file/line
    +my:2023/08/22 10:45:16 from mylog
    +ohmy:2023/08/22 10:45:16 from mylog
    +from buflog:buf:2023/08/22 10:45:16 hello
    +
    +

    These are wrapped for clarity of presentation +on the website; in reality they are emitted +on a single line.

    + +
    + +
    {"time":"2023-08-22T10:45:16.904166391-07:00",
    + "level":"INFO","msg":"hi there"}
    +{"time":"2023-08-22T10:45:16.904178985-07:00",
    +    "level":"INFO","msg":"hello again",
    +    "key":"val","age":25}
    +
    + + +

    + Next example: HTTP Client. +

    + + + + + + + + + From d1ca2ce65f0637d3006438ccdd4eeec1d3b842df Mon Sep 17 00:00:00 2001 From: Erazem Kokot Date: Mon, 2 Oct 2023 14:43:26 +0200 Subject: [PATCH 198/283] Update Atomic Counters example to use atomic.Uint64 (#490) * Update Atomic Counters example to use atomic.Uint64 This commit updates the Atomic Counters example to follow atomic's recommendation of using atomic.Uint64 instead of uint64 (same for other types) and then calling methods on it, instead of calling atomic.AddUint64(). It also updates the comments and empty lines a bit to look better on the website. * Run tools/build again * Fix comments --- examples/atomic-counters/atomic-counters.go | 23 +++++------ examples/atomic-counters/atomic-counters.hash | 4 +- public/atomic-counters | 40 ++++++++++--------- 3 files changed, 34 insertions(+), 33 deletions(-) diff --git a/examples/atomic-counters/atomic-counters.go b/examples/atomic-counters/atomic-counters.go index 046a347f3..5f8a2d7f4 100644 --- a/examples/atomic-counters/atomic-counters.go +++ b/examples/atomic-counters/atomic-counters.go @@ -15,9 +15,9 @@ import ( func main() { - // We'll use an unsigned integer to represent our + // We'll use an atomic integer type to represent our // (always-positive) counter. - var ops uint64 + var ops atomic.Uint64 // A WaitGroup will help us wait for all goroutines // to finish their work. @@ -30,12 +30,11 @@ func main() { go func() { for c := 0; c < 1000; c++ { - // To atomically increment the counter we - // use `AddUint64`, giving it the memory - // address of our `ops` counter with the - // `&` syntax. - atomic.AddUint64(&ops, 1) + + // To atomically increment the counter we use `Add`. + ops.Add(1) } + wg.Done() }() } @@ -43,10 +42,8 @@ func main() { // Wait until all the goroutines are done. wg.Wait() - // It's safe to access `ops` now because we know - // no other goroutine is writing to it. Reading - // atomics safely while they are being updated is - // also possible, using functions like - // `atomic.LoadUint64`. - fmt.Println("ops:", ops) + // Reading atomics safely while they are being updated is + // possible using functions like `Load`, although here it's + // safe anyway, because no goroutines are writing to 'ops'. + fmt.Println("ops:", ops.Load()) } diff --git a/examples/atomic-counters/atomic-counters.hash b/examples/atomic-counters/atomic-counters.hash index f4c10e6d5..2e18a611d 100644 --- a/examples/atomic-counters/atomic-counters.hash +++ b/examples/atomic-counters/atomic-counters.hash @@ -1,2 +1,2 @@ -7b491b40d56a77b01d8e2bd08366de081a4e8d99 -j-14agntvEO +806f385f4485c3e9d10fe319744dd58ab77adaaf +LfAMxMppwL- diff --git a/public/atomic-counters b/public/atomic-counters index fccef500f..0bd4299c2 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -46,7 +46,7 @@ counters accessed by multiple goroutines.

    - +
    package main
    @@ -77,13 +77,13 @@ counters accessed by multiple goroutines.

    -

    We’ll use an unsigned integer to represent our +

    We’ll use an atomic integer type to represent our (always-positive) counter.

    -
        var ops uint64
    +
        var ops atomic.Uint64
    @@ -114,11 +114,7 @@ counter exactly 1000 times.

    -

    To atomically increment the counter we -use AddUint64, giving it the memory -address of our ops counter with the -& syntax.

    - + @@ -127,15 +123,25 @@ address of our ops counter with the + + +

    To atomically increment the counter we use Add.

    + + + + +
                    ops.Add(1)
    +            }
    + + + -
                    atomic.AddUint64(&ops, 1)
    -            }
    -            wg.Done()
    +          
                wg.Done()
             }()
         }
    @@ -154,16 +160,14 @@ address of our ops counter with the -

    It’s safe to access ops now because we know -no other goroutine is writing to it. Reading -atomics safely while they are being updated is -also possible, using functions like -atomic.LoadUint64.

    +

    Reading atomics safely while they are being updated is +possible using functions like Load, although here it’s +safe anyway, because no goroutines are writing to ‘ops’.

    -
        fmt.Println("ops:", ops)
    +          
        fmt.Println("ops:", ops.Load())
     }
    @@ -216,7 +220,7 @@ state.

    From edab9620548a16993a2341d9d1d71ac8dadd4299 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 2 Oct 2023 05:48:21 -0700 Subject: [PATCH 199/283] Small comment updates to atomic-counters --- examples/atomic-counters/atomic-counters.go | 6 +++--- examples/atomic-counters/atomic-counters.hash | 4 ++-- examples/atomic-counters/atomic-counters.sh | 11 ++++++----- public/atomic-counters | 19 ++++++++++--------- 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/examples/atomic-counters/atomic-counters.go b/examples/atomic-counters/atomic-counters.go index 5f8a2d7f4..01d411546 100644 --- a/examples/atomic-counters/atomic-counters.go +++ b/examples/atomic-counters/atomic-counters.go @@ -42,8 +42,8 @@ func main() { // Wait until all the goroutines are done. wg.Wait() - // Reading atomics safely while they are being updated is - // possible using functions like `Load`, although here it's - // safe anyway, because no goroutines are writing to 'ops'. + // Here no goroutines are writing to 'ops', but using + // `Load` it's safe to atomically read a value even while + // other goroutines are (atomically) updating it. fmt.Println("ops:", ops.Load()) } diff --git a/examples/atomic-counters/atomic-counters.hash b/examples/atomic-counters/atomic-counters.hash index 2e18a611d..76cc67cb6 100644 --- a/examples/atomic-counters/atomic-counters.hash +++ b/examples/atomic-counters/atomic-counters.hash @@ -1,2 +1,2 @@ -806f385f4485c3e9d10fe319744dd58ab77adaaf -LfAMxMppwL- +3435537238237eb363f652dddb405788fec98c8b +HWE6h4-y-Fw diff --git a/examples/atomic-counters/atomic-counters.sh b/examples/atomic-counters/atomic-counters.sh index 1680a100c..4c84d742f 100644 --- a/examples/atomic-counters/atomic-counters.sh +++ b/examples/atomic-counters/atomic-counters.sh @@ -1,9 +1,10 @@ # We expect to get exactly 50,000 operations. Had we -# used the non-atomic `ops++` to increment the counter, -# we'd likely get a different number, changing between -# runs, because the goroutines would interfere with -# each other. Moreover, we'd get data race failures -# when running with the `-race` flag. +# used a non-atomic integer and incremented it with +# `ops++`, we'd likely get a different number, +# changing between runs, because the goroutines +# would interfere with each other. Moreover, we'd +# get data race failures when running with the +# `-race` flag. $ go run atomic-counters.go ops: 50000 diff --git a/public/atomic-counters b/public/atomic-counters index 0bd4299c2..ac967ccdc 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -46,7 +46,7 @@ counters accessed by multiple goroutines.

    - +
    package main
    @@ -160,9 +160,9 @@ counter exactly 1000 times.

    -

    Reading atomics safely while they are being updated is -possible using functions like Load, although here it’s -safe anyway, because no goroutines are writing to ‘ops’.

    +

    Here no goroutines are writing to ‘ops’, but using +Load it’s safe to atomically read a value even while +other goroutines are (atomically) updating it.

    @@ -179,11 +179,12 @@ safe anyway, because no goroutines are writing to ‘ops’.

    We expect to get exactly 50,000 operations. Had we -used the non-atomic ops++ to increment the counter, -we’d likely get a different number, changing between -runs, because the goroutines would interfere with -each other. Moreover, we’d get data race failures -when running with the -race flag.

    +used a non-atomic integer and incremented it with +ops++, we’d likely get a different number, +changing between runs, because the goroutines +would interfere with each other. Moreover, we’d +get data race failures when running with the +-race flag.

    From 41dd5d97b18e73c21b2954fb425486fe9277f8c2 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 28 Oct 2023 08:18:19 -0700 Subject: [PATCH 200/283] Add sample of logical operators in `if` statements Fixes #494 --- examples/if-else/if-else.go | 6 ++++++ examples/if-else/if-else.hash | 4 ++-- examples/if-else/if-else.sh | 1 + public/if-else | 19 +++++++++++++++++-- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/examples/if-else/if-else.go b/examples/if-else/if-else.go index 4de7c47bb..f59795c7e 100644 --- a/examples/if-else/if-else.go +++ b/examples/if-else/if-else.go @@ -19,6 +19,12 @@ func main() { fmt.Println("8 is divisible by 4") } + // Logical operators like `&&` and `||` are often + // useful in conditions. + if 7%2 == 0 || 8%2 == 0 { + fmt.Println("either 8 or 7 are even") + } + // A statement can precede conditionals; any variables // declared in this statement are available in the current // and all subsequent branches. diff --git a/examples/if-else/if-else.hash b/examples/if-else/if-else.hash index 37363db36..276f72796 100644 --- a/examples/if-else/if-else.hash +++ b/examples/if-else/if-else.hash @@ -1,2 +1,2 @@ -d6a962236fc1296684cd1ffb2d95d131ed84abde -U7xcpdutgCJ +152124e287cd55e549bc29bcb8693bf260d1b3ab +hTOHdmUcUxz diff --git a/examples/if-else/if-else.sh b/examples/if-else/if-else.sh index 52ccc1101..99f60ccfc 100644 --- a/examples/if-else/if-else.sh +++ b/examples/if-else/if-else.sh @@ -1,6 +1,7 @@ $ go run if-else.go 7 is odd 8 is divisible by 4 +either 7 or 8 are even 9 has 1 digit # There is no [ternary if](https://en.wikipedia.org/wiki/%3F:) diff --git a/public/if-else b/public/if-else index c394864a5..d40fe0d47 100644 --- a/public/if-else +++ b/public/if-else @@ -42,7 +42,7 @@ straight-forward.

    - +
    package main
    @@ -95,6 +95,20 @@ straight-forward.

    + + +

    Logical operators like && and || are often +useful in conditions.

    + + + + +
        if 7%2 == 0 || 8%2 == 0 {
    +        fmt.Println("either 8 or 7 are even")
    +    }
    + + +

    A statement can precede conditionals; any variables @@ -140,6 +154,7 @@ in Go, but that the braces are required.

    $ go run if-else.go 
     7 is odd
     8 is divisible by 4
    +either 7 or 8 are even
     9 has 1 digit
    @@ -172,7 +187,7 @@ for basic conditions.

    From 8a64f89840b72d8e42a467705d3520ea98eb2214 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 28 Oct 2023 08:22:37 -0700 Subject: [PATCH 201/283] Update directories sample to use WalkDir Since Go 1.16, WalkDir is the recommended alternative over Walk --- examples/directories/directories.go | 11 ++++++----- examples/directories/directories.hash | 4 ++-- public/directories | 15 ++++++++------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/examples/directories/directories.go b/examples/directories/directories.go index ecc2fb5d5..36a721b9a 100644 --- a/examples/directories/directories.go +++ b/examples/directories/directories.go @@ -5,6 +5,7 @@ package main import ( "fmt" + "io/fs" "os" "path/filepath" ) @@ -76,19 +77,19 @@ func main() { check(err) // We can also visit a directory *recursively*, - // including all its sub-directories. `Walk` accepts + // including all its sub-directories. `WalkDir` accepts // a callback function to handle every file or // directory visited. fmt.Println("Visiting subdir") - err = filepath.Walk("subdir", visit) + err = filepath.WalkDir("subdir", visit) } // `visit` is called for every file or directory found -// recursively by `filepath.Walk`. -func visit(p string, info os.FileInfo, err error) error { +// recursively by `filepath.WalkDir`. +func visit(path string, d fs.DirEntry, err error) error { if err != nil { return err } - fmt.Println(" ", p, info.IsDir()) + fmt.Println(" ", path, d.IsDir()) return nil } diff --git a/examples/directories/directories.hash b/examples/directories/directories.hash index f62b81a92..9b7005d47 100644 --- a/examples/directories/directories.hash +++ b/examples/directories/directories.hash @@ -1,2 +1,2 @@ -d2eaefdc6dbeaf130e4824403baa948b5845c0ec -cICbVSX51zI +21e35905e45d7b391823ea761d69199e3712d92c +ORNj2BPrLQr diff --git a/public/directories b/public/directories index 5dfbd6046..1629b1fda 100644 --- a/public/directories +++ b/public/directories @@ -42,7 +42,7 @@ - +
    package main
    @@ -55,6 +55,7 @@
    import (
         "fmt"
    +    "io/fs"
         "os"
         "path/filepath"
     )
    @@ -242,7 +243,7 @@ when listing the current directory.

    We can also visit a directory recursively, -including all its sub-directories. Walk accepts +including all its sub-directories. WalkDir accepts a callback function to handle every file or directory visited.

    @@ -250,7 +251,7 @@ directory visited.

        fmt.Println("Visiting subdir")
    -    err = filepath.Walk("subdir", visit)
    +    err = filepath.WalkDir("subdir", visit)
     }
    @@ -258,16 +259,16 @@ directory visited.

    visit is called for every file or directory found -recursively by filepath.Walk.

    +recursively by filepath.WalkDir.

    -
    func visit(p string, info os.FileInfo, err error) error {
    +          
    func visit(path string, d fs.DirEntry, err error) error {
         if err != nil {
             return err
         }
    -    fmt.Println(" ", p, info.IsDir())
    +    fmt.Println(" ", path, d.IsDir())
         return nil
     }
    @@ -316,7 +317,7 @@ recursively by filepath.Walk.

    From bc2c65c085def21575b25052b68dcd37a9415312 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 28 Oct 2023 09:24:45 -0700 Subject: [PATCH 202/283] Update chroma dependency --- go.mod | 2 +- go.sum | 4 ++-- public/maps | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 1f29711f4..190395da9 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/mmcgrana/gobyexample go 1.21 require ( - github.com/alecthomas/chroma/v2 v2.8.0 + github.com/alecthomas/chroma/v2 v2.10.0 github.com/aws/aws-sdk-go-v2 v1.9.0 github.com/aws/aws-sdk-go-v2/config v1.7.0 github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 diff --git a/go.sum b/go.sum index 4917b6426..edd27f0a9 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/alecthomas/assert/v2 v2.2.1 h1:XivOgYcduV98QCahG8T5XTezV5bylXe+lBxLG2K2ink= github.com/alecthomas/assert/v2 v2.2.1/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= -github.com/alecthomas/chroma/v2 v2.8.0 h1:w9WJUjFFmHHB2e8mRpL9jjy3alYDlU0QLDezj1xE264= -github.com/alecthomas/chroma/v2 v2.8.0/go.mod h1:yrkMI9807G1ROx13fhe1v6PN2DDeaR73L3d+1nmYQtw= +github.com/alecthomas/chroma/v2 v2.10.0 h1:T2iQOCCt4pRmRMfL55gTodMtc7cU0y7lc1Jb8/mK/64= +github.com/alecthomas/chroma/v2 v2.10.0/go.mod h1:4TQu7gdfuPjSh76j78ietmqh9LiurGF0EpseFXdKMBw= github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/aws/aws-sdk-go-v2 v1.9.0 h1:+S+dSqQCN3MSU5vJRu1HqHrq00cJn6heIMU7X9hcsoo= diff --git a/public/maps b/public/maps index 1f2146e3c..affb54a93 100644 --- a/public/maps +++ b/public/maps @@ -166,7 +166,7 @@ the clear builtin.

    -
        clear(m)
    +          
        clear(m)
         fmt.Println("map:", m)
    From 294387674ae00300f7aa8157ed62fc815a757fbd Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 28 Oct 2023 09:28:12 -0700 Subject: [PATCH 203/283] Update aws-adk-go dependencies --- go.mod | 30 ++++++++++++++++++------------ go.sum | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 12 deletions(-) diff --git a/go.mod b/go.mod index 190395da9..0e6fb3bd4 100644 --- a/go.mod +++ b/go.mod @@ -4,21 +4,27 @@ go 1.21 require ( github.com/alecthomas/chroma/v2 v2.10.0 - github.com/aws/aws-sdk-go-v2 v1.9.0 - github.com/aws/aws-sdk-go-v2/config v1.7.0 - github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 + github.com/aws/aws-sdk-go-v2 v1.21.2 + github.com/aws/aws-sdk-go-v2/config v1.19.1 + github.com/aws/aws-sdk-go-v2/service/s3 v1.40.2 github.com/russross/blackfriday/v2 v2.1.0 ) require ( - github.com/aws/aws-sdk-go-v2/credentials v1.4.0 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 // indirect - github.com/aws/smithy-go v1.8.0 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.14 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.13.43 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.15 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.38 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.6 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.15.2 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.23.2 // indirect + github.com/aws/smithy-go v1.15.0 // indirect github.com/dlclark/regexp2 v1.10.0 // indirect ) diff --git a/go.sum b/go.sum index edd27f0a9..923548f31 100644 --- a/go.sum +++ b/go.sum @@ -6,34 +6,71 @@ github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/aws/aws-sdk-go-v2 v1.9.0 h1:+S+dSqQCN3MSU5vJRu1HqHrq00cJn6heIMU7X9hcsoo= github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= +github.com/aws/aws-sdk-go-v2 v1.21.2 h1:+LXZ0sgo8quN9UOKXXzAWRT3FWd4NxeXWOZom9pE7GA= +github.com/aws/aws-sdk-go-v2 v1.21.2/go.mod h1:ErQhvNuEMhJjweavOYhxVkn2RUx7kQXVATHrjKtxIpM= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.14 h1:Sc82v7tDQ/vdU1WtuSyzZ1I7y/68j//HJ6uozND1IDs= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.14/go.mod h1:9NCTOURS8OpxvoAVHq79LK81/zC78hfRWFn+aL0SPcY= github.com/aws/aws-sdk-go-v2/config v1.7.0 h1:J2cZ7qe+3IpqBEXnHUrFrOjoB9BlsXg7j53vxcl5IVg= github.com/aws/aws-sdk-go-v2/config v1.7.0/go.mod h1:w9+nMZ7soXCe5nT46Ri354SNhXDQ6v+V5wqDjnZE+GY= +github.com/aws/aws-sdk-go-v2/config v1.19.1 h1:oe3vqcGftyk40icfLymhhhNysAwk0NfiwkDi2GTPMXs= +github.com/aws/aws-sdk-go-v2/config v1.19.1/go.mod h1:ZwDUgFnQgsazQTnWfeLWk5GjeqTQTL8lMkoE1UXzxdE= github.com/aws/aws-sdk-go-v2/credentials v1.4.0 h1:kmvesfjY861FzlCU9mvAfe01D9aeXcG2ZuC+k9F2YLM= github.com/aws/aws-sdk-go-v2/credentials v1.4.0/go.mod h1:dgGR+Qq7Wjcd4AOAW5Rf5Tnv3+x7ed6kETXyS9WCuAY= +github.com/aws/aws-sdk-go-v2/credentials v1.13.43 h1:LU8vo40zBlo3R7bAvBVy/ku4nxGEyZe9N8MqAeFTzF8= +github.com/aws/aws-sdk-go-v2/credentials v1.13.43/go.mod h1:zWJBz1Yf1ZtX5NGax9ZdNjhhI4rgjfgsyk6vTY1yfVg= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0 h1:OxTAgH8Y4BXHD6PGCJ8DHx2kaZPCQfSTqmDsdRZFezE= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0/go.mod h1:CpNzHK9VEFUCknu50kkB8z58AH2B5DvPP7ea1LHve/Y= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13 h1:PIktER+hwIG286DqXyvVENjgLTAwGgoeriLDD5C+YlQ= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13/go.mod h1:f/Ib/qYjhV2/qdsf79H3QP/eRE4AkVyEf6sk7XfZ1tg= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43 h1:nFBQlGtkbPzp/NjZLuFxRqmT91rLJkgvsEQs68h962Y= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43/go.mod h1:auo+PiyLl0n1l8A0e8RIeR8tOzYPfZZH/JNlrJ8igTQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37 h1:JRVhO25+r3ar2mKGP7E0LDl8K9/G36gjlqca5iQbaqc= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37/go.mod h1:Qe+2KtKml+FEsQF/DHmDV+xjtche/hwoF75EG4UlHW8= github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2 h1:d95cddM3yTm4qffj3P6EnP+TzX1SSkWaQypXSgT/hpA= github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2/go.mod h1:BQV0agm+JEhqR+2RT5e1XTFIDcAAV0eW6z2trp+iduw= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45 h1:hze8YsjSh8Wl1rYa1CJpRmXP21BvOBuc76YhW0HsuQ4= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45/go.mod h1:lD5M20o09/LCuQ2mE62Mb/iSdSlCNuj6H5ci7tW7OsE= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.6 h1:wmGLw2i8ZTlHLw7a9ULGfQbuccw8uIiNr6sol5bFzc8= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.6/go.mod h1:Q0Hq2X/NuL7z8b1Dww8rmOFl+jzusKEcyvkKspwdpyc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0 h1:gceOysEWNNwLd6cki65IMBZ4WAM0MwgBQq2n7kejoT8= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0/go.mod h1:v8ygadNyATSm6elwJ/4gzJwcFhri9RqS8skgHKiwXPU= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.15 h1:7R8uRYyXzdD71KWVCL78lJZltah6VVznXBazvKjfH58= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.15/go.mod h1:26SQUPcTNgV1Tapwdt4a1rOsYRsnBsJHLMPoxK2b0d8= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.38 h1:skaFGzv+3kA+v2BPKhuekeb1Hbb105+44r8ASC+q5SE= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.38/go.mod h1:epIZoRSSbRIwLPJU5F+OldHhwZPBdpDeQkRdCeY3+00= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0 h1:VNJ5NLBteVXEwE2F1zEXVmyIH58mZ6kIQGJoC7C+vkg= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0/go.mod h1:R1KK+vY8AfalhG1AOu5e35pOD2SdoPKQCFLTvnxiohk= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37 h1:WWZA/I2K4ptBS1kg0kV1JbBtG/umed0vwHRrmcr9z7k= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37/go.mod h1:vBmDnwWXWxNPFRMmG2m/3MKOe+xEcMDo1tanpaWCcck= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0 h1:B/1pIeV/oFnrOwhoMA6ASX+qT4FzMqn1MYsPiIXgMqQ= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0/go.mod h1:LKb3cKNQIMh+itGnEpKGcnL/6OIjPZqrtYah1w5f+3o= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.6 h1:9ulSU5ClouoPIYhDQdg9tpl83d5Yb91PXTKK+17q+ow= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.6/go.mod h1:lnc2taBsR9nTlz9meD+lhFZZ9EWY712QHrRflWpTcOA= github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 h1:nR9j0xMxpXk6orC/C03fbHNrbb1NaXp8LdVV7V1oVLE= github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0/go.mod h1:Qit9H3zjAmF7CLHOkrepE9b2ndX/2l3scstsM5g2jSk= +github.com/aws/aws-sdk-go-v2/service/s3 v1.40.2 h1:Ll5/YVCOzRB+gxPqs2uD0R7/MyATC0w85626glSKmp4= +github.com/aws/aws-sdk-go-v2/service/s3 v1.40.2/go.mod h1:Zjfqt7KhQK+PO1bbOsFNzKgaq7TcxzmEoDWN8lM0qzQ= github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 h1:sHXMIKYS6YiLPzmKSvDpPmOpJDHxmAUgbiF49YNVztg= github.com/aws/aws-sdk-go-v2/service/sso v1.4.0/go.mod h1:+1fpWnL96DL23aXPpMGbsmKe8jLTEfbjuQoA4WS1VaA= +github.com/aws/aws-sdk-go-v2/service/sso v1.15.2 h1:JuPGc7IkOP4AaqcZSIcyqLpFSqBWK32rM9+a1g6u73k= +github.com/aws/aws-sdk-go-v2/service/sso v1.15.2/go.mod h1:gsL4keucRCgW+xA85ALBpRFfdSLH4kHOVSnLMSuBECo= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3 h1:HFiiRkf1SdaAmV3/BHOFZ9DjFynPHj8G/UIO1lQS+fk= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3/go.mod h1:a7bHA82fyUXOm+ZSWKU6PIoBxrjSprdLoM8xPYvzYVg= github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 h1:1at4e5P+lvHNl2nUktdM2/v+rpICg/QSEr9TO/uW9vU= github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= +github.com/aws/aws-sdk-go-v2/service/sts v1.23.2 h1:0BkLfgeDjfZnZ+MhB3ONb01u9pwFYTCZVhlsSSBvlbU= +github.com/aws/aws-sdk-go-v2/service/sts v1.23.2/go.mod h1:Eows6e1uQEsc4ZaHANmsPRzAKcVDrcmjjWiih2+HUUQ= github.com/aws/smithy-go v1.8.0 h1:AEwwwXQZtUwP5Mz506FeXXrKBe0jA8gVM+1gEcSRooc= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= +github.com/aws/smithy-go v1.15.0 h1:PS/durmlzvAFpQHDs4wi4sNNP9ExsqZh6IlfdHXgKK8= +github.com/aws/smithy-go v1.15.0/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0= github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= From 991f8937ddbc30822e81463015f1785fd791d310 Mon Sep 17 00:00:00 2001 From: Boris Zhuravel <87899509+zhuboris@users.noreply.github.com> Date: Thu, 30 Nov 2023 16:02:23 +0300 Subject: [PATCH 204/283] Added example of reading from closed channel (#498) * Add example of reading from closed channel * Add second return value to read example Also revert too complicated paragraph --- examples/closing-channels/closing-channels.go | 8 ++++++ .../closing-channels/closing-channels.hash | 4 +-- examples/closing-channels/closing-channels.sh | 2 ++ public/closing-channels | 26 ++++++++++++++++--- 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/examples/closing-channels/closing-channels.go b/examples/closing-channels/closing-channels.go index 926d9b51e..edc86d866 100644 --- a/examples/closing-channels/closing-channels.go +++ b/examples/closing-channels/closing-channels.go @@ -47,4 +47,12 @@ func main() { // [synchronization](channel-synchronization) approach // we saw earlier. <-done + + // It is possible to read more from an empty closed channel. + // However, instead of waiting for a message, we will always + // immediately receive a zero value of the channel's type and + // a false bool flag indicating that we should stop reading from it. + j, isOpened := <-jobs + fmt.Println("no jobs to receive", j) + fmt.Println("awaiting more jobs:", isOpened) } diff --git a/examples/closing-channels/closing-channels.hash b/examples/closing-channels/closing-channels.hash index 3e33a0715..41fbccafe 100644 --- a/examples/closing-channels/closing-channels.hash +++ b/examples/closing-channels/closing-channels.hash @@ -1,2 +1,2 @@ -8f26c901e0f14df2ca40329a354c3ac86a5c3a07 -vCvRjcMq7p3 +3b474131d4d983ac5e53d8a6b94e069a8a4b775d +yLh6yhTGZeF diff --git a/examples/closing-channels/closing-channels.sh b/examples/closing-channels/closing-channels.sh index 013f8a879..195832850 100644 --- a/examples/closing-channels/closing-channels.sh +++ b/examples/closing-channels/closing-channels.sh @@ -7,6 +7,8 @@ sent job 3 received job 3 sent all jobs received all jobs +no jobs to receive 0 +awaiting more jobs: false # The idea of closed channels leads naturally to our next # example: `range` over channels. diff --git a/public/closing-channels b/public/closing-channels index a6310979d..4f98cbf67 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -43,7 +43,7 @@ completion to the channel’s receivers.

    - +
    package main
    @@ -125,10 +125,26 @@ channel, then closes it.

    synchronization approach we saw earlier.

    + + + +
        <-done
    + + + + + +

    It is possible to read more from an empty closed channel. +However, instead of waiting for a message, we will always +immediately receive a zero value of the channel’s type and +a false bool flag indicating that we should stop reading from it.

    + -
        <-done
    +          
        j, isOpened := <-jobs
    +    fmt.Println("no jobs to receive", j)
    +    fmt.Println("awaiting more jobs:", isOpened)
     }
    @@ -151,7 +167,9 @@ we saw earlier.

    sent job 3 received job 3 sent all jobs -received all jobs
    +
    received all jobs +no jobs to receive 0 +awaiting more jobs: false
    @@ -182,7 +200,7 @@ example: range over channels.

    From 461f6955d69bb468b92d9c9abeec55a3befac123 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 30 Nov 2023 05:08:42 -0800 Subject: [PATCH 205/283] Fix up formatting and phrasing for closed chan read --- examples/closing-channels/closing-channels.go | 16 +++++++------ .../closing-channels/closing-channels.hash | 4 ++-- examples/closing-channels/closing-channels.sh | 3 +-- public/closing-channels | 23 ++++++++++--------- 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/examples/closing-channels/closing-channels.go b/examples/closing-channels/closing-channels.go index edc86d866..9abc84373 100644 --- a/examples/closing-channels/closing-channels.go +++ b/examples/closing-channels/closing-channels.go @@ -48,11 +48,13 @@ func main() { // we saw earlier. <-done - // It is possible to read more from an empty closed channel. - // However, instead of waiting for a message, we will always - // immediately receive a zero value of the channel's type and - // a false bool flag indicating that we should stop reading from it. - j, isOpened := <-jobs - fmt.Println("no jobs to receive", j) - fmt.Println("awaiting more jobs:", isOpened) + // Reading from a closed channel succeeds immediately, + // returning the zero value of the underlying type. + // The optional second return value is `true` if the + // value received was delivered by a successful send + // operation to the channel, or `false` if it was a + // zero value generated because the channel is closed + // and empty. + _, ok := <-jobs + fmt.Println("received more jobs:", ok) } diff --git a/examples/closing-channels/closing-channels.hash b/examples/closing-channels/closing-channels.hash index 41fbccafe..ecbc461f3 100644 --- a/examples/closing-channels/closing-channels.hash +++ b/examples/closing-channels/closing-channels.hash @@ -1,2 +1,2 @@ -3b474131d4d983ac5e53d8a6b94e069a8a4b775d -yLh6yhTGZeF +13f0ccf3674db8e9631a424c4070f9d423f7dc11 +yZijZHYe22y diff --git a/examples/closing-channels/closing-channels.sh b/examples/closing-channels/closing-channels.sh index 195832850..8d6baff99 100644 --- a/examples/closing-channels/closing-channels.sh +++ b/examples/closing-channels/closing-channels.sh @@ -7,8 +7,7 @@ sent job 3 received job 3 sent all jobs received all jobs -no jobs to receive 0 -awaiting more jobs: false +received more jobs: false # The idea of closed channels leads naturally to our next # example: `range` over channels. diff --git a/public/closing-channels b/public/closing-channels index 4f98cbf67..331b79a2e 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -43,7 +43,7 @@ completion to the channel’s receivers.

    - +
    package main
    @@ -134,17 +134,19 @@ we saw earlier.

    -

    It is possible to read more from an empty closed channel. -However, instead of waiting for a message, we will always -immediately receive a zero value of the channel’s type and -a false bool flag indicating that we should stop reading from it.

    +

    Reading from a closed channel succeeds immediately, +returning the zero value of the underlying type. +The optional second return value is true if the +value received was delivered by a successful send +operation to the channel, or false if it was a +zero value generated because the channel is closed +and empty.

    -
        j, isOpened := <-jobs
    -    fmt.Println("no jobs to receive", j)
    -    fmt.Println("awaiting more jobs:", isOpened)
    +          
        _, ok := <-jobs
    +    fmt.Println("received more jobs:", ok)
     }
    @@ -168,8 +170,7 @@ a false bool flag indicating that we should stop reading from it.

    received job 3 sent all jobs received all jobs -no jobs to receive 0 -awaiting more jobs: false
    +
    received more jobs: false
    @@ -200,7 +201,7 @@ example: range over channels.

    From 6fdb46ead6b529b1c6c573208b7d53859a7e3103 Mon Sep 17 00:00:00 2001 From: Akhil Kumar Date: Sat, 9 Dec 2023 13:22:58 -0500 Subject: [PATCH 206/283] Update generics.sh with correct response (#500) --- examples/generics/generics.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/generics/generics.sh b/examples/generics/generics.sh index 4aa2d0729..0695f4f67 100644 --- a/examples/generics/generics.sh +++ b/examples/generics/generics.sh @@ -1,3 +1,7 @@ $ go run generics.go keys: [4 1 2] list: [10 13 23] + +# Note: The order of iteration over map keys is not defined in Go, +# so different invocations may result in different orders. +# The output need not necessarily be keys: [1 2 4]. \ No newline at end of file From ef7998951de0c1f474192f90f040ff8acc2294ea Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 9 Dec 2023 10:25:43 -0800 Subject: [PATCH 207/283] Fix up comment length and text, and generate public/ --- examples/generics/generics.sh | 6 +++--- public/generics | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/examples/generics/generics.sh b/examples/generics/generics.sh index 0695f4f67..4a3f2274e 100644 --- a/examples/generics/generics.sh +++ b/examples/generics/generics.sh @@ -2,6 +2,6 @@ $ go run generics.go keys: [4 1 2] list: [10 13 23] -# Note: The order of iteration over map keys is not defined in Go, -# so different invocations may result in different orders. -# The output need not necessarily be keys: [1 2 4]. \ No newline at end of file +# Note: The order of iteration over map keys is not +# defined in Go, so different invocations may +# result in different orders. diff --git a/public/generics b/public/generics index adee89770..c577e1afc 100644 --- a/public/generics +++ b/public/generics @@ -205,7 +205,7 @@ automatically.

    - +
    $ go run generics.go
     keys: [4 1 2]
    @@ -213,6 +213,19 @@ automatically.

    + + +

    Note: The order of iteration over map keys is not +defined in Go, so different invocations may +result in different orders.

    + + + + + + + + @@ -228,7 +241,7 @@ automatically.

    From 0c31ca89f0b3e2ca5165266d2d3c83305b5093d9 Mon Sep 17 00:00:00 2001 From: Siddharth Buddharaju <79242776+Deftly@users.noreply.github.com> Date: Fri, 29 Dec 2023 10:04:45 -0500 Subject: [PATCH 208/283] typo fix - if-else.sh (#502) Fixes #502 --- examples/if-else/if-else.sh | 4 ++-- public/if-else | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/if-else/if-else.sh b/examples/if-else/if-else.sh index 99f60ccfc..502ca1e03 100644 --- a/examples/if-else/if-else.sh +++ b/examples/if-else/if-else.sh @@ -1,7 +1,7 @@ -$ go run if-else.go +$ go run if-else.go 7 is odd 8 is divisible by 4 -either 7 or 8 are even +either 8 or 7 are even 9 has 1 digit # There is no [ternary if](https://en.wikipedia.org/wiki/%3F:) diff --git a/public/if-else b/public/if-else index d40fe0d47..7bc1b619e 100644 --- a/public/if-else +++ b/public/if-else @@ -151,10 +151,10 @@ in Go, but that the braces are required.

    -
    $ go run if-else.go 
    +          
    $ go run if-else.go
     7 is odd
     8 is divisible by 4
    -either 7 or 8 are even
    +either 8 or 7 are even
     9 has 1 digit
    From da72468520d40e3bf5d93d5f9974c11ff0a8a80e Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 29 Dec 2023 07:09:36 -0800 Subject: [PATCH 209/283] Reorder text to conform to output --- examples/if-else/if-else.go | 2 +- examples/if-else/if-else.hash | 4 ++-- public/if-else | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/if-else/if-else.go b/examples/if-else/if-else.go index f59795c7e..a2a2f14e6 100644 --- a/examples/if-else/if-else.go +++ b/examples/if-else/if-else.go @@ -21,7 +21,7 @@ func main() { // Logical operators like `&&` and `||` are often // useful in conditions. - if 7%2 == 0 || 8%2 == 0 { + if 8%2 == 0 || 7%2 == 0 { fmt.Println("either 8 or 7 are even") } diff --git a/examples/if-else/if-else.hash b/examples/if-else/if-else.hash index 276f72796..4de271b79 100644 --- a/examples/if-else/if-else.hash +++ b/examples/if-else/if-else.hash @@ -1,2 +1,2 @@ -152124e287cd55e549bc29bcb8693bf260d1b3ab -hTOHdmUcUxz +fd9e491f9891e6a9593c2c1d640c1df113ce3ccf +RKgKzCe7qcF diff --git a/public/if-else b/public/if-else index 7bc1b619e..1bb293a4e 100644 --- a/public/if-else +++ b/public/if-else @@ -42,7 +42,7 @@ straight-forward.

    - +
    package main
    @@ -103,7 +103,7 @@ useful in conditions.

    -
        if 7%2 == 0 || 8%2 == 0 {
    +          
        if 8%2 == 0 || 7%2 == 0 {
             fmt.Println("either 8 or 7 are even")
         }
    @@ -187,7 +187,7 @@ for basic conditions.

    From f7256dea96c85bacddf69d87fc90fbc1b91c65a3 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 31 Jan 2024 05:08:06 -0800 Subject: [PATCH 210/283] Update random number examples to match new 1.20 semantics Fixes #506 --- examples/random-numbers/random-numbers.go | 22 ++------ examples/random-numbers/random-numbers.hash | 4 +- examples/random-numbers/random-numbers.sh | 15 ++---- public/random-numbers | 56 +++++---------------- 4 files changed, 24 insertions(+), 73 deletions(-) diff --git a/examples/random-numbers/random-numbers.go b/examples/random-numbers/random-numbers.go index 53d0f381c..a6ec4c8be 100644 --- a/examples/random-numbers/random-numbers.go +++ b/examples/random-numbers/random-numbers.go @@ -7,7 +7,6 @@ package main import ( "fmt" "math/rand" - "time" ) func main() { @@ -28,22 +27,10 @@ func main() { fmt.Print((rand.Float64() * 5) + 5) fmt.Println() - // The default number generator is deterministic, so it'll - // produce the same sequence of numbers each time by default. - // To produce varying sequences, give it a seed that changes. - // Note that this is not safe to use for random numbers you - // intend to be secret; use `crypto/rand` for those. - s1 := rand.NewSource(time.Now().UnixNano()) - r1 := rand.New(s1) - - // Call the resulting `rand.Rand` just like the - // functions on the `rand` package. - fmt.Print(r1.Intn(100), ",") - fmt.Print(r1.Intn(100)) - fmt.Println() - - // If you seed a source with the same number, it - // produces the same sequence of random numbers. + // If you want a known seed, `NewSource` returns + // a `rand.Source` value that can be used to + // seed a new generator. The same seed will produce + // the same sequence of random numbers. s2 := rand.NewSource(42) r2 := rand.New(s2) fmt.Print(r2.Intn(100), ",") @@ -53,4 +40,5 @@ func main() { r3 := rand.New(s3) fmt.Print(r3.Intn(100), ",") fmt.Print(r3.Intn(100)) + fmt.Println() } diff --git a/examples/random-numbers/random-numbers.hash b/examples/random-numbers/random-numbers.hash index e099cc460..79d101416 100644 --- a/examples/random-numbers/random-numbers.hash +++ b/examples/random-numbers/random-numbers.hash @@ -1,2 +1,2 @@ -ea6a386e4e5602247b2203fa433d4419ff5a9489 -Enb5uJEx0Bt +1106f890032a51d24bb0a01d7e234c29b4fce005 +Op7Udbk3k8K diff --git a/examples/random-numbers/random-numbers.sh b/examples/random-numbers/random-numbers.sh index f9f2b5ba4..6221d5a7c 100644 --- a/examples/random-numbers/random-numbers.sh +++ b/examples/random-numbers/random-numbers.sh @@ -1,17 +1,12 @@ -# Depending on where you run this sample, some of the -# generated numbers may be different. Note that on -# the Go playground seeding with `time.Now()` still -# produces deterministic results due to the way the -# playground is implemented. +# Some of the generated numbers may be +# different when you run the sample. $ go run random-numbers.go -81,87 -0.6645600532184904 -7.123187485356329,8.434115364335547 -0,28 +44,20 +0.8090228139659177 +5.840125017402497,6.937056298890035 5,87 5,87 - # See the [`math/rand`](https://pkg.go.dev/math/rand) # package docs for references on other random quantities # that Go can provide. diff --git a/public/random-numbers b/public/random-numbers index 5b0a95f16..f4d3a1c81 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -43,7 +43,7 @@ generation.

    - +
    package main
    @@ -57,7 +57,6 @@ generation.

    import (
         "fmt"
         "math/rand"
    -    "time"
     )
    @@ -114,38 +113,10 @@ other ranges, for example 5.0 <= f' < 10.0.

    -

    The default number generator is deterministic, so it’ll -produce the same sequence of numbers each time by default. -To produce varying sequences, give it a seed that changes. -Note that this is not safe to use for random numbers you -intend to be secret; use crypto/rand for those.

    - - - - -
        s1 := rand.NewSource(time.Now().UnixNano())
    -    r1 := rand.New(s1)
    - - - - - -

    Call the resulting rand.Rand just like the -functions on the rand package.

    - - - - -
        fmt.Print(r1.Intn(100), ",")
    -    fmt.Print(r1.Intn(100))
    -    fmt.Println()
    - - - - - -

    If you seed a source with the same number, it -produces the same sequence of random numbers.

    +

    If you want a known seed, NewSource returns +a rand.Source value that can be used to +seed a new generator. The same seed will produce +the same sequence of random numbers.

    @@ -159,6 +130,7 @@ produces the same sequence of random numbers.

    r3 := rand.New(s3) fmt.Print(r3.Intn(100), ",") fmt.Print(r3.Intn(100)) + fmt.Println() }
    @@ -169,20 +141,16 @@ produces the same sequence of random numbers.

    -

    Depending on where you run this sample, some of the -generated numbers may be different. Note that on -the Go playground seeding with time.Now() still -produces deterministic results due to the way the -playground is implemented.

    +

    Some of the generated numbers may be +different when you run the sample.

    $ go run random-numbers.go
    -81,87
    -0.6645600532184904
    -7.123187485356329,8.434115364335547
    -0,28
    +44,20
    +0.8090228139659177
    +5.840125017402497,6.937056298890035
     5,87
     5,87
    @@ -216,7 +184,7 @@ that Go can provide.

    From ef87d6518aa2fd175ab1cd7f9fb5394ac73ab30a Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 7 Feb 2024 05:48:56 -0800 Subject: [PATCH 211/283] Update building Go versions to 1.22.0 --- .github/workflows/test.yml | 2 +- go.mod | 2 +- go.sum | 30 +----------------------------- 3 files changed, 3 insertions(+), 31 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fc52b39c8..c2f560f7f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.21.0] + go-version: [1.22.0] runs-on: ${{ matrix.os }} steps: diff --git a/go.mod b/go.mod index 0e6fb3bd4..13d697a54 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mmcgrana/gobyexample -go 1.21 +go 1.22.0 require ( github.com/alecthomas/chroma/v2 v2.10.0 diff --git a/go.sum b/go.sum index 923548f31..5a2b1a516 100644 --- a/go.sum +++ b/go.sum @@ -4,72 +4,46 @@ github.com/alecthomas/chroma/v2 v2.10.0 h1:T2iQOCCt4pRmRMfL55gTodMtc7cU0y7lc1Jb8 github.com/alecthomas/chroma/v2 v2.10.0/go.mod h1:4TQu7gdfuPjSh76j78ietmqh9LiurGF0EpseFXdKMBw= github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= -github.com/aws/aws-sdk-go-v2 v1.9.0 h1:+S+dSqQCN3MSU5vJRu1HqHrq00cJn6heIMU7X9hcsoo= -github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= github.com/aws/aws-sdk-go-v2 v1.21.2 h1:+LXZ0sgo8quN9UOKXXzAWRT3FWd4NxeXWOZom9pE7GA= github.com/aws/aws-sdk-go-v2 v1.21.2/go.mod h1:ErQhvNuEMhJjweavOYhxVkn2RUx7kQXVATHrjKtxIpM= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.14 h1:Sc82v7tDQ/vdU1WtuSyzZ1I7y/68j//HJ6uozND1IDs= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.14/go.mod h1:9NCTOURS8OpxvoAVHq79LK81/zC78hfRWFn+aL0SPcY= -github.com/aws/aws-sdk-go-v2/config v1.7.0 h1:J2cZ7qe+3IpqBEXnHUrFrOjoB9BlsXg7j53vxcl5IVg= -github.com/aws/aws-sdk-go-v2/config v1.7.0/go.mod h1:w9+nMZ7soXCe5nT46Ri354SNhXDQ6v+V5wqDjnZE+GY= github.com/aws/aws-sdk-go-v2/config v1.19.1 h1:oe3vqcGftyk40icfLymhhhNysAwk0NfiwkDi2GTPMXs= github.com/aws/aws-sdk-go-v2/config v1.19.1/go.mod h1:ZwDUgFnQgsazQTnWfeLWk5GjeqTQTL8lMkoE1UXzxdE= -github.com/aws/aws-sdk-go-v2/credentials v1.4.0 h1:kmvesfjY861FzlCU9mvAfe01D9aeXcG2ZuC+k9F2YLM= -github.com/aws/aws-sdk-go-v2/credentials v1.4.0/go.mod h1:dgGR+Qq7Wjcd4AOAW5Rf5Tnv3+x7ed6kETXyS9WCuAY= github.com/aws/aws-sdk-go-v2/credentials v1.13.43 h1:LU8vo40zBlo3R7bAvBVy/ku4nxGEyZe9N8MqAeFTzF8= github.com/aws/aws-sdk-go-v2/credentials v1.13.43/go.mod h1:zWJBz1Yf1ZtX5NGax9ZdNjhhI4rgjfgsyk6vTY1yfVg= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0 h1:OxTAgH8Y4BXHD6PGCJ8DHx2kaZPCQfSTqmDsdRZFezE= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.5.0/go.mod h1:CpNzHK9VEFUCknu50kkB8z58AH2B5DvPP7ea1LHve/Y= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13 h1:PIktER+hwIG286DqXyvVENjgLTAwGgoeriLDD5C+YlQ= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13/go.mod h1:f/Ib/qYjhV2/qdsf79H3QP/eRE4AkVyEf6sk7XfZ1tg= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43 h1:nFBQlGtkbPzp/NjZLuFxRqmT91rLJkgvsEQs68h962Y= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43/go.mod h1:auo+PiyLl0n1l8A0e8RIeR8tOzYPfZZH/JNlrJ8igTQ= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37 h1:JRVhO25+r3ar2mKGP7E0LDl8K9/G36gjlqca5iQbaqc= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37/go.mod h1:Qe+2KtKml+FEsQF/DHmDV+xjtche/hwoF75EG4UlHW8= -github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2 h1:d95cddM3yTm4qffj3P6EnP+TzX1SSkWaQypXSgT/hpA= -github.com/aws/aws-sdk-go-v2/internal/ini v1.2.2/go.mod h1:BQV0agm+JEhqR+2RT5e1XTFIDcAAV0eW6z2trp+iduw= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45 h1:hze8YsjSh8Wl1rYa1CJpRmXP21BvOBuc76YhW0HsuQ4= github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45/go.mod h1:lD5M20o09/LCuQ2mE62Mb/iSdSlCNuj6H5ci7tW7OsE= github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.6 h1:wmGLw2i8ZTlHLw7a9ULGfQbuccw8uIiNr6sol5bFzc8= github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.6/go.mod h1:Q0Hq2X/NuL7z8b1Dww8rmOFl+jzusKEcyvkKspwdpyc= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0 h1:gceOysEWNNwLd6cki65IMBZ4WAM0MwgBQq2n7kejoT8= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.3.0/go.mod h1:v8ygadNyATSm6elwJ/4gzJwcFhri9RqS8skgHKiwXPU= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.15 h1:7R8uRYyXzdD71KWVCL78lJZltah6VVznXBazvKjfH58= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.15/go.mod h1:26SQUPcTNgV1Tapwdt4a1rOsYRsnBsJHLMPoxK2b0d8= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.38 h1:skaFGzv+3kA+v2BPKhuekeb1Hbb105+44r8ASC+q5SE= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.38/go.mod h1:epIZoRSSbRIwLPJU5F+OldHhwZPBdpDeQkRdCeY3+00= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0 h1:VNJ5NLBteVXEwE2F1zEXVmyIH58mZ6kIQGJoC7C+vkg= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.3.0/go.mod h1:R1KK+vY8AfalhG1AOu5e35pOD2SdoPKQCFLTvnxiohk= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37 h1:WWZA/I2K4ptBS1kg0kV1JbBtG/umed0vwHRrmcr9z7k= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37/go.mod h1:vBmDnwWXWxNPFRMmG2m/3MKOe+xEcMDo1tanpaWCcck= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0 h1:B/1pIeV/oFnrOwhoMA6ASX+qT4FzMqn1MYsPiIXgMqQ= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.6.0/go.mod h1:LKb3cKNQIMh+itGnEpKGcnL/6OIjPZqrtYah1w5f+3o= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.6 h1:9ulSU5ClouoPIYhDQdg9tpl83d5Yb91PXTKK+17q+ow= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.6/go.mod h1:lnc2taBsR9nTlz9meD+lhFZZ9EWY712QHrRflWpTcOA= -github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 h1:nR9j0xMxpXk6orC/C03fbHNrbb1NaXp8LdVV7V1oVLE= -github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0/go.mod h1:Qit9H3zjAmF7CLHOkrepE9b2ndX/2l3scstsM5g2jSk= github.com/aws/aws-sdk-go-v2/service/s3 v1.40.2 h1:Ll5/YVCOzRB+gxPqs2uD0R7/MyATC0w85626glSKmp4= github.com/aws/aws-sdk-go-v2/service/s3 v1.40.2/go.mod h1:Zjfqt7KhQK+PO1bbOsFNzKgaq7TcxzmEoDWN8lM0qzQ= -github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 h1:sHXMIKYS6YiLPzmKSvDpPmOpJDHxmAUgbiF49YNVztg= -github.com/aws/aws-sdk-go-v2/service/sso v1.4.0/go.mod h1:+1fpWnL96DL23aXPpMGbsmKe8jLTEfbjuQoA4WS1VaA= github.com/aws/aws-sdk-go-v2/service/sso v1.15.2 h1:JuPGc7IkOP4AaqcZSIcyqLpFSqBWK32rM9+a1g6u73k= github.com/aws/aws-sdk-go-v2/service/sso v1.15.2/go.mod h1:gsL4keucRCgW+xA85ALBpRFfdSLH4kHOVSnLMSuBECo= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3 h1:HFiiRkf1SdaAmV3/BHOFZ9DjFynPHj8G/UIO1lQS+fk= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3/go.mod h1:a7bHA82fyUXOm+ZSWKU6PIoBxrjSprdLoM8xPYvzYVg= -github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 h1:1at4e5P+lvHNl2nUktdM2/v+rpICg/QSEr9TO/uW9vU= -github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= github.com/aws/aws-sdk-go-v2/service/sts v1.23.2 h1:0BkLfgeDjfZnZ+MhB3ONb01u9pwFYTCZVhlsSSBvlbU= github.com/aws/aws-sdk-go-v2/service/sts v1.23.2/go.mod h1:Eows6e1uQEsc4ZaHANmsPRzAKcVDrcmjjWiih2+HUUQ= -github.com/aws/smithy-go v1.8.0 h1:AEwwwXQZtUwP5Mz506FeXXrKBe0jA8gVM+1gEcSRooc= -github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/aws/smithy-go v1.15.0 h1:PS/durmlzvAFpQHDs4wi4sNNP9ExsqZh6IlfdHXgKK8= github.com/aws/smithy-go v1.15.0/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0= github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= @@ -79,7 +53,5 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= From 1143b547d7d36b5de93c8cd11a87ce392e8ba625 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 7 Feb 2024 05:54:30 -0800 Subject: [PATCH 212/283] Add Go 1.22's range-over-int example to `for` --- examples/for/for.go | 10 ++++++++-- examples/for/for.hash | 4 ++-- examples/for/for.sh | 9 ++++++--- public/for | 31 ++++++++++++++++++++++++------- 4 files changed, 40 insertions(+), 14 deletions(-) diff --git a/examples/for/for.go b/examples/for/for.go index 9a4df3055..83ca1bf71 100644 --- a/examples/for/for.go +++ b/examples/for/for.go @@ -15,10 +15,16 @@ func main() { } // A classic initial/condition/after `for` loop. - for j := 7; j <= 9; j++ { + for j := 0; j < 3; j++ { fmt.Println(j) } + // Another way of accomplishing the basic "do this + // N times" iteration is `range` over an integer. + for i := range 3 { + fmt.Println("range", i) + } + // `for` without a condition will loop repeatedly // until you `break` out of the loop or `return` from // the enclosing function. @@ -29,7 +35,7 @@ func main() { // You can also `continue` to the next iteration of // the loop. - for n := 0; n <= 5; n++ { + for n := range 6 { if n%2 == 0 { continue } diff --git a/examples/for/for.hash b/examples/for/for.hash index 9473e965f..0beaf5928 100644 --- a/examples/for/for.hash +++ b/examples/for/for.hash @@ -1,2 +1,2 @@ -7af221b7da2f2b22b0b1b0a1b365afc5a56ef815 -2-4H-ArwHHS +8eeb5be15c3c5fc3f9d0d8009dfcec771dc5e03d +_F2rYHNilKa diff --git a/examples/for/for.sh b/examples/for/for.sh index 12785ebb4..b7bc0767b 100644 --- a/examples/for/for.sh +++ b/examples/for/for.sh @@ -2,9 +2,12 @@ $ go run for.go 1 2 3 -7 -8 -9 +0 +1 +2 +range 0 +range 1 +range 2 loop 1 3 diff --git a/public/for b/public/for index 987ade2e9..514e97371 100644 --- a/public/for +++ b/public/for @@ -42,7 +42,7 @@ some basic types of for loops.

    - +
    package main
    @@ -89,12 +89,26 @@ some basic types of for loops.

    -
        for j := 7; j <= 9; j++ {
    +          
        for j := 0; j < 3; j++ {
             fmt.Println(j)
         }
    + + +

    Another way of accomplishing the basic “do this +N times” iteration is range over an integer.

    + + + + +
        for i := range 3 {
    +        fmt.Println("range", i)
    +    }
    + + +

    for without a condition will loop repeatedly @@ -119,7 +133,7 @@ the loop.

    -
        for n := 0; n <= 5; n++ {
    +          
        for n := range 6 {
             if n%2 == 0 {
                 continue
             }
    @@ -143,9 +157,12 @@ the loop.

    1 2 3 -7 -8 -9 +0 +1 +2 +range 0 +range 1 +range 2 loop 1 3 @@ -181,7 +198,7 @@ structures.

    From 5aa9ad70f3c7efebf459c42fb8dc9340b0212c2d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 7 Feb 2024 06:27:04 -0800 Subject: [PATCH 213/283] Update random-numbers example to use Go 1.22's math/rand/v2 Fixes #507 --- examples/random-numbers/random-numbers.go | 33 ++++++------ examples/random-numbers/random-numbers.hash | 4 +- examples/random-numbers/random-numbers.sh | 8 +-- public/random-numbers | 57 ++++++++++++--------- 4 files changed, 58 insertions(+), 44 deletions(-) diff --git a/examples/random-numbers/random-numbers.go b/examples/random-numbers/random-numbers.go index a6ec4c8be..d63d656cc 100644 --- a/examples/random-numbers/random-numbers.go +++ b/examples/random-numbers/random-numbers.go @@ -1,4 +1,4 @@ -// Go's `math/rand` package provides +// Go's `math/rand/v2` package provides // [pseudorandom number](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) // generation. @@ -6,15 +6,15 @@ package main import ( "fmt" - "math/rand" + "math/rand/v2" ) func main() { - // For example, `rand.Intn` returns a random `int` n, + // For example, `rand.IntN` returns a random `int` n, // `0 <= n < 100`. - fmt.Print(rand.Intn(100), ",") - fmt.Print(rand.Intn(100)) + fmt.Print(rand.IntN(100), ",") + fmt.Print(rand.IntN(100)) fmt.Println() // `rand.Float64` returns a `float64` `f`, @@ -27,18 +27,21 @@ func main() { fmt.Print((rand.Float64() * 5) + 5) fmt.Println() - // If you want a known seed, `NewSource` returns - // a `rand.Source` value that can be used to - // seed a new generator. The same seed will produce - // the same sequence of random numbers. - s2 := rand.NewSource(42) + // If you want a known seed, create a new + // `rand.Source` and pass it into the `New` + // constructor. `NewPCG` creates a new + // [PCG](https://en.wikipedia.org/wiki/Permuted_congruential_generator) + // source that requires a seed of two `uint64` + // numbers. + s2 := rand.NewPCG(42, 1024) r2 := rand.New(s2) - fmt.Print(r2.Intn(100), ",") - fmt.Print(r2.Intn(100)) + fmt.Print(r2.IntN(100), ",") + fmt.Print(r2.IntN(100)) fmt.Println() - s3 := rand.NewSource(42) + + s3 := rand.NewPCG(42, 1024) r3 := rand.New(s3) - fmt.Print(r3.Intn(100), ",") - fmt.Print(r3.Intn(100)) + fmt.Print(r3.IntN(100), ",") + fmt.Print(r3.IntN(100)) fmt.Println() } diff --git a/examples/random-numbers/random-numbers.hash b/examples/random-numbers/random-numbers.hash index 79d101416..e005e5f7c 100644 --- a/examples/random-numbers/random-numbers.hash +++ b/examples/random-numbers/random-numbers.hash @@ -1,2 +1,2 @@ -1106f890032a51d24bb0a01d7e234c29b4fce005 -Op7Udbk3k8K +76b8f86171ffcf9e7d5781fdf50c050a824acd9b +TkgmNAl8euK diff --git a/examples/random-numbers/random-numbers.sh b/examples/random-numbers/random-numbers.sh index 6221d5a7c..6c9b47170 100644 --- a/examples/random-numbers/random-numbers.sh +++ b/examples/random-numbers/random-numbers.sh @@ -1,12 +1,12 @@ # Some of the generated numbers may be # different when you run the sample. $ go run random-numbers.go -44,20 +68,56 0.8090228139659177 5.840125017402497,6.937056298890035 -5,87 -5,87 +94,49 +94,49 -# See the [`math/rand`](https://pkg.go.dev/math/rand) +# See the [`math/rand/v2`](https://pkg.go.dev/math/rand/v2) # package docs for references on other random quantities # that Go can provide. diff --git a/public/random-numbers b/public/random-numbers index f4d3a1c81..0598e4bc1 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -27,7 +27,7 @@ -

    Go’s math/rand package provides +

    Go’s math/rand/v2 package provides pseudorandom number generation.

    @@ -43,7 +43,7 @@ generation.

    - +
    package main
    @@ -56,7 +56,7 @@ generation.

    import (
         "fmt"
    -    "math/rand"
    +    "math/rand/v2"
     )
    @@ -73,14 +73,14 @@ generation.

    -

    For example, rand.Intn returns a random int n, +

    For example, rand.IntN returns a random int n, 0 <= n < 100.

    -
        fmt.Print(rand.Intn(100), ",")
    -    fmt.Print(rand.Intn(100))
    +          
        fmt.Print(rand.IntN(100), ",")
    +    fmt.Print(rand.IntN(100))
         fmt.Println()
    @@ -113,23 +113,34 @@ other ranges, for example 5.0 <= f' < 10.0.

    -

    If you want a known seed, NewSource returns -a rand.Source value that can be used to -seed a new generator. The same seed will produce -the same sequence of random numbers.

    +

    If you want a known seed, create a new +rand.Source and pass it into the New +constructor. NewPCG creates a new +PCG +source that requires a seed of two uint64 +numbers.

    - + -
        s2 := rand.NewSource(42)
    +          
        s2 := rand.NewPCG(42, 1024)
         r2 := rand.New(s2)
    -    fmt.Print(r2.Intn(100), ",")
    -    fmt.Print(r2.Intn(100))
    -    fmt.Println()
    -    s3 := rand.NewSource(42)
    +    fmt.Print(r2.IntN(100), ",")
    +    fmt.Print(r2.IntN(100))
    +    fmt.Println()
    + + + + + + + + + +
        s3 := rand.NewPCG(42, 1024)
         r3 := rand.New(s3)
    -    fmt.Print(r3.Intn(100), ",")
    -    fmt.Print(r3.Intn(100))
    +    fmt.Print(r3.IntN(100), ",")
    +    fmt.Print(r3.IntN(100))
         fmt.Println()
     }
    @@ -148,17 +159,17 @@ different when you run the sample.

    $ go run random-numbers.go
    -44,20
    +68,56
     0.8090228139659177
     5.840125017402497,6.937056298890035
    -5,87
    -5,87
    +
    94,49 +94,49
    -

    See the math/rand +

    See the math/rand/v2 package docs for references on other random quantities that Go can provide.

    @@ -184,7 +195,7 @@ that Go can provide.

    From a3fb3a3b5baf048c2919cf09cc454e49418674b7 Mon Sep 17 00:00:00 2001 From: Sreejith I V <46400271+pzerone@users.noreply.github.com> Date: Fri, 9 Feb 2024 18:21:32 +0530 Subject: [PATCH 214/283] Update waitgroups example to use go 1.22 (#508) gorutine closures inside for loops does not require variable reassignment since the 1.22 for loop changes --- examples/waitgroups/waitgroups.go | 4 ---- examples/waitgroups/waitgroups.hash | 4 ++-- public/waitgroups | 17 ++--------------- 3 files changed, 4 insertions(+), 21 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index 5ac70b52f..a8a446a2d 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -29,10 +29,6 @@ func main() { // counter for each. for i := 1; i <= 5; i++ { wg.Add(1) - // Avoid re-use of the same `i` value in each goroutine closure. - // See [the FAQ](https://golang.org/doc/faq#closures_and_goroutines) - // for more details. - i := i // Wrap the worker call in a closure that makes sure to tell // the WaitGroup that this worker is done. This way the worker diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index 5fdeaf5d4..5dc808bec 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -66d1c1cdb7e60f63b9b30938aa9c63b2262463ac -S98GjeaGBX0 +c81a54fed0cd96464456e05b46163329eb7c958b +fC_Chrkb5uA diff --git a/public/waitgroups b/public/waitgroups index 6b4465f34..6e9fdf477 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -42,7 +42,7 @@ use a wait group.

    - +
    package main
    @@ -122,19 +122,6 @@ counter for each.

    - - -

    Avoid re-use of the same i value in each goroutine closure. -See the FAQ -for more details.

    - - - - -
            i := i
    - - -

    Wrap the worker call in a closure that makes sure to tell @@ -230,7 +217,7 @@ is likely to be different for each invocation.

    From 9c71a850ebac886bb3bbc6e6ad5b83aa47153afc Mon Sep 17 00:00:00 2001 From: Aan Niraj Patel <37667704+aannirajpatel@users.noreply.github.com> Date: Thu, 22 Feb 2024 12:14:58 -0500 Subject: [PATCH 215/283] Fix verbiage for Strings and Runes (noissue) (#510) --- examples/strings-and-runes/strings-and-runes.go | 5 +++-- examples/strings-and-runes/strings-and-runes.hash | 4 ++-- public/strings-and-runes | 7 ++++--- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/examples/strings-and-runes/strings-and-runes.go b/examples/strings-and-runes/strings-and-runes.go index acbd0cc66..9501c8a94 100644 --- a/examples/strings-and-runes/strings-and-runes.go +++ b/examples/strings-and-runes/strings-and-runes.go @@ -38,8 +38,9 @@ func main() { // the `utf8` package. Note that the run-time of // `RuneCountInString` depends on the size of the string, // because it has to decode each UTF-8 rune sequentially. - // Some Thai characters are represented by multiple UTF-8 - // code points, so the result of this count may be surprising. + // Some Thai characters are represented by UTF-8 code points + // that can span multiple bytes, so the result of this count + // may be surprising. fmt.Println("Rune count:", utf8.RuneCountInString(s)) // A `range` loop handles strings specially and decodes diff --git a/examples/strings-and-runes/strings-and-runes.hash b/examples/strings-and-runes/strings-and-runes.hash index 99cc716e1..9f8571b81 100644 --- a/examples/strings-and-runes/strings-and-runes.hash +++ b/examples/strings-and-runes/strings-and-runes.hash @@ -1,2 +1,2 @@ -45a1127788eb4c0acfef48efee9ca386e06d4c58 -39BpTLf6BAz +ffbc918567cea7cdadcaee87ffc404a1d4f5c62a +-iNDXZ9IM3s diff --git a/public/strings-and-runes b/public/strings-and-runes index f5bf97e9e..84126885b 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -48,7 +48,7 @@ introduction to the topic.

    - +
    package main
    @@ -124,8 +124,9 @@ the bytes that constitute the code points in s.

    the utf8 package. Note that the run-time of RuneCountInString depends on the size of the string, because it has to decode each UTF-8 rune sequentially. -Some Thai characters are represented by multiple UTF-8 -code points, so the result of this count may be surprising.

    +Some Thai characters are represented by UTF-8 code points +that can span multiple bytes, so the result of this count +may be surprising.

    From 13d2e9a2f0b08022ee1961a18f2b2f173fd4beec Mon Sep 17 00:00:00 2001 From: ChrisMcKenzie Date: Wed, 13 Mar 2024 23:22:14 -0500 Subject: [PATCH 216/283] added: a dark mode in css for us night dwellers --- public/site.css | 91 +++++++++++++++++++++++++++++++++++++++++++++- templates/site.css | 91 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 180 insertions(+), 2 deletions(-) diff --git a/public/site.css b/public/site.css index f74c733c1..416a50fa1 100644 --- a/public/site.css +++ b/public/site.css @@ -42,6 +42,7 @@ table { border-spacing: 0; } + /* Layout and typography */ body { font-family: 'Georgia', serif; @@ -184,7 +185,7 @@ body .no { color: #880000 } /* Name.Constant */ body .nd { color: #AA22FF } /* Name.Decorator */ body .ni { color: #999999; font-weight: bold } /* Name.Entity */ body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { } /* Name.Function */ +body .nf { } /* Name.Function */ body .nl { color: #A0A000 } /* Name.Label */ body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ body .nt { color: #954121; font-weight: bold } /* Name.Tag */ @@ -211,3 +212,91 @@ body .vc { color: #19469D } /* Name.Variable.Class */ body .vg { color: #19469D } /* Name.Variable.Global */ body .vi { color: #19469D } /* Name.Variable.Instance */ body .il { color: #666666 } /* Literal.Number.Integer.Long */ + + +@media (prefers-color-scheme: dark) { + body { + background-color: #1e2030; + color: #f5f9ff; + } + a, a:visited { + color: #f5f9ff; + } + p.footer { + color: #ebedf0; + } + p.footer a, p.footer a:visited { + color: #ebedf0; + } + td.code { + background: #2f334d; + } + td.code.empty { + background: #1e2030; + } + /* Syntax highlighting */ + body .hll { background-color: #ffffcc } + body .err { border: 1px solid #FF0000 } /* Error */ + body .c { color: #408080; font-style: italic } /* Comment */ + body .k { color: rgb(252, 167, 234) } /* Keyword */ + body .o { color: #89ddff } /* Operator */ + body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ + body .cp { color: #BC7A00 } /* Comment.Preproc */ + body .c1 { color: #408080; font-style: italic } /* Comment.Single */ + body .cs { color: #408080; font-style: italic } /* Comment.Special */ + body .gd { color: #A00000 } /* Generic.Deleted */ + body .ge { font-style: italic } /* Generic.Emph */ + body .gr { color: #FF0000 } /* Generic.Error */ + body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ + body .gi { color: #00A000 } /* Generic.Inserted */ + body .go { color: rgb(130, 170, 255) } /* Generic.Output */ + body .gp { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Prompt */ + body .gs { font-weight: bold } /* Generic.Strong */ + body .gu { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Subheading */ + body .gt { color: #0040D0 } /* Generic.Traceback */ + body .kc { color: rgb(252, 167, 234) } /* Keyword.Constant */ + body .kd { color: rgb(252, 167, 234) } /* Keyword.Declaration */ + body .kn { color: rgb(252, 167, 234) } /* Keyword.Namespace */ + body .kp { color: rgb(252, 167, 234) } /* Keyword.Pseudo */ + body .kr { color: rgb(252, 167, 234); font-weight: bold } /* Keyword.Reserved */ + body .kt { color: #9ece6a } /* Keyword.Type */ + body .m { color: #2ac3de } /* Literal.Number */ + body .s { color: rgb(195, 232, 141) } /* Literal.String */ + body .na { color: #7D9029 } /* Name.Attribute */ + body .nb { color: rgb(252, 167, 234) } /* Name.Builtin */ + body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ + body .no { color: #880000 } /* Name.Constant */ + body .nd { color: #AA22FF } /* Name.Decorator */ + body .ni { color: #999999; font-weight: bold } /* Name.Entity */ + body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ + body .nf { color: rgb(130, 170, 255) } /* Name.Function */ + body .nl { color: #A0A000 } /* Name.Label */ + body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ + body .nt { color: rgb(252, 167, 234); font-weight: bold } /* Name.Tag */ + body .nv { color: #19469D } /* Name.Variable */ + body .nx { color: #c0caf5 } /* Name.Other */ + body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ + body .w { color: #bbbbbb } /* Text.Whitespace */ + body .mf { color: #2ac3de } /* Literal.Number.Float */ + body .mh { color: #2ac3de } /* Literal.Number.Hex */ + body .mi { color: #2ac3de } /* Literal.Number.Integer */ + body .mo { color: #2ac3de } /* Literal.Number.Oct */ + body .sb { color: rgb(195, 232, 141) } /* Literal.String.Backtick */ + body .sc { color: rgb(195, 232, 141) } /* Literal.String.Char */ + body .sd { color: rgb(195, 232, 141); font-style: italic } /* Literal.String.Doc */ + body .s2 { color: rgb(195, 232, 141) } /* Literal.String.Double */ + body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ + body .sh { color: rgb(195, 232, 141) } /* Literal.String.Heredoc */ + body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ + body .sx { color: rgb(252, 167, 234) } /* Literal.String.Other */ + body .sr { color: #BB6688 } /* Literal.String.Regex */ + body .s1 { color: rgb(195, 232, 141) } /* Literal.String.Single */ + body .ss { color: #19469D } /* Literal.String.Symbol */ + body .bp { color: #954121 } /* Name.Builtin.Pseudo */ + body .vc { color: #19469D } /* Name.Variable.Class */ + body .vg { color: #19469D } /* Name.Variable.Global */ + body .vi { color: #19469D } /* Name.Variable.Instance */ + body .il { color: #666666 } /* Literal.Number.Integer.Long */ + + +} diff --git a/templates/site.css b/templates/site.css index f74c733c1..416a50fa1 100644 --- a/templates/site.css +++ b/templates/site.css @@ -42,6 +42,7 @@ table { border-spacing: 0; } + /* Layout and typography */ body { font-family: 'Georgia', serif; @@ -184,7 +185,7 @@ body .no { color: #880000 } /* Name.Constant */ body .nd { color: #AA22FF } /* Name.Decorator */ body .ni { color: #999999; font-weight: bold } /* Name.Entity */ body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { } /* Name.Function */ +body .nf { } /* Name.Function */ body .nl { color: #A0A000 } /* Name.Label */ body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ body .nt { color: #954121; font-weight: bold } /* Name.Tag */ @@ -211,3 +212,91 @@ body .vc { color: #19469D } /* Name.Variable.Class */ body .vg { color: #19469D } /* Name.Variable.Global */ body .vi { color: #19469D } /* Name.Variable.Instance */ body .il { color: #666666 } /* Literal.Number.Integer.Long */ + + +@media (prefers-color-scheme: dark) { + body { + background-color: #1e2030; + color: #f5f9ff; + } + a, a:visited { + color: #f5f9ff; + } + p.footer { + color: #ebedf0; + } + p.footer a, p.footer a:visited { + color: #ebedf0; + } + td.code { + background: #2f334d; + } + td.code.empty { + background: #1e2030; + } + /* Syntax highlighting */ + body .hll { background-color: #ffffcc } + body .err { border: 1px solid #FF0000 } /* Error */ + body .c { color: #408080; font-style: italic } /* Comment */ + body .k { color: rgb(252, 167, 234) } /* Keyword */ + body .o { color: #89ddff } /* Operator */ + body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ + body .cp { color: #BC7A00 } /* Comment.Preproc */ + body .c1 { color: #408080; font-style: italic } /* Comment.Single */ + body .cs { color: #408080; font-style: italic } /* Comment.Special */ + body .gd { color: #A00000 } /* Generic.Deleted */ + body .ge { font-style: italic } /* Generic.Emph */ + body .gr { color: #FF0000 } /* Generic.Error */ + body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ + body .gi { color: #00A000 } /* Generic.Inserted */ + body .go { color: rgb(130, 170, 255) } /* Generic.Output */ + body .gp { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Prompt */ + body .gs { font-weight: bold } /* Generic.Strong */ + body .gu { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Subheading */ + body .gt { color: #0040D0 } /* Generic.Traceback */ + body .kc { color: rgb(252, 167, 234) } /* Keyword.Constant */ + body .kd { color: rgb(252, 167, 234) } /* Keyword.Declaration */ + body .kn { color: rgb(252, 167, 234) } /* Keyword.Namespace */ + body .kp { color: rgb(252, 167, 234) } /* Keyword.Pseudo */ + body .kr { color: rgb(252, 167, 234); font-weight: bold } /* Keyword.Reserved */ + body .kt { color: #9ece6a } /* Keyword.Type */ + body .m { color: #2ac3de } /* Literal.Number */ + body .s { color: rgb(195, 232, 141) } /* Literal.String */ + body .na { color: #7D9029 } /* Name.Attribute */ + body .nb { color: rgb(252, 167, 234) } /* Name.Builtin */ + body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ + body .no { color: #880000 } /* Name.Constant */ + body .nd { color: #AA22FF } /* Name.Decorator */ + body .ni { color: #999999; font-weight: bold } /* Name.Entity */ + body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ + body .nf { color: rgb(130, 170, 255) } /* Name.Function */ + body .nl { color: #A0A000 } /* Name.Label */ + body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ + body .nt { color: rgb(252, 167, 234); font-weight: bold } /* Name.Tag */ + body .nv { color: #19469D } /* Name.Variable */ + body .nx { color: #c0caf5 } /* Name.Other */ + body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ + body .w { color: #bbbbbb } /* Text.Whitespace */ + body .mf { color: #2ac3de } /* Literal.Number.Float */ + body .mh { color: #2ac3de } /* Literal.Number.Hex */ + body .mi { color: #2ac3de } /* Literal.Number.Integer */ + body .mo { color: #2ac3de } /* Literal.Number.Oct */ + body .sb { color: rgb(195, 232, 141) } /* Literal.String.Backtick */ + body .sc { color: rgb(195, 232, 141) } /* Literal.String.Char */ + body .sd { color: rgb(195, 232, 141); font-style: italic } /* Literal.String.Doc */ + body .s2 { color: rgb(195, 232, 141) } /* Literal.String.Double */ + body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ + body .sh { color: rgb(195, 232, 141) } /* Literal.String.Heredoc */ + body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ + body .sx { color: rgb(252, 167, 234) } /* Literal.String.Other */ + body .sr { color: #BB6688 } /* Literal.String.Regex */ + body .s1 { color: rgb(195, 232, 141) } /* Literal.String.Single */ + body .ss { color: #19469D } /* Literal.String.Symbol */ + body .bp { color: #954121 } /* Name.Builtin.Pseudo */ + body .vc { color: #19469D } /* Name.Variable.Class */ + body .vg { color: #19469D } /* Name.Variable.Global */ + body .vi { color: #19469D } /* Name.Variable.Instance */ + body .il { color: #666666 } /* Literal.Number.Integer.Long */ + + +} From c7e9d6f10a256c251ef339a61fbbbcd8a49c9211 Mon Sep 17 00:00:00 2001 From: ChrisMcKenzie Date: Thu, 14 Mar 2024 20:56:20 -0500 Subject: [PATCH 217/283] changed: to github-dark and a different background and more gray text --- public/site.css | 72 +++++++++++++++++++++++----------------------- templates/site.css | 72 +++++++++++++++++++++++----------------------- 2 files changed, 72 insertions(+), 72 deletions(-) diff --git a/public/site.css b/public/site.css index 416a50fa1..55a6b70e6 100644 --- a/public/site.css +++ b/public/site.css @@ -216,30 +216,30 @@ body .il { color: #666666 } /* Literal.Number.Integer.Long * @media (prefers-color-scheme: dark) { body { - background-color: #1e2030; - color: #f5f9ff; + background-color: #171b22; + color: #F0F6FC; } a, a:visited { - color: #f5f9ff; + color: #F0F6FC; } p.footer { - color: #ebedf0; + color: #6B7280; } p.footer a, p.footer a:visited { - color: #ebedf0; + color: #6B7280; } td.code { - background: #2f334d; + background: #0D1117; } td.code.empty { - background: #1e2030; + background: #171b22; } /* Syntax highlighting */ body .hll { background-color: #ffffcc } body .err { border: 1px solid #FF0000 } /* Error */ body .c { color: #408080; font-style: italic } /* Comment */ - body .k { color: rgb(252, 167, 234) } /* Keyword */ - body .o { color: #89ddff } /* Operator */ + body .k { color: #FF7B72 } /* Keyword */ + body .o { color: #FF7B72 } /* Operator */ body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ body .cp { color: #BC7A00 } /* Comment.Preproc */ body .c1 { color: #408080; font-style: italic } /* Comment.Single */ @@ -249,48 +249,48 @@ body .il { color: #666666 } /* Literal.Number.Integer.Long * body .gr { color: #FF0000 } /* Generic.Error */ body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ body .gi { color: #00A000 } /* Generic.Inserted */ - body .go { color: rgb(130, 170, 255) } /* Generic.Output */ - body .gp { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Prompt */ + body .go { color: #808080 } /* Generic.Output */ + body .gp { color: #F0883E ; font-weight: bold } /* Generic.Prompt */ body .gs { font-weight: bold } /* Generic.Strong */ - body .gu { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Subheading */ + body .gu { color: #F0883E ; font-weight: bold } /* Generic.Subheading */ body .gt { color: #0040D0 } /* Generic.Traceback */ - body .kc { color: rgb(252, 167, 234) } /* Keyword.Constant */ - body .kd { color: rgb(252, 167, 234) } /* Keyword.Declaration */ - body .kn { color: rgb(252, 167, 234) } /* Keyword.Namespace */ - body .kp { color: rgb(252, 167, 234) } /* Keyword.Pseudo */ - body .kr { color: rgb(252, 167, 234); font-weight: bold } /* Keyword.Reserved */ - body .kt { color: #9ece6a } /* Keyword.Type */ - body .m { color: #2ac3de } /* Literal.Number */ - body .s { color: rgb(195, 232, 141) } /* Literal.String */ + body .kc { color: #79C0FF } /* Keyword.Constant */ + body .kd { color: #FF7B72 } /* Keyword.Declaration */ + body .kn { color: #FF7B72 } /* Keyword.Namespace */ + body .kp { color: #FF7B72 } /* Keyword.Pseudo */ + body .kr { color: #FF7B72; font-weight: bold } /* Keyword.Reserved */ + body .kt { color: #FF7B72 } /* Keyword.Type */ + body .m { color: #2AC3DE } /* Literal.Number */ + body .s { color: #A5D6FF } /* Literal.String */ body .na { color: #7D9029 } /* Name.Attribute */ - body .nb { color: rgb(252, 167, 234) } /* Name.Builtin */ + body .nb { color: #E6EDF3 } /* Name.Builtin */ body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ body .no { color: #880000 } /* Name.Constant */ body .nd { color: #AA22FF } /* Name.Decorator */ body .ni { color: #999999; font-weight: bold } /* Name.Entity */ body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ - body .nf { color: rgb(130, 170, 255) } /* Name.Function */ + body .nf { color: #E6EDF3 } /* Name.Function */ body .nl { color: #A0A000 } /* Name.Label */ body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ - body .nt { color: rgb(252, 167, 234); font-weight: bold } /* Name.Tag */ + body .nt { color: #E6EDF3; font-weight: bold } /* Name.Tag */ body .nv { color: #19469D } /* Name.Variable */ - body .nx { color: #c0caf5 } /* Name.Other */ + body .nx { color: #E6EDF3 } /* Name.Other */ body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ - body .w { color: #bbbbbb } /* Text.Whitespace */ - body .mf { color: #2ac3de } /* Literal.Number.Float */ - body .mh { color: #2ac3de } /* Literal.Number.Hex */ - body .mi { color: #2ac3de } /* Literal.Number.Integer */ - body .mo { color: #2ac3de } /* Literal.Number.Oct */ - body .sb { color: rgb(195, 232, 141) } /* Literal.String.Backtick */ - body .sc { color: rgb(195, 232, 141) } /* Literal.String.Char */ - body .sd { color: rgb(195, 232, 141); font-style: italic } /* Literal.String.Doc */ - body .s2 { color: rgb(195, 232, 141) } /* Literal.String.Double */ + body .w { color: #BBBBBB } /* Text.Whitespace */ + body .mf { color: #A5D6FF } /* Literal.Number.Float */ + body .mh { color: #A5D6FF } /* Literal.Number.Hex */ + body .mi { color: #A5D6FF } /* Literal.Number.Integer */ + body .mo { color: #A5D6FF } /* Literal.Number.Oct */ + body .sb { color: #A5D6FF } /* Literal.String.Backtick */ + body .sc { color: #A5D6FF } /* Literal.String.Char */ + body .sd { color: #A5D6FF; font-style: italic } /* Literal.String.Doc */ + body .s2 { color: #A5D6FF } /* Literal.String.Double */ body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ - body .sh { color: rgb(195, 232, 141) } /* Literal.String.Heredoc */ + body .sh { color: #A5D6FF } /* Literal.String.Heredoc */ body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ - body .sx { color: rgb(252, 167, 234) } /* Literal.String.Other */ + body .sx { color: #E6EDF3 } /* Literal.String.Other */ body .sr { color: #BB6688 } /* Literal.String.Regex */ - body .s1 { color: rgb(195, 232, 141) } /* Literal.String.Single */ + body .s1 { color: #A5D6FF } /* Literal.String.Single */ body .ss { color: #19469D } /* Literal.String.Symbol */ body .bp { color: #954121 } /* Name.Builtin.Pseudo */ body .vc { color: #19469D } /* Name.Variable.Class */ diff --git a/templates/site.css b/templates/site.css index 416a50fa1..55a6b70e6 100644 --- a/templates/site.css +++ b/templates/site.css @@ -216,30 +216,30 @@ body .il { color: #666666 } /* Literal.Number.Integer.Long * @media (prefers-color-scheme: dark) { body { - background-color: #1e2030; - color: #f5f9ff; + background-color: #171b22; + color: #F0F6FC; } a, a:visited { - color: #f5f9ff; + color: #F0F6FC; } p.footer { - color: #ebedf0; + color: #6B7280; } p.footer a, p.footer a:visited { - color: #ebedf0; + color: #6B7280; } td.code { - background: #2f334d; + background: #0D1117; } td.code.empty { - background: #1e2030; + background: #171b22; } /* Syntax highlighting */ body .hll { background-color: #ffffcc } body .err { border: 1px solid #FF0000 } /* Error */ body .c { color: #408080; font-style: italic } /* Comment */ - body .k { color: rgb(252, 167, 234) } /* Keyword */ - body .o { color: #89ddff } /* Operator */ + body .k { color: #FF7B72 } /* Keyword */ + body .o { color: #FF7B72 } /* Operator */ body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ body .cp { color: #BC7A00 } /* Comment.Preproc */ body .c1 { color: #408080; font-style: italic } /* Comment.Single */ @@ -249,48 +249,48 @@ body .il { color: #666666 } /* Literal.Number.Integer.Long * body .gr { color: #FF0000 } /* Generic.Error */ body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ body .gi { color: #00A000 } /* Generic.Inserted */ - body .go { color: rgb(130, 170, 255) } /* Generic.Output */ - body .gp { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Prompt */ + body .go { color: #808080 } /* Generic.Output */ + body .gp { color: #F0883E ; font-weight: bold } /* Generic.Prompt */ body .gs { font-weight: bold } /* Generic.Strong */ - body .gu { color: rgb(130, 170, 255); font-weight: bold } /* Generic.Subheading */ + body .gu { color: #F0883E ; font-weight: bold } /* Generic.Subheading */ body .gt { color: #0040D0 } /* Generic.Traceback */ - body .kc { color: rgb(252, 167, 234) } /* Keyword.Constant */ - body .kd { color: rgb(252, 167, 234) } /* Keyword.Declaration */ - body .kn { color: rgb(252, 167, 234) } /* Keyword.Namespace */ - body .kp { color: rgb(252, 167, 234) } /* Keyword.Pseudo */ - body .kr { color: rgb(252, 167, 234); font-weight: bold } /* Keyword.Reserved */ - body .kt { color: #9ece6a } /* Keyword.Type */ - body .m { color: #2ac3de } /* Literal.Number */ - body .s { color: rgb(195, 232, 141) } /* Literal.String */ + body .kc { color: #79C0FF } /* Keyword.Constant */ + body .kd { color: #FF7B72 } /* Keyword.Declaration */ + body .kn { color: #FF7B72 } /* Keyword.Namespace */ + body .kp { color: #FF7B72 } /* Keyword.Pseudo */ + body .kr { color: #FF7B72; font-weight: bold } /* Keyword.Reserved */ + body .kt { color: #FF7B72 } /* Keyword.Type */ + body .m { color: #2AC3DE } /* Literal.Number */ + body .s { color: #A5D6FF } /* Literal.String */ body .na { color: #7D9029 } /* Name.Attribute */ - body .nb { color: rgb(252, 167, 234) } /* Name.Builtin */ + body .nb { color: #E6EDF3 } /* Name.Builtin */ body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ body .no { color: #880000 } /* Name.Constant */ body .nd { color: #AA22FF } /* Name.Decorator */ body .ni { color: #999999; font-weight: bold } /* Name.Entity */ body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ - body .nf { color: rgb(130, 170, 255) } /* Name.Function */ + body .nf { color: #E6EDF3 } /* Name.Function */ body .nl { color: #A0A000 } /* Name.Label */ body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ - body .nt { color: rgb(252, 167, 234); font-weight: bold } /* Name.Tag */ + body .nt { color: #E6EDF3; font-weight: bold } /* Name.Tag */ body .nv { color: #19469D } /* Name.Variable */ - body .nx { color: #c0caf5 } /* Name.Other */ + body .nx { color: #E6EDF3 } /* Name.Other */ body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ - body .w { color: #bbbbbb } /* Text.Whitespace */ - body .mf { color: #2ac3de } /* Literal.Number.Float */ - body .mh { color: #2ac3de } /* Literal.Number.Hex */ - body .mi { color: #2ac3de } /* Literal.Number.Integer */ - body .mo { color: #2ac3de } /* Literal.Number.Oct */ - body .sb { color: rgb(195, 232, 141) } /* Literal.String.Backtick */ - body .sc { color: rgb(195, 232, 141) } /* Literal.String.Char */ - body .sd { color: rgb(195, 232, 141); font-style: italic } /* Literal.String.Doc */ - body .s2 { color: rgb(195, 232, 141) } /* Literal.String.Double */ + body .w { color: #BBBBBB } /* Text.Whitespace */ + body .mf { color: #A5D6FF } /* Literal.Number.Float */ + body .mh { color: #A5D6FF } /* Literal.Number.Hex */ + body .mi { color: #A5D6FF } /* Literal.Number.Integer */ + body .mo { color: #A5D6FF } /* Literal.Number.Oct */ + body .sb { color: #A5D6FF } /* Literal.String.Backtick */ + body .sc { color: #A5D6FF } /* Literal.String.Char */ + body .sd { color: #A5D6FF; font-style: italic } /* Literal.String.Doc */ + body .s2 { color: #A5D6FF } /* Literal.String.Double */ body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ - body .sh { color: rgb(195, 232, 141) } /* Literal.String.Heredoc */ + body .sh { color: #A5D6FF } /* Literal.String.Heredoc */ body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ - body .sx { color: rgb(252, 167, 234) } /* Literal.String.Other */ + body .sx { color: #E6EDF3 } /* Literal.String.Other */ body .sr { color: #BB6688 } /* Literal.String.Regex */ - body .s1 { color: rgb(195, 232, 141) } /* Literal.String.Single */ + body .s1 { color: #A5D6FF } /* Literal.String.Single */ body .ss { color: #19469D } /* Literal.String.Symbol */ body .bp { color: #954121 } /* Name.Builtin.Pseudo */ body .vc { color: #19469D } /* Name.Variable.Class */ From 26c4409b7662296978024544b48c4c745485b3d2 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 17 Mar 2024 09:14:04 -0700 Subject: [PATCH 218/283] Darkmode style refactoring and tweaking Refactoring: * Refactor CSS to make clear what varies with light/dark mode and what doesn't. * Consistently use 2 spaces for indenting in CSS file. * Remove unused Chroma CSS classes to make styling easier to understand. * Add some comments about how Chroma CSS classes map to Go code. * Organize Chroma CSS classes so that like-styled classes are contiguous. * Display "operators" like regular code - doesn't make sense to style ":=" specially but not "=" e.g. Style tweaks: * Adjust dark mode styling to be less blue, more subdued. --- public/site.css | 345 ++++++++++++++++++--------------------------- templates/site.css | 345 ++++++++++++++++++--------------------------- 2 files changed, 272 insertions(+), 418 deletions(-) diff --git a/public/site.css b/public/site.css index 55a6b70e6..84d0b291e 100644 --- a/public/site.css +++ b/public/site.css @@ -12,131 +12,119 @@ article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { - margin: 0; - padding: 0; - border: 0; - font-size: 100%; - font: inherit; - vertical-align: baseline; + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { - display: block; + display: block; } body { - line-height: 1; + line-height: 1; } ol, ul { - list-style: none; + list-style: none; } blockquote, q { - quotes: none; + quotes: none; } blockquote:before, blockquote:after, q:before, q:after { - content: ''; - content: none; + content: ''; + content: none; } table { - border-collapse: collapse; - border-spacing: 0; + border-collapse: collapse; + border-spacing: 0; } /* Layout and typography */ body { - font-family: 'Georgia', serif; - font-size: 16px; - line-height: 20px; - color: #252519; + font-family: 'Georgia', serif; + font-size: 16px; + line-height: 20px; } em { - font-style: italic; -} -a, a:visited { - color: #261a3b; + font-style: italic; } h2 { - font-size: 32px; - line-height: 40px; - margin-top: 40px; + font-size: 32px; + line-height: 40px; + margin-top: 40px; } h2 a { - text-decoration: none; + text-decoration: none; } div.example { - width: 900px; - min-width: 900px; - max-width: 900px; - margin-left: auto; - margin-right: auto; - margin-bottom: 120px; + width: 900px; + min-width: 900px; + max-width: 900px; + margin-left: auto; + margin-right: auto; + margin-bottom: 120px; } div.example table { - margin-top: 15px; - margin-bottom: 20px; + margin-top: 15px; + margin-bottom: 20px; } p.next { - margin-bottom: 20px; + margin-bottom: 20px; } p.footer { - color: grey; - font-size: 75%; -} -p.footer a, p.footer a:visited { - color: grey; + font-size: 75%; } div#intro { - width: 420px; - min-width: 420px; - max-width: 420px; - margin-left: auto; - margin-right: auto; - margin-bottom: 120px; + width: 420px; + min-width: 420px; + max-width: 420px; + margin-left: auto; + margin-right: auto; + margin-bottom: 120px; } div#intro p { - padding-top: 20px; + padding-top: 20px; } div#intro ul { - padding-top: 20px; + padding-top: 20px; } table td { - border: 0; - outline: 0; + border: 0; + outline: 0; } td.docs { - width: 420px; - max-width: 420px; - min-width: 420px; - min-height: 5px; - vertical-align: top; - text-align: left; + width: 420px; + max-width: 420px; + min-width: 420px; + min-height: 5px; + vertical-align: top; + text-align: left; } td.docs p { - padding-right: 5px; - padding-top: 5px; - padding-bottom: 15px; + padding-right: 5px; + padding-top: 5px; + padding-bottom: 15px; } td.code { - width: 480px; - max-width: 480px; - min-width: 480px; - padding-top: 5px; - padding-right: 5px; - padding-left: 5px; - padding-bottom: 5px; - vertical-align: top; - background: #f0f0f0; + width: 480px; + max-width: 480px; + min-width: 480px; + padding-top: 5px; + padding-right: 5px; + padding-left: 5px; + padding-bottom: 5px; + vertical-align: top; } td.code.leading { - padding-bottom: 11px; -} -td.code.empty { - background: #ffffff; + padding-bottom: 11px; } pre, code { - font-size: 14px; line-height: 18px; - font-family: 'Menlo', 'Monaco', 'Consolas', 'Lucida Console', monospace; + font-size: 14px; line-height: 18px; + font-family: 'Menlo', 'Monaco', 'Consolas', 'Lucida Console', monospace; } img.copy, img.run { height: 16px; @@ -147,156 +135,95 @@ img.copy, img.run { cursor: pointer; } img.copy { - margin-right: 4px; + margin-right: 4px; +} + + +/* Colors: light mode */ +body { + background-color: #ffffff; + color: #252519; +} +a, a:visited { + color: #261a3b; +} +p.footer { + color: #808080; +} +p.footer a, p.footer a:visited { + color: #808080; +} +td.code { + background: #f0f0f0; +} +td.code.empty { + background: #ffffff; } -/* Syntax highlighting */ -body .hll { background-color: #ffffcc } -body .err { border: 1px solid #FF0000 } /* Error */ -body .c { color: #408080; font-style: italic } /* Comment */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121 } /* Keyword.Declaration */ -body .kn { color: #954121 } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ +/* Syntax highlighting: light mode */ +body .nx { } /* Name.Other: package, variable, struct, param, generic type names, etc. */ +body .nf { } /* Name.Function: function names (def and call) */ +body .o { } /* Operator: :=, &, *, +, &&, <, etc. */ +body .p { } /* Plain: = , . : [ ( { etc. */ +body .k { color: #954121 } /* Keyword: if, for, range, return, defer, etc. */ +body .kc { color: #954121 } /* Keyword.Constant: nil, true, false */ +body .kd { color: #954121 } /* Keyword.Declaration: func, var, type, struct, map, chan, etc. */ +body .kn { color: #954121 } /* Keyword.Namespace: package, import */ +body .nb { color: #954121 } /* Name.Builtin: make, len, delete, append, etc. */ +body .kt { color: #b00040 } /* Keyword.Type: string, int, byte, error, etc. */ +body .m { color: #666666 } /* Literal.Number */ +body .mf { color: #666666 } /* Literal.Number.Float */ +body .mh { color: #666666 } /* Literal.Number.Hex */ +body .mi { color: #666666 } /* Literal.Number.Integer */ +body .mo { color: #666666 } /* Literal.Number.Oct */ +body .s { color: #219161 } /* Literal.String */ +body .sc { color: #219161 } /* Literal.String.Char */ +body .gp { color: #000080 } /* Generic.Prompt: shell prompt */ +body .go { color: #808080 } /* Generic.Output: shell output */ +body .c1 { color: #808080 } /* Comment.Single */ @media (prefers-color-scheme: dark) { + /* Colors: dark mode */ body { - background-color: #171b22; - color: #F0F6FC; + background-color: #191919; + color: #d4d4d4; } a, a:visited { - color: #F0F6FC; + color: #e4e4e4; } p.footer { - color: #6B7280; + color: #898e98; } p.footer a, p.footer a:visited { - color: #6B7280; + color: #898e98; } td.code { - background: #0D1117; + background: #222222; } td.code.empty { - background: #171b22; + background: #191919; } - /* Syntax highlighting */ - body .hll { background-color: #ffffcc } - body .err { border: 1px solid #FF0000 } /* Error */ - body .c { color: #408080; font-style: italic } /* Comment */ - body .k { color: #FF7B72 } /* Keyword */ - body .o { color: #FF7B72 } /* Operator */ - body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ - body .cp { color: #BC7A00 } /* Comment.Preproc */ - body .c1 { color: #408080; font-style: italic } /* Comment.Single */ - body .cs { color: #408080; font-style: italic } /* Comment.Special */ - body .gd { color: #A00000 } /* Generic.Deleted */ - body .ge { font-style: italic } /* Generic.Emph */ - body .gr { color: #FF0000 } /* Generic.Error */ - body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ - body .gi { color: #00A000 } /* Generic.Inserted */ - body .go { color: #808080 } /* Generic.Output */ - body .gp { color: #F0883E ; font-weight: bold } /* Generic.Prompt */ - body .gs { font-weight: bold } /* Generic.Strong */ - body .gu { color: #F0883E ; font-weight: bold } /* Generic.Subheading */ - body .gt { color: #0040D0 } /* Generic.Traceback */ - body .kc { color: #79C0FF } /* Keyword.Constant */ - body .kd { color: #FF7B72 } /* Keyword.Declaration */ - body .kn { color: #FF7B72 } /* Keyword.Namespace */ - body .kp { color: #FF7B72 } /* Keyword.Pseudo */ - body .kr { color: #FF7B72; font-weight: bold } /* Keyword.Reserved */ - body .kt { color: #FF7B72 } /* Keyword.Type */ - body .m { color: #2AC3DE } /* Literal.Number */ - body .s { color: #A5D6FF } /* Literal.String */ - body .na { color: #7D9029 } /* Name.Attribute */ - body .nb { color: #E6EDF3 } /* Name.Builtin */ - body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ - body .no { color: #880000 } /* Name.Constant */ - body .nd { color: #AA22FF } /* Name.Decorator */ - body .ni { color: #999999; font-weight: bold } /* Name.Entity */ - body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ - body .nf { color: #E6EDF3 } /* Name.Function */ - body .nl { color: #A0A000 } /* Name.Label */ - body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ - body .nt { color: #E6EDF3; font-weight: bold } /* Name.Tag */ - body .nv { color: #19469D } /* Name.Variable */ - body .nx { color: #E6EDF3 } /* Name.Other */ - body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ - body .w { color: #BBBBBB } /* Text.Whitespace */ - body .mf { color: #A5D6FF } /* Literal.Number.Float */ - body .mh { color: #A5D6FF } /* Literal.Number.Hex */ - body .mi { color: #A5D6FF } /* Literal.Number.Integer */ - body .mo { color: #A5D6FF } /* Literal.Number.Oct */ - body .sb { color: #A5D6FF } /* Literal.String.Backtick */ - body .sc { color: #A5D6FF } /* Literal.String.Char */ - body .sd { color: #A5D6FF; font-style: italic } /* Literal.String.Doc */ - body .s2 { color: #A5D6FF } /* Literal.String.Double */ - body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ - body .sh { color: #A5D6FF } /* Literal.String.Heredoc */ - body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ - body .sx { color: #E6EDF3 } /* Literal.String.Other */ - body .sr { color: #BB6688 } /* Literal.String.Regex */ - body .s1 { color: #A5D6FF } /* Literal.String.Single */ - body .ss { color: #19469D } /* Literal.String.Symbol */ - body .bp { color: #954121 } /* Name.Builtin.Pseudo */ - body .vc { color: #19469D } /* Name.Variable.Class */ - body .vg { color: #19469D } /* Name.Variable.Global */ - body .vi { color: #19469D } /* Name.Variable.Instance */ - body .il { color: #666666 } /* Literal.Number.Integer.Long */ - - + + /* Syntax highlighting: dark mode */ + body .nx { } /* Name.Other */ + body .nf { } /* Name.Function */ + body .o { } /* Operator */ + body .p { } /* Plain */ + body .k { color: #a85751 } /* Keyword */ + body .kc { color: #a85751 } /* Keyword.Constant */ + body .kd { color: #a85751 } /* Keyword.Declaration */ + body .kn { color: #a85751 } /* Keyword.Namespace */ + body .nb { color: #a85751 } /* Name.Builtin */ + body .kt { color: #b04141 } /* Keyword.Type */ + body .m { color: #6489c1 } /* Literal.Number */ + body .mf { color: #6489c1 } /* Literal.Number.Float */ + body .mh { color: #6489c1 } /* Literal.Number.Hex */ + body .mi { color: #6489c1 } /* Literal.Number.Integer */ + body .mo { color: #6489c1 } /* Literal.Number.Oct */ + body .s { color: #6b866c } /* Literal.String */ + body .sc { color: #6b866c } /* Literal.String.Char */ + body .gp { color: #8567ab } /* Generic.Prompt */ + body .go { color: #808080 } /* Generic.Output */ + body .c1 { color: #808080 } /* Comment.Single */ } diff --git a/templates/site.css b/templates/site.css index 55a6b70e6..84d0b291e 100644 --- a/templates/site.css +++ b/templates/site.css @@ -12,131 +12,119 @@ article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { - margin: 0; - padding: 0; - border: 0; - font-size: 100%; - font: inherit; - vertical-align: baseline; + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { - display: block; + display: block; } body { - line-height: 1; + line-height: 1; } ol, ul { - list-style: none; + list-style: none; } blockquote, q { - quotes: none; + quotes: none; } blockquote:before, blockquote:after, q:before, q:after { - content: ''; - content: none; + content: ''; + content: none; } table { - border-collapse: collapse; - border-spacing: 0; + border-collapse: collapse; + border-spacing: 0; } /* Layout and typography */ body { - font-family: 'Georgia', serif; - font-size: 16px; - line-height: 20px; - color: #252519; + font-family: 'Georgia', serif; + font-size: 16px; + line-height: 20px; } em { - font-style: italic; -} -a, a:visited { - color: #261a3b; + font-style: italic; } h2 { - font-size: 32px; - line-height: 40px; - margin-top: 40px; + font-size: 32px; + line-height: 40px; + margin-top: 40px; } h2 a { - text-decoration: none; + text-decoration: none; } div.example { - width: 900px; - min-width: 900px; - max-width: 900px; - margin-left: auto; - margin-right: auto; - margin-bottom: 120px; + width: 900px; + min-width: 900px; + max-width: 900px; + margin-left: auto; + margin-right: auto; + margin-bottom: 120px; } div.example table { - margin-top: 15px; - margin-bottom: 20px; + margin-top: 15px; + margin-bottom: 20px; } p.next { - margin-bottom: 20px; + margin-bottom: 20px; } p.footer { - color: grey; - font-size: 75%; -} -p.footer a, p.footer a:visited { - color: grey; + font-size: 75%; } div#intro { - width: 420px; - min-width: 420px; - max-width: 420px; - margin-left: auto; - margin-right: auto; - margin-bottom: 120px; + width: 420px; + min-width: 420px; + max-width: 420px; + margin-left: auto; + margin-right: auto; + margin-bottom: 120px; } div#intro p { - padding-top: 20px; + padding-top: 20px; } div#intro ul { - padding-top: 20px; + padding-top: 20px; } table td { - border: 0; - outline: 0; + border: 0; + outline: 0; } td.docs { - width: 420px; - max-width: 420px; - min-width: 420px; - min-height: 5px; - vertical-align: top; - text-align: left; + width: 420px; + max-width: 420px; + min-width: 420px; + min-height: 5px; + vertical-align: top; + text-align: left; } td.docs p { - padding-right: 5px; - padding-top: 5px; - padding-bottom: 15px; + padding-right: 5px; + padding-top: 5px; + padding-bottom: 15px; } td.code { - width: 480px; - max-width: 480px; - min-width: 480px; - padding-top: 5px; - padding-right: 5px; - padding-left: 5px; - padding-bottom: 5px; - vertical-align: top; - background: #f0f0f0; + width: 480px; + max-width: 480px; + min-width: 480px; + padding-top: 5px; + padding-right: 5px; + padding-left: 5px; + padding-bottom: 5px; + vertical-align: top; } td.code.leading { - padding-bottom: 11px; -} -td.code.empty { - background: #ffffff; + padding-bottom: 11px; } pre, code { - font-size: 14px; line-height: 18px; - font-family: 'Menlo', 'Monaco', 'Consolas', 'Lucida Console', monospace; + font-size: 14px; line-height: 18px; + font-family: 'Menlo', 'Monaco', 'Consolas', 'Lucida Console', monospace; } img.copy, img.run { height: 16px; @@ -147,156 +135,95 @@ img.copy, img.run { cursor: pointer; } img.copy { - margin-right: 4px; + margin-right: 4px; +} + + +/* Colors: light mode */ +body { + background-color: #ffffff; + color: #252519; +} +a, a:visited { + color: #261a3b; +} +p.footer { + color: #808080; +} +p.footer a, p.footer a:visited { + color: #808080; +} +td.code { + background: #f0f0f0; +} +td.code.empty { + background: #ffffff; } -/* Syntax highlighting */ -body .hll { background-color: #ffffcc } -body .err { border: 1px solid #FF0000 } /* Error */ -body .c { color: #408080; font-style: italic } /* Comment */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121 } /* Keyword.Declaration */ -body .kn { color: #954121 } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ +/* Syntax highlighting: light mode */ +body .nx { } /* Name.Other: package, variable, struct, param, generic type names, etc. */ +body .nf { } /* Name.Function: function names (def and call) */ +body .o { } /* Operator: :=, &, *, +, &&, <, etc. */ +body .p { } /* Plain: = , . : [ ( { etc. */ +body .k { color: #954121 } /* Keyword: if, for, range, return, defer, etc. */ +body .kc { color: #954121 } /* Keyword.Constant: nil, true, false */ +body .kd { color: #954121 } /* Keyword.Declaration: func, var, type, struct, map, chan, etc. */ +body .kn { color: #954121 } /* Keyword.Namespace: package, import */ +body .nb { color: #954121 } /* Name.Builtin: make, len, delete, append, etc. */ +body .kt { color: #b00040 } /* Keyword.Type: string, int, byte, error, etc. */ +body .m { color: #666666 } /* Literal.Number */ +body .mf { color: #666666 } /* Literal.Number.Float */ +body .mh { color: #666666 } /* Literal.Number.Hex */ +body .mi { color: #666666 } /* Literal.Number.Integer */ +body .mo { color: #666666 } /* Literal.Number.Oct */ +body .s { color: #219161 } /* Literal.String */ +body .sc { color: #219161 } /* Literal.String.Char */ +body .gp { color: #000080 } /* Generic.Prompt: shell prompt */ +body .go { color: #808080 } /* Generic.Output: shell output */ +body .c1 { color: #808080 } /* Comment.Single */ @media (prefers-color-scheme: dark) { + /* Colors: dark mode */ body { - background-color: #171b22; - color: #F0F6FC; + background-color: #191919; + color: #d4d4d4; } a, a:visited { - color: #F0F6FC; + color: #e4e4e4; } p.footer { - color: #6B7280; + color: #898e98; } p.footer a, p.footer a:visited { - color: #6B7280; + color: #898e98; } td.code { - background: #0D1117; + background: #222222; } td.code.empty { - background: #171b22; + background: #191919; } - /* Syntax highlighting */ - body .hll { background-color: #ffffcc } - body .err { border: 1px solid #FF0000 } /* Error */ - body .c { color: #408080; font-style: italic } /* Comment */ - body .k { color: #FF7B72 } /* Keyword */ - body .o { color: #FF7B72 } /* Operator */ - body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ - body .cp { color: #BC7A00 } /* Comment.Preproc */ - body .c1 { color: #408080; font-style: italic } /* Comment.Single */ - body .cs { color: #408080; font-style: italic } /* Comment.Special */ - body .gd { color: #A00000 } /* Generic.Deleted */ - body .ge { font-style: italic } /* Generic.Emph */ - body .gr { color: #FF0000 } /* Generic.Error */ - body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ - body .gi { color: #00A000 } /* Generic.Inserted */ - body .go { color: #808080 } /* Generic.Output */ - body .gp { color: #F0883E ; font-weight: bold } /* Generic.Prompt */ - body .gs { font-weight: bold } /* Generic.Strong */ - body .gu { color: #F0883E ; font-weight: bold } /* Generic.Subheading */ - body .gt { color: #0040D0 } /* Generic.Traceback */ - body .kc { color: #79C0FF } /* Keyword.Constant */ - body .kd { color: #FF7B72 } /* Keyword.Declaration */ - body .kn { color: #FF7B72 } /* Keyword.Namespace */ - body .kp { color: #FF7B72 } /* Keyword.Pseudo */ - body .kr { color: #FF7B72; font-weight: bold } /* Keyword.Reserved */ - body .kt { color: #FF7B72 } /* Keyword.Type */ - body .m { color: #2AC3DE } /* Literal.Number */ - body .s { color: #A5D6FF } /* Literal.String */ - body .na { color: #7D9029 } /* Name.Attribute */ - body .nb { color: #E6EDF3 } /* Name.Builtin */ - body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ - body .no { color: #880000 } /* Name.Constant */ - body .nd { color: #AA22FF } /* Name.Decorator */ - body .ni { color: #999999; font-weight: bold } /* Name.Entity */ - body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ - body .nf { color: #E6EDF3 } /* Name.Function */ - body .nl { color: #A0A000 } /* Name.Label */ - body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ - body .nt { color: #E6EDF3; font-weight: bold } /* Name.Tag */ - body .nv { color: #19469D } /* Name.Variable */ - body .nx { color: #E6EDF3 } /* Name.Other */ - body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ - body .w { color: #BBBBBB } /* Text.Whitespace */ - body .mf { color: #A5D6FF } /* Literal.Number.Float */ - body .mh { color: #A5D6FF } /* Literal.Number.Hex */ - body .mi { color: #A5D6FF } /* Literal.Number.Integer */ - body .mo { color: #A5D6FF } /* Literal.Number.Oct */ - body .sb { color: #A5D6FF } /* Literal.String.Backtick */ - body .sc { color: #A5D6FF } /* Literal.String.Char */ - body .sd { color: #A5D6FF; font-style: italic } /* Literal.String.Doc */ - body .s2 { color: #A5D6FF } /* Literal.String.Double */ - body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ - body .sh { color: #A5D6FF } /* Literal.String.Heredoc */ - body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ - body .sx { color: #E6EDF3 } /* Literal.String.Other */ - body .sr { color: #BB6688 } /* Literal.String.Regex */ - body .s1 { color: #A5D6FF } /* Literal.String.Single */ - body .ss { color: #19469D } /* Literal.String.Symbol */ - body .bp { color: #954121 } /* Name.Builtin.Pseudo */ - body .vc { color: #19469D } /* Name.Variable.Class */ - body .vg { color: #19469D } /* Name.Variable.Global */ - body .vi { color: #19469D } /* Name.Variable.Instance */ - body .il { color: #666666 } /* Literal.Number.Integer.Long */ - - + + /* Syntax highlighting: dark mode */ + body .nx { } /* Name.Other */ + body .nf { } /* Name.Function */ + body .o { } /* Operator */ + body .p { } /* Plain */ + body .k { color: #a85751 } /* Keyword */ + body .kc { color: #a85751 } /* Keyword.Constant */ + body .kd { color: #a85751 } /* Keyword.Declaration */ + body .kn { color: #a85751 } /* Keyword.Namespace */ + body .nb { color: #a85751 } /* Name.Builtin */ + body .kt { color: #b04141 } /* Keyword.Type */ + body .m { color: #6489c1 } /* Literal.Number */ + body .mf { color: #6489c1 } /* Literal.Number.Float */ + body .mh { color: #6489c1 } /* Literal.Number.Hex */ + body .mi { color: #6489c1 } /* Literal.Number.Integer */ + body .mo { color: #6489c1 } /* Literal.Number.Oct */ + body .s { color: #6b866c } /* Literal.String */ + body .sc { color: #6b866c } /* Literal.String.Char */ + body .gp { color: #8567ab } /* Generic.Prompt */ + body .go { color: #808080 } /* Generic.Output */ + body .c1 { color: #808080 } /* Comment.Single */ } From fae3af5dac1b54f85bcff0416b88d7af6c41427d Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 17 Mar 2024 13:06:36 -0700 Subject: [PATCH 219/283] Try a slightly lighter dark --- public/site.css | 17 +++++++++-------- templates/site.css | 17 +++++++++-------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/public/site.css b/public/site.css index 84d0b291e..bbc8d8029 100644 --- a/public/site.css +++ b/public/site.css @@ -144,6 +144,9 @@ body { background-color: #ffffff; color: #252519; } +td.code.empty { + background: #ffffff; +} a, a:visited { color: #261a3b; } @@ -156,9 +159,6 @@ p.footer a, p.footer a:visited { td.code { background: #f0f0f0; } -td.code.empty { - background: #ffffff; -} /* Syntax highlighting: light mode */ body .nx { } /* Name.Other: package, variable, struct, param, generic type names, etc. */ @@ -186,9 +186,12 @@ body .c1 { color: #808080 } /* Comment.Single */ @media (prefers-color-scheme: dark) { /* Colors: dark mode */ body { - background-color: #191919; + background-color: #1f1f1f; color: #d4d4d4; } + td.code.empty { + background: #1f1f1f; + } a, a:visited { color: #e4e4e4; } @@ -199,11 +202,9 @@ body .c1 { color: #808080 } /* Comment.Single */ color: #898e98; } td.code { - background: #222222; - } - td.code.empty { - background: #191919; + background: #282828; } + /* Syntax highlighting: dark mode */ body .nx { } /* Name.Other */ diff --git a/templates/site.css b/templates/site.css index 84d0b291e..bbc8d8029 100644 --- a/templates/site.css +++ b/templates/site.css @@ -144,6 +144,9 @@ body { background-color: #ffffff; color: #252519; } +td.code.empty { + background: #ffffff; +} a, a:visited { color: #261a3b; } @@ -156,9 +159,6 @@ p.footer a, p.footer a:visited { td.code { background: #f0f0f0; } -td.code.empty { - background: #ffffff; -} /* Syntax highlighting: light mode */ body .nx { } /* Name.Other: package, variable, struct, param, generic type names, etc. */ @@ -186,9 +186,12 @@ body .c1 { color: #808080 } /* Comment.Single */ @media (prefers-color-scheme: dark) { /* Colors: dark mode */ body { - background-color: #191919; + background-color: #1f1f1f; color: #d4d4d4; } + td.code.empty { + background: #1f1f1f; + } a, a:visited { color: #e4e4e4; } @@ -199,11 +202,9 @@ body .c1 { color: #808080 } /* Comment.Single */ color: #898e98; } td.code { - background: #222222; - } - td.code.empty { - background: #191919; + background: #282828; } + /* Syntax highlighting: dark mode */ body .nx { } /* Name.Other */ From 4a0a0c057288db274b2f5a15cd4b85fa2f04b6a7 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 17 Mar 2024 13:13:54 -0700 Subject: [PATCH 220/283] Text adjusted for lighter backgrounds --- public/site.css | 2 +- templates/site.css | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/public/site.css b/public/site.css index bbc8d8029..f21439ceb 100644 --- a/public/site.css +++ b/public/site.css @@ -187,7 +187,7 @@ body .c1 { color: #808080 } /* Comment.Single */ /* Colors: dark mode */ body { background-color: #1f1f1f; - color: #d4d4d4; + color: #dadada; } td.code.empty { background: #1f1f1f; diff --git a/templates/site.css b/templates/site.css index bbc8d8029..f21439ceb 100644 --- a/templates/site.css +++ b/templates/site.css @@ -187,7 +187,7 @@ body .c1 { color: #808080 } /* Comment.Single */ /* Colors: dark mode */ body { background-color: #1f1f1f; - color: #d4d4d4; + color: #dadada; } td.code.empty { background: #1f1f1f; From 3dd6791ca2c9d4c97e48ebfae520849974e47d0d Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Tue, 19 Mar 2024 14:43:53 -0700 Subject: [PATCH 221/283] Slight tweaks to foreground colors for lightened background --- public/site.css | 32 ++++++++++++++++---------------- templates/site.css | 32 ++++++++++++++++---------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/public/site.css b/public/site.css index f21439ceb..4366758b4 100644 --- a/public/site.css +++ b/public/site.css @@ -211,20 +211,20 @@ body .c1 { color: #808080 } /* Comment.Single */ body .nf { } /* Name.Function */ body .o { } /* Operator */ body .p { } /* Plain */ - body .k { color: #a85751 } /* Keyword */ - body .kc { color: #a85751 } /* Keyword.Constant */ - body .kd { color: #a85751 } /* Keyword.Declaration */ - body .kn { color: #a85751 } /* Keyword.Namespace */ - body .nb { color: #a85751 } /* Name.Builtin */ - body .kt { color: #b04141 } /* Keyword.Type */ - body .m { color: #6489c1 } /* Literal.Number */ - body .mf { color: #6489c1 } /* Literal.Number.Float */ - body .mh { color: #6489c1 } /* Literal.Number.Hex */ - body .mi { color: #6489c1 } /* Literal.Number.Integer */ - body .mo { color: #6489c1 } /* Literal.Number.Oct */ - body .s { color: #6b866c } /* Literal.String */ - body .sc { color: #6b866c } /* Literal.String.Char */ - body .gp { color: #8567ab } /* Generic.Prompt */ - body .go { color: #808080 } /* Generic.Output */ - body .c1 { color: #808080 } /* Comment.Single */ + body .k { color: #af5a54 } /* Keyword */ + body .kc { color: #af5a54 } /* Keyword.Constant */ + body .kd { color: #af5a54 } /* Keyword.Declaration */ + body .kn { color: #af5a54 } /* Keyword.Namespace */ + body .nb { color: #af5a54 } /* Name.Builtin */ + body .kt { color: #b64343 } /* Keyword.Type */ + body .m { color: #688ec8 } /* Literal.Number */ + body .mf { color: #688ec8 } /* Literal.Number.Float */ + body .mh { color: #688ec8 } /* Literal.Number.Hex */ + body .mi { color: #688ec8 } /* Literal.Number.Integer */ + body .mo { color: #688ec8 } /* Literal.Number.Oct */ + body .s { color: #718e72 } /* Literal.String */ + body .sc { color: #718e72 } /* Literal.String.Char */ + body .gp { color: #8a6ab1 } /* Generic.Prompt */ + body .go { color: #868686 } /* Generic.Output */ + body .c1 { color: #868686 } /* Comment.Single */ } diff --git a/templates/site.css b/templates/site.css index f21439ceb..4366758b4 100644 --- a/templates/site.css +++ b/templates/site.css @@ -211,20 +211,20 @@ body .c1 { color: #808080 } /* Comment.Single */ body .nf { } /* Name.Function */ body .o { } /* Operator */ body .p { } /* Plain */ - body .k { color: #a85751 } /* Keyword */ - body .kc { color: #a85751 } /* Keyword.Constant */ - body .kd { color: #a85751 } /* Keyword.Declaration */ - body .kn { color: #a85751 } /* Keyword.Namespace */ - body .nb { color: #a85751 } /* Name.Builtin */ - body .kt { color: #b04141 } /* Keyword.Type */ - body .m { color: #6489c1 } /* Literal.Number */ - body .mf { color: #6489c1 } /* Literal.Number.Float */ - body .mh { color: #6489c1 } /* Literal.Number.Hex */ - body .mi { color: #6489c1 } /* Literal.Number.Integer */ - body .mo { color: #6489c1 } /* Literal.Number.Oct */ - body .s { color: #6b866c } /* Literal.String */ - body .sc { color: #6b866c } /* Literal.String.Char */ - body .gp { color: #8567ab } /* Generic.Prompt */ - body .go { color: #808080 } /* Generic.Output */ - body .c1 { color: #808080 } /* Comment.Single */ + body .k { color: #af5a54 } /* Keyword */ + body .kc { color: #af5a54 } /* Keyword.Constant */ + body .kd { color: #af5a54 } /* Keyword.Declaration */ + body .kn { color: #af5a54 } /* Keyword.Namespace */ + body .nb { color: #af5a54 } /* Name.Builtin */ + body .kt { color: #b64343 } /* Keyword.Type */ + body .m { color: #688ec8 } /* Literal.Number */ + body .mf { color: #688ec8 } /* Literal.Number.Float */ + body .mh { color: #688ec8 } /* Literal.Number.Hex */ + body .mi { color: #688ec8 } /* Literal.Number.Integer */ + body .mo { color: #688ec8 } /* Literal.Number.Oct */ + body .s { color: #718e72 } /* Literal.String */ + body .sc { color: #718e72 } /* Literal.String.Char */ + body .gp { color: #8a6ab1 } /* Generic.Prompt */ + body .go { color: #868686 } /* Generic.Output */ + body .c1 { color: #868686 } /* Comment.Single */ } From cdb9266e26daab52bb592bbdca92f93d6bde495f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=BCttler?= Date: Thu, 21 Mar 2024 14:22:47 +0100 Subject: [PATCH 222/283] Add wrapping errors (#517) Fixes #334 * Add wrapping errors. Before there was one page about error handling. Now there are three. A simple page (the first part of the existing page). Then a new page about wrapping errors. And the third page is the second half of the existing page (custom errors). * ... addressed pr feedback. * ./tools/build was run. --- examples.txt | 2 + examples/custom-errors/custom-errors.go | 47 ++++ examples/custom-errors/custom-errors.hash | 2 + examples/custom-errors/custom-errors.sh | 2 + examples/errors/errors.go | 52 +--- examples/errors/errors.hash | 4 +- examples/errors/errors.sh | 8 +- .../wrapping-and-sentinel-errors.go | 71 ++++++ .../wrapping-and-sentinel-errors.hash | 2 + .../wrapping-and-sentinel-errors.sh | 16 ++ public/custom-errors | 185 ++++++++++++++ public/errors | 128 ++-------- public/goroutines | 2 +- public/index.html | 4 + public/wrapping-and-sentinel-errors | 239 ++++++++++++++++++ 15 files changed, 596 insertions(+), 168 deletions(-) create mode 100644 examples/custom-errors/custom-errors.go create mode 100644 examples/custom-errors/custom-errors.hash create mode 100644 examples/custom-errors/custom-errors.sh create mode 100644 examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go create mode 100644 examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash create mode 100644 examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh create mode 100644 public/custom-errors create mode 100644 public/wrapping-and-sentinel-errors diff --git a/examples.txt b/examples.txt index b637704b8..1607fcdec 100644 --- a/examples.txt +++ b/examples.txt @@ -22,6 +22,8 @@ Interfaces Struct Embedding Generics Errors +Wrapping and Sentinel Errors +Custom Errors Goroutines Channels Channel Buffering diff --git a/examples/custom-errors/custom-errors.go b/examples/custom-errors/custom-errors.go new file mode 100644 index 000000000..89dcbc041 --- /dev/null +++ b/examples/custom-errors/custom-errors.go @@ -0,0 +1,47 @@ +// It's possible to use custom types as `error`s by +// implementing the `Error()` method on them. Here's a +// variant on the example above that uses a custom type +// to explicitly represent an argument error. + +package main + +import ( + "errors" + "fmt" +) + +// It's possible to use custom types as `error`s by +// implementing the `Error()` method on them. Here's a +// variant on the example above that uses a custom type +// to explicitly represent an argument error. +// A custom error type has usualy the suffix "Error". +type argError struct { + arg int + message string +} + +func (e *argError) Error() string { + return fmt.Sprintf("%d - %s", e.arg, e.message) +} + +func f(arg int) (int, error) { + if arg == 42 { + // In this case we use `&argError` syntax to build + // a new struct, supplying values for the two + // fields `arg` and `message`. + return -1, &argError{arg, "can't work with it"} + } + return arg + 3, nil +} + +func main() { + // If you want to programmatically use the data in + // a custom error, you'll need to get the error as an + // instance of the custom error with errors.As() + _, err := f(42) + var ae *argError + if errors.As(err, &ae) { + fmt.Println(ae.arg) + fmt.Println(ae.message) + } +} diff --git a/examples/custom-errors/custom-errors.hash b/examples/custom-errors/custom-errors.hash new file mode 100644 index 000000000..04fe7b4a3 --- /dev/null +++ b/examples/custom-errors/custom-errors.hash @@ -0,0 +1,2 @@ +e7d16589797f94ba3ad1e75449b5f27c71d73a41 +9pZvObLbmb8 diff --git a/examples/custom-errors/custom-errors.sh b/examples/custom-errors/custom-errors.sh new file mode 100644 index 000000000..d534739b5 --- /dev/null +++ b/examples/custom-errors/custom-errors.sh @@ -0,0 +1,2 @@ +42 +can't work with it \ No newline at end of file diff --git a/examples/errors/errors.go b/examples/errors/errors.go index b8501392d..9d3b17ebf 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -16,13 +16,11 @@ import ( // By convention, errors are the last return value and // have type `error`, a built-in interface. -func f1(arg int) (int, error) { +func f(arg int) (int, error) { if arg == 42 { - // `errors.New` constructs a basic `error` value // with the given error message. return -1, errors.New("can't work with 42") - } // A `nil` value in the error position indicates that @@ -30,58 +28,16 @@ func f1(arg int) (int, error) { return arg + 3, nil } -// It's possible to use custom types as `error`s by -// implementing the `Error()` method on them. Here's a -// variant on the example above that uses a custom type -// to explicitly represent an argument error. -type argError struct { - arg int - prob string -} - -func (e *argError) Error() string { - return fmt.Sprintf("%d - %s", e.arg, e.prob) -} - -func f2(arg int) (int, error) { - if arg == 42 { - - // In this case we use `&argError` syntax to build - // a new struct, supplying values for the two - // fields `arg` and `prob`. - return -1, &argError{arg, "can't work with it"} - } - return arg + 3, nil -} - func main() { - // The two loops below test out each of our // error-returning functions. Note that the use of an // inline error check on the `if` line is a common // idiom in Go code. for _, i := range []int{7, 42} { - if r, e := f1(i); e != nil { - fmt.Println("f1 failed:", e) + if r, e := f(i); e != nil { + fmt.Println("f failed:", e) } else { - fmt.Println("f1 worked:", r) + fmt.Println("f worked:", r) } } - for _, i := range []int{7, 42} { - if r, e := f2(i); e != nil { - fmt.Println("f2 failed:", e) - } else { - fmt.Println("f2 worked:", r) - } - } - - // If you want to programmatically use the data in - // a custom error, you'll need to get the error as an - // instance of the custom error type via type - // assertion. - _, e := f2(42) - if ae, ok := e.(*argError); ok { - fmt.Println(ae.arg) - fmt.Println(ae.prob) - } } diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index a1f74a51c..e368e59fc 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -00affa44cc98f14c2b10934a4187c9445fac0fe6 -NiJOpCPO3L0 +bd2a75026d7959adf8e633c6084343740dfe842e +o2xrWWk_1MU diff --git a/examples/errors/errors.sh b/examples/errors/errors.sh index 54315ae7d..959a9c120 100644 --- a/examples/errors/errors.sh +++ b/examples/errors/errors.sh @@ -1,10 +1,6 @@ $ go run errors.go -f1 worked: 10 -f1 failed: can't work with 42 -f2 worked: 10 -f2 failed: 42 - can't work with it -42 -can't work with it +f worked: 10 +f failed: can't work with 42 # See this [great post](https://go.dev/blog/error-handling-and-go) # on the Go blog for more on error handling. diff --git a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go new file mode 100644 index 000000000..f26822a94 --- /dev/null +++ b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go @@ -0,0 +1,71 @@ +// Wrapping errors is a technique that allows you to add additional context +// to an error while preserving the original error. +// This approach is beneficial for debugging and understanding +// the chain of events that led to an error, especially in +// complex applications with multiple layers of function calls. + +package main + +import ( + "errors" + "fmt" + "math/rand/v2" +) + +// A sentinel error is a predeclared error variable that is used to +// signify a specific error condition. It allows error values to be compared +// directly via errors.Is() specific types of errors. +var ErrOutOfTea = fmt.Errorf("no more tea available") + +var ErrPower = fmt.Errorf("can't boil water") + +func MakeTea() error { + if rand.Int32N(4) == 0 { + return ErrOutOfTea + } + if rand.Int32N(7) == 0 { + // You can wrap an error with %w + return fmt.Errorf("add custom text: %w", ErrPower) + } + return nil +} + +func main() { + err := makeTeaSeveralTimes() + if err != nil { + fmt.Println("One or serveral errors occured") + } +} + +func makeTeaSeveralTimes() error { + var allErrs []error + for range 14 { + err := MakeTea() + if err != nil { + allErrs = append(allErrs, err) + // errors.Is is a function in Go that checks if a given error + // matches a specific error value. It's used to determine whether + // an error (or any error in its chain) is equivalent to a particular + // target error. This is especially useful with wrapped or nested errors, + // allowing you to identify specific error types or sentinel errors in + // a chain of errors. + // By using several if-statements we can handle + // different sentinel errors. + // A switch statement is not applicable here. + if errors.Is(err, ErrOutOfTea) { + fmt.Println("We should buy new tea!") + continue + } + if errors.Is(err, ErrPower) { + fmt.Println("Now it is dark.") + continue + } + fmt.Printf("Some unknown error: %s", err) + continue + } + fmt.Println("The tea is warm and inviting.") + } + + // Several errors can be joined to one error. + return errors.Join(allErrs...) +} diff --git a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash new file mode 100644 index 000000000..e2886c952 --- /dev/null +++ b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash @@ -0,0 +1,2 @@ +7e7e1b26a554f1737d79c8f64336548711eae60a +9Ck6s3dPplR diff --git a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh new file mode 100644 index 000000000..47535559e --- /dev/null +++ b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh @@ -0,0 +1,16 @@ +$ go run wrapping-and-sentinel-errors.go +The tea is warm and inviting. +The tea is warm and inviting. +The tea is warm and inviting. +The tea is warm and inviting. +We should buy new tea! +The tea is warm and inviting. +The tea is warm and inviting. +The tea is warm and inviting. +Now it is dark. +The tea is warm and inviting. +The tea is warm and inviting. +The tea is warm and inviting. +We should buy new tea! +The tea is warm and inviting. +One or serveral errors occured diff --git a/public/custom-errors b/public/custom-errors new file mode 100644 index 000000000..9d8c9641d --- /dev/null +++ b/public/custom-errors @@ -0,0 +1,185 @@ + + + + + Go by Example: Custom Errors + + + + +
    +

    Go by Example: Custom Errors

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    It’s possible to use custom types as errors by +implementing the Error() method on them. Here’s a +variant on the example above that uses a custom type +to explicitly represent an argument error.

    + +
    + + +
    + + + +
    package main
    +
    + + + +
    import (
    +    "errors"
    +    "fmt"
    +)
    +
    +

    It’s possible to use custom types as errors by +implementing the Error() method on them. Here’s a +variant on the example above that uses a custom type +to explicitly represent an argument error. +A custom error type has usualy the suffix “Error”.

    + +
    + +
    type argError struct {
    +    arg     int
    +    message string
    +}
    +
    + + + +
    func (e *argError) Error() string {
    +    return fmt.Sprintf("%d - %s", e.arg, e.message)
    +}
    +
    +

    In this case we use &argError syntax to build +a new struct, supplying values for the two +fields arg and message.

    + +
    + +
    func f(arg int) (int, error) {
    +    if arg == 42 {
    +
    + + + +
            return -1, &argError{arg, "can't work with it"}
    +    }
    +    return arg + 3, nil
    +}
    +
    +

    If you want to programmatically use the data in +a custom error, you’ll need to get the error as an +instance of the custom error with errors.As()

    + +
    + +
    func main() {
    +
    + + + +
        _, err := f(42)
    +    var ae *argError
    +    if errors.As(err, &ae) {
    +        fmt.Println(ae.arg)
    +        fmt.Println(ae.message)
    +    }
    +}
    +
    + + + + + + + + +
    + + + +
    42
    +can't work with it
    +
    + + +

    + Next example: Goroutines. +

    + + + + +
    + + + + diff --git a/public/errors b/public/errors index ab084adae..f2c73c07f 100644 --- a/public/errors +++ b/public/errors @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'goroutines'; + window.location.href = 'wrapping-and-sentinel-errors'; } } @@ -48,7 +48,7 @@ non-error tasks.

    - +
    package main
    @@ -74,7 +74,7 @@ have type error, a built-in interface.

    -
    func f1(arg int) (int, error) {
    +          
    func f(arg int) (int, error) {
         if arg == 42 {
    @@ -87,17 +87,8 @@ with the given error message.

    -
            return -1, errors.New("can't work with 42")
    - - - - - - - - - -
        }
    +
            return -1, errors.New("can't work with 42")
    +    }
    @@ -114,72 +105,6 @@ there was no error.

    - - -

    It’s possible to use custom types as errors by -implementing the Error() method on them. Here’s a -variant on the example above that uses a custom type -to explicitly represent an argument error.

    - - - - -
    type argError struct {
    -    arg  int
    -    prob string
    -}
    - - - - - - - - - -
    func (e *argError) Error() string {
    -    return fmt.Sprintf("%d - %s", e.arg, e.prob)
    -}
    - - - - - - - - - -
    func f2(arg int) (int, error) {
    -    if arg == 42 {
    - - - - - -

    In this case we use &argError syntax to build -a new struct, supplying values for the two -fields arg and prob.

    - - - - -
            return -1, &argError{arg, "can't work with it"}
    -    }
    -    return arg + 3, nil
    -}
    - - - - - - - - - -
    func main() {
    - - -

    The two loops below test out each of our @@ -190,37 +115,22 @@ idiom in Go code.

    -
        for _, i := range []int{7, 42} {
    -        if r, e := f1(i); e != nil {
    -            fmt.Println("f1 failed:", e)
    -        } else {
    -            fmt.Println("f1 worked:", r)
    -        }
    -    }
    -    for _, i := range []int{7, 42} {
    -        if r, e := f2(i); e != nil {
    -            fmt.Println("f2 failed:", e)
    -        } else {
    -            fmt.Println("f2 worked:", r)
    -        }
    -    }
    +
    func main() {
    -

    If you want to programmatically use the data in -a custom error, you’ll need to get the error as an -instance of the custom error type via type -assertion.

    - + -
        _, e := f2(42)
    -    if ae, ok := e.(*argError); ok {
    -        fmt.Println(ae.arg)
    -        fmt.Println(ae.prob)
    +          
        for _, i := range []int{7, 42} {
    +        if r, e := f(i); e != nil {
    +            fmt.Println("f failed:", e)
    +        } else {
    +            fmt.Println("f worked:", r)
    +        }
         }
     }
    @@ -237,12 +147,8 @@ assertion.

    $ go run errors.go
    -f1 worked: 10
    -f1 failed: can't work with 42
    -f2 worked: 10
    -f2 failed: 42 - can't work with it
    -42
    -can't work with it
    +
    f worked: 10 +f failed: can't work with 42
    @@ -262,7 +168,7 @@ on the Go blog for more on error handling.

    - Next example: Goroutines. + Next example: Wrapping and Sentinel Errors.

    @@ -273,7 +179,7 @@ on the Go blog for more on error handling.

    diff --git a/public/goroutines b/public/goroutines index 6b16ea9d9..b9784c738 100644 --- a/public/goroutines +++ b/public/goroutines @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'errors'; + window.location.href = 'custom-errors'; } diff --git a/public/index.html b/public/index.html index 54853fec8..2daeb4ec3 100644 --- a/public/index.html +++ b/public/index.html @@ -75,6 +75,10 @@

    Go by Example

  • Errors
  • +
  • Wrapping and Sentinel Errors
  • + +
  • Custom Errors
  • +
  • Goroutines
  • Channels
  • diff --git a/public/wrapping-and-sentinel-errors b/public/wrapping-and-sentinel-errors new file mode 100644 index 000000000..4de8e844d --- /dev/null +++ b/public/wrapping-and-sentinel-errors @@ -0,0 +1,239 @@ + + + + + Go by Example: Wrapping and Sentinel Errors + + + + +
    +

    Go by Example: Wrapping and Sentinel Errors

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Wrapping errors is a technique that allows you to add additional context +to an error while preserving the original error. +This approach is beneficial for debugging and understanding +the chain of events that led to an error, especially in +complex applications with multiple layers of function calls.

    + +
    + + +
    + + + +
    package main
    +
    + + + +
    import (
    +    "errors"
    +    "fmt"
    +    "math/rand/v2"
    +)
    +
    +

    A sentinel error is a predeclared error variable that is used to +signify a specific error condition. It allows error values to be compared +directly via errors.Is() specific types of errors.

    + +
    + +
    var ErrOutOfTea = fmt.Errorf("no more tea available")
    +
    + + + +
    var ErrPower = fmt.Errorf("can't boil water")
    +
    +

    You can wrap an error with %w

    + +
    + +
    func MakeTea() error {
    +    if rand.Int32N(4) == 0 {
    +        return ErrOutOfTea
    +    }
    +    if rand.Int32N(7) == 0 {
    +
    + + + +
            return fmt.Errorf("add custom text: %w", ErrPower)
    +    }
    +    return nil
    +}
    +
    + + + +
    func main() {
    +    err := makeTeaSeveralTimes()
    +    if err != nil {
    +        fmt.Println("One or serveral errors occured")
    +    }
    +}
    +
    +

    errors.Is is a function in Go that checks if a given error +matches a specific error value. It’s used to determine whether +an error (or any error in its chain) is equivalent to a particular +target error. This is especially useful with wrapped or nested errors, +allowing you to identify specific error types or sentinel errors in +a chain of errors. +By using several if-statements we can handle +different sentinel errors. +A switch statement is not applicable here.

    + +
    + +
    func makeTeaSeveralTimes() error {
    +    var allErrs []error
    +    for range 14 {
    +        err := MakeTea()
    +        if err != nil {
    +            allErrs = append(allErrs, err)
    +
    + + + +
                if errors.Is(err, ErrOutOfTea) {
    +                fmt.Println("We should buy new tea!")
    +                continue
    +            }
    +            if errors.Is(err, ErrPower) {
    +                fmt.Println("Now it is dark.")
    +                continue
    +            }
    +            fmt.Printf("Some unknown error: %s", err)
    +            continue
    +        }
    +        fmt.Println("The tea is warm and inviting.")
    +    }
    +
    +

    Several errors can be joined to one error.

    + +
    + +
        return errors.Join(allErrs...)
    +}
    +
    + + + + + + + + +
    + + + +
    $ go run wrapping-and-sentinel-errors.go
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +We should buy new tea!
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +Now it is dark.
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +The tea is warm and inviting.
    +We should buy new tea!
    +The tea is warm and inviting.
    +One or serveral errors occured
    +
    + + +

    + Next example: Custom Errors. +

    + + + + +
    + + + + From a8332aad7a007fefcf99f1eb2265a0fe3996c306 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 21 Mar 2024 07:23:33 -0700 Subject: [PATCH 223/283] Consolidate wrapping-and-sentinel-errors into errors --- examples.txt | 1 - examples/errors/errors.go | 54 ++++- examples/errors/errors.hash | 4 +- examples/errors/errors.sh | 9 +- .../wrapping-and-sentinel-errors.go | 71 ------- .../wrapping-and-sentinel-errors.hash | 2 - .../wrapping-and-sentinel-errors.sh | 16 -- public/custom-errors | 2 +- public/errors | 135 +++++++++--- public/index.html | 2 - public/wrapping-and-sentinel-errors | 198 +----------------- 11 files changed, 167 insertions(+), 327 deletions(-) delete mode 100644 examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go delete mode 100644 examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash delete mode 100644 examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh diff --git a/examples.txt b/examples.txt index 1607fcdec..60849cc63 100644 --- a/examples.txt +++ b/examples.txt @@ -22,7 +22,6 @@ Interfaces Struct Embedding Generics Errors -Wrapping and Sentinel Errors Custom Errors Goroutines Channels diff --git a/examples/errors/errors.go b/examples/errors/errors.go index 9d3b17ebf..8218deb58 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -4,8 +4,12 @@ // the overloaded single result / error value sometimes // used in C. Go's approach makes it easy to see which // functions return errors and to handle them using the -// same language constructs employed for any other, +// same language constructs employed for other, // non-error tasks. +// +// See the documentation of the [errors package](https://pkg.go.dev/errors) +// and [this blog post](https://go.dev/blog/go1.13-errors) for additional +// details. package main @@ -28,16 +32,56 @@ func f(arg int) (int, error) { return arg + 3, nil } +// A sentinel error is a predeclared error variable that is used to +// signify a specific error condition. +var ErrOutOfTea = fmt.Errorf("no more tea available") +var ErrPower = fmt.Errorf("can't boil water") + +func makeTea(arg int) error { + if arg == 2 { + return ErrOutOfTea + } else if arg == 4 { + + // We can wrap errors with higher-level errors to add + // context. The simplest way to do this is with the + // `%w` verb in `fmt.Errorf`. Wrapped errors + // create a logical chain (A wraps B, which wraps C, etc.) + // that can be queried with functions like `errors.Is` + // and `errors.As`. + return fmt.Errorf("making tea: %w", ErrPower) + } + return nil +} + func main() { - // The two loops below test out each of our - // error-returning functions. Note that the use of an - // inline error check on the `if` line is a common - // idiom in Go code. for _, i := range []int{7, 42} { + + // It's common to use an inline error check in the `if` + // line. if r, e := f(i); e != nil { fmt.Println("f failed:", e) } else { fmt.Println("f worked:", r) } } + + for i := range 5 { + if err := makeTea(i); err != nil { + + // `errors.Is` checks that a given error (or any error in its chain) + // matches a specific error value. This is especially useful with wrapped or + // nested errors, allowing you to identify specific error types or sentinel + // errors in a chain of errors. + if errors.Is(err, ErrOutOfTea) { + fmt.Println("We should buy new tea!") + } else if errors.Is(err, ErrPower) { + fmt.Println("Now it is dark.") + } else { + fmt.Printf("unknown error: %s\n", err) + } + continue + } + + fmt.Println("Tea is ready!") + } } diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index e368e59fc..2ccb8c1e2 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -bd2a75026d7959adf8e633c6084343740dfe842e -o2xrWWk_1MU +1d5cbeac0932979a8925f4e959d3854edfcd6bcb +JJk4OyQSOYB diff --git a/examples/errors/errors.sh b/examples/errors/errors.sh index 959a9c120..034c9ed3a 100644 --- a/examples/errors/errors.sh +++ b/examples/errors/errors.sh @@ -1,6 +1,7 @@ -$ go run errors.go f worked: 10 f failed: can't work with 42 - -# See this [great post](https://go.dev/blog/error-handling-and-go) -# on the Go blog for more on error handling. +Tea is ready! +Tea is ready! +We should buy new tea! +Tea is ready! +Now it is dark. diff --git a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go deleted file mode 100644 index f26822a94..000000000 --- a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.go +++ /dev/null @@ -1,71 +0,0 @@ -// Wrapping errors is a technique that allows you to add additional context -// to an error while preserving the original error. -// This approach is beneficial for debugging and understanding -// the chain of events that led to an error, especially in -// complex applications with multiple layers of function calls. - -package main - -import ( - "errors" - "fmt" - "math/rand/v2" -) - -// A sentinel error is a predeclared error variable that is used to -// signify a specific error condition. It allows error values to be compared -// directly via errors.Is() specific types of errors. -var ErrOutOfTea = fmt.Errorf("no more tea available") - -var ErrPower = fmt.Errorf("can't boil water") - -func MakeTea() error { - if rand.Int32N(4) == 0 { - return ErrOutOfTea - } - if rand.Int32N(7) == 0 { - // You can wrap an error with %w - return fmt.Errorf("add custom text: %w", ErrPower) - } - return nil -} - -func main() { - err := makeTeaSeveralTimes() - if err != nil { - fmt.Println("One or serveral errors occured") - } -} - -func makeTeaSeveralTimes() error { - var allErrs []error - for range 14 { - err := MakeTea() - if err != nil { - allErrs = append(allErrs, err) - // errors.Is is a function in Go that checks if a given error - // matches a specific error value. It's used to determine whether - // an error (or any error in its chain) is equivalent to a particular - // target error. This is especially useful with wrapped or nested errors, - // allowing you to identify specific error types or sentinel errors in - // a chain of errors. - // By using several if-statements we can handle - // different sentinel errors. - // A switch statement is not applicable here. - if errors.Is(err, ErrOutOfTea) { - fmt.Println("We should buy new tea!") - continue - } - if errors.Is(err, ErrPower) { - fmt.Println("Now it is dark.") - continue - } - fmt.Printf("Some unknown error: %s", err) - continue - } - fmt.Println("The tea is warm and inviting.") - } - - // Several errors can be joined to one error. - return errors.Join(allErrs...) -} diff --git a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash deleted file mode 100644 index e2886c952..000000000 --- a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.hash +++ /dev/null @@ -1,2 +0,0 @@ -7e7e1b26a554f1737d79c8f64336548711eae60a -9Ck6s3dPplR diff --git a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh b/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh deleted file mode 100644 index 47535559e..000000000 --- a/examples/wrapping-and-sentinel-errors/wrapping-and-sentinel-errors.sh +++ /dev/null @@ -1,16 +0,0 @@ -$ go run wrapping-and-sentinel-errors.go -The tea is warm and inviting. -The tea is warm and inviting. -The tea is warm and inviting. -The tea is warm and inviting. -We should buy new tea! -The tea is warm and inviting. -The tea is warm and inviting. -The tea is warm and inviting. -Now it is dark. -The tea is warm and inviting. -The tea is warm and inviting. -The tea is warm and inviting. -We should buy new tea! -The tea is warm and inviting. -One or serveral errors occured diff --git a/public/custom-errors b/public/custom-errors index 9d8c9641d..8c3826be9 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -9,7 +9,7 @@ onkeydown = (e) => { if (e.key == "ArrowLeft") { - window.location.href = 'wrapping-and-sentinel-errors'; + window.location.href = 'errors'; } diff --git a/public/errors b/public/errors index f2c73c07f..13e940c76 100644 --- a/public/errors +++ b/public/errors @@ -14,7 +14,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'wrapping-and-sentinel-errors'; + window.location.href = 'custom-errors'; } } @@ -33,9 +33,13 @@ the exceptions used in languages like Java and Ruby and the overloaded single result / error value sometimes used in C. Go’s approach makes it easy to see which functions return errors and to handle them using the -same language constructs employed for any other, +same language constructs employed for other, non-error tasks.

    +

    See the documentation of the errors package +and this blog post for additional +details.

    + @@ -48,7 +52,7 @@ non-error tasks.

    - +
    package main
    @@ -107,15 +111,14 @@ there was no error.

    -

    The two loops below test out each of our -error-returning functions. Note that the use of an -inline error check on the if line is a common -idiom in Go code.

    +

    A sentinel error is a predeclared error variable that is used to +signify a specific error condition.

    -
    func main() {
    +
    var ErrOutOfTea = fmt.Errorf("no more tea available")
    +var ErrPower = fmt.Errorf("can't boil water")
    @@ -123,44 +126,124 @@ idiom in Go code.

    - + -
        for _, i := range []int{7, 42} {
    -        if r, e := f(i); e != nil {
    +          
    func makeTea(arg int) error {
    +    if arg == 2 {
    +        return ErrOutOfTea
    +    } else if arg == 4 {
    + + + + + +

    We can wrap errors with higher-level errors to add +context. The simplest way to do this is with the +%w verb in fmt.Errorf. Wrapped errors +create a logical chain (A wraps B, that wraps C, etc.) +that can be queried with functions like errors.Is +and errors.As.

    + + + + +
            return fmt.Errorf("making tea: %w", ErrPower)
    +    }
    +    return nil
    +}
    + + + + + + + + + +
    func main() {
    +    for _, i := range []int{7, 42} {
    + + + + + +

    It’s common to use an inline error check in the if +line.

    + + + + +
            if r, e := f(i); e != nil {
                 fmt.Println("f failed:", e)
             } else {
                 fmt.Println("f worked:", r)
             }
    -    }
    -}
    +
    }
    - - - - - + + + + + + + +
    -
    $ go run errors.go
    -f worked: 10
    -f failed: can't work with 42
    +
        for i := range 5 {
    +        if err := makeTea(i); err != nil {
    -

    See this great post -on the Go blog for more on error handling.

    +

    errors.Is checks that a given error (or any error in its chain) +matches a specific error value. This is especially useful with wrapped or +nested errors, allowing you to identify specific error types or sentinel +errors in a chain of errors.

    + - +
                if errors.Is(err, ErrOutOfTea) {
    +                fmt.Println("We should buy new tea!")
    +            } else if errors.Is(err, ErrPower) {
    +                fmt.Println("Now it is dark.")
    +            } else {
    +                fmt.Printf("unknown error: %s\n", err)
    +            }
    +            continue
    +        }
    +
    + + + +
            fmt.Println("Tea is ready!")
    +    }
    +}
    +
    + + + + + + @@ -168,7 +251,7 @@ on the Go blog for more on error handling.

    - Next example: Wrapping and Sentinel Errors. + Next example: Custom Errors.

    @@ -179,7 +262,7 @@ on the Go blog for more on error handling.

    diff --git a/public/index.html b/public/index.html index 2daeb4ec3..f462690d9 100644 --- a/public/index.html +++ b/public/index.html @@ -75,8 +75,6 @@

    Go by Example

  • Errors
  • -
  • Wrapping and Sentinel Errors
  • -
  • Custom Errors
  • Goroutines
  • diff --git a/public/wrapping-and-sentinel-errors b/public/wrapping-and-sentinel-errors index 4de8e844d..669d87223 100644 --- a/public/wrapping-and-sentinel-errors +++ b/public/wrapping-and-sentinel-errors @@ -23,202 +23,6 @@

    Go by Example: Wrapping and Sentinel Errors

    -
    + + + +
    f worked: 10
    +f failed: can't work with 42
    +Tea is ready!
    +Tea is ready!
    +We should buy new tea!
    +Tea is ready!
    +Now it is dark.
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    Wrapping errors is a technique that allows you to add additional context -to an error while preserving the original error. -This approach is beneficial for debugging and understanding -the chain of events that led to an error, especially in -complex applications with multiple layers of function calls.

    - -
    - - -
    - - - -
    package main
    -
    - - - -
    import (
    -    "errors"
    -    "fmt"
    -    "math/rand/v2"
    -)
    -
    -

    A sentinel error is a predeclared error variable that is used to -signify a specific error condition. It allows error values to be compared -directly via errors.Is() specific types of errors.

    - -
    - -
    var ErrOutOfTea = fmt.Errorf("no more tea available")
    -
    - - - -
    var ErrPower = fmt.Errorf("can't boil water")
    -
    -

    You can wrap an error with %w

    - -
    - -
    func MakeTea() error {
    -    if rand.Int32N(4) == 0 {
    -        return ErrOutOfTea
    -    }
    -    if rand.Int32N(7) == 0 {
    -
    - - - -
            return fmt.Errorf("add custom text: %w", ErrPower)
    -    }
    -    return nil
    -}
    -
    - - - -
    func main() {
    -    err := makeTeaSeveralTimes()
    -    if err != nil {
    -        fmt.Println("One or serveral errors occured")
    -    }
    -}
    -
    -

    errors.Is is a function in Go that checks if a given error -matches a specific error value. It’s used to determine whether -an error (or any error in its chain) is equivalent to a particular -target error. This is especially useful with wrapped or nested errors, -allowing you to identify specific error types or sentinel errors in -a chain of errors. -By using several if-statements we can handle -different sentinel errors. -A switch statement is not applicable here.

    - -
    - -
    func makeTeaSeveralTimes() error {
    -    var allErrs []error
    -    for range 14 {
    -        err := MakeTea()
    -        if err != nil {
    -            allErrs = append(allErrs, err)
    -
    - - - -
                if errors.Is(err, ErrOutOfTea) {
    -                fmt.Println("We should buy new tea!")
    -                continue
    -            }
    -            if errors.Is(err, ErrPower) {
    -                fmt.Println("Now it is dark.")
    -                continue
    -            }
    -            fmt.Printf("Some unknown error: %s", err)
    -            continue
    -        }
    -        fmt.Println("The tea is warm and inviting.")
    -    }
    -
    -

    Several errors can be joined to one error.

    - -
    - -
        return errors.Join(allErrs...)
    -}
    -
    - - - - - - - - -
    - - - -
    $ go run wrapping-and-sentinel-errors.go
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -We should buy new tea!
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -Now it is dark.
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -The tea is warm and inviting.
    -We should buy new tea!
    -The tea is warm and inviting.
    -One or serveral errors occured
    -
    -

    Next example: Custom Errors. @@ -232,7 +36,7 @@ A switch statement is not applicable here.

    From 61cf4c732e8a45fdb1e9148fec7610f046941ca3 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 21 Mar 2024 09:43:14 -0700 Subject: [PATCH 224/283] Update custom errors example --- examples/custom-errors/custom-errors.go | 24 ++++++++------- examples/custom-errors/custom-errors.hash | 4 +-- examples/errors/errors.hash | 4 +-- public/custom-errors | 36 +++++++++++------------ public/errors | 4 +-- 5 files changed, 37 insertions(+), 35 deletions(-) diff --git a/examples/custom-errors/custom-errors.go b/examples/custom-errors/custom-errors.go index 89dcbc041..9ae87c493 100644 --- a/examples/custom-errors/custom-errors.go +++ b/examples/custom-errors/custom-errors.go @@ -10,38 +10,40 @@ import ( "fmt" ) -// It's possible to use custom types as `error`s by -// implementing the `Error()` method on them. Here's a -// variant on the example above that uses a custom type -// to explicitly represent an argument error. -// A custom error type has usualy the suffix "Error". +// A custom error type usualy has the suffix "Error". type argError struct { arg int message string } +// Adding this `Error` method makes `argError` implement +// the `error` interface. func (e *argError) Error() string { return fmt.Sprintf("%d - %s", e.arg, e.message) } func f(arg int) (int, error) { if arg == 42 { - // In this case we use `&argError` syntax to build - // a new struct, supplying values for the two - // fields `arg` and `message`. + + // Return our custom error. return -1, &argError{arg, "can't work with it"} } return arg + 3, nil } func main() { - // If you want to programmatically use the data in - // a custom error, you'll need to get the error as an - // instance of the custom error with errors.As() + + // `errors.As` is a more advanced version of `errors.Is`. + // It checks that a given error (or any error in its chain) + // matches a specific error value and converts to that + // value if so, returning `true`. If there's no match, it + // returns `false`. _, err := f(42) var ae *argError if errors.As(err, &ae) { fmt.Println(ae.arg) fmt.Println(ae.message) + } else { + fmt.Println("err doesn't match argError") } } diff --git a/examples/custom-errors/custom-errors.hash b/examples/custom-errors/custom-errors.hash index 04fe7b4a3..d2b8d8728 100644 --- a/examples/custom-errors/custom-errors.hash +++ b/examples/custom-errors/custom-errors.hash @@ -1,2 +1,2 @@ -e7d16589797f94ba3ad1e75449b5f27c71d73a41 -9pZvObLbmb8 +d683e0ed9ff7d43167778cd45055485d4f0b5e4e +qd4Y1z0D6By diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index 2ccb8c1e2..7c4fca29b 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -1d5cbeac0932979a8925f4e959d3854edfcd6bcb -JJk4OyQSOYB +30f1a998472cabd8c445722dfc5ed8bed1c077cf +RmcBBb-4Nc_V diff --git a/public/custom-errors b/public/custom-errors index 8c3826be9..9ae780c7e 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -44,7 +44,7 @@ to explicitly represent an argument error.

    - +
    package main
    @@ -64,11 +64,7 @@ to explicitly represent an argument error.

    -

    It’s possible to use custom types as errors by -implementing the Error() method on them. Here’s a -variant on the example above that uses a custom type -to explicitly represent an argument error. -A custom error type has usualy the suffix “Error”.

    +

    A custom error type usualy has the suffix “Error”.

    @@ -82,7 +78,9 @@ A custom error type has usualy the suffix “Error”.

    - +

    Adding this Error method makes argError implement +the error interface.

    + @@ -94,10 +92,7 @@ A custom error type has usualy the suffix “Error”.

    -

    In this case we use &argError syntax to build -a new struct, supplying values for the two -fields arg and message.

    - + @@ -108,7 +103,8 @@ fields arg and message.

    - +

    Return our custom error.

    + @@ -121,10 +117,7 @@ fields arg and message.

    -

    If you want to programmatically use the data in -a custom error, you’ll need to get the error as an -instance of the custom error with errors.As()

    - + @@ -134,7 +127,12 @@ instance of the custom error with errors.As()

    - +

    errors.As is a more advanced version of errors.Is. +It checks that a given error (or any error in its chain) +matches a specific error value and converts to that +value if so, returning true. If there’s no match, it +returns false.

    + @@ -143,6 +141,8 @@ instance of the custom error with errors.As()

    if errors.As(err, &ae) { fmt.Println(ae.arg) fmt.Println(ae.message) + } else { + fmt.Println("err doesn't match argError") } }
    @@ -178,7 +178,7 @@ instance of the custom error with errors.As()

    diff --git a/public/errors b/public/errors index 13e940c76..9d3997a2f 100644 --- a/public/errors +++ b/public/errors @@ -52,7 +52,7 @@ details.

    - +
    package main
    @@ -140,7 +140,7 @@ signify a specific error condition.

    We can wrap errors with higher-level errors to add context. The simplest way to do this is with the %w verb in fmt.Errorf. Wrapped errors -create a logical chain (A wraps B, that wraps C, etc.) +create a logical chain (A wraps B, which wraps C, etc.) that can be queried with functions like errors.Is and errors.As.

    From ff35b38200dce837c8de374cada37a98352091b4 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 21 Mar 2024 09:45:32 -0700 Subject: [PATCH 225/283] Remove deleted example from public --- public/wrapping-and-sentinel-errors | 43 ----------------------------- 1 file changed, 43 deletions(-) delete mode 100644 public/wrapping-and-sentinel-errors diff --git a/public/wrapping-and-sentinel-errors b/public/wrapping-and-sentinel-errors deleted file mode 100644 index 669d87223..000000000 --- a/public/wrapping-and-sentinel-errors +++ /dev/null @@ -1,43 +0,0 @@ - - - - - Go by Example: Wrapping and Sentinel Errors - - - - -
    -

    Go by Example: Wrapping and Sentinel Errors

    - - -

    - Next example: Custom Errors. -

    - - - - -
    - - - - From bee6d2d9137d07776c71cef693d45582444caec7 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 21 Mar 2024 09:50:51 -0700 Subject: [PATCH 226/283] Fix wording slightly --- examples/custom-errors/custom-errors.go | 4 ++-- examples/custom-errors/custom-errors.hash | 4 ++-- examples/errors/errors.go | 2 +- examples/errors/errors.hash | 4 ++-- public/custom-errors | 6 +++--- public/errors | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/examples/custom-errors/custom-errors.go b/examples/custom-errors/custom-errors.go index 9ae87c493..96ffad466 100644 --- a/examples/custom-errors/custom-errors.go +++ b/examples/custom-errors/custom-errors.go @@ -35,8 +35,8 @@ func main() { // `errors.As` is a more advanced version of `errors.Is`. // It checks that a given error (or any error in its chain) - // matches a specific error value and converts to that - // value if so, returning `true`. If there's no match, it + // matches a specific error type and converts to a value + // of that type, returning `true`. If there's no match, it // returns `false`. _, err := f(42) var ae *argError diff --git a/examples/custom-errors/custom-errors.hash b/examples/custom-errors/custom-errors.hash index d2b8d8728..50509500e 100644 --- a/examples/custom-errors/custom-errors.hash +++ b/examples/custom-errors/custom-errors.hash @@ -1,2 +1,2 @@ -d683e0ed9ff7d43167778cd45055485d4f0b5e4e -qd4Y1z0D6By +9ee495d1322218925d6c654626398d7f3de0e208 +uhdXdp_OCct diff --git a/examples/errors/errors.go b/examples/errors/errors.go index 8218deb58..fe037996d 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -32,7 +32,7 @@ func f(arg int) (int, error) { return arg + 3, nil } -// A sentinel error is a predeclared error variable that is used to +// A sentinel error is a predeclared variable that is used to // signify a specific error condition. var ErrOutOfTea = fmt.Errorf("no more tea available") var ErrPower = fmt.Errorf("can't boil water") diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index 7c4fca29b..75e3c8bcf 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -30f1a998472cabd8c445722dfc5ed8bed1c077cf -RmcBBb-4Nc_V +805db04c4efb743792093f6dd7fbb6828be59cc2 +j6odYuFpOeb diff --git a/public/custom-errors b/public/custom-errors index 9ae780c7e..b47ba63d4 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -44,7 +44,7 @@ to explicitly represent an argument error.

    - +
    package main
    @@ -129,8 +129,8 @@ the error interface.

    errors.As is a more advanced version of errors.Is. It checks that a given error (or any error in its chain) -matches a specific error value and converts to that -value if so, returning true. If there’s no match, it +matches a specific error type and converts to a value +of that type, returning true. If there’s no match, it returns false.

    diff --git a/public/errors b/public/errors index 9d3997a2f..f0240036e 100644 --- a/public/errors +++ b/public/errors @@ -52,7 +52,7 @@ details.

    - +
    package main
    @@ -111,7 +111,7 @@ there was no error.

    -

    A sentinel error is a predeclared error variable that is used to +

    A sentinel error is a predeclared variable that is used to signify a specific error condition.

    From f8d60193e1c2fb9c0b2da0b046fdf280101c86bc Mon Sep 17 00:00:00 2001 From: John Daniels Date: Thu, 28 Mar 2024 13:35:14 +0000 Subject: [PATCH 227/283] Add the shell prompt/command to custom-errors.sh (#519) * Add the shell promt/command to custom-errors.sh * Add prompt/command to errors example --------- Co-authored-by: John --- examples/custom-errors/custom-errors.sh | 3 ++- examples/errors/errors.sh | 1 + public/custom-errors | 3 ++- public/errors | 3 ++- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/examples/custom-errors/custom-errors.sh b/examples/custom-errors/custom-errors.sh index d534739b5..33b7bed5e 100644 --- a/examples/custom-errors/custom-errors.sh +++ b/examples/custom-errors/custom-errors.sh @@ -1,2 +1,3 @@ +$ go run custom-errors.sh 42 -can't work with it \ No newline at end of file +can't work with it diff --git a/examples/errors/errors.sh b/examples/errors/errors.sh index 034c9ed3a..c5f4e545f 100644 --- a/examples/errors/errors.sh +++ b/examples/errors/errors.sh @@ -1,3 +1,4 @@ +$ go run errors.sh f worked: 10 f failed: can't work with 42 Tea is ready! diff --git a/public/custom-errors b/public/custom-errors index b47ba63d4..9bc7fd193 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -158,7 +158,8 @@ returns false.

    -
    42
    +          
    $ go run custom-errors.sh
    +42
     can't work with it
    diff --git a/public/errors b/public/errors index f0240036e..ddc4dab67 100644 --- a/public/errors +++ b/public/errors @@ -237,7 +237,8 @@ errors in a chain of errors.

    -
    f worked: 10
    +          
    $ go run errors.sh
    +f worked: 10
     f failed: can't work with 42
     Tea is ready!
     Tea is ready!
    
    From 7958694c0ea91d3bef545cc4857a53e8c5eab48d Mon Sep 17 00:00:00 2001
    From: adriancuadrado 
    Date: Mon, 15 Apr 2024 16:34:57 +0200
    Subject: [PATCH 228/283] Add an example with automatic array size (#522)
    MIME-Version: 1.0
    Content-Type: text/plain; charset=UTF-8
    Content-Transfer-Encoding: 8bit
    
    * Add am example with automatic array size
    
    You can learn more about this here: https://go.dev/blog/slices-intro#arrays
    
    * Update arrays.sh
    
    Forgot about this file 😅
    
    * Added example with indices in the initialization
    
    * Added multi-dimensional array initialization example
    
    * Removed clarification about commas
    
    * Run tools/build
    
    * Fixed output mismatch
    ---
     examples/arrays/arrays.go   | 18 +++++++++++++
     examples/arrays/arrays.hash |  4 +--
     examples/arrays/arrays.sh   |  3 +++
     public/arrays               | 53 ++++++++++++++++++++++++++++++++++---
     4 files changed, 72 insertions(+), 6 deletions(-)
    
    diff --git a/examples/arrays/arrays.go b/examples/arrays/arrays.go
    index 010a7e564..06b4c17b2 100644
    --- a/examples/arrays/arrays.go
    +++ b/examples/arrays/arrays.go
    @@ -31,6 +31,16 @@ func main() {
     	b := [5]int{1, 2, 3, 4, 5}
     	fmt.Println("dcl:", b)
     
    +	// You can also have the compiler count the number of
    +	// elements for you with `...`
    +	b = [...]int{1, 2, 3, 4, 5}
    +	fmt.Println("dcl:", b)
    +
    +	// If you specify the index with `:`, the elements in
    +	// between will be zeroed.
    +	b = [...]int{100, 3: 400, 500}
    +	fmt.Println("idx:", b)
    +
     	// Array types are one-dimensional, but you can
     	// compose types to build multi-dimensional data
     	// structures.
    @@ -41,4 +51,12 @@ func main() {
     		}
     	}
     	fmt.Println("2d: ", twoD)
    +
    +	// You can create and initialize multi-dimensional
    +	// arrays at once too.
    +	twoD = [2][3]int{
    +		{1, 2, 3},
    +		{1, 2, 3},
    +	}
    +	fmt.Println("2d: ", twoD)
     }
    diff --git a/examples/arrays/arrays.hash b/examples/arrays/arrays.hash
    index 8e1c671d9..12253ebfc 100644
    --- a/examples/arrays/arrays.hash
    +++ b/examples/arrays/arrays.hash
    @@ -1,2 +1,2 @@
    -e2bdc11af83f9c6964cfa0e06e4642943b3055ae
    -bBVikSoZ1Z7
    +789f9faa91c359e5337ace4f80b38428f39d4e7b
    +zVIFeNnUdwv
    diff --git a/examples/arrays/arrays.sh b/examples/arrays/arrays.sh
    index 76c43f6c3..bce55ab8b 100644
    --- a/examples/arrays/arrays.sh
    +++ b/examples/arrays/arrays.sh
    @@ -6,4 +6,7 @@ set: [0 0 0 0 100]
     get: 100
     len: 5
     dcl: [1 2 3 4 5]
    +dcl: [1 2 3 4 5]
    +idx: [100 0 0 400 500]
     2d:  [[0 1 2] [1 2 3]]
    +2d:  [[1 2 3] [1 2 3]]
    diff --git a/public/arrays b/public/arrays
    index 675a3f3b9..028fc060f 100644
    --- a/public/arrays
    +++ b/public/arrays
    @@ -44,7 +44,7 @@ scenarios.

    - +
    package main
    @@ -123,6 +123,32 @@ in one line.

    + + +

    You can also have the compiler count the number of +elements for you with ...

    + + + + +
        b = [...]int{1, 2, 3, 4, 5}
    +    fmt.Println("dcl:", b)
    + + + + + +

    If you specify the index with :, the elements in +between will be zeroed.

    + + + + +
        b = [...]int{100, 3: 400, 500}
    +    fmt.Println("idx:", b)
    + + +

    Array types are one-dimensional, but you can @@ -130,7 +156,7 @@ compose types to build multi-dimensional data structures.

    - +
        var twoD [2][3]int
         for i := 0; i < 2; i++ {
    @@ -138,6 +164,22 @@ structures.

    twoD[i][j] = i + j } } + fmt.Println("2d: ", twoD)
    + + + + + +

    You can create and initialize multi-dimensional +arrays at once too.

    + + + + +
        twoD = [2][3]int{
    +        {1, 2, 3},
    +        {1, 2, 3},
    +    }
         fmt.Println("2d: ", twoD)
     }
    @@ -161,7 +203,10 @@ when printed with fmt.Println.

    get: 100 len: 5 dcl: [1 2 3 4 5] -2d: [[0 1 2] [1 2 3]]
    +
    dcl: [1 2 3 4 5] +idx: [100 0 0 400 500] +2d: [[0 1 2] [1 2 3]] +2d: [[1 2 3] [1 2 3]]
    @@ -180,7 +225,7 @@ when printed with fmt.Println.

    From baadeda6643eb5fbd8590375fa5cbe2111e6ca43 Mon Sep 17 00:00:00 2001 From: Elias Kauppi <11910622+kauppie@users.noreply.github.com> Date: Mon, 29 Apr 2024 15:47:21 +0300 Subject: [PATCH 229/283] Use seek enums and show other seek methods (#524) * Use seek whence values * Add examples of seeking with other methods --- examples/reading-files/reading-files.go | 19 ++++++++--- examples/reading-files/reading-files.hash | 4 +-- public/reading-files | 39 +++++++++++++++++++---- 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/examples/reading-files/reading-files.go b/examples/reading-files/reading-files.go index 81edc196c..3bbf86463 100644 --- a/examples/reading-files/reading-files.go +++ b/examples/reading-files/reading-files.go @@ -43,7 +43,7 @@ func main() { // You can also `Seek` to a known location in the file // and `Read` from there. - o2, err := f.Seek(6, 0) + o2, err := f.Seek(6, io.SeekStart) check(err) b2 := make([]byte, 2) n2, err := f.Read(b2) @@ -51,20 +51,29 @@ func main() { fmt.Printf("%d bytes @ %d: ", n2, o2) fmt.Printf("%v\n", string(b2[:n2])) + // Other methods of seeking are relative to the + // current cursor position, + _, err = f.Seek(4, io.SeekCurrent) + check(err) + + // and relative to the end of the file. + _, err = f.Seek(-10, io.SeekEnd) + check(err) + // The `io` package provides some functions that may // be helpful for file reading. For example, reads // like the ones above can be more robustly // implemented with `ReadAtLeast`. - o3, err := f.Seek(6, 0) + o3, err := f.Seek(6, io.SeekStart) check(err) b3 := make([]byte, 2) n3, err := io.ReadAtLeast(f, b3, 2) check(err) fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3)) - // There is no built-in rewind, but `Seek(0, 0)` - // accomplishes this. - _, err = f.Seek(0, 0) + // There is no built-in rewind, but + // `Seek(0, io.SeekStart)` accomplishes this. + _, err = f.Seek(0, io.SeekStart) check(err) // The `bufio` package implements a buffered diff --git a/examples/reading-files/reading-files.hash b/examples/reading-files/reading-files.hash index 42509298d..be6468fb1 100644 --- a/examples/reading-files/reading-files.hash +++ b/examples/reading-files/reading-files.hash @@ -1,2 +1,2 @@ -5351edae47bb2f2c9b5d4b9682b8176beb0c24e5 -DF2Wo8nDKaF +754d3ce4873b6f8f1c81364bfcf5fedb17020c11 +upAKv1DPNMp diff --git a/public/reading-files b/public/reading-files index fceb4bd8a..085f564ee 100644 --- a/public/reading-files +++ b/public/reading-files @@ -43,7 +43,7 @@ reading files.

    - +
    package main
    @@ -141,7 +141,7 @@ and Read from there.

    -
        o2, err := f.Seek(6, 0)
    +          
        o2, err := f.Seek(6, io.SeekStart)
         check(err)
         b2 := make([]byte, 2)
         n2, err := f.Read(b2)
    @@ -151,6 +151,31 @@ and Read from there.

    + + +

    Other methods of seeking are relative to the +current cursor position,

    + + + + +
        _, err = f.Seek(4, io.SeekCurrent)
    +    check(err)
    + + + + + +

    and relative to the end of the file.

    + + + + +
        _, err = f.Seek(-10, io.SeekEnd)
    +    check(err)
    + + +

    The io package provides some functions that may @@ -161,7 +186,7 @@ implemented with ReadAtLeast.

    -
        o3, err := f.Seek(6, 0)
    +          
        o3, err := f.Seek(6, io.SeekStart)
         check(err)
         b3 := make([]byte, 2)
         n3, err := io.ReadAtLeast(f, b3, 2)
    @@ -172,13 +197,13 @@ implemented with ReadAtLeast.

    -

    There is no built-in rewind, but Seek(0, 0) -accomplishes this.

    +

    There is no built-in rewind, but +Seek(0, io.SeekStart) accomplishes this.

    -
        _, err = f.Seek(0, 0)
    +          
        _, err = f.Seek(0, io.SeekStart)
         check(err)
    @@ -262,7 +287,7 @@ be scheduled immediately after Opening with From 665183dcd839e2fa8dabd397c7a8ff5752c1cf26 Mon Sep 17 00:00:00 2001 From: Zhizhen He Date: Wed, 1 May 2024 11:38:05 +0800 Subject: [PATCH 230/283] Fix typo in a comment (#525) --- examples/custom-errors/custom-errors.go | 2 +- examples/custom-errors/custom-errors.hash | 4 ++-- public/custom-errors | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/custom-errors/custom-errors.go b/examples/custom-errors/custom-errors.go index 96ffad466..30cbe9960 100644 --- a/examples/custom-errors/custom-errors.go +++ b/examples/custom-errors/custom-errors.go @@ -10,7 +10,7 @@ import ( "fmt" ) -// A custom error type usualy has the suffix "Error". +// A custom error type usually has the suffix "Error". type argError struct { arg int message string diff --git a/examples/custom-errors/custom-errors.hash b/examples/custom-errors/custom-errors.hash index 50509500e..a4772dccd 100644 --- a/examples/custom-errors/custom-errors.hash +++ b/examples/custom-errors/custom-errors.hash @@ -1,2 +1,2 @@ -9ee495d1322218925d6c654626398d7f3de0e208 -uhdXdp_OCct +e63d61872edce05ea3ec797958eff48d1decfbd8 +qKKTjmc6SuB diff --git a/public/custom-errors b/public/custom-errors index 9bc7fd193..36672dda5 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -44,7 +44,7 @@ to explicitly represent an argument error.

    - +
    package main
    @@ -64,7 +64,7 @@ to explicitly represent an argument error.

    -

    A custom error type usualy has the suffix “Error”.

    +

    A custom error type usually has the suffix “Error”.

    From e5e90317bd70200309747be5aad14205ff6f6690 Mon Sep 17 00:00:00 2001 From: EmNudge <24513691+EmNudge@users.noreply.github.com> Date: Wed, 1 May 2024 06:50:23 -0700 Subject: [PATCH 231/283] fix ending extension (#526) --- examples/custom-errors/custom-errors.sh | 2 +- examples/errors/errors.sh | 2 +- public/custom-errors | 2 +- public/errors | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/custom-errors/custom-errors.sh b/examples/custom-errors/custom-errors.sh index 33b7bed5e..ee763301e 100644 --- a/examples/custom-errors/custom-errors.sh +++ b/examples/custom-errors/custom-errors.sh @@ -1,3 +1,3 @@ -$ go run custom-errors.sh +$ go run custom-errors.go 42 can't work with it diff --git a/examples/errors/errors.sh b/examples/errors/errors.sh index c5f4e545f..f517aa840 100644 --- a/examples/errors/errors.sh +++ b/examples/errors/errors.sh @@ -1,4 +1,4 @@ -$ go run errors.sh +$ go run errors.go f worked: 10 f failed: can't work with 42 Tea is ready! diff --git a/public/custom-errors b/public/custom-errors index 36672dda5..5e8dfc4dd 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -158,7 +158,7 @@ returns false.

    -
    $ go run custom-errors.sh
    +          
    $ go run custom-errors.go
     42
     can't work with it
    diff --git a/public/errors b/public/errors index ddc4dab67..ebe576d3c 100644 --- a/public/errors +++ b/public/errors @@ -237,7 +237,7 @@ errors in a chain of errors.

    -
    $ go run errors.sh
    +          
    $ go run errors.go
     f worked: 10
     f failed: can't work with 42
     Tea is ready!
    
    From e6b7ae87b53adc5ad2ebed7b175086c9537b36cb Mon Sep 17 00:00:00 2001
    From: Henrik Sylvester Oddergaard 
    Date: Sat, 11 May 2024 17:54:34 +0200
    Subject: [PATCH 232/283] Stop breaking browser navigation shortcuts. (#527)
    
    On Linux Chrome I use ALT + Arrows to go back in the browser, but instead
    it paginates between examples.
    
    Fixed it by checking for special key modifiers and do nothing (to the let the browser handle it).
    I think the user always intends a system shortcut if they use a modifier key.
    ---
     public/arrays                          | 3 +++
     public/atomic-counters                 | 3 +++
     public/base64-encoding                 | 3 +++
     public/channel-buffering               | 3 +++
     public/channel-directions              | 3 +++
     public/channel-synchronization         | 3 +++
     public/channels                        | 3 +++
     public/closing-channels                | 3 +++
     public/closures                        | 3 +++
     public/command-line-arguments          | 3 +++
     public/command-line-flags              | 3 +++
     public/command-line-subcommands        | 3 +++
     public/constants                       | 3 +++
     public/context                         | 3 +++
     public/custom-errors                   | 3 +++
     public/defer                           | 3 +++
     public/directories                     | 3 +++
     public/embed-directive                 | 3 +++
     public/environment-variables           | 3 +++
     public/epoch                           | 3 +++
     public/errors                          | 3 +++
     public/execing-processes               | 3 +++
     public/exit                            | 3 +++
     public/file-paths                      | 3 +++
     public/for                             | 3 +++
     public/functions                       | 3 +++
     public/generics                        | 3 +++
     public/goroutines                      | 3 +++
     public/hello-world                     | 3 +++
     public/http-client                     | 3 +++
     public/http-server                     | 3 +++
     public/if-else                         | 3 +++
     public/interfaces                      | 3 +++
     public/json                            | 3 +++
     public/line-filters                    | 3 +++
     public/logging                         | 3 +++
     public/maps                            | 3 +++
     public/methods                         | 3 +++
     public/multiple-return-values          | 3 +++
     public/mutexes                         | 3 +++
     public/non-blocking-channel-operations | 3 +++
     public/number-parsing                  | 3 +++
     public/panic                           | 3 +++
     public/pointers                        | 3 +++
     public/random-numbers                  | 3 +++
     public/range                           | 3 +++
     public/range-over-channels             | 3 +++
     public/rate-limiting                   | 3 +++
     public/reading-files                   | 3 +++
     public/recover                         | 3 +++
     public/recursion                       | 3 +++
     public/regular-expressions             | 3 +++
     public/select                          | 3 +++
     public/sha256-hashes                   | 3 +++
     public/signals                         | 3 +++
     public/slices                          | 3 +++
     public/sorting                         | 3 +++
     public/sorting-by-functions            | 3 +++
     public/spawning-processes              | 3 +++
     public/stateful-goroutines             | 3 +++
     public/string-formatting               | 3 +++
     public/string-functions                | 3 +++
     public/strings-and-runes               | 3 +++
     public/struct-embedding                | 3 +++
     public/structs                         | 3 +++
     public/switch                          | 3 +++
     public/temporary-files-and-directories | 3 +++
     public/testing-and-benchmarking        | 3 +++
     public/text-templates                  | 3 +++
     public/tickers                         | 3 +++
     public/time                            | 3 +++
     public/time-formatting-parsing         | 3 +++
     public/timeouts                        | 3 +++
     public/timers                          | 3 +++
     public/url-parsing                     | 3 +++
     public/values                          | 3 +++
     public/variables                       | 3 +++
     public/variadic-functions              | 3 +++
     public/waitgroups                      | 3 +++
     public/worker-pools                    | 3 +++
     public/writing-files                   | 3 +++
     public/xml                             | 3 +++
     templates/example.tmpl                 | 3 +++
     83 files changed, 249 insertions(+)
    
    diff --git a/public/arrays b/public/arrays
    index 028fc060f..7693d73a4 100644
    --- a/public/arrays
    +++ b/public/arrays
    @@ -7,6 +7,9 @@
       
       
    +  
    +    
    +

    Go by Example: Enums

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Enumerated types (enums) are a special case of +sum types. +An enum is a type that has a fixed number of possible +values, each with a distinct name. Go doesn’t have an +enum type as a distinct language feature, but enums +are simple to implement using existing language idioms.

    + +
    + + +
    + + + +
    package main
    +
    + + + +
    import "fmt"
    +
    +

    Our enum type ServerState has an underlying int type.

    + +
    + +
    type ServerState int
    +
    +

    The possible values for ServerState are defined as +constants. The special keyword iota +generates successive constant values automatically; in this +case 0, 1, 2 and so on.

    + +
    + +
    const (
    +    StateIdle = iota
    +    StateConnected
    +    StateError
    +    StateRetrying
    +)
    +
    +

    By implementing the fmt.Stringer +interface, values of StateType can be printed out or converted +to strings.

    + +

    This can get cumbersome if there are many possible values. In such +cases the stringer tool +can be used in conjunction with go:generate to automate the +process. See this post +for a longer explanation.

    + +
    + +
    var stateName = map[ServerState]string{
    +    StateIdle:      "idle",
    +    StateConnected: "connected",
    +    StateError:     "error",
    +    StateRetrying:  "retrying",
    +}
    +
    + + + +
    func (ss ServerState) String() string {
    +    return stateName[ss]
    +}
    +
    +

    If we have a value of type int, we cannot pass it to transition - the +compiler will complain about type mismatch. This provides some degree of +compile-time type safety for enums.

    + +
    + +
    func main() {
    +    ns := transition(StateIdle)
    +    fmt.Println(ns)
    +
    + + + +
        ns2 := transition(ns)
    +    fmt.Println(ns2)
    +}
    +
    +

    transition emulates a state transition for a +server; it takes the existing state and returns +a new state.

    + +
    + +
    func transition(s ServerState) ServerState {
    +    switch s {
    +    case StateIdle:
    +        return StateConnected
    +    case StateConnected, StateRetrying:
    +
    +

    Suppose we check some predicates here to +determine the next state…

    + +
    + +
            return StateIdle
    +    case StateError:
    +        return StateError
    +    default:
    +        panic(fmt.Errorf("unwknown state: %s", s))
    +    }
    +
    + + + +
        return StateConnected
    +}
    +
    + + + + + + + + +
    + + + +
    $ go run enums.go
    +connected
    +idle
    +
    + + +

    + Next example: Struct Embedding. +

    + + + + +
    + + + + diff --git a/public/index.html b/public/index.html index f462690d9..7f9eeb32e 100644 --- a/public/index.html +++ b/public/index.html @@ -69,6 +69,8 @@

    Go by Example

  • Interfaces
  • +
  • Enums
  • +
  • Struct Embedding
  • Generics
  • diff --git a/public/interfaces b/public/interfaces index 5bbbb3a07..15a381113 100644 --- a/public/interfaces +++ b/public/interfaces @@ -17,7 +17,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'struct-embedding'; + window.location.href = 'enums'; } } @@ -210,7 +210,7 @@ these structs as arguments to measure.

    - Next example: Struct Embedding. + Next example: Enums.

    diff --git a/public/struct-embedding b/public/struct-embedding index 33a9c7e78..e2b995e1f 100644 --- a/public/struct-embedding +++ b/public/struct-embedding @@ -12,7 +12,7 @@ } if (e.key == "ArrowLeft") { - window.location.href = 'interfaces'; + window.location.href = 'enums'; } From d774175f3103e56f3bbaf22d12618afd0054019b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=20G=C3=B6rkem=20=C3=87i=C3=A7ek?= Date: Wed, 15 May 2024 15:28:41 +0300 Subject: [PATCH 235/283] Fix typo in the enums example (#530) --- examples/enums/enums.go | 2 +- examples/enums/enums.hash | 4 ++-- public/enums | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/enums/enums.go b/examples/enums/enums.go index a65a04d27..9514ce679 100644 --- a/examples/enums/enums.go +++ b/examples/enums/enums.go @@ -24,7 +24,7 @@ const ( ) // By implementing the [fmt.Stringer](https://pkg.go.dev/fmt#Stringer) -// interface, values of `StateType` can be printed out or converted +// interface, values of `ServerState` can be printed out or converted // to strings. // // This can get cumbersome if there are many possible values. In such diff --git a/examples/enums/enums.hash b/examples/enums/enums.hash index 0367fc00c..0e031a72c 100644 --- a/examples/enums/enums.hash +++ b/examples/enums/enums.hash @@ -1,2 +1,2 @@ -1c5bf51fa651a25eb6d9d2d24cf7dbd2713aca0c --6dSwyy83xj +b93a8b040a9c2d0de4050689f6eaab2ff0aa4644 +NyVXnLsm3cu diff --git a/public/enums b/public/enums index 12d1d740b..1ee936d81 100644 --- a/public/enums +++ b/public/enums @@ -49,7 +49,7 @@ are simple to implement using existing language idioms.

    - +
    package main
    @@ -97,7 +97,7 @@ case 0, 1, 2 and so on.

    By implementing the fmt.Stringer -interface, values of StateType can be printed out or converted +interface, values of ServerState can be printed out or converted to strings.

    This can get cumbersome if there are many possible values. In such From 942f1814678527531da9df0b2f729e08a262ceae Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Fri, 24 May 2024 07:10:46 -0700 Subject: [PATCH 236/283] Adjust the index page intro text slightly * Fix grammar * Reword language goals to align with Go team's comms * Mention "latest major release" assumption Fixes #532 --- public/index.html | 14 +++++++++----- templates/index.tmpl | 14 +++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/public/index.html b/public/index.html index 7f9eeb32e..9835a7deb 100644 --- a/public/index.html +++ b/public/index.html @@ -11,11 +11,10 @@

    Go by Example

    Go is an open source programming language designed for - building simple, fast, and reliable software. - Please read the official - documentation - to learn a bit about Go code, tools packages, - and modules. + building scalable, secure and reliable software. + Please read the + official documentation + to learn more.

    @@ -25,6 +24,11 @@

    Go by Example

    browse the full list below.

    +

    + Unless stated otherwise, examples here assume the + latest major release Go. +

    +
    • Hello World
    • diff --git a/templates/index.tmpl b/templates/index.tmpl index 520f68bc0..9e086861b 100644 --- a/templates/index.tmpl +++ b/templates/index.tmpl @@ -11,11 +11,10 @@

      Go is an open source programming language designed for - building simple, fast, and reliable software. - Please read the official - documentation - to learn a bit about Go code, tools packages, - and modules. + building scalable, secure and reliable software. + Please read the + official documentation + to learn more.

      @@ -25,6 +24,11 @@ browse the full list below.

      +

      + Unless stated otherwise, examples here assume the + latest major release Go. +

      +
        {{range .}}
      • {{.Name}}
      • From 308d4be3002d30a01ccf7341d269243b3395cdb8 Mon Sep 17 00:00:00 2001 From: Jon Webb Date: Mon, 10 Jun 2024 09:01:47 -0400 Subject: [PATCH 237/283] Fix typo in examples/enums/enums.go (#537) "unwknown" -> "unknown" in default switch case panic message. --- examples/enums/enums.go | 2 +- examples/enums/enums.hash | 4 ++-- public/enums | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/enums/enums.go b/examples/enums/enums.go index 9514ce679..b90e559e9 100644 --- a/examples/enums/enums.go +++ b/examples/enums/enums.go @@ -68,7 +68,7 @@ func transition(s ServerState) ServerState { case StateError: return StateError default: - panic(fmt.Errorf("unwknown state: %s", s)) + panic(fmt.Errorf("unknown state: %s", s)) } return StateConnected diff --git a/examples/enums/enums.hash b/examples/enums/enums.hash index 0e031a72c..13330aeb1 100644 --- a/examples/enums/enums.hash +++ b/examples/enums/enums.hash @@ -1,2 +1,2 @@ -b93a8b040a9c2d0de4050689f6eaab2ff0aa4644 -NyVXnLsm3cu +7237bf811864fcd24b6d43341faf1af147a51b20 +0hX2sAX1N6Q diff --git a/public/enums b/public/enums index 1ee936d81..70f7891bf 100644 --- a/public/enums +++ b/public/enums @@ -49,7 +49,7 @@ are simple to implement using existing language idioms.

        - +
        package main
        @@ -186,7 +186,7 @@ determine the next state…

        case StateError: return StateError default: - panic(fmt.Errorf("unwknown state: %s", s)) + panic(fmt.Errorf("unknown state: %s", s)) }
    @@ -233,7 +233,7 @@ determine the next state…

    From 5cd7f20d83887ba363830fb03e64af4059fe41e0 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Mon, 17 Jun 2024 21:36:54 +0000 Subject: [PATCH 238/283] Use console consistently for readme blocks --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b433df35..05cff6f31 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ $ tools/build-loop To see the site locally: -``` +```console $ tools/serve ``` From aa04b844797092edeadbd664a75e18f4bd6e353d Mon Sep 17 00:00:00 2001 From: Joseph Myers Date: Wed, 3 Jul 2024 11:24:40 -0500 Subject: [PATCH 239/283] Remove unreachable code from enums example (#540) * remove unreachable code from switch in enums example * run build/tools to generate static content in /public --- examples/enums/enums.go | 2 -- examples/enums/enums.hash | 4 ++-- public/enums | 18 ++++-------------- 3 files changed, 6 insertions(+), 18 deletions(-) diff --git a/examples/enums/enums.go b/examples/enums/enums.go index b90e559e9..6c516453c 100644 --- a/examples/enums/enums.go +++ b/examples/enums/enums.go @@ -70,6 +70,4 @@ func transition(s ServerState) ServerState { default: panic(fmt.Errorf("unknown state: %s", s)) } - - return StateConnected } diff --git a/examples/enums/enums.hash b/examples/enums/enums.hash index 13330aeb1..311d55424 100644 --- a/examples/enums/enums.hash +++ b/examples/enums/enums.hash @@ -1,2 +1,2 @@ -7237bf811864fcd24b6d43341faf1af147a51b20 -0hX2sAX1N6Q +097dc14a53f63735563f6f75314c30908aa46748 +3zjUiM66KZe diff --git a/public/enums b/public/enums index 70f7891bf..1b8f390ed 100644 --- a/public/enums +++ b/public/enums @@ -49,7 +49,7 @@ are simple to implement using existing language idioms.

    - +
    package main
    @@ -180,24 +180,14 @@ a new state.

    determine the next state…

    - +
            return StateIdle
         case StateError:
             return StateError
         default:
             panic(fmt.Errorf("unknown state: %s", s))
    -    }
    - - - - - - - - - -
        return StateConnected
    +    }
     }
    @@ -233,7 +223,7 @@ determine the next state…

    From 9ee93ffbf5f0187b1705b15ece9f73aa5e6be6f3 Mon Sep 17 00:00:00 2001 From: "Set Kyar Wa Lar (Universe)" Date: Mon, 8 Jul 2024 21:15:15 +0800 Subject: [PATCH 240/283] Add Burmese version translation (#541) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 05cff6f31..ddfa1d3bb 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ Contributor translations of the Go by Example site are available in: * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) * [Brazilian Portuguese](https://lcslitx.github.io/GoEmExemplos/) by [lcslitx](https://github.com/LCSLITX) * [Vietnamese](https://gobyexample.vn/) by [s6k Gopher](https://github.com/s6k-gopher/gobyexample-vn) +* [Burmese](https://setkyar.github.io/gobyexample) by [Set Kyar Wa Lar](https://github.com/setkyar/gobyexample) ### Thanks From b832df61a6897d3c4145d213c20b33ebb4bd1f52 Mon Sep 17 00:00:00 2001 From: "David E." <76119744+havidtech@users.noreply.github.com> Date: Mon, 5 Aug 2024 13:50:34 +0100 Subject: [PATCH 241/283] fix: change "encoding.xml" to "encoding/xml" (#546) --- examples/xml/xml.go | 2 +- examples/xml/xml.hash | 4 ++-- public/xml | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/xml/xml.go b/examples/xml/xml.go index 4affc12cd..858a8b8c3 100644 --- a/examples/xml/xml.go +++ b/examples/xml/xml.go @@ -1,5 +1,5 @@ // Go offers built-in support for XML and XML-like -// formats with the `encoding.xml` package. +// formats with the `encoding/xml` package. package main diff --git a/examples/xml/xml.hash b/examples/xml/xml.hash index 56c0a9aae..e3a2770ac 100644 --- a/examples/xml/xml.hash +++ b/examples/xml/xml.hash @@ -1,2 +1,2 @@ -4b9dfaf797591099f6fcb762241289b1662a9250 -OVq7kNMk0GR +d64993474fdf0571436db63a82974d74932ba256 +vsP5mIrNJOG diff --git a/public/xml b/public/xml index edfc836ff..f2c32787c 100644 --- a/public/xml +++ b/public/xml @@ -31,7 +31,7 @@

    Go offers built-in support for XML and XML-like -formats with the encoding.xml package.

    +formats with the encoding/xml package.

    @@ -45,7 +45,7 @@ formats with the encoding.xml package.

    - +
    package main
    From 1a760375bd124e274d067130b386af5819eeab26 Mon Sep 17 00:00:00 2001 From: Alex <43649615+bustosalex1@users.noreply.github.com> Date: Wed, 14 Aug 2024 09:41:56 -0400 Subject: [PATCH 242/283] Fix example name in its .sh --- examples/context/context.sh | 2 +- public/context | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/context/context.sh b/examples/context/context.sh index 68d6f4db1..b6377d69e 100644 --- a/examples/context/context.sh +++ b/examples/context/context.sh @@ -1,5 +1,5 @@ # Run the server in the background. -$ go run context-in-http-servers.go & +$ go run context.go & # Simulate a client request to `/hello`, hitting # Ctrl+C shortly after starting to signal diff --git a/public/context b/public/context index c1e99e67e..a6bec16df 100644 --- a/public/context +++ b/public/context @@ -154,7 +154,7 @@ route, and start serving.

    -
    $ go run context-in-http-servers.go &
    +
    $ go run context.go &
    From bf195bf4ebb89c0dd70e21cab0c8244cd4130f87 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 14 Aug 2024 08:14:52 -0700 Subject: [PATCH 243/283] Clarify GC in structs example Fixes #550 --- examples/structs/structs.go | 6 ++++-- examples/structs/structs.hash | 4 ++-- public/structs | 8 +++++--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/examples/structs/structs.go b/examples/structs/structs.go index d56c0aa60..f06b61dca 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -14,8 +14,10 @@ type person struct { // `newPerson` constructs a new person struct with the given name. func newPerson(name string) *person { - // You can safely return a pointer to local variable - // as a local variable will survive the scope of the function. + // Go is a garbage collected language; you can safely + // return a pointer to a local variable - it will only + // be cleaned up by the garbage collector when there + // are no active references to it. p := person{name: name} p.age = 42 return &p diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index 372123828..da28967d4 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -80344041b9268370bb6c73190afb1269e26f52fe -ex1J3oieEeo +b50c1756bf9a2ea7f8853f7f7cb7a61d5efebfc3 +56SPo-L2nMN diff --git a/public/structs b/public/structs index 47089d0aa..78cc03f2b 100644 --- a/public/structs +++ b/public/structs @@ -46,7 +46,7 @@ records.

    - +
    package main
    @@ -88,8 +88,10 @@ records.

    -

    You can safely return a pointer to local variable -as a local variable will survive the scope of the function.

    +

    Go is a garbage collected language; you can safely +return a pointer to a local variable - it will only +be cleaned up by the garbage collector when there +are no active references to it.

    From f7120b2cc1d963677a96db3d49b31df255c9d296 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 17 Aug 2024 07:32:29 -0700 Subject: [PATCH 244/283] Suggest latest version on the home page --- public/index.html | 4 +++- templates/index.tmpl | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/public/index.html b/public/index.html index 9835a7deb..6dc95675a 100644 --- a/public/index.html +++ b/public/index.html @@ -26,7 +26,9 @@

    Go by Example

    Unless stated otherwise, examples here assume the - latest major release Go. + latest major release Go + and may use new language features. Try to upgrade to the latest + version if something isn't working.

      diff --git a/templates/index.tmpl b/templates/index.tmpl index 9e086861b..b1fb70053 100644 --- a/templates/index.tmpl +++ b/templates/index.tmpl @@ -26,7 +26,9 @@

      Unless stated otherwise, examples here assume the - latest major release Go. + latest major release Go + and may use new language features. Try to upgrade to the latest + version if something isn't working.

        From d51709a1712b3e2689ebb81f4873e83679fadd24 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 06:13:09 -0700 Subject: [PATCH 245/283] Rename range example to prepare for expansion --- examples.txt | 2 +- .../range-over-built-in-types.go} | 7 +++--- .../range-over-built-in-types.hash | 2 ++ .../range-over-built-in-types.sh} | 2 +- .../range-over-channels.go | 2 +- .../range-over-channels.hash | 4 ++-- examples/range/range.hash | 2 -- public/functions | 2 +- public/index.html | 4 ++-- public/maps | 4 ++-- public/pointers | 2 +- public/{range => range-over-built-in-types} | 23 ++++++++++--------- public/range-over-channels | 4 ++-- public/recursion | 4 ++-- 14 files changed, 33 insertions(+), 31 deletions(-) rename examples/{range/range.go => range-over-built-in-types/range-over-built-in-types.go} (86%) create mode 100644 examples/range-over-built-in-types/range-over-built-in-types.hash rename examples/{range/range.sh => range-over-built-in-types/range-over-built-in-types.sh} (63%) delete mode 100644 examples/range/range.hash rename public/{range => range-over-built-in-types} (94%) diff --git a/examples.txt b/examples.txt index 1d5a650a5..3dc0533d8 100644 --- a/examples.txt +++ b/examples.txt @@ -8,12 +8,12 @@ Switch Arrays Slices Maps -Range Functions Multiple Return Values Variadic Functions Closures Recursion +Range over Built-in Types Pointers Strings and Runes Structs diff --git a/examples/range/range.go b/examples/range-over-built-in-types/range-over-built-in-types.go similarity index 86% rename from examples/range/range.go rename to examples/range-over-built-in-types/range-over-built-in-types.go index ec44c3fa0..6a55eb148 100644 --- a/examples/range/range.go +++ b/examples/range-over-built-in-types/range-over-built-in-types.go @@ -1,6 +1,7 @@ -// _range_ iterates over elements in a variety of data -// structures. Let's see how to use `range` with some -// of the data structures we've already learned. +// _range_ iterates over elements in a variety of +// built-in data structures. Let's see how to +// use `range` with some of the data structures +// we've already learned. package main diff --git a/examples/range-over-built-in-types/range-over-built-in-types.hash b/examples/range-over-built-in-types/range-over-built-in-types.hash new file mode 100644 index 000000000..ad6a64216 --- /dev/null +++ b/examples/range-over-built-in-types/range-over-built-in-types.hash @@ -0,0 +1,2 @@ +3d8c61f02f98892be9d3ff25d48da0bfb31bbd25 +S171w0PjgsD diff --git a/examples/range/range.sh b/examples/range-over-built-in-types/range-over-built-in-types.sh similarity index 63% rename from examples/range/range.sh rename to examples/range-over-built-in-types/range-over-built-in-types.sh index e3f40d8a9..261634293 100644 --- a/examples/range/range.sh +++ b/examples/range-over-built-in-types/range-over-built-in-types.sh @@ -1,4 +1,4 @@ -$ go run range.go +$ go run range-over-built-in-types.go sum: 9 index: 1 a -> apple diff --git a/examples/range-over-channels/range-over-channels.go b/examples/range-over-channels/range-over-channels.go index d8aa729fe..356c1289c 100644 --- a/examples/range-over-channels/range-over-channels.go +++ b/examples/range-over-channels/range-over-channels.go @@ -1,4 +1,4 @@ -// In a [previous](range) example we saw how `for` and +// In a [previous](range-over-built-in-types) example we saw how `for` and // `range` provide iteration over basic data structures. // We can also use this syntax to iterate over // values received from a channel. diff --git a/examples/range-over-channels/range-over-channels.hash b/examples/range-over-channels/range-over-channels.hash index b3b135cfe..89918ad06 100644 --- a/examples/range-over-channels/range-over-channels.hash +++ b/examples/range-over-channels/range-over-channels.hash @@ -1,2 +1,2 @@ -1812ab409c07ea4209106ee4c0d2eb597fccd717 -yQMclmwOYs9 +446dea3a7cb9e16ce3e17a6649c719e764936740 +8vAhX6eX1wy diff --git a/examples/range/range.hash b/examples/range/range.hash deleted file mode 100644 index f2e2c7bc8..000000000 --- a/examples/range/range.hash +++ /dev/null @@ -1,2 +0,0 @@ -c8da490660d234fc420f39d9b8a4aba27f8aba46 -kRsyWNmLFLz diff --git a/public/functions b/public/functions index 3b3669f19..7823b6dda 100644 --- a/public/functions +++ b/public/functions @@ -12,7 +12,7 @@ } if (e.key == "ArrowLeft") { - window.location.href = 'range'; + window.location.href = 'maps'; } diff --git a/public/index.html b/public/index.html index 6dc95675a..aa8cc7b8e 100644 --- a/public/index.html +++ b/public/index.html @@ -53,8 +53,6 @@

        Go by Example

      • Maps
      • -
      • Range
      • -
      • Functions
      • Multiple Return Values
      • @@ -65,6 +63,8 @@

        Go by Example

      • Recursion
      • +
      • Range over Built-in Types
      • +
      • Pointers
      • Strings and Runes
      • diff --git a/public/maps b/public/maps index 63a401dc5..b8b899ad7 100644 --- a/public/maps +++ b/public/maps @@ -17,7 +17,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'range'; + window.location.href = 'functions'; } } @@ -250,7 +250,7 @@ printed with fmt.Println.

        - Next example: Range. + Next example: Functions.

        diff --git a/public/pointers b/public/pointers index 84babb6a9..3d5276d58 100644 --- a/public/pointers +++ b/public/pointers @@ -12,7 +12,7 @@ } if (e.key == "ArrowLeft") { - window.location.href = 'recursion'; + window.location.href = 'range-over-built-in-types'; } diff --git a/public/range b/public/range-over-built-in-types similarity index 94% rename from public/range rename to public/range-over-built-in-types index add3bff03..0d47ff6eb 100644 --- a/public/range +++ b/public/range-over-built-in-types @@ -2,7 +2,7 @@ - Go by Example: Range + Go by Example: Range over Built-in Types -
        -

        Go by Example: Range

        +
        +

        Go by Example: Range over Built-in Types

        @@ -162,7 +163,7 @@ details.

        diff --git a/public/recursion b/public/recursion index 52b78375e..bb53831b9 100644 --- a/public/recursion +++ b/public/recursion @@ -17,7 +17,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'pointers'; + window.location.href = 'range-over-built-in-types'; } } @@ -159,7 +159,7 @@ knows which function to call with fib here.

        - Next example: Pointers. + Next example: Range over Built-in Types.

        From 6ed788f3f55d1414a05f482c69b33f6f7afabdcb Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 06:43:09 -0700 Subject: [PATCH 246/283] Update generics example to prepare for iteration --- examples/generics/generics.go | 45 ++++++++++++++++++--------------- examples/generics/generics.hash | 4 +-- examples/generics/generics.sh | 6 +---- public/generics | 43 ++++++++++++++++--------------- 4 files changed, 51 insertions(+), 47 deletions(-) diff --git a/examples/generics/generics.go b/examples/generics/generics.go index c6fa91afd..470594293 100644 --- a/examples/generics/generics.go +++ b/examples/generics/generics.go @@ -5,20 +5,22 @@ package main import "fmt" -// As an example of a generic function, `MapKeys` takes -// a map of any type and returns a slice of its keys. -// This function has two type parameters - `K` and `V`; -// `K` has the `comparable` _constraint_, meaning that -// we can compare values of this type with the `==` and -// `!=` operators. This is required for map keys in Go. -// `V` has the `any` constraint, meaning that it's not -// restricted in any way (`any` is an alias for `interface{}`). -func MapKeys[K comparable, V any](m map[K]V) []K { - r := make([]K, 0, len(m)) - for k := range m { - r = append(r, k) +// As an example of a generic function, `SlicesIndex` takes +// a slice of any `comparable` type and an element of that +// type and returns the index of the first occurrence of +// v in s, or -1 if not present. The `comparable` constraint +// means that we can compare values of this type with the +// `==` and `!=` operators. For a more thorough explanation +// of this type signature, see [this blog post](https://go.dev/blog/deconstructing-type-parameters). +// Note that this function exists in the standard library +// as [slices.Index](https://pkg.go.dev/slices#Index). +func SlicesIndex[S ~[]E, E comparable](s S, v E) int { + for i := range s { + if v == s[i] { + return i + } } - return r + return -1 } // As an example of a generic type, `List` is a @@ -45,7 +47,10 @@ func (lst *List[T]) Push(v T) { } } -func (lst *List[T]) GetAll() []T { +// AllElements returns all the List elements as a slice. +// In the next example we'll see a more idiomatic way +// of iterating over all elements of custom types. +func (lst *List[T]) AllElements() []T { var elems []T for e := lst.head; e != nil; e = e.next { elems = append(elems, e.val) @@ -54,21 +59,21 @@ func (lst *List[T]) GetAll() []T { } func main() { - var m = map[int]string{1: "2", 2: "4", 4: "8"} + var s = []string{"foo", "bar", "zoo"} // When invoking generic functions, we can often rely // on _type inference_. Note that we don't have to - // specify the types for `K` and `V` when - // calling `MapKeys` - the compiler infers them + // specify the types for `S` and `E` when + // calling `SlicesIndex` - the compiler infers them // automatically. - fmt.Println("keys:", MapKeys(m)) + fmt.Println("index of zoo:", SlicesIndex(s, "zoo")) // ... though we could also specify them explicitly. - _ = MapKeys[int, string](m) + _ = SlicesIndex[[]string, string](s, "zoo") lst := List[int]{} lst.Push(10) lst.Push(13) lst.Push(23) - fmt.Println("list:", lst.GetAll()) + fmt.Println("list:", lst.AllElements()) } diff --git a/examples/generics/generics.hash b/examples/generics/generics.hash index 2b23af56f..6722b2e39 100644 --- a/examples/generics/generics.hash +++ b/examples/generics/generics.hash @@ -1,2 +1,2 @@ -91465956a90881ec8b4cca3968b9aa1f6d9f1447 -uXlb-AyeYmQ +d6b4792fc509f0dcd84f15ed92097f52a73eb877 +MNfKskDAZ6d diff --git a/examples/generics/generics.sh b/examples/generics/generics.sh index 4a3f2274e..90b52a3d5 100644 --- a/examples/generics/generics.sh +++ b/examples/generics/generics.sh @@ -1,7 +1,3 @@ $ go run generics.go -keys: [4 1 2] +index of zoo: 2 list: [10 13 23] - -# Note: The order of iteration over map keys is not -# defined in Go, so different invocations may -# result in different orders. diff --git a/public/generics b/public/generics index 7dd37cac0..908131f95 100644 --- a/public/generics +++ b/public/generics @@ -45,7 +45,7 @@ @@ -62,24 +62,26 @@ @@ -155,7 +157,7 @@ parameters in place. The type is List[T], not List.

        func main() {
        -    var m = map[int]string{1: "2", 2: "4", 4: "8"}
        + var s = []string{"foo", "bar", "zoo"} @@ -163,14 +165,14 @@ parameters in place. The type is List[T], not List.

        When invoking generic functions, we can often rely on type inference. Note that we don’t have to -specify the types for K and V when -calling MapKeys - the compiler infers them +specify the types for S and E when +calling SlicesIndex - the compiler infers them automatically.

        @@ -181,7 +183,8 @@ automatically.

        @@ -244,7 +247,7 @@ result in different orders.

        From 2f31c1f6c11590790f3445a655569c62f45952f4 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 07:04:38 -0700 Subject: [PATCH 247/283] Initial example of range over custom types --- examples.txt | 1 + examples/generics/generics.hash | 4 +- .../range-over-custom-types.go | 72 ++++++ .../range-over-custom-types.hash | 2 + .../range-over-custom-types.sh | 5 + go.mod | 2 +- public/errors | 2 +- public/generics | 39 ++- public/index.html | 2 + public/range-over-custom-types | 230 ++++++++++++++++++ 10 files changed, 330 insertions(+), 29 deletions(-) create mode 100644 examples/range-over-custom-types/range-over-custom-types.go create mode 100644 examples/range-over-custom-types/range-over-custom-types.hash create mode 100644 examples/range-over-custom-types/range-over-custom-types.sh create mode 100644 public/range-over-custom-types diff --git a/examples.txt b/examples.txt index 3dc0533d8..909ed623a 100644 --- a/examples.txt +++ b/examples.txt @@ -22,6 +22,7 @@ Interfaces Enums Struct Embedding Generics +Range over Custom Types Errors Custom Errors Goroutines diff --git a/examples/generics/generics.hash b/examples/generics/generics.hash index 6722b2e39..ef92af1b8 100644 --- a/examples/generics/generics.hash +++ b/examples/generics/generics.hash @@ -1,2 +1,2 @@ -d6b4792fc509f0dcd84f15ed92097f52a73eb877 -MNfKskDAZ6d +1ad71763360077271687c5e9d147c89c0b580b0a +7v7vElzhAeO diff --git a/examples/range-over-custom-types/range-over-custom-types.go b/examples/range-over-custom-types/range-over-custom-types.go new file mode 100644 index 000000000..9d6c38aa9 --- /dev/null +++ b/examples/range-over-custom-types/range-over-custom-types.go @@ -0,0 +1,72 @@ +// Starting with version 1.23, Go has added support for +// [iterators](https://go.dev/blog/range-functions), +// which lets us range over custom types. + +package main + +import ( + "fmt" + "iter" + "slices" +) + +// Let's look at the `List` type from the +// [previous example](generics) again. In that example +// we had an `AllElements` method that returned a slice +// of all elements in the list. With Go iterators, we +// can do it better - as shown below. +type List[T any] struct { + head, tail *element[T] +} + +type element[T any] struct { + next *element[T] + val T +} + +func (lst *List[T]) Push(v T) { + if lst.tail == nil { + lst.head = &element[T]{val: v} + lst.tail = lst.head + } else { + lst.tail.next = &element[T]{val: v} + lst.tail = lst.tail.next + } +} + +// All returns an _iterator_, which in Go is a function +// with a special signature. +func (lst *List[T]) All() iter.Seq[T] { + return func(yield func(T) bool) { + // The iterator function takes another function as + // a parameter, called `yield` by convention (but + // the name can be arbitrary). It will call `yield` for + // every element we want to iterate over, and note `yield`'s + // return value for a potential early termination. + for e := lst.head; e != nil; e = e.next { + if !yield(e.val) { + return + } + } + } +} + +func main() { + lst := List[int]{} + lst.Push(10) + lst.Push(13) + lst.Push(23) + + // Since `List.All` returns an interator, it can be used + // in a regular `range` loop! + for e := range lst.All() { + fmt.Println(e) + } + + // Packages like [slices](https://pkg.go.dev/slices) have + // a number of useful functions to work with iterators. + // For example, `Collect` takes any iterator and collects + // all its values into a slice. + all := slices.Collect(lst.All()) + fmt.Println("all:", all) +} diff --git a/examples/range-over-custom-types/range-over-custom-types.hash b/examples/range-over-custom-types/range-over-custom-types.hash new file mode 100644 index 000000000..156f23aab --- /dev/null +++ b/examples/range-over-custom-types/range-over-custom-types.hash @@ -0,0 +1,2 @@ +28edd55763e81476f37e68085f5f79555c15ffe8 +Dc3AddmC8Jc diff --git a/examples/range-over-custom-types/range-over-custom-types.sh b/examples/range-over-custom-types/range-over-custom-types.sh new file mode 100644 index 000000000..cb58fdcf2 --- /dev/null +++ b/examples/range-over-custom-types/range-over-custom-types.sh @@ -0,0 +1,5 @@ +10 +13 +23 +all: [10 13 23] + diff --git a/go.mod b/go.mod index 13d697a54..abfd002be 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mmcgrana/gobyexample -go 1.22.0 +go 1.23.0 require ( github.com/alecthomas/chroma/v2 v2.10.0 diff --git a/public/errors b/public/errors index 5f49faf4f..e1e00982f 100644 --- a/public/errors +++ b/public/errors @@ -12,7 +12,7 @@ } if (e.key == "ArrowLeft") { - window.location.href = 'generics'; + window.location.href = 'range-over-custom-types'; } diff --git a/public/generics b/public/generics index 908131f95..5758c6c45 100644 --- a/public/generics +++ b/public/generics @@ -17,7 +17,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'errors'; + window.location.href = 'range-over-custom-types'; } } @@ -45,7 +45,7 @@ @@ -136,11 +136,14 @@ parameters in place. The type is List[T], not List.

        @@ -183,8 +186,7 @@ automatically.

        @@ -198,7 +200,7 @@ automatically.

        lst.Push(10) lst.Push(13) lst.Push(23) - fmt.Println("list:", lst.GetAll()) + fmt.Println("list:", lst.AllElements()) } @@ -211,32 +213,19 @@ automatically.

        - - - - - -
        -

        range iterates over elements in a variety of data -structures. Let’s see how to use range with some -of the data structures we’ve already learned.

        +

        range iterates over elements in a variety of +built-in data structures. Let’s see how to +use range with some of the data structures +we’ve already learned.

        @@ -46,7 +47,7 @@ of the data structures we’ve already learned.

        - +
        package main
        -
        $ go run range.go
        +          
        $ go run range-over-built-in-types.go
         sum: 9
         index: 1
         a -> apple
        @@ -178,7 +179,7 @@ details.

        - Next example: Functions. + Next example: Pointers.

        diff --git a/public/range-over-channels b/public/range-over-channels index 106d83bc8..9892eca32 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -30,7 +30,7 @@
        -

        In a previous example we saw how for and +

        In a previous example we saw how for and range provide iteration over basic data structures. We can also use this syntax to iterate over values received from a channel.

        @@ -47,7 +47,7 @@ values received from a channel.

        - +
        package main
        - +
        package main
        -

        As an example of a generic function, MapKeys takes -a map of any type and returns a slice of its keys. -This function has two type parameters - K and V; -K has the comparable constraint, meaning that -we can compare values of this type with the == and -!= operators. This is required for map keys in Go. -V has the any constraint, meaning that it’s not -restricted in any way (any is an alias for interface{}).

        +

        As an example of a generic function, SlicesIndex takes +a slice of any comparable type and an element of that +type and returns the index of the first occurrence of +v in s, or -1 if not present. The comparable constraint +means that we can compare values of this type with the +== and != operators. For a more thorough explanation +of this type signature, see this blog post. +Note that this function exists in the standard library +as slices.Index.

        -
        func MapKeys[K comparable, V any](m map[K]V) []K {
        -    r := make([]K, 0, len(m))
        -    for k := range m {
        -        r = append(r, k)
        +          
        func SlicesIndex[S ~[]E, E comparable](s S, v E) int {
        +    for i := range s {
        +        if v == s[i] {
        +            return i
        +        }
             }
        -    return r
        +    return -1
         }
        -
            fmt.Println("keys:", MapKeys(m))
        +
            fmt.Println("index of foo:", SlicesIndex(s, "foo"))
        -
            _ = MapKeys[int, string](m)
        +
            //_ = MapKeys[int, string](m)
        +
        - +
        package main
        - +

        AllElements returns all the List elements as a slice. +In the next example we’ll see a more idiomatic way +of iterating over all elements of custom types.

        +
        -
        func (lst *List[T]) GetAll() []T {
        +          
        func (lst *List[T]) AllElements() []T {
             var elems []T
             for e := lst.head; e != nil; e = e.next {
                 elems = append(elems, e.val)
        @@ -172,7 +175,7 @@ automatically.

        -
            fmt.Println("index of foo:", SlicesIndex(s, "foo"))
        +
            fmt.Println("index of zoo:", SlicesIndex(s, "zoo"))
        -
            //_ = MapKeys[int, string](m)
        -
        +
            _ = SlicesIndex[[]string, string](s, "zoo")
        +
        $ go run generics.go
        -keys: [4 1 2]
        +index of zoo: 2
         list: [10 13 23]
        -

        Note: The order of iteration over map keys is not -defined in Go, so different invocations may -result in different orders.

        - -
        - - -

        - Next example: Errors. + Next example: Range over Custom Types.

        @@ -247,7 +236,7 @@ result in different orders.

        diff --git a/public/index.html b/public/index.html index aa8cc7b8e..40e33b1ad 100644 --- a/public/index.html +++ b/public/index.html @@ -81,6 +81,8 @@

        Go by Example

      • Generics
      • +
      • Range over Custom Types
      • +
      • Errors
      • Custom Errors
      • diff --git a/public/range-over-custom-types b/public/range-over-custom-types new file mode 100644 index 000000000..ee763a6d2 --- /dev/null +++ b/public/range-over-custom-types @@ -0,0 +1,230 @@ + + + + + Go by Example: Range over Custom Types + + + + +
        +

        Go by Example: Range over Custom Types

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        +

        Starting with version 1.23, Go has added support for +iterators, +which lets us range over custom types.

        + +
        + + +
        + + + +
        package main
        +
        + + + +
        import (
        +    "fmt"
        +    "iter"
        +    "slices"
        +)
        +
        +

        Let’s look at the List type from the +previous example again. In that example +we had an AllElements method that returned a slice +of all elements in the list. With Go iterators, we +can do it better - as shown below.

        + +
        + +
        type List[T any] struct {
        +    head, tail *element[T]
        +}
        +
        + + + +
        type element[T any] struct {
        +    next *element[T]
        +    val  T
        +}
        +
        + + + +
        func (lst *List[T]) Push(v T) {
        +    if lst.tail == nil {
        +        lst.head = &element[T]{val: v}
        +        lst.tail = lst.head
        +    } else {
        +        lst.tail.next = &element[T]{val: v}
        +        lst.tail = lst.tail.next
        +    }
        +}
        +
        +

        All returns an iterator, which in Go is a function +with a special signature.

        + +
        + +
        func (lst *List[T]) All() iter.Seq[T] {
        +    return func(yield func(T) bool) {
        +
        +

        The iterator function takes another function as +a parameter, called yield by convention (but +the name can be arbitrary). It will call yield for +every element we want to iterate over, and note yield’s +return value for a potential early termination.

        + +
        + +
                for e := lst.head; e != nil; e = e.next {
        +            if !yield(e.val) {
        +                return
        +            }
        +        }
        +    }
        +}
        +
        + + + +
        func main() {
        +    lst := List[int]{}
        +    lst.Push(10)
        +    lst.Push(13)
        +    lst.Push(23)
        +
        +

        Since List.All returns an interator, it can be used +in a regular range loop!

        + +
        + +
            for e := range lst.All() {
        +        fmt.Println(e)
        +    }
        +
        +

        Packages like slices have +a number of useful functions to work with iterators. +For example, Collect takes any iterator and collects +all its values into a slice.

        + +
        + +
            all := slices.Collect(lst.All())
        +    fmt.Println("all:", all)
        +}
        +
        + + + + + + + + +
        + + + +
        10
        +13
        +23
        +all: [10 13 23]
        +
        + + +

        + Next example: Errors. +

        + + + + +
        + + + + From 4d27fb58cf1d593c83568ff378338852c8a9b558 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 07:15:28 -0700 Subject: [PATCH 248/283] Small tweaks to the sample --- examples/range-over-custom-types/range-over-custom-types.go | 6 +++--- .../range-over-custom-types/range-over-custom-types.hash | 4 ++-- public/range-over-custom-types | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/range-over-custom-types/range-over-custom-types.go b/examples/range-over-custom-types/range-over-custom-types.go index 9d6c38aa9..d578bc301 100644 --- a/examples/range-over-custom-types/range-over-custom-types.go +++ b/examples/range-over-custom-types/range-over-custom-types.go @@ -35,7 +35,7 @@ func (lst *List[T]) Push(v T) { } // All returns an _iterator_, which in Go is a function -// with a special signature. +// with a [special signature](https://pkg.go.dev/iter#Seq). func (lst *List[T]) All() iter.Seq[T] { return func(yield func(T) bool) { // The iterator function takes another function as @@ -57,8 +57,8 @@ func main() { lst.Push(13) lst.Push(23) - // Since `List.All` returns an interator, it can be used - // in a regular `range` loop! + // Since `List.All` returns an iterator, we can use it + // in a regular `range` loop. for e := range lst.All() { fmt.Println(e) } diff --git a/examples/range-over-custom-types/range-over-custom-types.hash b/examples/range-over-custom-types/range-over-custom-types.hash index 156f23aab..76c749245 100644 --- a/examples/range-over-custom-types/range-over-custom-types.hash +++ b/examples/range-over-custom-types/range-over-custom-types.hash @@ -1,2 +1,2 @@ -28edd55763e81476f37e68085f5f79555c15ffe8 -Dc3AddmC8Jc +3576a8e614e8e47a0541e800e017d4f9aa2504a3 +q2H-p_moUTy diff --git a/public/range-over-custom-types b/public/range-over-custom-types index ee763a6d2..ddbd0a922 100644 --- a/public/range-over-custom-types +++ b/public/range-over-custom-types @@ -46,7 +46,7 @@ which lets us range over custom types.

        - +
        package main
        @@ -116,7 +116,7 @@ can do it better - as shown below.

        All returns an iterator, which in Go is a function -with a special signature.

        +with a special signature.

        From a0e4c0787ede2189b061a9a1d9517f37a0eb73f2 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 07:27:28 -0700 Subject: [PATCH 249/283] Rename range over iterators sample and add a bit more sample --- examples.txt | 2 +- .../range-over-custom-types.hash | 2 - .../range-over-iterators.go} | 29 ++++++- .../range-over-iterators.hash | 2 + .../range-over-iterators.sh} | 6 ++ public/errors | 2 +- public/generics | 4 +- public/index.html | 2 +- ...over-custom-types => range-over-iterators} | 87 ++++++++++++++++--- 9 files changed, 117 insertions(+), 19 deletions(-) delete mode 100644 examples/range-over-custom-types/range-over-custom-types.hash rename examples/{range-over-custom-types/range-over-custom-types.go => range-over-iterators/range-over-iterators.go} (73%) create mode 100644 examples/range-over-iterators/range-over-iterators.hash rename examples/{range-over-custom-types/range-over-custom-types.sh => range-over-iterators/range-over-iterators.sh} (68%) rename public/{range-over-custom-types => range-over-iterators} (70%) diff --git a/examples.txt b/examples.txt index 909ed623a..6f44bd595 100644 --- a/examples.txt +++ b/examples.txt @@ -22,7 +22,7 @@ Interfaces Enums Struct Embedding Generics -Range over Custom Types +Range over Iterators Errors Custom Errors Goroutines diff --git a/examples/range-over-custom-types/range-over-custom-types.hash b/examples/range-over-custom-types/range-over-custom-types.hash deleted file mode 100644 index 76c749245..000000000 --- a/examples/range-over-custom-types/range-over-custom-types.hash +++ /dev/null @@ -1,2 +0,0 @@ -3576a8e614e8e47a0541e800e017d4f9aa2504a3 -q2H-p_moUTy diff --git a/examples/range-over-custom-types/range-over-custom-types.go b/examples/range-over-iterators/range-over-iterators.go similarity index 73% rename from examples/range-over-custom-types/range-over-custom-types.go rename to examples/range-over-iterators/range-over-iterators.go index d578bc301..ea9041dc8 100644 --- a/examples/range-over-custom-types/range-over-custom-types.go +++ b/examples/range-over-iterators/range-over-iterators.go @@ -1,6 +1,6 @@ // Starting with version 1.23, Go has added support for // [iterators](https://go.dev/blog/range-functions), -// which lets us range over custom types. +// which lets us range over pretty much anything! package main @@ -51,6 +51,23 @@ func (lst *List[T]) All() iter.Seq[T] { } } +// Iteration doesn't require an underlying data structure, +// and doesn't even have to be finite! Here's a function +// returning an iterator over Fibonacci numbers: it keeps +// running as long as `yield` keeps returning `true`. +func genFib() iter.Seq[int] { + return func(yield func(int) bool) { + a, b := 1, 1 + + for { + if !yield(a) { + return + } + a, b = b, a+b + } + } +} + func main() { lst := List[int]{} lst.Push(10) @@ -69,4 +86,14 @@ func main() { // all its values into a slice. all := slices.Collect(lst.All()) fmt.Println("all:", all) + + for n := range genFib() { + + // Once the loop hits `break` or an early return, the `yield` function + // passed to the iterator will return `false`. + if n >= 10 { + break + } + fmt.Println(n) + } } diff --git a/examples/range-over-iterators/range-over-iterators.hash b/examples/range-over-iterators/range-over-iterators.hash new file mode 100644 index 000000000..ee781b407 --- /dev/null +++ b/examples/range-over-iterators/range-over-iterators.hash @@ -0,0 +1,2 @@ +375f830fbe82633900d572c9077302143463a2e3 +BayyagaCK83 diff --git a/examples/range-over-custom-types/range-over-custom-types.sh b/examples/range-over-iterators/range-over-iterators.sh similarity index 68% rename from examples/range-over-custom-types/range-over-custom-types.sh rename to examples/range-over-iterators/range-over-iterators.sh index cb58fdcf2..7fa2b5918 100644 --- a/examples/range-over-custom-types/range-over-custom-types.sh +++ b/examples/range-over-iterators/range-over-iterators.sh @@ -2,4 +2,10 @@ 13 23 all: [10 13 23] +1 +1 +2 +3 +5 +8 diff --git a/public/errors b/public/errors index e1e00982f..5830d24be 100644 --- a/public/errors +++ b/public/errors @@ -12,7 +12,7 @@ } if (e.key == "ArrowLeft") { - window.location.href = 'range-over-custom-types'; + window.location.href = 'range-over-iterators'; } diff --git a/public/generics b/public/generics index 5758c6c45..a0d8bb294 100644 --- a/public/generics +++ b/public/generics @@ -17,7 +17,7 @@ if (e.key == "ArrowRight") { - window.location.href = 'range-over-custom-types'; + window.location.href = 'range-over-iterators'; } } @@ -225,7 +225,7 @@ automatically.

        - Next example: Range over Custom Types. + Next example: Range over Iterators.

        diff --git a/public/index.html b/public/index.html index 40e33b1ad..21de726ca 100644 --- a/public/index.html +++ b/public/index.html @@ -81,7 +81,7 @@

        Go by Example

      • Generics
      • -
      • Range over Custom Types
      • +
      • Range over Iterators
      • Errors
      • diff --git a/public/range-over-custom-types b/public/range-over-iterators similarity index 70% rename from public/range-over-custom-types rename to public/range-over-iterators index ddbd0a922..4cec9ff57 100644 --- a/public/range-over-custom-types +++ b/public/range-over-iterators @@ -2,7 +2,7 @@ - Go by Example: Range over Custom Types + Go by Example: Range over Iterators -
        -

        Go by Example: Range over Custom Types

        +
        +

        Go by Example: Range over Iterators

        @@ -32,7 +32,7 @@ @@ -147,6 +147,39 @@ return value for a potential early termination.

        + + + + + + + + + + - + + + + + + + + + + @@ -204,7 +263,13 @@ all its values into a slice.

        10
         13
         23
        -all: [10 13 23]
        +all: [10 13 23] +1 +1 +2 +3 +5 +8 @@ -223,7 +288,7 @@ all its values into a slice.

        From 9b3626a96902b735e406253dbe024db6f4d1c055 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 16:15:41 -0700 Subject: [PATCH 250/283] Update GH action workflow to Go 1.23 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c2f560f7f..eeff59fbb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.22.0] + go-version: [1.23.0] runs-on: ${{ matrix.os }} steps: From 9f66cb2ffd473cff6599a9955c5fc4b53c07341c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 21 Aug 2024 16:20:10 -0700 Subject: [PATCH 251/283] Update generated HTML --- examples/range-over-iterators/range-over-iterators.hash | 4 ++-- public/range-over-iterators | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/range-over-iterators/range-over-iterators.hash b/examples/range-over-iterators/range-over-iterators.hash index ee781b407..548dd0cb6 100644 --- a/examples/range-over-iterators/range-over-iterators.hash +++ b/examples/range-over-iterators/range-over-iterators.hash @@ -1,2 +1,2 @@ -375f830fbe82633900d572c9077302143463a2e3 -BayyagaCK83 +80571e7bb21ff847addac0ea92b3ddf86be86cb6 +JsdFcZac4E- diff --git a/public/range-over-iterators b/public/range-over-iterators index 4cec9ff57..586130690 100644 --- a/public/range-over-iterators +++ b/public/range-over-iterators @@ -46,7 +46,7 @@ which lets us range over pretty much anything!

        @@ -236,7 +236,7 @@ all its values into a slice.

        @@ -86,7 +86,7 @@ case 0, 1, 2 and so on.

        @@ -91,9 +91,9 @@ base case of fact(0).

        From 795124176cc36416c7bb5bdb1854f33fcc814732 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Mon, 30 Dec 2024 20:28:35 +0530 Subject: [PATCH 256/283] Added json.NewDecoder example (#566) * Update json.go adding example for json.NewDecoder * updated as per Contributings.md instructions --- examples/json/json.go | 8 ++++++++ examples/json/json.hash | 4 ++-- public/json | 24 ++++++++++++++++++++---- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/examples/json/json.go b/examples/json/json.go index 259478632..aac870e77 100644 --- a/examples/json/json.go +++ b/examples/json/json.go @@ -8,6 +8,7 @@ import ( "encoding/json" "fmt" "os" + "strings" ) // We'll use these two structs to demonstrate encoding and @@ -121,4 +122,11 @@ func main() { enc := json.NewEncoder(os.Stdout) d := map[string]int{"apple": 5, "lettuce": 7} enc.Encode(d) + + // We can also decode JSON directly from `os.Reader` + dec := json.NewDecoder(strings.NewReader(str)) + res1 := response2{} + dec.Decode(&res1) + fmt.Println(res1) + fmt.Println(res1.Fruits[1]) } diff --git a/examples/json/json.hash b/examples/json/json.hash index 60f6c01bd..6958f8dad 100644 --- a/examples/json/json.hash +++ b/examples/json/json.hash @@ -1,2 +1,2 @@ -35295476f817fe575619b6168273a29eddd7f545 -JOQpRGJWAxR +75a5664321dafe10fa623c187b90f079c5319a3c +jR7IEUPQF8T diff --git a/public/json b/public/json index b5d0f5815..55f2280ce 100644 --- a/public/json +++ b/public/json @@ -46,7 +46,7 @@ data types.

        @@ -61,6 +61,7 @@ data types.

        "encoding/json" "fmt" "os" + "strings" ) @@ -313,11 +314,26 @@ stream JSON encodings directly to os.Writers like os.Stdout or even HTTP response bodies.

        - + + + + + @@ -379,7 +395,7 @@ for more.

        From 58894bd0f4be6a55d859f652e26e2706e1cf1fdd Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 30 Dec 2024 07:03:07 -0800 Subject: [PATCH 257/283] Update text and output of json example slightly --- examples/json/json.go | 4 ++-- examples/json/json.hash | 4 ++-- examples/json/json.sh | 1 + public/json | 11 ++++++----- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/examples/json/json.go b/examples/json/json.go index aac870e77..0443d7213 100644 --- a/examples/json/json.go +++ b/examples/json/json.go @@ -123,10 +123,10 @@ func main() { d := map[string]int{"apple": 5, "lettuce": 7} enc.Encode(d) - // We can also decode JSON directly from `os.Reader` + // Streaming reads from `os.Reader`s like `os.Stdin` + // or HTTP request bodies is done with `json.Decoder`. dec := json.NewDecoder(strings.NewReader(str)) res1 := response2{} dec.Decode(&res1) fmt.Println(res1) - fmt.Println(res1.Fruits[1]) } diff --git a/examples/json/json.hash b/examples/json/json.hash index 6958f8dad..57a0e2aa6 100644 --- a/examples/json/json.hash +++ b/examples/json/json.hash @@ -1,2 +1,2 @@ -75a5664321dafe10fa623c187b90f079c5319a3c -jR7IEUPQF8T +db25fb3a8b52215441ebe0a5d6a4d4f1a8be5917 +zwf9dZ4pUPW diff --git a/examples/json/json.sh b/examples/json/json.sh index a21ef9dd3..bee89cdba 100644 --- a/examples/json/json.sh +++ b/examples/json/json.sh @@ -13,6 +13,7 @@ a {1 [apple peach]} apple {"apple":5,"lettuce":7} +{1 [apple peach]} # We've covered the basic of JSON in Go here, but check diff --git a/public/json b/public/json index 55f2280ce..b7f885547 100644 --- a/public/json +++ b/public/json @@ -46,7 +46,7 @@ data types.

        @@ -324,7 +324,8 @@ stream JSON encodings directly to os.Writers like @@ -362,7 +362,8 @@ stream JSON encodings directly to os.Writers like a {1 [apple peach]} apple -{"apple":5,"lettuce":7} +{"apple":5,"lettuce":7} +{1 [apple peach]} @@ -395,7 +396,7 @@ for more.

        From 858d4754161b75d118eaffb4cf32edb162a4b260 Mon Sep 17 00:00:00 2001 From: kevin-kho Date: Mon, 6 Jan 2025 05:40:39 -0800 Subject: [PATCH 258/283] added type assertion example (#567) * added type assertion example * simplified example --- examples/interfaces/interfaces.go | 15 +++++++++ examples/interfaces/interfaces.hash | 4 +-- examples/interfaces/interfaces.sh | 1 + public/interfaces | 52 +++++++++++++++++++++++++---- 4 files changed, 64 insertions(+), 8 deletions(-) diff --git a/examples/interfaces/interfaces.go b/examples/interfaces/interfaces.go index 806ffa7d4..26170d5a5 100644 --- a/examples/interfaces/interfaces.go +++ b/examples/interfaces/interfaces.go @@ -51,6 +51,15 @@ func measure(g geometry) { fmt.Println(g.perim()) } +// Type assertion can be performed to explicitly check the runtime type of the value. +// It allows the access of fields and methods belonging to the specific type. +// See [`switch` example](switch) for an alternative approach to handle type assertion. +func detectCircle(g geometry) { + if c, ok := g.(circle); ok { + fmt.Println(c.radius) + } +} + func main() { r := rect{width: 3, height: 4} c := circle{radius: 5} @@ -61,4 +70,10 @@ func main() { // these structs as arguments to `measure`. measure(r) measure(c) + + // `detectCircle` takes structs that satisfy the `geometry` interface + // if the struct is of type `circle`, it prints out the radius. + detectCircle(r) // doesn't print anything. + detectCircle(c) + } diff --git a/examples/interfaces/interfaces.hash b/examples/interfaces/interfaces.hash index b228f689a..535026771 100644 --- a/examples/interfaces/interfaces.hash +++ b/examples/interfaces/interfaces.hash @@ -1,2 +1,2 @@ -d4ea9541521cfee94107ba9331d0dabb1f9f16c1 -XJASG4MxBQr +9a362e2c9aed98013fa9b91af81d6cc373979db6 +tfsLP7R0dtH diff --git a/examples/interfaces/interfaces.sh b/examples/interfaces/interfaces.sh index b71147638..b87092729 100644 --- a/examples/interfaces/interfaces.sh +++ b/examples/interfaces/interfaces.sh @@ -5,6 +5,7 @@ $ go run interfaces.go {5} 78.53981633974483 31.41592653589793 +5 # To learn more about Go's interfaces, check out this # [great blog post](https://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go). diff --git a/public/interfaces b/public/interfaces index 15a381113..9e02f1a36 100644 --- a/public/interfaces +++ b/public/interfaces @@ -45,7 +45,7 @@ signatures.

        @@ -146,6 +146,23 @@ to work on any geometry.

        + + + + + - + + + + + + + + + + @@ -190,7 +229,8 @@ these structs as arguments to measure.

        14 {5} 78.53981633974483 -31.41592653589793 +31.41592653589793 +5 @@ -221,7 +261,7 @@ these structs as arguments to measure.

        From ad9cea3a5434cf85f3bb14070ff1282d82269be9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 6 Jan 2025 05:47:45 -0800 Subject: [PATCH 259/283] Tweak interface example type assertion + update link --- examples/interfaces/interfaces.go | 13 +++++------ examples/interfaces/interfaces.hash | 4 ++-- examples/interfaces/interfaces.sh | 6 ++--- public/interfaces | 35 ++++++++++------------------- 4 files changed, 22 insertions(+), 36 deletions(-) diff --git a/examples/interfaces/interfaces.go b/examples/interfaces/interfaces.go index 26170d5a5..b6844f376 100644 --- a/examples/interfaces/interfaces.go +++ b/examples/interfaces/interfaces.go @@ -51,12 +51,12 @@ func measure(g geometry) { fmt.Println(g.perim()) } -// Type assertion can be performed to explicitly check the runtime type of the value. -// It allows the access of fields and methods belonging to the specific type. -// See [`switch` example](switch) for an alternative approach to handle type assertion. +// Sometimes it's useful to know the runtime type of an +// interface value. One option is using a *type assertion* +// as shown here; another is a [type `switch`](switch). func detectCircle(g geometry) { if c, ok := g.(circle); ok { - fmt.Println(c.radius) + fmt.Println("circle with radius", c.radius) } } @@ -71,9 +71,6 @@ func main() { measure(r) measure(c) - // `detectCircle` takes structs that satisfy the `geometry` interface - // if the struct is of type `circle`, it prints out the radius. - detectCircle(r) // doesn't print anything. + detectCircle(r) detectCircle(c) - } diff --git a/examples/interfaces/interfaces.hash b/examples/interfaces/interfaces.hash index 535026771..4d07d2c3f 100644 --- a/examples/interfaces/interfaces.hash +++ b/examples/interfaces/interfaces.hash @@ -1,2 +1,2 @@ -9a362e2c9aed98013fa9b91af81d6cc373979db6 -tfsLP7R0dtH +6324a4bdb756a0ec2ccc60e13c97d2650e730ed6 +xAAbgd7GOKD diff --git a/examples/interfaces/interfaces.sh b/examples/interfaces/interfaces.sh index b87092729..a67a8b14c 100644 --- a/examples/interfaces/interfaces.sh +++ b/examples/interfaces/interfaces.sh @@ -5,7 +5,7 @@ $ go run interfaces.go {5} 78.53981633974483 31.41592653589793 -5 +circle with radius 5 -# To learn more about Go's interfaces, check out this -# [great blog post](https://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go). +# To understand how Go's interfaces work under the hood, +# check out this [blog post](https://research.swtch.com/interfaces). diff --git a/public/interfaces b/public/interfaces index 9e02f1a36..cd8daed03 100644 --- a/public/interfaces +++ b/public/interfaces @@ -45,7 +45,7 @@ signatures.

        @@ -148,16 +148,16 @@ to work on any geometry.

        @@ -190,26 +190,15 @@ these structs as arguments to measure.

        - - - - - @@ -230,14 +219,14 @@ if the struct is of type circle, it prints out the radius.

        {5} 78.53981633974483 31.41592653589793 -5 +circle with radius 5 @@ -162,7 +162,7 @@ current cursor position,

        @@ -174,7 +174,7 @@ current cursor position,

        @@ -290,7 +290,7 @@ be scheduled immediately after Opening with From 9f92e064a170f351f0578d416c4440dd9781fc4a Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 29 Jan 2025 05:39:08 -0800 Subject: [PATCH 262/283] Clean up the defer example a bit --- examples/defer/defer.go | 4 +--- examples/defer/defer.hash | 4 ++-- public/defer | 20 +++++--------------- 3 files changed, 8 insertions(+), 20 deletions(-) diff --git a/examples/defer/defer.go b/examples/defer/defer.go index b4077c7b8..58836bc07 100644 --- a/examples/defer/defer.go +++ b/examples/defer/defer.go @@ -37,7 +37,6 @@ func createFile(p string) *os.File { func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data") - } func closeFile(f *os.File) { @@ -46,7 +45,6 @@ func closeFile(f *os.File) { // It's important to check for errors when closing a // file, even in a deferred function. if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) + panic(err) } } diff --git a/examples/defer/defer.hash b/examples/defer/defer.hash index de9f4dad0..662ed7a0f 100644 --- a/examples/defer/defer.hash +++ b/examples/defer/defer.hash @@ -1,2 +1,2 @@ -f0eb978a0cdbacc5e4d709bccce6cea6b71be39f -5SDVfc_jxbg +249d0bc915e075a664be8b4e9115aa9568c8999e +nhAzhDn_jga diff --git a/public/defer b/public/defer index 51a08a7a7..125f87fb8 100644 --- a/public/defer +++ b/public/defer @@ -47,7 +47,7 @@ purposes of cleanup. defer is often used where e.g. @@ -121,17 +121,8 @@ of the enclosing function (main), after
        func writeFile(f *os.File) {
             fmt.Println("writing")
        -    fmt.Fprintln(f, "data")
        - - - - - - @@ -156,8 +147,7 @@ file, even in a deferred function.

        @@ -197,7 +187,7 @@ after being written.

        From a0afe45ff3ec13349bbb4556fa7c7e3a2403ea3e Mon Sep 17 00:00:00 2001 From: hudem1 <55464342+hudem1@users.noreply.github.com> Date: Sat, 8 Feb 2025 23:47:55 +0100 Subject: [PATCH 263/283] clarify a comment w.r.t. empty slice (#571) * fix: Added go for routines - Correct doc * fix: applied PR reviews * fix: build file --- examples/slices/slices.go | 2 +- examples/slices/slices.hash | 4 ++-- public/slices | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/slices/slices.go b/examples/slices/slices.go index 541b582b3..ea8cad2fe 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -17,7 +17,7 @@ func main() { var s []string fmt.Println("uninit:", s, s == nil, len(s) == 0) - // To create an empty slice with non-zero length, use + // To create a slice with non-zero length, use // the builtin `make`. Here we make a slice of // `string`s of length `3` (initially zero-valued). // By default a new slice's capacity is equal to its diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index e671db628..6085ebcb5 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -522c14373ae9581dd3001be32530cdf940637646 -kiy1StxorBF +891d4ef82ef90184a5e1f0f24b6cb2fcc2f58e6e +L9rtMOCQOVn diff --git a/public/slices b/public/slices index 37fcd989f..6cc2c5e35 100644 --- a/public/slices +++ b/public/slices @@ -45,7 +45,7 @@ a more powerful interface to sequences than arrays.

        @@ -90,7 +90,7 @@ length 0.

        @@ -143,7 +143,7 @@ walks over them and performs the test logic.

        @@ -266,7 +267,7 @@ benchmark function names with a regexp.

        From d393387262db53c5af8a81bc2a644b844b9a282b Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 13 May 2025 05:35:37 -0700 Subject: [PATCH 267/283] Fix link to http-server from context.go Also rename .hash file for consistency Fixes #603 --- examples/context/context.go | 2 +- examples/context/context.hash | 4 ++-- examples/http-server/{http-servers.hash => http-server.hash} | 0 public/context | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) rename examples/http-server/{http-servers.hash => http-server.hash} (100%) diff --git a/examples/context/context.go b/examples/context/context.go index ae519804e..dc2957a64 100644 --- a/examples/context/context.go +++ b/examples/context/context.go @@ -1,5 +1,5 @@ // In the previous example we looked at setting up a simple -// [HTTP server](http-servers). HTTP servers are useful for +// [HTTP server](http-server). HTTP servers are useful for // demonstrating the usage of `context.Context` for // controlling cancellation. A `Context` carries deadlines, // cancellation signals, and other request-scoped values diff --git a/examples/context/context.hash b/examples/context/context.hash index c4604b666..451cd796a 100644 --- a/examples/context/context.hash +++ b/examples/context/context.hash @@ -1,2 +1,2 @@ -a9537bfea55bca15d8db1c453e2d9852f9d447e1 -0_bu1o8rIBO +94a35a6172346b56737ed907a2320bd30f98995d +7G1TlQrnbF1 diff --git a/examples/http-server/http-servers.hash b/examples/http-server/http-server.hash similarity index 100% rename from examples/http-server/http-servers.hash rename to examples/http-server/http-server.hash diff --git a/public/context b/public/context index 134804efd..8e664b517 100644 --- a/public/context +++ b/public/context @@ -31,7 +31,7 @@ From 7f3bbdab22fb19e2ea52831a1d47e6fd0b40a0d9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 13 May 2025 05:42:49 -0700 Subject: [PATCH 268/283] Rename .hash file for consistency Fixes #593 --- examples/http-client/{http-clients.hash => http-client.hash} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename examples/http-client/{http-clients.hash => http-client.hash} (100%) diff --git a/examples/http-client/http-clients.hash b/examples/http-client/http-client.hash similarity index 100% rename from examples/http-client/http-clients.hash rename to examples/http-client/http-client.hash From b7838276041c4f028ccd460d71f0352b333e5cf9 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Tue, 13 May 2025 05:44:38 -0700 Subject: [PATCH 269/283] Remove broken translation links Fixes #587 --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index ddfa1d3bb..467da2a14 100644 --- a/README.md +++ b/README.md @@ -65,13 +65,11 @@ Contributor translations of the Go by Example site are available in: * [Chinese](https://gobyexample-cn.github.io/) by [gobyexample-cn](https://github.com/gobyexample-cn) * [French](http://le-go-par-l-exemple.keiruaprod.fr) by [keirua](https://github.com/keirua/gobyexample) -* [Italian](https://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) * [Ukrainian](https://butuzov.github.io/gobyexample/) by [butuzov](https://github.com/butuzov/gobyexample) * [Brazilian Portuguese](https://lcslitx.github.io/GoEmExemplos/) by [lcslitx](https://github.com/LCSLITX) -* [Vietnamese](https://gobyexample.vn/) by [s6k Gopher](https://github.com/s6k-gopher/gobyexample-vn) * [Burmese](https://setkyar.github.io/gobyexample) by [Set Kyar Wa Lar](https://github.com/setkyar/gobyexample) ### Thanks From bd94e3e926df722b3ad461a39c14854121a0acd4 Mon Sep 17 00:00:00 2001 From: Asutosh Padhi <49114164+asutosh2203@users.noreply.github.com> Date: Sat, 17 May 2025 07:32:15 +0530 Subject: [PATCH 270/283] =?UTF-8?q?Fix=20incorrect=20comment=20style=20in?= =?UTF-8?q?=20timers.sh=20(//=20=E2=86=92=20#)=20(#605)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #604 --- examples/timers/timers.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/timers/timers.sh b/examples/timers/timers.sh index 4f62fbdb6..0446efef3 100644 --- a/examples/timers/timers.sh +++ b/examples/timers/timers.sh @@ -1,6 +1,6 @@ -// The first timer will fire ~2s after we start the -// program, but the second should be stopped before it has -// a chance to fire. +# The first timer will fire ~2s after we start the +# program, but the second should be stopped before it has +# a chance to fire. $ go run timers.go Timer 1 fired Timer 2 stopped From 10aea2d282d3a9fea527e89c34430fca3e892da8 Mon Sep 17 00:00:00 2001 From: Matt Nathan Date: Mon, 2 Jun 2025 16:27:06 +0100 Subject: [PATCH 271/283] Replace for ;; with for range int in all examples (#609) This to be more idiomatic of Go since it was introduced. --- examples/arrays/arrays.go | 4 ++-- examples/arrays/arrays.hash | 4 ++-- examples/atomic-counters/atomic-counters.go | 4 ++-- examples/atomic-counters/atomic-counters.hash | 4 ++-- examples/goroutines/goroutines.go | 2 +- examples/goroutines/goroutines.hash | 4 ++-- examples/mutexes/mutexes.go | 2 +- examples/mutexes/mutexes.hash | 4 ++-- examples/rate-limiting/rate-limiting.go | 2 +- examples/rate-limiting/rate-limiting.hash | 4 ++-- examples/select/select.go | 2 +- examples/select/select.hash | 4 ++-- examples/slices/slices.go | 4 ++-- examples/slices/slices.hash | 4 ++-- examples/stateful-goroutines/stateful-goroutines.go | 4 ++-- examples/stateful-goroutines/stateful-goroutines.hash | 4 ++-- public/arrays | 8 ++++---- public/atomic-counters | 8 ++++---- public/goroutines | 6 +++--- public/mutexes | 6 +++--- public/rate-limiting | 6 +++--- public/select | 6 +++--- public/slices | 8 ++++---- public/stateful-goroutines | 8 ++++---- 24 files changed, 56 insertions(+), 56 deletions(-) diff --git a/examples/arrays/arrays.go b/examples/arrays/arrays.go index 06b4c17b2..90cfad652 100644 --- a/examples/arrays/arrays.go +++ b/examples/arrays/arrays.go @@ -45,8 +45,8 @@ func main() { // compose types to build multi-dimensional data // structures. var twoD [2][3]int - for i := 0; i < 2; i++ { - for j := 0; j < 3; j++ { + for i := range 2 { + for j := range 3 { twoD[i][j] = i + j } } diff --git a/examples/arrays/arrays.hash b/examples/arrays/arrays.hash index 12253ebfc..3107734ed 100644 --- a/examples/arrays/arrays.hash +++ b/examples/arrays/arrays.hash @@ -1,2 +1,2 @@ -789f9faa91c359e5337ace4f80b38428f39d4e7b -zVIFeNnUdwv +96cbe484a18a0dd8c1839a92963447bed94cc997 +-NFSggT7dFH diff --git a/examples/atomic-counters/atomic-counters.go b/examples/atomic-counters/atomic-counters.go index 01d411546..cefb870a5 100644 --- a/examples/atomic-counters/atomic-counters.go +++ b/examples/atomic-counters/atomic-counters.go @@ -25,11 +25,11 @@ func main() { // We'll start 50 goroutines that each increment the // counter exactly 1000 times. - for i := 0; i < 50; i++ { + for range 50 { wg.Add(1) go func() { - for c := 0; c < 1000; c++ { + for range 1000 { // To atomically increment the counter we use `Add`. ops.Add(1) diff --git a/examples/atomic-counters/atomic-counters.hash b/examples/atomic-counters/atomic-counters.hash index 76cc67cb6..bec0b661a 100644 --- a/examples/atomic-counters/atomic-counters.hash +++ b/examples/atomic-counters/atomic-counters.hash @@ -1,2 +1,2 @@ -3435537238237eb363f652dddb405788fec98c8b -HWE6h4-y-Fw +cb0a6d420c43d4d3128266738622a6a45b56bcfd +MmpbKHe1ldr diff --git a/examples/goroutines/goroutines.go b/examples/goroutines/goroutines.go index 4943ec93f..2b9e26c1e 100644 --- a/examples/goroutines/goroutines.go +++ b/examples/goroutines/goroutines.go @@ -8,7 +8,7 @@ import ( ) func f(from string) { - for i := 0; i < 3; i++ { + for i := range 3 { fmt.Println(from, ":", i) } } diff --git a/examples/goroutines/goroutines.hash b/examples/goroutines/goroutines.hash index 63a8b2c4a..7ea80e0b6 100644 --- a/examples/goroutines/goroutines.hash +++ b/examples/goroutines/goroutines.hash @@ -1,2 +1,2 @@ -08aa2b9e426724e07ec83162eb6892648ccc7fd5 -I7scqRijEJt +b7455068d7f944d7c1a2764e5ec05bee53296e62 +0fx_WokYVFO diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index 5992881fb..c373b0faa 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -42,7 +42,7 @@ func main() { // This function increments a named counter // in a loop. doIncrement := func(name string, n int) { - for i := 0; i < n; i++ { + for range n { c.inc(name) } wg.Done() diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 043180976..4bd883114 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -d858d466e806a9dcb5992c8c2a3c6dc377a7a904 -JU735qy2UmB +1c56c75162419ced8437b7ebe53ee65e5479f645 +CawzyQnvH6W diff --git a/examples/rate-limiting/rate-limiting.go b/examples/rate-limiting/rate-limiting.go index f1e84c1c1..64ea99697 100644 --- a/examples/rate-limiting/rate-limiting.go +++ b/examples/rate-limiting/rate-limiting.go @@ -44,7 +44,7 @@ func main() { burstyLimiter := make(chan time.Time, 3) // Fill up the channel to represent allowed bursting. - for i := 0; i < 3; i++ { + for range 3 { burstyLimiter <- time.Now() } diff --git a/examples/rate-limiting/rate-limiting.hash b/examples/rate-limiting/rate-limiting.hash index 3b6573225..cefddcbee 100644 --- a/examples/rate-limiting/rate-limiting.hash +++ b/examples/rate-limiting/rate-limiting.hash @@ -1,2 +1,2 @@ -4f327f5bd5ac199ae5590652563ea6ca4ce7eff5 -lqf7pC2FUeT +c1eee474067ad718e57df5c55242ba4711e7bcb7 +y9V3goQfy5m diff --git a/examples/select/select.go b/examples/select/select.go index d2ce16e5a..f313bb85c 100644 --- a/examples/select/select.go +++ b/examples/select/select.go @@ -29,7 +29,7 @@ func main() { // We'll use `select` to await both of these values // simultaneously, printing each one as it arrives. - for i := 0; i < 2; i++ { + for range 2 { select { case msg1 := <-c1: fmt.Println("received", msg1) diff --git a/examples/select/select.hash b/examples/select/select.hash index e18682219..a3213c304 100644 --- a/examples/select/select.hash +++ b/examples/select/select.hash @@ -1,2 +1,2 @@ -33fe111b666efb3243c9cbd0ba12b2e795d90fab -FzONhs4-tae +b10a3f618c232683fba207e56e4b4cda812fd377 +dOrjUfgGwB2 diff --git a/examples/slices/slices.go b/examples/slices/slices.go index ea8cad2fe..e9939eddb 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -84,10 +84,10 @@ func main() { // structures. The length of the inner slices can // vary, unlike with multi-dimensional arrays. twoD := make([][]int, 3) - for i := 0; i < 3; i++ { + for i := range 3 { innerLen := i + 1 twoD[i] = make([]int, innerLen) - for j := 0; j < innerLen; j++ { + for j := range innerLen { twoD[i][j] = i + j } } diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index 6085ebcb5..1664e33be 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -891d4ef82ef90184a5e1f0f24b6cb2fcc2f58e6e -L9rtMOCQOVn +4db1907fd5137325a1e3c3fc50950d4250ed1a4b +9-U3-8sKQun diff --git a/examples/stateful-goroutines/stateful-goroutines.go b/examples/stateful-goroutines/stateful-goroutines.go index 11a6f088d..b09357018 100644 --- a/examples/stateful-goroutines/stateful-goroutines.go +++ b/examples/stateful-goroutines/stateful-goroutines.go @@ -73,7 +73,7 @@ func main() { // Each read requires constructing a `readOp`, sending // it over the `reads` channel, and then receiving the // result over the provided `resp` channel. - for r := 0; r < 100; r++ { + for range 100 { go func() { for { read := readOp{ @@ -89,7 +89,7 @@ func main() { // We start 10 writes as well, using a similar // approach. - for w := 0; w < 10; w++ { + for range 10 { go func() { for { write := writeOp{ diff --git a/examples/stateful-goroutines/stateful-goroutines.hash b/examples/stateful-goroutines/stateful-goroutines.hash index 0ed448fc6..fc4958793 100644 --- a/examples/stateful-goroutines/stateful-goroutines.hash +++ b/examples/stateful-goroutines/stateful-goroutines.hash @@ -1,2 +1,2 @@ -04a59d09868df58e9edf5930d38efd25cbb92861 -TBcWd-OfnaA +ae1a9ffac4407f564ae1458f2464d3c87deaf2df +uX6AcrTXA-a diff --git a/public/arrays b/public/arrays index b19bc52f2..45614324a 100644 --- a/public/arrays +++ b/public/arrays @@ -47,7 +47,7 @@ scenarios.

        @@ -162,8 +162,8 @@ structures.

        @@ -110,7 +110,7 @@ counter exactly 1000 times.

        @@ -122,7 +122,7 @@ counter exactly 1000 times.

        @@ -224,7 +224,7 @@ state.

        diff --git a/public/goroutines b/public/goroutines index 6bdc52634..f062fa809 100644 --- a/public/goroutines +++ b/public/goroutines @@ -44,7 +44,7 @@ @@ -69,7 +69,7 @@ @@ -153,7 +153,7 @@ in a loop.

        @@ -145,7 +145,7 @@ channel will allow bursts of up to 3 events.

        @@ -242,7 +242,7 @@ then serve the remaining 2 with ~200ms delays each.

        diff --git a/public/select b/public/select index a3bf62244..2d5bd39a3 100644 --- a/public/select +++ b/public/select @@ -46,7 +46,7 @@ select is a powerful feature of Go.

        @@ -114,7 +114,7 @@ simultaneously, printing each one as it arrives.

        @@ -241,10 +241,10 @@ vary, unlike with multi-dimensional arrays.

        @@ -174,7 +174,7 @@ result over the provided resp channel.

        @@ -91,7 +91,7 @@ it a lot below.

        Here’s a sample of the functions available in strings. Since these are functions from the package, not methods on the string object itself, -we need pass the string in question as the first +we need to pass the string in question as the first argument to the function. You can find more functions in the strings package docs.

        From 0d3b379224f69a9b6f459d9695de212acbb78596 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 13 Aug 2025 06:32:29 -0700 Subject: [PATCH 273/283] Update go to 1.25.0 in go.mod --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 8940fc0a0..2a007dafe 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mmcgrana/gobyexample -go 1.24.0 +go 1.25.0 require ( github.com/alecthomas/chroma/v2 v2.10.0 From 4035ec4127feaee975ae4b62a0a83a00f405772a Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 13 Aug 2025 06:46:13 -0700 Subject: [PATCH 274/283] Update waitgroups sample to use the new WaitGroup.Go --- examples/waitgroups/waitgroups.go | 19 ++++++------------ examples/waitgroups/waitgroups.hash | 4 ++-- public/waitgroups | 31 ++++++++--------------------- 3 files changed, 16 insertions(+), 38 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index a8a446a2d..588c4f83c 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -25,23 +25,16 @@ func main() { // explicitly passed into functions, it should be done *by pointer*. var wg sync.WaitGroup - // Launch several goroutines and increment the WaitGroup - // counter for each. + // Launch several goroutines using `WaitGroup.Go` for i := 1; i <= 5; i++ { - wg.Add(1) - - // Wrap the worker call in a closure that makes sure to tell - // the WaitGroup that this worker is done. This way the worker - // itself does not have to be aware of the concurrency primitives - // involved in its execution. - go func() { - defer wg.Done() + wg.Go(func() { worker(i) - }() + }) } - // Block until the WaitGroup counter goes back to 0; - // all the workers notified they're done. + // Block until all the goroutines started by `wg` are + // done. A goroutine is done when the function it invokes + // returns. wg.Wait() // Note that this approach has no straightforward way diff --git a/examples/waitgroups/waitgroups.hash b/examples/waitgroups/waitgroups.hash index 5dc808bec..890450a93 100644 --- a/examples/waitgroups/waitgroups.hash +++ b/examples/waitgroups/waitgroups.hash @@ -1,2 +1,2 @@ -c81a54fed0cd96464456e05b46163329eb7c958b -fC_Chrkb5uA +97b564243e41a3a86f8c8417268fa942c05d881f +csaELahJTWt diff --git a/public/waitgroups b/public/waitgroups index 97d0ee270..80919f1e9 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -45,7 +45,7 @@ use a wait group.

        @@ -114,39 +114,24 @@ explicitly passed into functions, it should be done by pointer.

        - - - - - @@ -156,7 +156,6 @@ in a loop.

        for range n { c.inc(name) } - wg.Done() } @@ -170,10 +169,33 @@ and two of them access the same counter.

        + + + + + + + + + + @@ -234,7 +256,7 @@ management task using only goroutines and channels.

        From 12661f58a2668415a6d1d2a75ca8b15b24124142 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 8 Sep 2025 06:54:12 -0700 Subject: [PATCH 278/283] Update Go version to 1.25.1 in CI and go.mod --- .github/workflows/test.yml | 2 +- go.mod | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index eeff59fbb..929bee42b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go-version: [1.23.0] + go-version: [1.25.1] runs-on: ${{ matrix.os }} steps: diff --git a/go.mod b/go.mod index 2a007dafe..48a2259c8 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mmcgrana/gobyexample -go 1.25.0 +go 1.25.1 require ( github.com/alecthomas/chroma/v2 v2.10.0 From 8590989b27ea562ce4e7a57ed252651b1287cda0 Mon Sep 17 00:00:00 2001 From: Andrea Raponi Date: Fri, 26 Sep 2025 14:42:08 +0200 Subject: [PATCH 279/283] Add Italian translation link to README (#624) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 467da2a14..e525f636b 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ Contributor translations of the Go by Example site are available in: * [Chinese](https://gobyexample-cn.github.io/) by [gobyexample-cn](https://github.com/gobyexample-cn) * [French](http://le-go-par-l-exemple.keiruaprod.fr) by [keirua](https://github.com/keirua/gobyexample) +* [Italian](https://gobyexampleit.andrearaponi.it/) by [andrearaponi](https://github.com/andrearaponi/gobyexample-it) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus) From d2eea4102a7d56f58aa7187cd00919f9a29fa028 Mon Sep 17 00:00:00 2001 From: Oleh Baibula <119193741+obaibula@users.noreply.github.com> Date: Tue, 30 Sep 2025 00:18:54 +0300 Subject: [PATCH 280/283] Improve Spawning Processes, using errors.As (#625) --- .../spawning-processes/spawning-processes.go | 12 ++++++++---- .../spawning-processes/spawning-processes.hash | 4 ++-- public/spawning-processes | 16 ++++++++++------ 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/examples/spawning-processes/spawning-processes.go b/examples/spawning-processes/spawning-processes.go index 891c21f3e..a0374f01d 100644 --- a/examples/spawning-processes/spawning-processes.go +++ b/examples/spawning-processes/spawning-processes.go @@ -4,6 +4,7 @@ package main import ( + "errors" "fmt" "io" "os/exec" @@ -35,11 +36,14 @@ func main() { // code. _, err = exec.Command("date", "-x").Output() if err != nil { - switch e := err.(type) { - case *exec.Error: + var execErr *exec.Error + var exitErr *exec.ExitError + switch { + case errors.As(err, &execErr): fmt.Println("failed executing:", err) - case *exec.ExitError: - fmt.Println("command exit rc =", e.ExitCode()) + case errors.As(err, &exitErr): + exitCode := exitErr.ExitCode() + fmt.Println("command exit rc =", exitCode) default: panic(err) } diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index 011964455..af4ec3ac8 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -5303cfb969de556a875db17972b4107b6f70ba10 -rmnQdR-dMWU +3020b65601d80e67c575785c8d2616163a0423a5 +uOmOn18nMDw diff --git a/public/spawning-processes b/public/spawning-processes index e22e71a12..a75d8f7d1 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -45,7 +45,7 @@ processes.

        @@ -57,6 +57,7 @@ processes.

        diff --git a/public/errors b/public/errors index fbd6816f1..ea56d1f4e 100644 --- a/public/errors +++ b/public/errors @@ -32,11 +32,11 @@ @@ -170,7 +170,7 @@ and errors.As.

        diff --git a/public/spawning-processes b/public/spawning-processes index a75d8f7d1..4ea960918 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -30,7 +30,7 @@ @@ -45,7 +45,7 @@ processes.

        From e263c6bbd304feb25671fa1f273bdcd2a037598c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 6 Oct 2025 05:56:05 -0700 Subject: [PATCH 282/283] Slighly clarify channel-synchronization comment Fixes #626 --- examples/channel-synchronization/channel-synchronization.sh | 6 +++--- public/channel-synchronization | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/channel-synchronization/channel-synchronization.sh b/examples/channel-synchronization/channel-synchronization.sh index b3496b309..51ca2bd67 100644 --- a/examples/channel-synchronization/channel-synchronization.sh +++ b/examples/channel-synchronization/channel-synchronization.sh @@ -1,6 +1,6 @@ $ go run channel-synchronization.go working...done -# If you removed the `<- done` line from this program, the -# program would exit before the `worker` even -# started. +# If you removed the `<- done` line from this program, +# the program could exit before the `worker` finished +# its work, or in some cases even before it started. diff --git a/public/channel-synchronization b/public/channel-synchronization index f10341e43..5938104b4 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -147,9 +147,9 @@ worker on the channel.

        @@ -120,8 +120,8 @@ signify a specific error condition.

        @@ -266,7 +266,7 @@ errors in a chain of errors.

        Starting with version 1.23, Go has added support for iterators, -which lets us range over custom types.

        +which lets us range over pretty much anything!

        @@ -46,7 +46,7 @@ which lets us range over custom types.

        - +
        package main
        +

        Iteration doesn’t require an underlying data structure, +and doesn’t even have to be finite! Here’s a function +returning an iterator over Fibonacci numbers: it keeps +running as long as yield keeps returning true.

        + +
        + +
        func genFib() iter.Seq[int] {
        +    return func(yield func(int) bool) {
        +        a, b := 1, 1
        +
        + + + +
                for {
        +            if !yield(a) {
        +                return
        +            }
        +            a, b = b, a+b
        +        }
        +    }
        +}
        +
        @@ -163,8 +196,8 @@ return value for a potential early termination.

        -

        Since List.All returns an interator, it can be used -in a regular range loop!

        +

        Since List.All returns an iterator, we can use it +in a regular range loop.

        @@ -183,10 +216,36 @@ For example, Collect takes any iterator and collects all its values into a slice.

        +
            all := slices.Collect(lst.All())
        -    fmt.Println("all:", all)
        +    fmt.Println("all:", all)
        +
        + + + +
            for n := range genFib() {
        +
        +

        Once the loop hits break or an early return, the yield function +passed to the iterator will return false, stopping the iterator.

        + +
        + +
                if n >= 10 {
        +            break
        +        }
        +        fmt.Println(n)
        +    }
         }
        - +
        package main

        Once the loop hits break or an early return, the yield function -passed to the iterator will return false, stopping the iterator.

        +passed to the iterator will return false.

        From 17b2ecf8d78df017396ccbf9e9444e0fd86ef794 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Wed, 11 Sep 2024 10:48:28 -0700 Subject: [PATCH 252/283] Add type to const definitions for enum values Fixes #552 --- examples/enums/enums.go | 2 +- examples/enums/enums.hash | 4 ++-- public/enums | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/enums/enums.go b/examples/enums/enums.go index 6c516453c..c0cf90c42 100644 --- a/examples/enums/enums.go +++ b/examples/enums/enums.go @@ -17,7 +17,7 @@ type ServerState int // generates successive constant values automatically; in this // case 0, 1, 2 and so on. const ( - StateIdle = iota + StateIdle ServerState = iota StateConnected StateError StateRetrying diff --git a/examples/enums/enums.hash b/examples/enums/enums.hash index 311d55424..cc85b6a8e 100644 --- a/examples/enums/enums.hash +++ b/examples/enums/enums.hash @@ -1,2 +1,2 @@ -097dc14a53f63735563f6f75314c30908aa46748 -3zjUiM66KZe +ee42927ee1c864794570e23e8dadb2d20d64a4fd +prQMptP_p1s diff --git a/public/enums b/public/enums index 1b8f390ed..7eeee1a2e 100644 --- a/public/enums +++ b/public/enums @@ -49,7 +49,7 @@ are simple to implement using existing language idioms.

        - +
        package main
        const (
        -    StateIdle = iota
        +    StateIdle ServerState = iota
             StateConnected
             StateError
             StateRetrying
        @@ -223,7 +223,7 @@ determine the next state…

        From 78ecc3f8c142ed33f500273458ef315a9a33d34b Mon Sep 17 00:00:00 2001 From: wwwstephen Date: Mon, 23 Sep 2024 14:00:36 +0100 Subject: [PATCH 253/283] Correct inaccuracy in recursion description. (#554) --- examples/recursion/recursion.go | 6 +++--- examples/recursion/recursion.hash | 4 ++-- public/recursion | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/recursion/recursion.go b/examples/recursion/recursion.go index b85deb882..17d9c1dce 100644 --- a/examples/recursion/recursion.go +++ b/examples/recursion/recursion.go @@ -18,9 +18,9 @@ func fact(n int) int { func main() { fmt.Println(fact(7)) - // Closures can also be recursive, but this requires the - // closure to be declared with a typed `var` explicitly - // before it's defined. + // Anonymous functions can also be recursive, but this requires + // explicitly declaring a variable with `var` to store + // the function before it's defined. var fib func(n int) int fib = func(n int) int { diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index 7237c6a7b..832d7fc9b 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -cdbd1a6957b3e2d7d9baa9efe4581ba4f8f3e753 -MBTKk9VpAiK +5787b4a187dc208dcdae43c7fdc0ba19b821ed94 +k4IRATLn9cE diff --git a/public/recursion b/public/recursion index bb53831b9..887189419 100644 --- a/public/recursion +++ b/public/recursion @@ -46,7 +46,7 @@ Here’s a classic example.

        - +
        package main
        -

        Closures can also be recursive, but this requires the -closure to be declared with a typed var explicitly -before it’s defined.

        +

        Anonymous functions can also be recursive, but this requires +explicitly declaring a variable with var to store +the function before it’s defined.

        From 81ec07ea0a54f796ddad768c0108394d467687e8 Mon Sep 17 00:00:00 2001 From: wwwstephen Date: Mon, 23 Sep 2024 21:33:02 +0100 Subject: [PATCH 254/283] Correct inaccuracy in recursion description. (#555) Co-authored-by: Eli Bendersky --- examples/range-over-iterators/range-over-iterators.sh | 1 + public/range-over-iterators | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/range-over-iterators/range-over-iterators.sh b/examples/range-over-iterators/range-over-iterators.sh index 7fa2b5918..e717d5594 100644 --- a/examples/range-over-iterators/range-over-iterators.sh +++ b/examples/range-over-iterators/range-over-iterators.sh @@ -1,3 +1,4 @@ +$ go run range-over-iterators.go 10 13 23 diff --git a/public/range-over-iterators b/public/range-over-iterators index 586130690..d8fac9471 100644 --- a/public/range-over-iterators +++ b/public/range-over-iterators @@ -260,7 +260,8 @@ passed to the iterator will return false.

        -
        10
        +          
        $ go run range-over-iterators.go
        +10
         13
         23
         all: [10 13 23]
        
        From bc680ed6b2a7b2fab8a511242cccfdbc5a78b100 Mon Sep 17 00:00:00 2001
        From: =?UTF-8?q?Marek=20Fur=C3=A1k?=
         <38523093+mfurak@users.noreply.github.com>
        Date: Mon, 4 Nov 2024 13:03:43 +0000
        Subject: [PATCH 255/283] Fix http-server filename (#559)
        
        * Fix filename for running the http-server example
        
        * Generate the fixed HTML
        ---
         examples/http-server/http-server.sh | 2 +-
         public/http-server                  | 2 +-
         2 files changed, 2 insertions(+), 2 deletions(-)
        
        diff --git a/examples/http-server/http-server.sh b/examples/http-server/http-server.sh
        index 2db5f4542..5a5e3558b 100644
        --- a/examples/http-server/http-server.sh
        +++ b/examples/http-server/http-server.sh
        @@ -1,5 +1,5 @@
         # Run the server in the background.
        -$ go run http-servers.go &
        +$ go run http-server.go &
         
         # Access the `/hello` route.
         $ curl localhost:8090/hello
        diff --git a/public/http-server b/public/http-server
        index 54bf4aab6..4b6124c38 100644
        --- a/public/http-server
        +++ b/public/http-server
        @@ -162,7 +162,7 @@ router we’ve just set up.

        -
        $ go run http-servers.go &
        +
        $ go run http-server.go &
        - +
        package main
        +
            enc := json.NewEncoder(os.Stdout)
             d := map[string]int{"apple": 5, "lettuce": 7}
        -    enc.Encode(d)
        +    enc.Encode(d)
        +
        +

        We can also decode JSON directly from os.Reader

        + +
        + +
            dec := json.NewDecoder(strings.NewReader(str))
        +    res1 := response2{}
        +    dec.Decode(&res1)
        +    fmt.Println(res1)
        +    fmt.Println(res1.Fruits[1])
         }
        - +
        package main
        -

        We can also decode JSON directly from os.Reader

        +

        Streaming reads from os.Readers like os.Stdin +or HTTP request bodies is done with json.Decoder.

        @@ -333,7 +334,6 @@ stream JSON encodings directly to os.Writers like res1 := response2{} dec.Decode(&res1) fmt.Println(res1) - fmt.Println(res1.Fruits[1]) }
        - +
        package main
        +

        Type assertion can be performed to explicitly check the runtime type of the value. +It allows the access of fields and methods belonging to the specific type. +See switch example for an alternative approach to handle type assertion.

        + +
        + +
        func detectCircle(g geometry) {
        +    if c, ok := g.(circle); ok {
        +        fmt.Println(c.radius)
        +    }
        +}
        +
        @@ -166,11 +183,33 @@ instances of these structs as arguments to measure.

        +
            measure(r)
        -    measure(c)
        -}
        + measure(c) +
        +

        detectCircle takes structs that satisfy the geometry interface +if the struct is of type circle, it prints out the radius.

        + +
        + +
            detectCircle(r) // doesn't print anything.
        +    detectCircle(c)
        +
        + + + +
        }
        - +
        package main
        -

        Type assertion can be performed to explicitly check the runtime type of the value. -It allows the access of fields and methods belonging to the specific type. -See switch example for an alternative approach to handle type assertion.

        +

        Sometimes it’s useful to know the runtime type of an +interface value. One option is using a type assertion +as shown here; another is a type switch.

        func detectCircle(g geometry) {
             if c, ok := g.(circle); ok {
        -        fmt.Println(c.radius)
        +        fmt.Println("circle with radius", c.radius)
             }
         }
        -

        detectCircle takes structs that satisfy the geometry interface -if the struct is of type circle, it prints out the radius.

        - -
        - -
            detectCircle(r) // doesn't print anything.
        -    detectCircle(c)
        -
        -
        }
        +
            detectCircle(r)
        +    detectCircle(c)
        +}
        -

        To learn more about Go’s interfaces, check out this -great blog post.

        +

        To understand how Go’s interfaces work under the hood, +check out this blog post.

        @@ -261,7 +250,7 @@ if the struct is of type circle, it prints out the radius.

        From 86216051fc1b82aa432ee4c6a699653cefa38e61 Mon Sep 17 00:00:00 2001 From: Anthony Buchholz Date: Sat, 11 Jan 2025 08:31:07 -0600 Subject: [PATCH 260/283] Add rel="next" to example.tmpl file for the next link (#569) --- public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 2 +- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 2 +- public/command-line-arguments | 2 +- public/command-line-flags | 2 +- public/command-line-subcommands | 2 +- public/constants | 2 +- public/context | 2 +- public/custom-errors | 2 +- public/defer | 2 +- public/directories | 2 +- public/embed-directive | 2 +- public/enums | 2 +- public/environment-variables | 2 +- public/epoch | 2 +- public/errors | 2 +- public/execing-processes | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/generics | 2 +- public/goroutines | 2 +- public/hello-world | 2 +- public/http-client | 2 +- public/http-server | 2 +- public/if-else | 2 +- public/interfaces | 2 +- public/json | 2 +- public/line-filters | 2 +- public/logging | 2 +- public/maps | 2 +- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 2 +- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 2 +- public/random-numbers | 2 +- public/range-over-built-in-types | 2 +- public/range-over-channels | 2 +- public/range-over-iterators | 2 +- public/rate-limiting | 2 +- public/reading-files | 2 +- public/recover | 2 +- public/recursion | 2 +- public/regular-expressions | 2 +- public/select | 2 +- public/sha256-hashes | 2 +- public/signals | 2 +- public/slices | 2 +- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 2 +- public/strings-and-runes | 2 +- public/struct-embedding | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing-and-benchmarking | 2 +- public/text-templates | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 2 +- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- templates/example.tmpl | 2 +- 84 files changed, 84 insertions(+), 84 deletions(-) diff --git a/public/arrays b/public/arrays index 5f14bd04e..b19bc52f2 100644 --- a/public/arrays +++ b/public/arrays @@ -217,7 +217,7 @@ when printed with fmt.Println.

        - Next example: Slices. + Next example: .

        diff --git a/public/atomic-counters b/public/atomic-counters index efd77ba6d..4cfe179f2 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -213,7 +213,7 @@ state.

        - Next example: Mutexes. + Next example: .

        diff --git a/public/base64-encoding b/public/base64-encoding index 1087feb63..b0cbd8236 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -167,7 +167,7 @@ but they both decode to the original string as desired.

        - Next example: Reading Files. + Next example: .

        diff --git a/public/channel-buffering b/public/channel-buffering index b2a29327c..f57e1bb26 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -133,7 +133,7 @@ concurrent receive.

        - Next example: Channel Synchronization. + Next example: .

        diff --git a/public/channel-directions b/public/channel-directions index be0ff1ee1..631f50cfe 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -127,7 +127,7 @@ receive on this channel.

        - Next example: Select. + Next example: .

        diff --git a/public/channel-synchronization b/public/channel-synchronization index 989ce71b8..367d58f7e 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -162,7 +162,7 @@ started.

        - Next example: Channel Directions. + Next example: .

        diff --git a/public/channels b/public/channels index ebe9c90a7..408561d2d 100644 --- a/public/channels +++ b/public/channels @@ -148,7 +148,7 @@ message without having to use any other synchronization.

        - Next example: Channel Buffering. + Next example: .

        diff --git a/public/closing-channels b/public/closing-channels index ca4b3c23f..352fbbeaf 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -193,7 +193,7 @@ example: range over channels.

        - Next example: Range over Channels. + Next example: .

        diff --git a/public/closures b/public/closures index e6ebd9c00..4893fbd33 100644 --- a/public/closures +++ b/public/closures @@ -168,7 +168,7 @@ recursion.

        - Next example: Recursion. + Next example: .

        diff --git a/public/command-line-arguments b/public/command-line-arguments index 0a695f549..a2cbcd859 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -150,7 +150,7 @@ with flags.

        - Next example: Command-Line Flags. + Next example: .

        diff --git a/public/command-line-flags b/public/command-line-flags index 82ef2c452..ab12461e5 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -274,7 +274,7 @@ and show the help text again.

        - Next example: Command-Line Subcommands. + Next example: .

        diff --git a/public/command-line-subcommands b/public/command-line-subcommands index 39a52ff44..36a4743ba 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -233,7 +233,7 @@ way to parameterize programs.

        - Next example: Environment Variables. + Next example: .

        diff --git a/public/constants b/public/constants index 124457d26..2a48ee078 100644 --- a/public/constants +++ b/public/constants @@ -159,7 +159,7 @@ assignment or function call. For example, here

        - Next example: For. + Next example: .

        diff --git a/public/context b/public/context index a6bec16df..134804efd 100644 --- a/public/context +++ b/public/context @@ -179,7 +179,7 @@ cancellation.

        - Next example: Spawning Processes. + Next example: .

        diff --git a/public/custom-errors b/public/custom-errors index 48e62612b..a86e48c33 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -171,7 +171,7 @@ returns false.

        - Next example: Goroutines. + Next example: .

        diff --git a/public/defer b/public/defer index ae77a77ee..51a08a7a7 100644 --- a/public/defer +++ b/public/defer @@ -186,7 +186,7 @@ after being written.

        - Next example: Recover. + Next example: .

        diff --git a/public/directories b/public/directories index 87ad888e5..c291d3e16 100644 --- a/public/directories +++ b/public/directories @@ -309,7 +309,7 @@ recursively by filepath.WalkDir.

        - Next example: Temporary Files and Directories. + Next example: .

        diff --git a/public/embed-directive b/public/embed-directive index be868b136..fcf619532 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -182,7 +182,7 @@ this example can only be run on your local machine.)

        - Next example: Testing and Benchmarking. + Next example: .

        diff --git a/public/enums b/public/enums index 7eeee1a2e..47d30afd6 100644 --- a/public/enums +++ b/public/enums @@ -212,7 +212,7 @@ determine the next state…

        - Next example: Struct Embedding. + Next example: .

        diff --git a/public/environment-variables b/public/environment-variables index 713676129..94a2eaaef 100644 --- a/public/environment-variables +++ b/public/environment-variables @@ -165,7 +165,7 @@ program picks that value up.

        - Next example: Logging. + Next example: .

        diff --git a/public/epoch b/public/epoch index 2f6c32f48..105d5d249 100644 --- a/public/epoch +++ b/public/epoch @@ -151,7 +151,7 @@ parsing and formatting.

        - Next example: Time Formatting / Parsing. + Next example: .

        diff --git a/public/errors b/public/errors index 5830d24be..6cd153ba6 100644 --- a/public/errors +++ b/public/errors @@ -255,7 +255,7 @@ errors in a chain of errors.

        - Next example: Custom Errors. + Next example: .

        diff --git a/public/execing-processes b/public/execing-processes index d5becd917..fe3a962cc 100644 --- a/public/execing-processes +++ b/public/execing-processes @@ -181,7 +181,7 @@ processes covers most use cases for fork.

        - Next example: Signals. + Next example: .

        diff --git a/public/file-paths b/public/file-paths index e3f1dd003..eb7ac6883 100644 --- a/public/file-paths +++ b/public/file-paths @@ -218,7 +218,7 @@ be made relative to base.

        - Next example: Directories. + Next example: .

        diff --git a/public/for b/public/for index edb2e3e55..59804363a 100644 --- a/public/for +++ b/public/for @@ -190,7 +190,7 @@ structures.

        - Next example: If/Else. + Next example: .

        diff --git a/public/functions b/public/functions index 7823b6dda..e61950cd1 100644 --- a/public/functions +++ b/public/functions @@ -169,7 +169,7 @@ multiple return values, which we’ll look at next.

        - Next example: Multiple Return Values. + Next example: .

        diff --git a/public/generics b/public/generics index a0d8bb294..016205fff 100644 --- a/public/generics +++ b/public/generics @@ -225,7 +225,7 @@ automatically.

        - Next example: Range over Iterators. + Next example: .

        diff --git a/public/goroutines b/public/goroutines index ec9e9de82..6bdc52634 100644 --- a/public/goroutines +++ b/public/goroutines @@ -184,7 +184,7 @@ concurrent Go programs: channels.

        - Next example: Channels. + Next example: .

        diff --git a/public/hello-world b/public/hello-world index 9418998e4..6cfec0b6a 100644 --- a/public/hello-world +++ b/public/hello-world @@ -117,7 +117,7 @@ learn more about the language.

        - Next example: Values. + Next example: .

        diff --git a/public/http-client b/public/http-client index 9c64c2767..4e6aa6ea8 100644 --- a/public/http-client +++ b/public/http-client @@ -147,7 +147,7 @@ settings.

        - Next example: HTTP Server. + Next example: .

        diff --git a/public/http-server b/public/http-server index 4b6124c38..d747c0dd2 100644 --- a/public/http-server +++ b/public/http-server @@ -182,7 +182,7 @@ router we’ve just set up.

        - Next example: Context. + Next example: .

        diff --git a/public/if-else b/public/if-else index 706213f11..7d6d520ba 100644 --- a/public/if-else +++ b/public/if-else @@ -179,7 +179,7 @@ for basic conditions.

        - Next example: Switch. + Next example: .

        diff --git a/public/interfaces b/public/interfaces index cd8daed03..2db5cc383 100644 --- a/public/interfaces +++ b/public/interfaces @@ -239,7 +239,7 @@ check out this blog post.

        - Next example: Enums. + Next example: .

        diff --git a/public/json b/public/json index b7f885547..f8e417b40 100644 --- a/public/json +++ b/public/json @@ -385,7 +385,7 @@ for more.

        - Next example: XML. + Next example: .

        diff --git a/public/line-filters b/public/line-filters index 2d6948ff0..b1e33790f 100644 --- a/public/line-filters +++ b/public/line-filters @@ -178,7 +178,7 @@ lowercase lines.

        - Next example: File Paths. + Next example: .

        diff --git a/public/logging b/public/logging index 0160af896..b06df458c 100644 --- a/public/logging +++ b/public/logging @@ -261,7 +261,7 @@ on a single line.

        - Next example: HTTP Client. + Next example: .

        diff --git a/public/maps b/public/maps index b8b899ad7..c6c5b5450 100644 --- a/public/maps +++ b/public/maps @@ -250,7 +250,7 @@ printed with fmt.Println.

        - Next example: Functions. + Next example: .

        diff --git a/public/methods b/public/methods index 2f17c79ff..30a086207 100644 --- a/public/methods +++ b/public/methods @@ -173,7 +173,7 @@ naming related sets of methods: interfaces.

        - Next example: Interfaces. + Next example: .

        diff --git a/public/multiple-return-values b/public/multiple-return-values index 4a7825d36..1fdfae34a 100644 --- a/public/multiple-return-values +++ b/public/multiple-return-values @@ -146,7 +146,7 @@ feature of Go functions; we’ll look at this next.

        - Next example: Variadic Functions. + Next example: .

        diff --git a/public/mutexes b/public/mutexes index 79c68e819..9e76e592b 100644 --- a/public/mutexes +++ b/public/mutexes @@ -223,7 +223,7 @@ management task using only goroutines and channels.

        - Next example: Stateful Goroutines. + Next example: .

        diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations index c71d35511..971f1cd3c 100644 --- a/public/non-blocking-channel-operations +++ b/public/non-blocking-channel-operations @@ -156,7 +156,7 @@ on both messages and signals.

        - Next example: Closing Channels. + Next example: .

        diff --git a/public/number-parsing b/public/number-parsing index 211133c96..67e8caf26 100644 --- a/public/number-parsing +++ b/public/number-parsing @@ -187,7 +187,7 @@ bits.

        - Next example: URL Parsing. + Next example: .

        diff --git a/public/panic b/public/panic index 1a031b5c8..5371d85ba 100644 --- a/public/panic +++ b/public/panic @@ -166,7 +166,7 @@ to use error-indicating return values wherever possible.

        - Next example: Defer. + Next example: .

        diff --git a/public/pointers b/public/pointers index 3d5276d58..7c661f543 100644 --- a/public/pointers +++ b/public/pointers @@ -169,7 +169,7 @@ the memory address for that variable.

        - Next example: Strings and Runes. + Next example: .

        diff --git a/public/random-numbers b/public/random-numbers index c976fafef..9029b1cfa 100644 --- a/public/random-numbers +++ b/public/random-numbers @@ -187,7 +187,7 @@ that Go can provide.

        - Next example: Number Parsing. + Next example: .

        diff --git a/public/range-over-built-in-types b/public/range-over-built-in-types index 0d47ff6eb..f05e49368 100644 --- a/public/range-over-built-in-types +++ b/public/range-over-built-in-types @@ -179,7 +179,7 @@ details.

        - Next example: Pointers. + Next example: .

        diff --git a/public/range-over-channels b/public/range-over-channels index 9892eca32..2bd5973ab 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -136,7 +136,7 @@ values be received.

        - Next example: Timers. + Next example: .

        diff --git a/public/range-over-iterators b/public/range-over-iterators index d8fac9471..0137ee504 100644 --- a/public/range-over-iterators +++ b/public/range-over-iterators @@ -278,7 +278,7 @@ passed to the iterator will return false.

        - Next example: Errors. + Next example: .

        diff --git a/public/rate-limiting b/public/rate-limiting index 69be081d0..bc14f14b6 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -231,7 +231,7 @@ then serve the remaining 2 with ~200ms delays each.

        - Next example: Atomic Counters. + Next example: .

        diff --git a/public/reading-files b/public/reading-files index 42199fe2e..e8372512c 100644 --- a/public/reading-files +++ b/public/reading-files @@ -279,7 +279,7 @@ be scheduled immediately after Opening with

        - Next example: Writing Files. + Next example: .

        diff --git a/public/recover b/public/recover index fc8a8afa1..3618aa6ab 100644 --- a/public/recover +++ b/public/recover @@ -174,7 +174,7 @@ panic and resumes in the deferred closure.

        - Next example: String Functions. + Next example: .

        diff --git a/public/recursion b/public/recursion index 887189419..15f2926a9 100644 --- a/public/recursion +++ b/public/recursion @@ -159,7 +159,7 @@ knows which function to call with fib here.

        - Next example: Range over Built-in Types. + Next example: .

        diff --git a/public/regular-expressions b/public/regular-expressions index 6bce2e398..0805c2db8 100644 --- a/public/regular-expressions +++ b/public/regular-expressions @@ -301,7 +301,7 @@ the regexp package docs.

        - Next example: JSON. + Next example: .

        diff --git a/public/select b/public/select index cdd10e611..a3bf62244 100644 --- a/public/select +++ b/public/select @@ -161,7 +161,7 @@ concurrently.

        - Next example: Timeouts. + Next example: .

        diff --git a/public/sha256-hashes b/public/sha256-hashes index 2206d9616..f7a2e8fe1 100644 --- a/public/sha256-hashes +++ b/public/sha256-hashes @@ -176,7 +176,7 @@ you should carefully research

        - Next example: Base64 Encoding. + Next example: .

        diff --git a/public/signals b/public/signals index 24a6dd4ee..6c3987456 100644 --- a/public/signals +++ b/public/signals @@ -188,7 +188,7 @@ causing the program to print interrupt and then exit.

        - Next example: Exit. + Next example: .

        diff --git a/public/slices b/public/slices index 36d2868f6..37fcd989f 100644 --- a/public/slices +++ b/public/slices @@ -311,7 +311,7 @@ Go’s other key builtin data structure: maps.

        - Next example: Maps. + Next example: .

        diff --git a/public/sorting b/public/sorting index 1f79771bd..c85fbc725 100644 --- a/public/sorting +++ b/public/sorting @@ -137,7 +137,7 @@ a slice is already in sorted order.

        - Next example: Sorting by Functions. + Next example: .

        diff --git a/public/sorting-by-functions b/public/sorting-by-functions index 52255e013..8173d4476 100644 --- a/public/sorting-by-functions +++ b/public/sorting-by-functions @@ -175,7 +175,7 @@ doubt, benchmark!

        - Next example: Panic. + Next example: .

        diff --git a/public/spawning-processes b/public/spawning-processes index 5a0d16c21..331cc1011 100644 --- a/public/spawning-processes +++ b/public/spawning-processes @@ -253,7 +253,7 @@ an error message and non-zero return code.

        - Next example: Exec'ing Processes. + Next example: .

        diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 9a7c87fd0..628d45ad3 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -282,7 +282,7 @@ program.

        - Next example: Sorting. + Next example: .

        diff --git a/public/string-formatting b/public/string-formatting index 3648027dc..9e1d8f1de 100644 --- a/public/string-formatting +++ b/public/string-formatting @@ -397,7 +397,7 @@ and returns a string without printing it anywhere.

        - Next example: Text Templates. + Next example: .

        diff --git a/public/string-functions b/public/string-functions index 6ad38f824..1b28524b8 100644 --- a/public/string-functions +++ b/public/string-functions @@ -145,7 +145,7 @@ package docs.

        - Next example: String Formatting. + Next example: .

        diff --git a/public/strings-and-runes b/public/strings-and-runes index fe99c4239..32fcc8888 100644 --- a/public/strings-and-runes +++ b/public/strings-and-runes @@ -253,7 +253,7 @@ can compare a rune value to a rune literal directly.

        - Next example: Structs. + Next example: .

        diff --git a/public/struct-embedding b/public/struct-embedding index e2b995e1f..ca3d42bf9 100644 --- a/public/struct-embedding +++ b/public/struct-embedding @@ -218,7 +218,7 @@ we see that a container now implements the

        - Next example: Generics. + Next example: .

        diff --git a/public/structs b/public/structs index 78cc03f2b..6ea352dab 100644 --- a/public/structs +++ b/public/structs @@ -254,7 +254,7 @@ struct type. This technique is commonly used for

        - Next example: Methods. + Next example: .

        diff --git a/public/switch b/public/switch index 5bce8f1d4..9f4dfed5b 100644 --- a/public/switch +++ b/public/switch @@ -181,7 +181,7 @@ type corresponding to its clause.

        - Next example: Arrays. + Next example: .

        diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index 532fde0ac..9e22d356d 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -211,7 +211,7 @@ prefixing them with our temporary directory.

        - Next example: Embed Directive. + Next example: .

        diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking index 3b181243c..87d4b70db 100644 --- a/public/testing-and-benchmarking +++ b/public/testing-and-benchmarking @@ -255,7 +255,7 @@ benchmark function names with a regexp.

        - Next example: Command-Line Arguments. + Next example: .

        diff --git a/public/text-templates b/public/text-templates index a18bc6925..43f715661 100644 --- a/public/text-templates +++ b/public/text-templates @@ -243,7 +243,7 @@ the range block {{.}} is set to the current item of the iteration.<

        - Next example: Regular Expressions. + Next example: .

        diff --git a/public/tickers b/public/tickers index 295c86d71..f02bf8b0f 100644 --- a/public/tickers +++ b/public/tickers @@ -151,7 +151,7 @@ before we stop it.

        - Next example: Worker Pools. + Next example: .

        diff --git a/public/time b/public/time index 9886fbc88..7154f3d9b 100644 --- a/public/time +++ b/public/time @@ -240,7 +240,7 @@ the Unix epoch.

        - Next example: Epoch. + Next example: .

        diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing index ac5301102..714792c69 100644 --- a/public/time-formatting-parsing +++ b/public/time-formatting-parsing @@ -180,7 +180,7 @@ explaining the parsing problem.

        - Next example: Random Numbers. + Next example: .

        diff --git a/public/timeouts b/public/timeouts index 445f06dcb..e59cc6c63 100644 --- a/public/timeouts +++ b/public/timeouts @@ -161,7 +161,7 @@ out and the second succeeding.

        - Next example: Non-Blocking Channel Operations. + Next example: .

        diff --git a/public/timers b/public/timers index e1cbb89be..8f264ce9b 100644 --- a/public/timers +++ b/public/timers @@ -162,7 +162,7 @@ a chance to fire.

        - Next example: Tickers. + Next example: .

        diff --git a/public/url-parsing b/public/url-parsing index aaf7547c0..b1e4343a5 100644 --- a/public/url-parsing +++ b/public/url-parsing @@ -207,7 +207,7 @@ pieces that we extracted.

        - Next example: SHA256 Hashes. + Next example: .

        diff --git a/public/values b/public/values index 65844279a..459cf8ad6 100644 --- a/public/values +++ b/public/values @@ -132,7 +132,7 @@ basic examples.

        - Next example: Variables. + Next example: .

        diff --git a/public/variables b/public/variables index ced1bdd72..8d8afb4b3 100644 --- a/public/variables +++ b/public/variables @@ -160,7 +160,7 @@ This syntax is only available inside functions.

        - Next example: Constants. + Next example: .

        diff --git a/public/variadic-functions b/public/variadic-functions index 52e4f9e0d..e1477e43b 100644 --- a/public/variadic-functions +++ b/public/variadic-functions @@ -164,7 +164,7 @@ to form closures, which we’ll look at next.

        - Next example: Closures. + Next example: .

        diff --git a/public/waitgroups b/public/waitgroups index c6c96d173..97d0ee270 100644 --- a/public/waitgroups +++ b/public/waitgroups @@ -209,7 +209,7 @@ is likely to be different for each invocation.

        - Next example: Rate Limiting. + Next example: .

        diff --git a/public/worker-pools b/public/worker-pools index c54ac4900..2ba7e1e2d 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -198,7 +198,7 @@ there are 3 workers operating concurrently.

        - Next example: WaitGroups. + Next example: .

        diff --git a/public/writing-files b/public/writing-files index 515d6860c..7a6000333 100644 --- a/public/writing-files +++ b/public/writing-files @@ -252,7 +252,7 @@ we’ve just seen to the stdin and stdout streams.

        - Next example: Line Filters. + Next example: .

        diff --git a/public/xml b/public/xml index f2c32787c..4ed95a6b7 100644 --- a/public/xml +++ b/public/xml @@ -249,7 +249,7 @@ to nest all plants under <parent><child>... - Next example: Time. + Next example: .

        diff --git a/templates/example.tmpl b/templates/example.tmpl index 1f1716ab4..997cfd1c1 100644 --- a/templates/example.tmpl +++ b/templates/example.tmpl @@ -42,7 +42,7 @@ {{end}} {{if .NextExample}}

        - Next example: {{.NextExample.Name}}. + Next example: .

        {{end}} {{ template "footer" }} From 2a6ddb935bcc6037cc28c732bbc6d9d1773fa785 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 20 Jan 2025 18:49:13 -0800 Subject: [PATCH 261/283] Fix Seek distances to work with sample data file The text in reading-files.sh suggests creating a 9-byte file, and the current Seek distances error out. Fixes #564 --- examples/reading-files/reading-files.go | 4 ++-- examples/reading-files/reading-files.hash | 4 ++-- public/reading-files | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/reading-files/reading-files.go b/examples/reading-files/reading-files.go index 3bbf86463..1a863dc31 100644 --- a/examples/reading-files/reading-files.go +++ b/examples/reading-files/reading-files.go @@ -53,11 +53,11 @@ func main() { // Other methods of seeking are relative to the // current cursor position, - _, err = f.Seek(4, io.SeekCurrent) + _, err = f.Seek(2, io.SeekCurrent) check(err) // and relative to the end of the file. - _, err = f.Seek(-10, io.SeekEnd) + _, err = f.Seek(-4, io.SeekEnd) check(err) // The `io` package provides some functions that may diff --git a/examples/reading-files/reading-files.hash b/examples/reading-files/reading-files.hash index be6468fb1..f1be9c3d2 100644 --- a/examples/reading-files/reading-files.hash +++ b/examples/reading-files/reading-files.hash @@ -1,2 +1,2 @@ -754d3ce4873b6f8f1c81364bfcf5fedb17020c11 -upAKv1DPNMp +db59474ee414017c3021706ceb35d5e355f967b3 +SKTzfpnV0To diff --git a/public/reading-files b/public/reading-files index e8372512c..740f96d19 100644 --- a/public/reading-files +++ b/public/reading-files @@ -46,7 +46,7 @@ reading files.

        - +
        package main
        -
            _, err = f.Seek(4, io.SeekCurrent)
        +          
            _, err = f.Seek(2, io.SeekCurrent)
             check(err)
        -
            _, err = f.Seek(-10, io.SeekEnd)
        +          
            _, err = f.Seek(-4, io.SeekEnd)
             check(err)
        - +
        package main
        - - - -
        }
        + fmt.Fprintln(f, "data") +}
            if err != nil {
        -        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        -        os.Exit(1)
        +        panic(err)
             }
         }
        - +
        package main
        -

        To create an empty slice with non-zero length, use +

        To create a slice with non-zero length, use the builtin make. Here we make a slice of strings of length 3 (initially zero-valued). By default a new slice’s capacity is equal to its From dc4d2810342b2ee7bc1f7e06075b91b7150a5714 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 24 Feb 2025 06:11:01 -0800 Subject: [PATCH 264/283] Update testing-and-benchmarking for new benchmark Loop of Go 1.24 --- examples/testing-and-benchmarking/main_test.go | 15 ++++++++------- .../testing-and-benchmarking.hash | 2 ++ examples/testing-and-benchmarking/testing.hash | 2 -- 3 files changed, 10 insertions(+), 9 deletions(-) create mode 100644 examples/testing-and-benchmarking/testing-and-benchmarking.hash delete mode 100644 examples/testing-and-benchmarking/testing.hash diff --git a/examples/testing-and-benchmarking/main_test.go b/examples/testing-and-benchmarking/main_test.go index 86111d4c0..334ec5ba2 100644 --- a/examples/testing-and-benchmarking/main_test.go +++ b/examples/testing-and-benchmarking/main_test.go @@ -54,7 +54,7 @@ func TestIntMinTableDriven(t *testing.T) { } for _, tt := range tests { - // t.Run enables running "subtests", one for each + // `t.Run` enables running "subtests", one for each // table entry. These are shown separately // when executing `go test -v`. testname := fmt.Sprintf("%d,%d", tt.a, tt.b) @@ -68,13 +68,14 @@ func TestIntMinTableDriven(t *testing.T) { } // Benchmark tests typically go in `_test.go` files and are -// named beginning with `Benchmark`. The `testing` runner -// executes each benchmark function several times, increasing -// `b.N` on each run until it collects a precise measurement. +// named beginning with `Benchmark`. +// Any code that's required for the benchmark to run but should +// not be measured goes before this loop. func BenchmarkIntMin(b *testing.B) { - // Typically the benchmark runs a function we're - // benchmarking in a loop `b.N` times. - for i := 0; i < b.N; i++ { + for b.Loop() { + // The benchmark runner will automatically execute this loop + // body many times to determine a reasonable estimate of the + // run-time of a single iteration. IntMin(1, 2) } } diff --git a/examples/testing-and-benchmarking/testing-and-benchmarking.hash b/examples/testing-and-benchmarking/testing-and-benchmarking.hash new file mode 100644 index 000000000..6cca94a32 --- /dev/null +++ b/examples/testing-and-benchmarking/testing-and-benchmarking.hash @@ -0,0 +1,2 @@ +565e50f23b399cdbca4aedeb8b62b9f6ad097443 +osZckbKSkse diff --git a/examples/testing-and-benchmarking/testing.hash b/examples/testing-and-benchmarking/testing.hash deleted file mode 100644 index 7ecf04f85..000000000 --- a/examples/testing-and-benchmarking/testing.hash +++ /dev/null @@ -1,2 +0,0 @@ -3671aaf0eee9f6d2b68e51b09997be767edfe97c -PlzU16wwEWE From da87dfa854af14e8b26fad771ccb61d8ccc3583d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 24 Feb 2025 06:12:04 -0800 Subject: [PATCH 265/283] Update go version to 1.24 --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index abfd002be..8940fc0a0 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mmcgrana/gobyexample -go 1.23.0 +go 1.24.0 require ( github.com/alecthomas/chroma/v2 v2.10.0 From 6552c2cd2a4fc541a0fc901f305bac3b7f3ab1d7 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 24 Feb 2025 06:12:20 -0800 Subject: [PATCH 266/283] Update public html of testin-and-benchmarking --- public/testing-and-benchmarking | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking index 87d4b70db..c95c396e7 100644 --- a/public/testing-and-benchmarking +++ b/public/testing-and-benchmarking @@ -50,7 +50,7 @@ typically lives in the same package as the code it tests.

        - +
        package main
        -

        t.Run enables running “subtests”, one for each +

        t.Run enables running “subtests”, one for each table entry. These are shown separately when executing go test -v.

        @@ -175,27 +175,28 @@ when executing go test -v.

        Benchmark tests typically go in _test.go files and are -named beginning with Benchmark. The testing runner -executes each benchmark function several times, increasing -b.N on each run until it collects a precise measurement.

        +named beginning with Benchmark. +Any code that’s required for the benchmark to run but should +not be measured goes before this loop.

        -
        func BenchmarkIntMin(b *testing.B) {
        +
        func BenchmarkIntMin(b *testing.B) {
        +    for b.Loop() {
        -

        Typically the benchmark runs a function we’re -benchmarking in a loop b.N times.

        +

        The benchmark runner will automatically execute this loop +body many times to determine a reasonable estimate of the +run-time of a single iteration.

        -
            for i := 0; i < b.N; i++ {
        -        IntMin(1, 2)
        +          
                IntMin(1, 2)
             }
         }

        In the previous example we looked at setting up a simple -HTTP server. HTTP servers are useful for +HTTP server. HTTP servers are useful for demonstrating the usage of context.Context for controlling cancellation. A Context carries deadlines, cancellation signals, and other request-scoped values @@ -39,7 +39,7 @@ across API boundaries and goroutines.

        - +
        package main
        - +
        package main
            var twoD [2][3]int
        -    for i := 0; i < 2; i++ {
        -        for j := 0; j < 3; j++ {
        +    for i := range 2 {
        +        for j := range 3 {
                     twoD[i][j] = i + j
                 }
             }
        @@ -228,7 +228,7 @@ when printed with fmt.Println.

        diff --git a/public/atomic-counters b/public/atomic-counters index 4cfe179f2..89648fd0d 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -49,7 +49,7 @@ counters accessed by multiple goroutines.

        - +
        package main
        -
            for i := 0; i < 50; i++ {
        +          
            for range 50 {
                 wg.Add(1)
                go func() {
        -            for c := 0; c < 1000; c++ {
        + for range 1000 {
        - +
        package main
        func f(from string) {
        -    for i := 0; i < 3; i++ {
        +    for i := range 3 {
                 fmt.Println(from, ":", i)
             }
         }
        @@ -195,7 +195,7 @@ concurrent Go programs: channels.

        diff --git a/public/mutexes b/public/mutexes index 9e76e592b..ceb4a86f3 100644 --- a/public/mutexes +++ b/public/mutexes @@ -47,7 +47,7 @@ to safely access data across multiple goroutines.

        - +
        package main
            doIncrement := func(name string, n int) {
        -        for i := 0; i < n; i++ {
        +        for range n {
                     c.inc(name)
                 }
                 wg.Done()
        @@ -234,7 +234,7 @@ management task using only goroutines and channels.

        diff --git a/public/rate-limiting b/public/rate-limiting index bc14f14b6..033749fa1 100644 --- a/public/rate-limiting +++ b/public/rate-limiting @@ -48,7 +48,7 @@ channels, and tickers.

        - +
        package main
        -
            for i := 0; i < 3; i++ {
        +          
            for range 3 {
                 burstyLimiter <- time.Now()
             }
        - +
        package main
        -
            for i := 0; i < 2; i++ {
        +          
            for range 2 {
                 select {
                 case msg1 := <-c1:
                     fmt.Println("received", msg1)
        @@ -172,7 +172,7 @@ concurrently.

        diff --git a/public/slices b/public/slices index 6cc2c5e35..571ae319f 100644 --- a/public/slices +++ b/public/slices @@ -45,7 +45,7 @@ a more powerful interface to sequences than arrays.

        - +
        package main
            twoD := make([][]int, 3)
        -    for i := 0; i < 3; i++ {
        +    for i := range 3 {
                 innerLen := i + 1
                 twoD[i] = make([]int, innerLen)
        -        for j := 0; j < innerLen; j++ {
        +        for j := range innerLen {
                     twoD[i][j] = i + j
                 }
             }
        @@ -322,7 +322,7 @@ Go’s other key builtin data structure: maps.

        diff --git a/public/stateful-goroutines b/public/stateful-goroutines index 628d45ad3..27a7f1d22 100644 --- a/public/stateful-goroutines +++ b/public/stateful-goroutines @@ -51,7 +51,7 @@ by exactly 1 goroutine.

        - +
        package main
        -
            for r := 0; r < 100; r++ {
        +          
            for range 100 {
                 go func() {
                     for {
                         read := readOp{
        @@ -198,7 +198,7 @@ approach.

        -
            for w := 0; w < 10; w++ {
        +          
            for range 10 {
                 go func() {
                     for {
                         write := writeOp{
        @@ -293,7 +293,7 @@ program.

        From cecfee722917cdd9493f14fed064a0ddd8b1be1a Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 9 Jun 2025 05:20:47 -0700 Subject: [PATCH 272/283] Fix typo Fixes #610 --- examples/string-functions/string-functions.go | 2 +- examples/string-functions/string-functions.hash | 4 ++-- public/string-functions | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/string-functions/string-functions.go b/examples/string-functions/string-functions.go index 739b5473c..a30752b5a 100644 --- a/examples/string-functions/string-functions.go +++ b/examples/string-functions/string-functions.go @@ -18,7 +18,7 @@ func main() { // Here's a sample of the functions available in // `strings`. Since these are functions from the // package, not methods on the string object itself, - // we need pass the string in question as the first + // we need to pass the string in question as the first // argument to the function. You can find more // functions in the [`strings`](https://pkg.go.dev/strings) // package docs. diff --git a/examples/string-functions/string-functions.hash b/examples/string-functions/string-functions.hash index 7a51d460b..916dab71c 100644 --- a/examples/string-functions/string-functions.hash +++ b/examples/string-functions/string-functions.hash @@ -1,2 +1,2 @@ -a8fc7e03fd17f6d432adf2f0e991461630ce4350 -DSKkoyx9Rcy +e1e2ea01b9c79fecebfece602915e9367b02a083 +wKSAzxfs96O diff --git a/public/string-functions b/public/string-functions index 1b28524b8..d4690640b 100644 --- a/public/string-functions +++ b/public/string-functions @@ -46,7 +46,7 @@ to give you a sense of the package.

        - +
        package main
        - +
        package main
        -

        Launch several goroutines and increment the WaitGroup -counter for each.

        +

        Launch several goroutines using WaitGroup.Go

            for i := 1; i <= 5; i++ {
        -        wg.Add(1)
        -
        -

        Wrap the worker call in a closure that makes sure to tell -the WaitGroup that this worker is done. This way the worker -itself does not have to be aware of the concurrency primitives -involved in its execution.

        - -
        - -
                go func() {
        -            defer wg.Done()
        +        wg.Go(func() {
                     worker(i)
        -        }()
        +        })
             }
        -

        Block until the WaitGroup counter goes back to 0; -all the workers notified they’re done.

        +

        Block until all the goroutines started by wg are +done. A goroutine is done when the function it invokes +returns.

        @@ -220,7 +205,7 @@ is likely to be different for each invocation.

        From fdd9bb0fcd83bbb48de6043b3141b3fcb427e729 Mon Sep 17 00:00:00 2001 From: Jacob Thwaites <43198438+JacobThwaites@users.noreply.github.com> Date: Fri, 29 Aug 2025 21:30:36 +0200 Subject: [PATCH 275/283] ignore navigation if command key held on MacOS (#621) --- public/arrays | 2 +- public/atomic-counters | 2 +- public/base64-encoding | 2 +- public/channel-buffering | 2 +- public/channel-directions | 2 +- public/channel-synchronization | 2 +- public/channels | 2 +- public/closing-channels | 2 +- public/closures | 2 +- public/command-line-arguments | 2 +- public/command-line-flags | 2 +- public/command-line-subcommands | 2 +- public/constants | 2 +- public/context | 2 +- public/custom-errors | 2 +- public/defer | 2 +- public/directories | 2 +- public/embed-directive | 2 +- public/enums | 2 +- public/environment-variables | 2 +- public/epoch | 2 +- public/errors | 2 +- public/execing-processes | 2 +- public/exit | 2 +- public/file-paths | 2 +- public/for | 2 +- public/functions | 2 +- public/generics | 2 +- public/goroutines | 2 +- public/hello-world | 2 +- public/http-client | 2 +- public/http-server | 2 +- public/if-else | 2 +- public/interfaces | 2 +- public/json | 2 +- public/line-filters | 2 +- public/logging | 2 +- public/maps | 2 +- public/methods | 2 +- public/multiple-return-values | 2 +- public/mutexes | 2 +- public/non-blocking-channel-operations | 2 +- public/number-parsing | 2 +- public/panic | 2 +- public/pointers | 2 +- public/random-numbers | 2 +- public/range-over-built-in-types | 2 +- public/range-over-channels | 2 +- public/range-over-iterators | 2 +- public/rate-limiting | 2 +- public/reading-files | 2 +- public/recover | 2 +- public/recursion | 2 +- public/regular-expressions | 2 +- public/select | 2 +- public/sha256-hashes | 2 +- public/signals | 2 +- public/slices | 2 +- public/sorting | 2 +- public/sorting-by-functions | 2 +- public/spawning-processes | 2 +- public/stateful-goroutines | 2 +- public/string-formatting | 2 +- public/string-functions | 2 +- public/strings-and-runes | 2 +- public/struct-embedding | 2 +- public/structs | 2 +- public/switch | 2 +- public/temporary-files-and-directories | 2 +- public/testing-and-benchmarking | 2 +- public/text-templates | 2 +- public/tickers | 2 +- public/time | 2 +- public/time-formatting-parsing | 2 +- public/timeouts | 2 +- public/timers | 2 +- public/url-parsing | 2 +- public/values | 2 +- public/variables | 2 +- public/variadic-functions | 2 +- public/waitgroups | 2 +- public/worker-pools | 2 +- public/writing-files | 2 +- public/xml | 2 +- templates/example.tmpl | 2 +- 85 files changed, 85 insertions(+), 85 deletions(-) diff --git a/public/arrays b/public/arrays index 45614324a..fc3379e12 100644 --- a/public/arrays +++ b/public/arrays @@ -7,7 +7,7 @@ From d7a40615a5413cb505f9e6fed8f5a518bc3a8274 Mon Sep 17 00:00:00 2001 From: Dawid Gala <115001848+Dawo9889@users.noreply.github.com> Date: Mon, 8 Sep 2025 15:52:26 +0200 Subject: [PATCH 277/283] (minor): update mutexes example to use wg.Go instead of manual creation (#623) * (minor): update mutexes example to use wg.Go instead of manual creation * Create an output Fixes #622 --------- Co-authored-by: Gala --- examples/mutexes/mutexes.go | 16 +++++++++++----- examples/mutexes/mutexes.hash | 4 ++-- public/mutexes | 36 ++++++++++++++++++++++++++++------- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index c373b0faa..b6e5a14d4 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -45,16 +45,22 @@ func main() { for range n { c.inc(name) } - wg.Done() } // Run several goroutines concurrently; note // that they all access the same `Container`, // and two of them access the same counter. - wg.Add(3) - go doIncrement("a", 10000) - go doIncrement("a", 10000) - go doIncrement("b", 10000) + wg.Go(func() { + doIncrement("a", 10000) + }) + + wg.Go(func() { + doIncrement("a", 10000) + }) + + wg.Go(func() { + doIncrement("b", 10000) + }) // Wait for the goroutines to finish wg.Wait() diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 4bd883114..68900ea9b 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -1c56c75162419ced8437b7ebe53ee65e5479f645 -CawzyQnvH6W +5271a346794ed097df21fb0f2b2d3d01c9bb361c +u0VAVSWRlU0 diff --git a/public/mutexes b/public/mutexes index 9eb626883..e8a56f125 100644 --- a/public/mutexes +++ b/public/mutexes @@ -47,7 +47,7 @@ to safely access data across multiple goroutines.

        - +
        package main
        -
            wg.Add(3)
        -    go doIncrement("a", 10000)
        -    go doIncrement("a", 10000)
        -    go doIncrement("b", 10000)
        +
            wg.Go(func() {
        +        doIncrement("a", 10000)
        +    })
        +
        + + + +
            wg.Go(func() {
        +        doIncrement("a", 10000)
        +    })
        +
        + + + +
            wg.Go(func() {
        +        doIncrement("b", 10000)
        +    })
        - +
        package main
        import (
        +    "errors"
             "fmt"
             "io"
             "os/exec"
        @@ -120,11 +121,14 @@ code.

            _, err = exec.Command("date", "-x").Output()
             if err != nil {
        -        switch e := err.(type) {
        -        case *exec.Error:
        +        var execErr *exec.Error
        +        var exitErr *exec.ExitError
        +        switch {
        +        case errors.As(err, &execErr):
                     fmt.Println("failed executing:", err)
        -        case *exec.ExitError:
        -            fmt.Println("command exit rc =", e.ExitCode())
        +        case errors.As(err, &exitErr):
        +            exitCode := exitErr.ExitCode()
        +            fmt.Println("command exit rc =", exitCode)
                 default:
                     panic(err)
                 }
        @@ -264,7 +268,7 @@ an error message and non-zero return code.

        From f6feee969fdd25fc3ab28a14c42c1ff758f86d7e Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 29 Sep 2025 14:27:42 -0700 Subject: [PATCH 281/283] Slight tweaks to wording --- examples/custom-errors/custom-errors.go | 2 +- examples/custom-errors/custom-errors.hash | 4 ++-- examples/errors/errors.go | 12 ++++++------ examples/errors/errors.hash | 4 ++-- examples/spawning-processes/spawning-processes.go | 2 +- .../spawning-processes/spawning-processes.hash | 4 ++-- public/custom-errors | 4 ++-- public/errors | 14 +++++++------- public/spawning-processes | 4 ++-- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/examples/custom-errors/custom-errors.go b/examples/custom-errors/custom-errors.go index 30cbe9960..11c140d3a 100644 --- a/examples/custom-errors/custom-errors.go +++ b/examples/custom-errors/custom-errors.go @@ -1,4 +1,4 @@ -// It's possible to use custom types as `error`s by +// It's possible to define custom error types by // implementing the `Error()` method on them. Here's a // variant on the example above that uses a custom type // to explicitly represent an argument error. diff --git a/examples/custom-errors/custom-errors.hash b/examples/custom-errors/custom-errors.hash index a4772dccd..75b9da953 100644 --- a/examples/custom-errors/custom-errors.hash +++ b/examples/custom-errors/custom-errors.hash @@ -1,2 +1,2 @@ -e63d61872edce05ea3ec797958eff48d1decfbd8 -qKKTjmc6SuB +560ba2e87e0a2b1b8b07dd7b81152da0af88f97b +6oW6K8iylu- diff --git a/examples/errors/errors.go b/examples/errors/errors.go index fe037996d..304a03aef 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -1,10 +1,10 @@ // In Go it's idiomatic to communicate errors via an // explicit, separate return value. This contrasts with -// the exceptions used in languages like Java and Ruby and -// the overloaded single result / error value sometimes -// used in C. Go's approach makes it easy to see which -// functions return errors and to handle them using the -// same language constructs employed for other, +// the exceptions used in languages like Java, Python and +// Ruby and the overloaded single result / error value +// sometimes used in C. Go's approach makes it easy to +// see which functions return errors and to handle them +// using the same language constructs employed for other, // non-error tasks. // // See the documentation of the [errors package](https://pkg.go.dev/errors) @@ -56,7 +56,7 @@ func makeTea(arg int) error { func main() { for _, i := range []int{7, 42} { - // It's common to use an inline error check in the `if` + // It's idiomatic to use an inline error check in the `if` // line. if r, e := f(i); e != nil { fmt.Println("f failed:", e) diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index 75e3c8bcf..dc8302c13 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -805db04c4efb743792093f6dd7fbb6828be59cc2 -j6odYuFpOeb +36c6f61252233bdc5d9645f2a372338f7c6fe446 +ycKDxFlusrP diff --git a/examples/spawning-processes/spawning-processes.go b/examples/spawning-processes/spawning-processes.go index a0374f01d..39103db9d 100644 --- a/examples/spawning-processes/spawning-processes.go +++ b/examples/spawning-processes/spawning-processes.go @@ -1,4 +1,4 @@ -// Sometimes our Go programs need to spawn other, non-Go +// Sometimes our Go programs need to spawn other // processes. package main diff --git a/examples/spawning-processes/spawning-processes.hash b/examples/spawning-processes/spawning-processes.hash index af4ec3ac8..7a4e2e35c 100644 --- a/examples/spawning-processes/spawning-processes.hash +++ b/examples/spawning-processes/spawning-processes.hash @@ -1,2 +1,2 @@ -3020b65601d80e67c575785c8d2616163a0423a5 -uOmOn18nMDw +b3cd5b25049dd2ce6e2a2c8bd58a21ed7a20104b +bFqSoJG9bKR diff --git a/public/custom-errors b/public/custom-errors index 24442197c..a0e697b57 100644 --- a/public/custom-errors +++ b/public/custom-errors @@ -30,7 +30,7 @@
        -

        It’s possible to use custom types as errors by +

        It’s possible to define custom error types by implementing the Error() method on them. Here’s a variant on the example above that uses a custom type to explicitly represent an argument error.

        @@ -47,7 +47,7 @@ to explicitly represent an argument error.

        - +
        package main

        In Go it’s idiomatic to communicate errors via an explicit, separate return value. This contrasts with -the exceptions used in languages like Java and Ruby and -the overloaded single result / error value sometimes -used in C. Go’s approach makes it easy to see which -functions return errors and to handle them using the -same language constructs employed for other, +the exceptions used in languages like Java, Python and +Ruby and the overloaded single result / error value +sometimes used in C. Go’s approach makes it easy to +see which functions return errors and to handle them +using the same language constructs employed for other, non-error tasks.

        See the documentation of the errors package @@ -55,7 +55,7 @@ details.

        - +
        package main
        -

        It’s common to use an inline error check in the if +

        It’s idiomatic to use an inline error check in the if line.

        -

        Sometimes our Go programs need to spawn other, non-Go +

        Sometimes our Go programs need to spawn other processes.

        - +
        package main
        -

        If you removed the <- done line from this program, the -program would exit before the worker even -started.

        +

        If you removed the <- done line from this program, +the program could exit before the worker finished +its work, or in some cases even before it started.

        From 981a5753c290b90f1fdadd09153f4d49d6f22039 Mon Sep 17 00:00:00 2001 From: Antony Lau <167767900+antonlau-1@users.noreply.github.com> Date: Thu, 9 Oct 2025 13:37:16 +0100 Subject: [PATCH 283/283] Update error example (#627) * clarify error package usage * run tools/build locally to generate html changes --- examples/errors/errors.go | 4 ++-- examples/errors/errors.hash | 4 ++-- public/errors | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/errors/errors.go b/examples/errors/errors.go index 304a03aef..8ee1856a7 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -34,8 +34,8 @@ func f(arg int) (int, error) { // A sentinel error is a predeclared variable that is used to // signify a specific error condition. -var ErrOutOfTea = fmt.Errorf("no more tea available") -var ErrPower = fmt.Errorf("can't boil water") +var ErrOutOfTea = errors.New("no more tea available") +var ErrPower = errors.New("can't boil water") func makeTea(arg int) error { if arg == 2 { diff --git a/examples/errors/errors.hash b/examples/errors/errors.hash index dc8302c13..a25b41fdc 100644 --- a/examples/errors/errors.hash +++ b/examples/errors/errors.hash @@ -1,2 +1,2 @@ -36c6f61252233bdc5d9645f2a372338f7c6fe446 -ycKDxFlusrP +75d3f026abf0216f67669751cbf300f09da311e5 +H-SmHpaHY3v diff --git a/public/errors b/public/errors index ea56d1f4e..9ecbc147b 100644 --- a/public/errors +++ b/public/errors @@ -55,7 +55,7 @@ details.

        - +
        package main
        -
        var ErrOutOfTea = fmt.Errorf("no more tea available")
        -var ErrPower = fmt.Errorf("can't boil water")
        +
        var ErrOutOfTea = errors.New("no more tea available")
        +var ErrPower = errors.New("can't boil water")