*/
202 | p > code, li > code, div > code {
203 | margin: 2px 4px 2px 4px;
204 | font-size: 90%;
205 | color: #a4323c;
206 | background-color: #f4f4f4;
207 | border-radius: 3px;
208 | font-weight: normal;
209 | }
210 |
211 |
--------------------------------------------------------------------------------
/sheets/eg.md:
--------------------------------------------------------------------------------
1 |
2 | Example
3 | =======
4 |
5 | Formatting
6 | ----------
7 |
8 | #### Formatting examples
9 |
10 | - Some useful information *in italics* and **in bold**.
11 | - `int itCode();` in here.
12 | - Ctrl + A is for 'orses.
13 | - Notes: Inline note
14 |
15 |
16 | #### Sub heading
17 |
18 | Note this must be >h2.
19 |
20 | - another list
21 | - with items
22 | * and sublist
23 | * with more items
24 | - and back to the other list
25 | - which ends here
26 |
27 |
28 | This is a small table example:
29 |
30 | Country | Size | Food
31 | ------- | ---- | ----
32 | UK | small | chips
33 | US | big | burgers
34 | France | medium | cheese
35 |
36 |
37 | This is an extension, lists with splits, for values-comments:
38 |
39 | - `RGB(255,0,0)` :: red
40 | - `RGB(0,255)` :: green
41 | - `RGB(0,0,255)` :: blue
42 |
43 | More text:
44 |
45 | - `${parameter:-word}` :: If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
46 | - `${parameter:=word}` :: If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
47 | - `${parameter:?word}` :: If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
48 | - `${parameter:+word}` :: If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
49 |
50 |
51 | ### heading 3
52 | #### heading 4
53 | ##### heading 5
54 | ###### heading 6
55 |
56 |
57 | Table
58 | -----
59 |
60 | Big table example:
61 |
62 | Key | Value
63 | --- | -----
64 | Apple | Pears
65 | Tomarto | Tomayto
66 | `code` | nice
67 |
68 |
69 | Shortcut | Comment
70 | ------------------------------ | -----------------------------------------
71 | CTRL + A | move to beginning of line
72 | CTRL + B | moves backward one character
73 | CTRL + C | halts the current command
74 | CTRL + D | deletes one character backward or logs out of current session, similar to exit
75 | CTRL + E | moves to end of line
76 | CTRL + F | moves forward one character
77 | CTRL + G | aborts the current editing command and ring the terminal bell
78 | CTRL + J | same as RETURN
79 | CTRL + K | deletes (kill) forward to end of line
80 | CTRL + L | clears screen and redisplay the line
81 |
82 |
83 | Code
84 | ----
85 |
86 | #### Some BASH
87 |
88 | This is a BASH example.
89 |
90 | ```bash
91 | #!/bin/bash
92 |
93 | ###### BEGIN CONFIG
94 | ACCEPTED_HOSTS="/root/.hag_accepted.conf"
95 | BE_VERBOSE=false
96 | ###### END CONFIG
97 |
98 | if [ "$UID" -ne 0 ]
99 | then
100 | echo "Superuser rights is required"
101 | echo 'Printing the # sign'
102 | exit 2
103 | fi
104 |
105 | if test $# -eq 0
106 | then
107 | elif test [ $1 == 'start' ]
108 | else
109 | fi
110 |
111 | genApacheConf(){
112 | if [[ "$2" = "www" ]]
113 | then
114 | full_domain=$1
115 | else
116 | full_domain=$2.$1
117 | fi
118 | host_root="${APACHE_HOME_DIR}$1/$2/$(title)"
119 | echo -e "# Host $1/$2 :"
120 | }
121 | ```
122 |
123 | #### Some Python
124 |
125 | ```python
126 | @requires_authorization
127 | def somefunc(param1='', param2=0):
128 | r'''A docstring'''
129 | if param1 > param2: # interesting
130 | print 'Gre\'ater'
131 | return (param2 - param1 + 1 + 0b10l) or None
132 |
133 | class SomeClass:
134 | pass
135 |
136 | >>> message = '''interpreter
137 | ... prompt'''
138 | ```
139 |
140 | #### Some Lua
141 |
142 | ```lua
143 | --[[
144 | Simple signal/slot implementation
145 | ]]
146 | local signal_mt = {
147 | __index = {
148 | register = table.insert
149 | }
150 | }
151 | function signal_mt.__index:emit(... --[[ Comment in params ]])
152 | for _, slot in ipairs(self) do
153 | slot(self, ...)
154 | end
155 | end
156 | local function create_signal()
157 | return setmetatable({}, signal_mt)
158 | end
159 |
160 | -- Signal test
161 | local signal = create_signal()
162 | signal:register(function(signal, ...)
163 | print(...)
164 | end)
165 | signal:emit('Answer to Life, the Universe, and Everything:', 42)
166 |
167 | --[==[ [=[ [[
168 | Nested ]]
169 | multi-line ]=]
170 | comment ]==]
171 | [==[ Nested
172 | [=[ multi-line
173 | [[ string
174 | ]] ]=] ]==]
175 | ```
176 |
177 | Notes
178 | -----
179 |
180 |
181 |
182 | #### A test
183 |
184 | Test "with quotes" **bold**
185 |
186 | #### Code test
187 |
188 | ```lua
189 | if something then
190 | -- do something
191 | local function create_signal()
192 | return setmetatable({}, signal_mt)
193 | end
194 | end
195 | ```
196 |
197 | #### colours
198 |
199 | red
200 |
201 |
202 | Useful links
203 | ------------
204 | - [Cheatsheet Github page](https://github.com/billyquith/cheatsheet)
205 | - [Markdown syntax](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#tables)
206 |
--------------------------------------------------------------------------------
/sheets/cmake.md:
--------------------------------------------------------------------------------
1 | cmake
2 | =====
3 |
4 | Commands
5 | --------
6 |
7 |
8 | ### add_definitions
9 |
10 | ```
11 | add_definitions(-DFOO -DBAR ...)
12 | ```
13 |
14 | Adds definitions to the compiler command line for targets in the current directory and below.
15 |
16 | ### find_package
17 |
18 | ```raw
19 | find_package( [version] [EXACT] [QUIET] [MODULE]
20 | [REQUIRED] [[COMPONENTS] [components...]]
21 | [OPTIONAL_COMPONENTS components...]
22 | [NO_POLICY_SCOPE])`
23 | ```
24 | [docs](https://cmake.org/cmake/help/latest/command/find_package.html)
25 |
26 | Finds and loads settings from an external project (in "module mode"). `_FOUND` set indicates found. `QUIET`
27 | disables messages if package not found. `MODULE` option disables the second signature. `REQUIRED`
28 | option stops processing with an error message if package not be found.
29 |
30 | A package-specific list of required components may be listed after the `COMPONENTS` option.
31 | Additional optional components may be listed after `OPTIONAL_COMPONENTS`.
32 |
33 | `[version]` argument requests a version with which the package found should be compatible (format
34 | is `major[.minor[.patch[.tweak]]]`). The `EXACT` option requests that the version be matched exactly.
35 | If no `[version]` and/or component list is given to a recursive invocation inside a find-module, the
36 | corresponding arguments are forwarded automatically from the outer call (including the `EXACT` flag
37 | for `[version]`). Version support is currently provided only on a package-by-package basis (details
38 | below).
39 |
40 | User code should generally look for packages using the above simple signature. See doc link for
41 | more complicated version.
42 |
43 | The command has two modes by which it searches for packages: “Module” mode and “Config” mode.
44 | *Module mode* is available when the command is invoked with the above reduced signature. CMake
45 | searches for a file called `Find.cmake` in the `CMAKE_MODULE_PATH` followed by the CMake
46 | installation. If the file is found, it is read and processed by CMake. It is responsible for
47 | finding the package, checking the version, and producing any needed messages. Many find-modules
48 | provide limited or no support for versioning; check the module documentation. If no module is found
49 | and the MODULE option is not given the command proceeds to Config mode.
50 |
51 | e.g.
52 | ```cmake
53 | find_package(SDL 2.0 REQUIRED)
54 | if(SDL_FOUND)
55 | include_directories(${SDL_INCLUDE_DIRS})
56 | link_libraries(${SDL_LIBRARIES})
57 | endif()
58 | ```
59 |
60 | ### message
61 |
62 | ```
63 | message([] "message to display" ...)
64 | ```
65 |
66 | ``:
67 |
68 | - (none) :: Important information
69 | - STATUS :: Incidental information
70 | - WARNING :: CMake Warning, continue processing
71 | - AUTHOR_WARNING :: CMake Warning (dev), continue processing
72 | - SEND_ERROR :: CMake Error, continue processing, but skip generation
73 | - FATAL_ERROR :: CMake Error, stop processing and generation
74 | - DEPRECATION :: CMake Deprecation Error or Warning if variable `CMAKE_ERROR_DEPRECATED`
75 | or `CMAKE_WARN_DEPRECATED` is enabled, respectively, else no message.
76 |
77 | ### set
78 |
79 | ```
80 | set(... [PARENT_SCOPE])
81 | ```
82 |
83 |
84 | Set given `` in the current function or directory scope. If `PARENT_SCOPE` given variable
85 | set in scope above. Each new directory or function creates a new scope.
86 |
87 | ### source_group
88 |
89 | ```
90 | source_group( [FILES ...] [REGULAR_EXPRESSION ])
91 | ```
92 |
93 | Group files in IDE folders. `` may contain backslashes to specify subgroups:
94 | `source_group(outer\\inner ...)`
95 |
96 | - `FILES` :: Source files specified placed group ``. Relative paths are interpreted with
97 | respect to the current source directory.
98 | - `REGULAR_EXPRESSION` :: File names matching the regex placed in group ``. If matches
99 | multiple groups, last group matching favored, if any.
100 |
101 | To set folder for project once added:
102 |
103 | ```
104 | set_property(TARGET ${PROJ} PROPERTY FOLDER ${folder})
105 | ```
106 |
107 |
108 | Targets
109 | -------
110 |
111 | ### Library
112 |
113 | ```cmake
114 | add_library( [STATIC | SHARED | MODULE]
115 | [EXCLUDE_FROM_ALL]
116 | source1 [source2 ...])
117 | ```
118 | [docs](https://cmake.org/cmake/help/latest/command/add_library.html)
119 |
120 | Adds library called `` built from source files listed. `` corresponds to the logical
121 | target name and must be globally unique within a project. `STATIC`, `SHARED`, or `MODULE` may be
122 | given to specify the type of library to be created.
123 |
124 | - STATIC `.a`, object archive.
125 | - SHARED `.dylib`, dynamically loadable library.
126 | - MODULE `.so`, shared library module. OSX: `.bundle` plug-in.
127 |
128 | ### Executable
129 |
130 | ```cmake
131 | add_executable( [WIN32] [MACOSX_BUNDLE]
132 | [EXCLUDE_FROM_ALL]
133 | source1 [source2 ...])```
134 | [docs](https://cmake.org/cmake/help/latest/command/add_executable.html)
135 |
136 | Adds executable called `` to be built from the source files listed. `` corresponds to
137 | the logical target name and must be globally unique within a project. The actual file name of the
138 | executable built is constructed based on conventions of the native platform (such as `.exe`
139 | or just `` ).
140 |
141 | By default the executable file will be created in the build tree directory corresponding to the
142 | source tree directory in which the command was invoked. See `RUNTIME_OUTPUT_DIRECTORY` target
143 | property to change this location. See `OUTPUT_NAME` target property to change the `` part of
144 | the final file name.
145 |
146 | - If `WIN32` is given the property `WIN32_EXECUTABLE` will be set on the target created.
147 | - If `MACOSX_BUNDLE` is given the corresponding property will be set on the created target.
148 | - If `EXCLUDE_FROM_ALL` is given the corresponding property will be set on the created target.
149 |
150 | ### Flags
151 |
152 | #### C++11
153 |
154 | Equivalent to `-std=c++11` but backward compatible for GCC 4.6 on Travic-CI.
155 | ```cmake
156 | add_definitions(-std=c++0x)
157 | ```
158 |
159 | ### Output
160 |
161 | - `CMAKE__OUTPUT_DIRECTORY`.
162 | - `ARCHIVE` is static library, `LIBRARY` is shared library, `RUNTIME` is executable.
163 | - *Note*, config is appended to this path, e.g. `Debug` (see below)
164 |
165 | ```cmake
166 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${OUTDIR}/lib)
167 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${OUTDIR}/lib) # or `bin` so DLLs in executable dir
168 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${OUTDIR}/bin)
169 | ```
170 |
171 | - `_OUTPUT_DIRECTORY_` : set full path for specific target configuration.
172 |
173 | ```cmake
174 | set_target_properties(myapp PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${OUTDIR}/bin)
175 | ```
176 |
177 |
178 | Skeleton
179 | --------
180 |
181 | ### Skeleton project
182 |
183 | Root `CMakeLists.txt`;
184 |
185 | ```cmake
186 | cmake_minimum_required(VERSION 2.8.3)
187 | project(PROJECT_NAME)
188 |
189 | option(WANT_DOCS "Want project documentation" ON)
190 |
191 | if(WANT_DOCS)
192 | find_package(Doxygen)
193 | if(DOXYGEN_FOUND)
194 | # add a Doxygen target to the "all" target
195 | add_custom_target(doxygen
196 | ALL
197 | COMMAND doxygen Doxyfile > ${DEV_NULL}
198 | WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
199 | )
200 | else()
201 | message(WARNING "Doxygen not found")
202 | endif(DOXYGEN_FOUND)
203 | endif(WANT_DOCS)
204 |
205 | add_subdirectory(src/lib)
206 | add_subdirectory(src/app)
207 | ```
208 |
209 | #### src/lib/CMakeLists.txt
210 |
211 | ```cmake
212 | include_directories("${PROJECT_SOURCE_DIR}/src")
213 | ```
214 |
215 | #### src/app/CMakeLists.txt
216 |
217 | ```cmake
218 | include_directories("${PROJECT_SOURCE_DIR}/src")
219 | ```
220 |
221 |
222 | Links
223 | -----
224 |
225 | - [Current docs](https://cmake.org/cmake/help/latest/):
226 | - [Commands](https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html).
227 |
228 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | Cheatsheet
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
330 |
331 |
332 |
333 |
--------------------------------------------------------------------------------
/sheets/swift.md:
--------------------------------------------------------------------------------
1 | Swift
2 | =====
3 |
4 | Variables
5 | ---------
6 |
7 | ### Scalar
8 |
9 | ```
10 | println("Hello, world")
11 | var myVariable = 42 // variable (can't be nil)
12 | let π = 3.1415926 // constant
13 | let (x, y) = (10, 20) // x = 10, y = 20
14 | let explicitDouble: Double = 1_000.000_1 // 1,000.0001
15 | let label = "some text " + String(myVariable) // Casting
16 | let piText = "Pi = \(π)" // String interpolation
17 | var optionalString: String? = "optional" // Can be nil
18 | optionalString = nil
19 |
20 | /* Did you know /* you can nest multiline comments */ ? */
21 | ```
22 |
23 | ### Arrays
24 |
25 | ```swift
26 | var shoppingList = ["catfish", "water", "lemons"] // Array
27 | shoppingList[1] = "bottle of water" // update
28 | shoppingList.count // size of array (3)
29 | shoppingList.append("eggs")
30 | shoppingList += ["Milk"]
31 | ```
32 |
33 | Array slicing
34 |
35 | ```
36 | var fibList = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 5]
37 | fibList[4..<6] // [3, 5]. Note: the end range value is exclusive
38 | fibList[0..<(fibList.endIndex-1)] // all except last item
39 | ```
40 |
41 | Subscripting returns the Slice type, instead of the Array type.
42 | You may need to cast it to Array in order to satisfy the type checker
43 |
44 | ```
45 | Array(fibList[0..<4])
46 | ```
47 |
48 | Variants of creating an array. All three are equivalent.
49 |
50 | ```
51 | var emptyArray1 = [String]()
52 | var emptyArray2: [String] = []
53 | var emptyArray3: [String] = [String]()
54 | ```
55 |
56 | ### Dictionaries
57 |
58 | ```
59 | var occupations = [ // Dictionary
60 | "Malcolm": "Captain",
61 | "kaylee": "Mechanic"
62 | ]
63 | occupations["Jayne"] = "Public Relations"
64 | var emptyDictionary = Dictionary()
65 | ```
66 |
67 |
68 | Control Flow
69 | ------------
70 |
71 | ### for
72 |
73 | Over an array:
74 |
75 | ```
76 | let myArray = [1, 1, 2, 3, 5]
77 | for value in myArray { // for loop (array)
78 | if value == 1 {
79 | println("One!")
80 | } else {
81 | println("Not one!")
82 | }
83 | }
84 | ```
85 |
86 | Over a dictionary:
87 |
88 | ```
89 | var dict = [
90 | "name": "Steve Jobs",
91 | "title": "CEO",
92 | "company": "Apple"
93 | ]
94 | for (key, value) in dict { // for loop (dictionary)
95 | println("\(key): \(value)")
96 | }
97 | ```
98 |
99 | Ranged. Use `..` to exclude the last item.
100 |
101 | ```
102 | for i in -1...1 { // [-1, 0, 1] // for loop (range)
103 | println(i)
104 | }
105 |
106 | for _ in 1...3 { // for loop (ignoring iterator)
107 | // Do something three times.
108 | }
109 | ```
110 |
111 | ### While
112 |
113 | ```
114 | var i = 1
115 | while i < 1000 { // while loop
116 | i *= 2
117 | }
118 | ```
119 |
120 | ### Do While
121 |
122 | ```
123 | do { // do-while loop
124 | println("hello")
125 | } while 1 == 2
126 | ```
127 |
128 | ### Switch
129 |
130 | Note, no fallthrough.
131 |
132 | ```
133 | let vegetable = "red pepper"
134 | switch vegetable { // Switch
135 | case "celery":
136 | let vegetableComment = "Add some raisins and make ants on a log."
137 | case "cucumber", "watercress":
138 | let vegetableComment = "That would make a good tea sandwich."
139 | case let x where x.hasSuffix("pepper"):
140 | let vegetableComment = "Is it a spicy \(x)?"
141 | default: // required (in order to cover all possible input)
142 | let vegetableComment = "Everything tastes good in soup."
143 | }
144 | ```
145 |
146 | ```
147 | // Switch to validate plist content
148 | let city:Dictionary = [
149 | "name" : "Qingdao",
150 | "population" : 2_721_000,
151 | "abbr" : "QD"
152 | ]
153 | switch (city["name"], city["population"], city["abbr"]) {
154 | case (.Some(let cityName as NSString),
155 | .Some(let pop as NSNumber),
156 | .Some(let abbr as NSString))
157 | where abbr.length == 2:
158 | println("City Name: \(cityName) | Abbr.:\(abbr) Population: \(pop)")
159 | default:
160 | println("Not a valid city")
161 | }
162 | ```
163 |
164 | Functions
165 | ---------
166 |
167 | ### Functions
168 |
169 | Functions are a first-class type, meaning they can be nested in functions and can be
170 | passed around.
171 |
172 | ```
173 | func greet(name: String, day: String) -> String {
174 | return "Hello \(name), today is \(day)."
175 | }
176 | greet("Bob", "Tuesday") // call the greet function
177 | ```
178 |
179 | Function that returns multiple items in a tuple
180 |
181 | ```
182 | func getGasPrices() -> (Double, Double, Double) {
183 | return (3.59, 3.69, 3.79)
184 | }
185 | ```
186 |
187 | Function that takes variable number of arguments, collecting them into an array
188 |
189 | ```
190 | func setup(numbers: Int...) {
191 | // do something
192 | }
193 | setup(5, 16, 38) // call the setup function with array of inputs
194 | ```
195 |
196 | Nested functions can organize code that is long or complex
197 |
198 | ```
199 | func printWelcomeMessage() -> String {
200 | var y = "Hello,"
201 | func add() {
202 | y += " world"
203 | }
204 | add()
205 | return y
206 | }
207 | printWelcomeMessage() // Hello world
208 | ```
209 |
210 | Passing and returning functions
211 |
212 | ```
213 | func makeIncrementer() -> (Int -> Int) {
214 | func addOne(number: Int) -> Int {
215 | return 1 + number
216 | }
217 | return addOne
218 | }
219 | var increment = makeIncrementer()
220 | increment(7)
221 | ```
222 |
223 | ### Closures
224 |
225 | ```
226 | Functions are special case closures ({})
227 | // Closure example.
228 | // `->` separates the arguments and return type
229 | // `in` separates the closure header from the closure body
230 | var numbers = [1, 2, 3, 4, 5]
231 | numbers.map({
232 | (number: Int) -> Int in
233 | let result = 3 * number
234 | return result
235 | })
236 |
237 | // When the type is known, like above, we can do this
238 | numbers = [1, 2, 6]
239 | numbers = numbers.map({ number in 3 * number })
240 | println(numbers) // [3, 6, 18]
241 |
242 | // When a closure is the last argument, you can place it after the )
243 | // When a closure is the only argument, you can omit the () entirely
244 | // You can also refer to closure arguments by position ($0, $1, ...) rather than name
245 | numbers = [2, 5, 1]
246 | numbers.map { 3 * $0 } // [6, 15, 3]
247 | ```
248 |
249 |
250 | Classes & Enums
251 | ---------------
252 |
253 | ### Classes
254 |
255 | All methods and properties of a class are public. If you just need to store data in a
256 | structured object, you should use a struct
257 |
258 | ```
259 | // A parent class of Square
260 | class Shape {
261 | init() {
262 | }
263 |
264 | func getArea() -> Int {
265 | return 0;
266 | }
267 | }
268 |
269 | // A simple class `Square` extends `Shape`
270 | class Square: Shape {
271 | var sideLength: Int
272 |
273 | // Custom getter and setter property
274 | var perimeter: Int {
275 | get {
276 | return 4 * sideLength
277 | }
278 | set {
279 | sideLength = newValue / 4
280 | }
281 | }
282 |
283 | init(sideLength: Int) {
284 | self.sideLength = sideLength
285 | super.init()
286 | }
287 |
288 | func shrink() {
289 | if sideLength > 0 {
290 | --sideLength
291 | }
292 | }
293 |
294 | override func getArea() -> Int {
295 | return sideLength * sideLength
296 | }
297 | }
298 |
299 | var mySquare = Square(sideLength: 5)
300 | print(mySquare.getArea()) // 25
301 | mySquare.shrink()
302 | print(mySquare.sideLength) // 4
303 |
304 | // Access the Square class object, equivalent to [Square class] in Objective-C.
305 | Square.self
306 |
307 | //example for 'willSet' and 'didSet'
308 | class StepCounter {
309 | var totalSteps: Int = 0 {
310 | willSet(newTotalSteps) {
311 | println("About to set totalSteps to \(newTotalSteps)")
312 | }
313 | didSet {
314 | if totalSteps > oldValue {
315 | println("Added \(totalSteps - oldValue) steps to 'totalSteps'")
316 | }
317 | }
318 | }
319 | }
320 |
321 | var stepCounter = StepCounter()
322 | stepCounter.totalSteps = 100 // About to set totalSteps to 100 \n Added 100 steps to 'totalSteps'
323 | stepCounter.totalSteps = 145 // About to set totalSteps to 145 \n Added 45 steps to 'totalSteps'
324 | ```
325 |
326 | If you don't need a custom getter and setter, but still want to run code
327 | before an after getting or setting a property, you can use `willSet` and `didSet`.
328 |
329 | ### Enums
330 |
331 | Enums can optionally be of a specific type or on their own. They can contain methods
332 | like classes.
333 |
334 | ```
335 | enum Suit {
336 | case Spades, Hearts, Diamonds, Clubs
337 | func getIcon() -> String {
338 | switch self {
339 | case .Spades: return "♤"
340 | case .Hearts: return "♡"
341 | case .Diamonds: return "♢"
342 | case .Clubs: return "♧"
343 | }
344 | }
345 | }
346 | ```
347 |
348 |
349 | Protocols
350 | ---------
351 |
352 | A protocol defines a blueprint of methods, properties, and other requirements
353 | that suit a particular task or piece of functionality.
354 |
355 | ```
356 | protocol SomeProtocol {
357 | // protocol definition goes here
358 | }
359 | ```
360 |
361 | Extensions & Overloading
362 | ------------------------
363 |
364 | ### Extensions
365 |
366 | Add extra functionality to an already created type:
367 |
368 | ```
369 | // adds the methods first and rest to the array type
370 | extension Array {
371 | func first () -> Any? {
372 | return self[0]
373 | }
374 | func rest () -> Array {
375 | if self.count >= 1 {
376 | return Array(self[1..self.endIndex])
377 | } else {
378 | return []
379 | }
380 | }
381 | }
382 | ```
383 |
384 | ### Operator Overloading
385 |
386 | You can overwrite existing operators or define new operators for existing or custom types.
387 |
388 | ```
389 | @infix func + (a: Int, b: Int) -> Int { // Overwrite existing types
390 | return a - b
391 | }
392 | var x = 5 + 4 // x is 1
393 | ```
394 |
395 | *You can't overwrite the `=` operator.* Add operators for new types:
396 |
397 | ```
398 | struct Vector2D {
399 | var x = 0.0, y = 0.0
400 | }
401 |
402 | @infix func + (left: Vector2D, right: Vector2D) -> Vector2D {
403 | return Vector2D(x: left.x + right.x, y: left.y + right.y)
404 | }
405 | ```
406 |
407 | Operators can be prefix, infix, or postfix. You have to add `@assignment` if you wish
408 | to define compound assignment operators like `+=`, `++` or `-=`.
409 |
410 | ```
411 | @assignment func += (inout left: Vector2D, right: Vector2D) {
412 | left = left + right
413 | }
414 | ```
415 |
416 | Operator overloading is limited to the following symbols: `/ = - + * % < > ! & | ^ . ~`
417 |
418 |
419 | Generics
420 | --------
421 |
422 | Generic code enables you to write flexible, reusable functions and types that can work
423 | with any type.
424 |
425 | ```
426 | // Generic function, which swaps two any values.
427 | func swapTwoValues(inout a: T, inout b: T) {
428 | let temporaryA = a
429 | a = b
430 | b = temporaryA
431 | }
432 |
433 | // Generic collection type called `Stack`.
434 | struct Stack {
435 | var elements = T[]()
436 |
437 | mutating func push(element: T) {
438 | elements.append(element)
439 | }
440 |
441 | mutating func pop() -> T {
442 | return elements.removeLast()
443 | }
444 | }
445 | ```
446 |
447 | We can use certain type constraints on the types with generic functions and generic
448 | types. Use where after the type name to specify a list of requirements.
449 |
450 | ```
451 | // Generic function, which checks that the sequence contains a specified value.
452 | func containsValue<
453 | T where T: Sequence, T.GeneratorType.Element: Equatable>
454 | (sequence: T, valueToFind: T.GeneratorType.Element) -> Bool {
455 |
456 | for value in sequence {
457 | if value == valueToFind {
458 | return true
459 | }
460 | }
461 |
462 | return false
463 | }
464 | ```
465 |
466 | In the simple cases, you can omit where and simply write the protocol or class name
467 | after a colon. Writing `` is the same as writing ``.
468 |
469 |
470 | Useful links
471 | ------------
472 |
473 | - [Swift homepage](https://developer.apple.com/swift/).
474 | - [Swift Gitbook](https://mhm5000.gitbooks.io/swift-cheat-sheet/content/dictionaries/index.html) :
475 | origin of these samples.
476 |
477 |
478 | Notes
479 | -----
480 |
481 |
482 |
483 |
484 |
485 |
--------------------------------------------------------------------------------
/sheets/glsl.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | GLSL
4 | ====
5 |
6 | Vertex Shader
7 | -------------
8 |
9 | - [OpenGL wiki](https://www.opengl.org/wiki/Vertex_Shader)
10 |
11 | #### Built-in inputs
12 |
13 | ```glsl
14 | in int gl_VertexID;
15 | in int gl_InstanceID;
16 | ```
17 |
18 | - `gl_VertexID`: index of vertex being processed. When using non-indexed rendering, it is the
19 | effective index of the current vertex (the number of vertices processed + the first value). For
20 | indexed rendering, it is the index used to fetch this vertex from the buffer. Note: gl_VertexID
21 | will have the base vertex applied to it.
22 | - `gl_InstanceID`: index of instance when doing some form of instanced rendering. Instance
23 | count always starts at 0, even when using base instance calls. When not using instanced
24 | rendering, this value 0.
25 |
26 | #### User input
27 |
28 | ```glsl
29 | layout(location = 2) in vec4 a_vec;
30 | ```
31 |
32 | - `layout(location = #)` optional attribute index. Matrices take one index per column.
33 |
34 | #### Output
35 |
36 | ``` glsl
37 | out gl_PerVertex
38 | {
39 | vec4 gl_Position;
40 | float gl_PointSize;
41 | float gl_ClipDistance[];
42 | };
43 | ```
44 |
45 | - `gl_PerVertex` defines *interface block* for outputs. Block is defined without instance name,
46 | so prefixing not required.
47 | - `gl_Position`: clip-space output position of the current vertex.
48 | - `gl_PointSize`: pixel width/height of point being rasterized, when rendering point primitives.
49 | Clamped to the `GL_POINT_SIZE_RANGE`.
50 | - `gl_ClipDistance`: allows the shader to set the distance from the vertex to each user-defined
51 | clipping half-space.
52 |
53 |
54 | Fragment Shader
55 | ---------------
56 |
57 | - [OpenGL wiki](https://www.opengl.org/wiki/Fragment_Shader)
58 | - Fragment shaders are technically an optional shader stage, e.g. shadow mapping. If none, Fragment
59 | output colour values undefined. However, depth and stencil values output = input.
60 | - Fragment shaders have access to the `discard` command. Causes output values to be discarded.
61 | Fragment does not proceed to next pipeline stages.
62 |
63 | #### Built-in inputs
64 |
65 | ``` glsl
66 | in vec4 gl_FragCoord;
67 | in bool gl_FrontFacing;
68 | in vec2 gl_PointCoord;
69 | ```
70 | ``` glsl
71 | // All the following are allowed redeclaration that change behavior
72 | layout(origin_upper_left) in vec4 gl_FragCoord;
73 | layout(pixel_center_integer) in vec4 gl_FragCoord;
74 | layout(origin_upper_left, pixel_center_integer) in vec4 gl_FragCoord;
75 | ```
76 |
77 | - `gl_FragCoord`: location of the fragment in window space. XYZ components are the *window-space*
78 | position of the fragment. Z will be written to the depth buffer if `gl_FragDepth` not written
79 | to. W component is 1/Wclip, where Wclip is the interpolated W of clip-space `gl_Position` from
80 | last Vertex Processing stage. The coordinate space of `gl_FragCoord` can be modified by redeclaring it:
81 | - `layout(origin_upper_left) in vec4 gl_FragCoord;` : This means that the origin for
82 | `gl_FragCoord`'s window-space will be the upper-left of the screen, rather than the usual
83 | lower-left.
84 | - `layout(pixel_center_integer) in vec4 gl_FragCoord;` : OpenGL window space is defined so pixel
85 | centers are on *half-integer* boundaries. Center of lower-left pixel is (0.5, 0.5). Using
86 | `pixel_center_integer` adjust gl_FragCoord such that whole integer values represent pixel
87 | centers. Both of these exist to be compatible with D3D's window space. Unless you need your
88 | shaders to have this compatibility, you are advised not to use these features.
89 | - `gl_FrontFacing`: True if this fragment was generated by the front-face of the primitive; else
90 | false if back. Only triangles have a back face; else this always true.
91 |
92 | - `gl_PointCoord`: Location *within a point primitive*; defines fragment position relative to side
93 | of point, range [0,1], (0,0) upper-left. Points effectively window-space squares of certain pixel
94 | size, defined by single vertex. Origin can be switched to a bottom-left origin by calling
95 | `glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);`
96 |
97 | **OpenGL 4.0+**:
98 |
99 | ```glsl
100 | in int gl_SampleID;
101 | in vec2 gl_SamplePosition;
102 | in int gl_SampleMaskIn[];
103 | ```
104 |
105 | - `gl_SampleID`: Current sample that this fragment is rasterized for. *Warning:* Using this forces
106 | shader evaluation per-sample. Since much of the point of multisampling is to avoid that, you
107 | should use it only when you must.
108 | - `gl_SamplePosition`: This is the location of the current sample for the fragment within the
109 | pixel's area, with values, range [0,1]. Origin is the bottom-left of the pixel. *Warning:* Using
110 | this forces this shader evaluation per-sample. Since much of the point of multisampling is to
111 | avoid that, you should use it only when you must.
112 | - `gl_SampleMaskIn`: When using multisampling, this variable contains a bitfield for the sample
113 | mask of the fragment being generated. The array is as long as needed to fill in the number of
114 | samples supported by the GL implementation.
115 |
116 | Some Fragment shader built-in inputs will take values specified by OpenGL, but these values can be overridden by user control.
117 |
118 | ```glsl
119 | in float gl_ClipDistance[];
120 | in int gl_PrimitiveID;
121 | ```
122 |
123 | - `gl_ClipDistance`: This array contains the interpolated clipping plane half-spaces, as output
124 | for vertices from the last Vertex Processing stage.
125 | - `gl_PrimitiveID`: index of the current primitive being rendered by this drawing command.
126 |
127 | **OpenGL 4.3+**:
128 |
129 | ```glsl
130 | in int gl_Layer;
131 | in int gl_ViewportIndex;
132 | ```
133 |
134 | - `gl_Layer`: either 0 or the layer number for this primitive output by the Geometry Shader.
135 | - `gl_ViewportIndex`: either 0 or the viewport index for primitive output by the Geometry Shader.
136 |
137 | #### Outputs
138 |
139 | ```glsl
140 | layout(location = 1) out int materialID;
141 | layout(location = 4) out vec3 normal;
142 | layout(location = 0) out vec4 diffuseColor;
143 | layout(location = 3) out vec3 position;
144 | layout(location = 2) out vec4 specularColor;
145 | ```
146 |
147 |
148 | Tips
149 | ----
150 |
151 | ### Use Swizzle
152 |
153 | ```glsl
154 | gl_Position.x = in_pos.x;
155 | gl_Position.y = in_pos.y;
156 | ```
157 | faster as:
158 | ```glsl
159 | gl_Position.xy = in_pos.xy;
160 | ```
161 |
162 | ### MAD
163 |
164 | Use multiply-add, i.e. A*B + C.
165 | ```glsl
166 | vec4 result1 = (value / 2.0) + 1.0;
167 | vec4 result2 = (1.0 + variable) * 0.5;
168 |
169 | // is more efficient as:
170 | vec4 result1 = (value * 0.5) + 1.0;
171 | vec4 result2 = 0.5 * variable + 0.5; // A*B + C
172 | ```
173 |
174 | Swizzle can be combined:
175 | ```glsl
176 | myOutputColor.xyz = myColor.xyz;
177 | myOutputColor.w = 1.0;
178 | gl_FragColor = myOutputColor;
179 |
180 | // or, better:
181 | const vec2 constantList = vec2(1.0, 0.0);
182 | gl_FragColor = mycolor.xyzw * constantList.xxxy + constantList.yyyx;
183 | ```
184 |
185 | ### Mix for lerp
186 |
187 | ```glsl
188 | vec3 colorRGB_0, colorRGB_1;
189 | float alpha;
190 | resultRGB = colorRGB_0 * (1.0 - alpha) + colorRGB_1 * alpha;
191 | ```
192 |
193 | better, MAD:
194 | ```glsl
195 | resultRGB = colorRGB_0 + alpha * (colorRGB_1 - colorRGB_0);
196 | ```
197 |
198 | best, `mix`:
199 | ```glsl
200 | resultRGB = mix(colorRGB_0, colorRGB_1, alpha);
201 | ```
202 |
203 |
204 | Types
205 | -----
206 |
207 | The OpenGL Shading Language supports the following basic data types, grouped as follows.
208 |
209 | ### Transparent types
210 |
211 | Type | Meaning
212 | ---- | -------
213 | `void` | for functions that do not return a value
214 | `bool` | a conditional type, taking on values of true or false
215 | `int` | a signed integer
216 | `uint` | an unsigned integer
217 | `float` | a single-precision floating-point scalar
218 | `double` | a double-precision floating-point scalar
219 | `vecN` | a multi-component single-precision floating-point vector. N = [2,3,4].
220 | `dvecN` | a multi-component double-precision floating-point vector. N = [2,3,4].
221 | `bvecN` | a multi-component Boolean vector. N = [2,3,4].
222 | `ivecN` | a multi-component signed integer vector. N = [2,3,4].
223 | `ivecN` | a multi-component unsigned integer vector. N = [2,3,4].
224 | `matN` | an N×N single-precision floating-point matrix. N = [2,3,4].
225 | `matNxN` | same as a `matN`
226 | `matNxM` | an NxM double-precision floating-point matrix with N columns and M rows. N,M = [2,3,4].
227 | `dmatN` | an N×N double-precision floating-point matrix. N = [2,3,4].
228 | `dmatNxN` | same as a `dmatN`
229 | `dmatNxM` | an NxM double-precision floating-point matrix with N columns and M rows. N,M = [2,3,4].
230 |
231 | ### Floating-Point Opaque Types
232 |
233 | Type | Meaning
234 | ---- | -------
235 | `sampler1D`, `image1D` | a handle for accessing a 1D texture
236 | `sampler2D`, `image2D` | a handle for accessing a 2D texture
237 | `sampler3D`, `image3D` | a handle for accessing a 3D texture
238 | `samplerCube`, `imageCube` | a handle for accessing a cube mapped texture
239 | `sampler2DRect`, `image2DRect` | a handle for accessing a rectangle texture
240 | `sampler1DArray`, `image1DArray` | a handle for accessing a 1D array texture
241 | `sampler2DArray`, `image2DArray` | a handle for accessing a 2D array texture
242 | `samplerBuffer`, `imageBuffer` | a handle for accessing a buffer texture
243 | `sampler2DMS`, `image2DMS` | a handle for accessing a 2D multi-sample texture
244 | `sampler2DMSArray`, `image2DMSArray` | a handle for accessing a 2D multi-sample array texture
245 | `samplerCubeArray`, `imageCubeArray` | a handle for accessing a cube map array texture
246 | `sampler1DShadow` |` `a handle for accessing a 1D depth texture with comparison
247 | `sampler2DShadow` | a handle for accessing a 2D depth texture with comparison
248 | `sampler2DRectShadow` | a handle for accessing a rectangle texture with comparison
249 | `sampler1DArrayShadow` | a handle for accessing a 1D array depth texture with comparison
250 | `sampler2DArrayShadow` | a handle for accessing a 2D array depth texture with comparison
251 | `samplerCubeShadow` | a handle for accessing a cube map depth texture with comparison
252 | `samplerCubeArrayShadow` | a handle for accessing a cube map array depth texture with comparison
253 |
254 | TODO - add other opaque types
255 |
256 | ### Storage Qualifiers
257 |
258 | Variable declarations may have at most one storage qualifier specified in front of the type. These are summarized as
259 |
260 | Storage Qualifier | Meaning
261 | ----------------- | -------
262 | none: default | local read/write memory, or an input parameter to a function
263 | `const` | a variable whose value cannot be changed
264 | `in` | linkage into a shader from a previous stage, variable is copied in
265 | `out` | linkage out of a shader to a subsequent stage, variable is copied out
266 | `attribute` | compatibility profile only and vertex language only; same as in when in a vertex shader
267 | `uniform` | value does not change across the primitive being processed, uniforms form the linkage between a shader, OpenGL, and the application
268 | `varying` | compatibility profile only and vertex and fragment languages only; same as out when in a vertex shader and same as in when in a fragment shader
269 | `buffer` | value is stored in a buffer object, and can be read or written both by shader invocations and the OpenGL API
270 | `shared` | compute shader only; variable storage is shared across all work items in a local work group
271 |
272 |
273 | Glossary
274 | --------
275 |
276 | - **Compute Processor**: programmable unit that operates independently from the other shader
277 | processors. Compilation units written in the OpenGL Shading Language to run on this processor are
278 | called *compute shaders*. It does not have any predefined inputs nor any fixed-function outputs.
279 | It is not part of the graphics pipeline and its visible side effects are through changes to
280 | images, storage buffers, and atomic counters. A compute shader operates on a group of work items
281 | called a *work group*.
282 | - **Fragment Processor**: programmable unit that operates on fragment values and their associated
283 | data. Compilation units written in the OpenGL Shading Language to run on this processor are
284 | called *fragment shaders*. A fragment shader cannot change a fragment's (x, y) position. Access
285 | to neighboring fragments is not allowed. The values computed by the fragment shader are
286 | ultimately used to update framebuffer memory or texture memory, depending on the current OpenGL
287 | state and the OpenGL command that caused the fragments to be generated.
288 | - **Geometry Processor**: programmable unit that operates on data for incoming vertices for a
289 | primitive assembled after vertex processing and outputs a sequence of vertices forming output
290 | primitives. Compilation units written in the OpenGL Shading Language to run on this processor are
291 | called *geometry shaders*. This single invocation can emit a variable number of vertices that are
292 | assembled into primitives of a declared output primitive type and passed to subsequent pipeline
293 | stages.
294 | - **Opaque Types**: opaque handles to other objects. These objects are accessed through built-in
295 | functions, not through direct reading or writing of the declared variable. They can only be
296 | declared as function parameters or in uniform-qualified variables.
297 | - **Output Variables**: Declared using the storage qualifier `out`. They form the output interface
298 | between the declaring shader and the subsequent stages of the OpenGL pipeline. Output variables
299 | must be declared at global scope. During shader execution they will behave as normal unqualified
300 | global variables. Their values are copied out to the subsequent pipeline stage on shader exit.
301 | Only output variables that are read by the subsequent pipeline stage need to be written; it is
302 | allowed to have superfluous declarations of output variables.
303 | - **Uniform Variables**: The `uniform` qualifier is used to declare global variables whose values
304 | are the same across the entire primitive being processed. All uniform variables are *read-only*
305 | and are initialized externally either at link time or through the API. The link-time initial
306 | value is either the value of the variable's initializer, if present, or 0 if no initializer is
307 | present. Opaque types cannot have initializers, or a compile-time error results.
308 | - **Vertex Processor**: programmable unit that operates on incoming vertices and their
309 | associated data. Compilation units written in the OpenGL Shading Language to run on this
310 | processor are called *vertex shaders*.
311 | - **Work group**: a collection of shader invocations that execute the same code, potentially in
312 | parallel. An invocation within a work group may share data with other members of the same work
313 | group through shared variables and issue memory and control barriers to synchronize with other
314 | members of the same work group.
315 |
316 |
317 | ### Links
318 |
319 | - Source for this doc: https://www.opengl.org/registry/doc/GLSLangSpec.4.40.pdf
320 | - [GLSL wikipedia](https://en.wikipedia.org/wiki/OpenGL_Shading_Language)
321 | - [OpenGL wiki GLSL](https://www.opengl.org/wiki/OpenGL_Shading_Language)
322 |
323 |
--------------------------------------------------------------------------------
/sheets/bash.md:
--------------------------------------------------------------------------------
1 |
2 | BASH
3 | ====
4 |
5 | References
6 | ----------
7 |
8 | - [BASH reference manual](https://www.gnu.org/software/bash/manual/bash.html).
9 | - [Grymoire](http://www.grymoire.com/Unix/index.html) - intro to UNIX concepts
10 | - [ss64 UNIX commands](http://ss64.com/bash/) - help on each command
11 | - [Shell Fu](http://www.shell-fu.org)
12 |
13 |
14 | Control
15 | -------
16 |
17 | ### Logic
18 |
19 | ```bash
20 | if [ EXPRESSION ]; then
21 | COMMANDS
22 | fi
23 | ```
24 |
25 | ```bash
26 | if [ EXPRESSION ]; then
27 | COMMANDS
28 | else
29 | COMMANDS
30 | fi
31 | ```
32 |
33 | ```bash
34 | if [ EXPRESSION ]; then
35 | commands
36 | elif [ EXPRESSION2 ]; then
37 | COMMANDS
38 | else
39 | COMMANDS
40 | fi
41 | ```
42 |
43 | ```bash
44 | case STRING in
45 | str1) COMMANDS;;
46 | str2) COMMANDS;;
47 | *) COMMANDS;;
48 | esac
49 | ```
50 |
51 | ```bash
52 | LIST="one two three"
53 | for VAR1 in $LIST
54 | do
55 | COMMANDS
56 | done
57 | ```
58 |
59 | ```bash
60 | while [ EXPRESSION ]
61 | do
62 | COMMANDS
63 | done
64 | ```
65 |
66 | ```bash
67 | until [ EXPRESSION ]
68 | do
69 | COMMANDS
70 | done
71 | ```
72 |
73 | #### Select
74 |
75 | Easy generation of menus:
76 |
77 | ```bash
78 | select NAME [in WORDS]; do COMMANDS; done
79 | ```
80 |
81 | - WORDS is expanded, generating *list of items*.
82 | - *List* is printed on the *stderr stream*, each preceded by a number.
83 | - `select N; do COMMANDS; done` - line is read from the standard input, as if `in "$@"` specified.
84 |
85 | The *PS3 prompt* is then displayed and a line is *read from stdin*:
86 |
87 | - If input line a *number* corresponding to displayed word, value of name is set to word.
88 | - If input line *empty*, the words and prompt are displayed again.
89 | - If *EOF* is read, the select command completes.
90 | - Any *other* value read causes name to be set to null.
91 | - The line read is saved in the *variable REPLY*.
92 |
93 | The commands are executed after each selection until a break command is executed (or Ctrl + D).
94 |
95 | ```bash
96 | # Pick a filename from the current directory, and.out displays the name and
97 | # index of the file selected.
98 | select fname in *;
99 | do
100 | echo "You picked $fname \($REPLY\)";
101 | break;
102 | done
103 | ```
104 |
105 | ### Functions
106 |
107 | Functions are declared using syntax:
108 |
109 | ```bash
110 | [function] NAME [()] COMPOUND-COMMAND [ REDIRECTIONS ]
111 | ```
112 |
113 | Functions can have input and output *redirected*. E.g. when called,
114 | *input* comes from`foo.in`, *output* to `foo.out`, and *error* to `foo.err`:
115 |
116 | ```bash
117 | function foo() {
118 | COMMANDS;
119 | } < foo.in > foo.out 2> foo.err
120 |
121 | ```
122 |
123 |
124 | Input
125 | -----
126 |
127 | #### read
128 |
129 | Synopsis: `read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]` [docs](https://www.gnu.org/software/bash/manual/bash.html#index-read)
130 |
131 | - `-a aname` :: Words are assigned to array variable `aname`, starting at 0. All elements are removed from aname before the assignment. Other name arguments are ignored.
132 | - `-d delim` :: The first character of delim is used to terminate the input line, rather than newline.
133 | - `-e` :: Readline used to obtain line.
134 | - `-i text` :: If Readline used, text placed into editing buffer before editing begins.
135 | - `-n nchars` :: read returns after reading nchars characters rather than waiting for a complete line of input, but honors a delimiter if fewer than nchars characters are read before the delimiter.
136 | - `-N nchars` :: read returns after exactly nchars characters, unless EOF is encountered or read times out. Delimiter chars are not special and do not cause read to return until nchars characters are read. Result is not split on the characters in IFS; the intent is that the variable is assigned exactly the characters read.
137 | - `-p prompt` :: Display prompt, without a trailing newline, before attempting to read any input. Prompt is displayed only if input is coming from a terminal.
138 | - `-r` :: If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.
139 | - `-s` :: Silent mode. If input is coming from a terminal, characters are not echoed.
140 | - `-t timeout` :: Timeout after timeout seconds. Only effective if reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If read times out, read saves any partial input read into the specified variable name. If timeout is 0, read returns immediately, without trying to read and data. The exit status is 0 if input is available on the specified file descriptor, non-zero otherwise. The exit status is greater than 128 if the timeout is exceeded.
141 | - `-u fd` :: Read input from file descriptor fd.
142 |
143 | ```bash
144 | read -p "prompt> " VAR
145 | echo ${VAR:-"Nothing entered"}
146 | ```
147 |
148 | #### getopts
149 |
150 | ```bash
151 | while getopts "a:b" options; do
152 | case "${options}" in
153 | a) A=${OPTARG} ;;
154 | b) echo "B" ;;
155 | :) echo "Option ${OPTARG} expects an argument" && exit 2 ;;
156 | *) echo "Unknown option" && exit 2 ;;
157 | esac
158 | done
159 | ```
160 |
161 | Output
162 | ------
163 |
164 | #### cat
165 |
166 | Synopsis: `cat [-benstuv] [file ...]`
167 |
168 | Print the contents of file1 to the standard output:
169 |
170 | ```bash
171 | cat file1
172 | ```
173 |
174 | Sequentially print the contents of file1 and file2 to the file file3, truncating file3 if it
175 | already exists.
176 |
177 | ```bash
178 | cat file1 file2 > file3
179 | ```
180 |
181 | Print the contents of file1, print data it receives from the standard input until receive an
182 | `EOF` (`^D`) character, print the contents of file2, read and output contents of the standard input
183 | again, then finally output the contents of file3.
184 |
185 | ```bash
186 | cat file1 - file2 - file3
187 | ```
188 |
189 | Write between markers, with redirection, to file1:
190 |
191 | ```bash
192 | cat << EOM > file1
193 | This line will write to the file.
194 | ${THIS} will also write to the file, with the variable contents substituted.
195 | EOM
196 | ```
197 |
198 |
199 | Tests
200 | -----
201 |
202 | `test expression` or `[ expression ]`
203 |
204 | #### Numeric Comparisons
205 |
206 | - `int1 -eq int2` :: True if int1 is equal to int2.
207 | - `int1 -ge int2` :: True if int1 is greater than or equal to int2.
208 | - `int1 -gt int2` :: True if int1 is greater than int2.
209 | - `int1 -le int2` :: True if int1 is less than or equal to int2
210 | - `int1 -lt int2` :: True if int1 is less than int2
211 | - `int1 -ne int2` :: True if int1 is not equal to int2
212 |
213 |
214 | #### String Comparisons
215 |
216 | - `str1 = str2` :: True if str1 is identical to str2.
217 | - `str1 != str2` :: True if str1 is not identical to str2.
218 | - `str` :: True if str is not null.
219 | - `-n str` :: True if the length of str is greater than zero.
220 | - `-z str` :: True if the length of str is equal to zero. (zero is different than null)
221 |
222 |
223 | #### File Comparisons
224 |
225 | - `-d filename` :: True if file, filename is a directory.
226 | - `-f filename` :: True if file, filename is an ordinary file.
227 | - `-r filename` :: True if file, filename can be read by the process.
228 | - `-s filename` :: True if file, filename has a nonzero length.
229 | - `-w filename` :: True if file, filename can be written by the process.
230 | - `-x filename` :: True if file, filename is executable.
231 |
232 |
233 | #### Expression Comparisons
234 |
235 | - `!expression` :: True if expression is not true.
236 | - `expr1 -a expr2` :: True if expr1 and expr2 are true. ( && , and )
237 | - `expr1 -o expr2` :: True if expr1 or expr2 is true. ( ||, or )
238 |
239 |
240 | Variables
241 | ---------
242 |
243 | #### Arguments
244 |
245 | - `$0` :: Stores the first word of the entered command (the name of the shell program).
246 | - `$1-$N` :: Stores the arguments (variables) that were passed to the shell program from the command line.
247 | - `$*` :: Stores all the arguments that were entered on the command line `($1 $2 ...)`.
248 | - `"$@"` :: Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).
249 | - `$?` :: Stores the exit value of the last command that was executed.
250 |
251 | #### Defaults
252 |
253 | - `${PARAM:-WORD}` :: If PARAM is unset or null, the expansion of WORD is substituted. Otherwise, the value of PARAM is substituted.
254 | - `${PARAM:=WORD}` :: If PARAM is unset or null, the expansion of WORD is assigned to PARAM. The value of PARAM is then substituted. Positional parameters and special parameters may not be assigned to in this way.
255 | - `${PARAM:?WORD}` :: If PARAM is null or unset, the expansion of WORD (or a message to that effect if WORD is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of PARAM is substituted.
256 | - `${PARAM:+WORD}` :: If PARAM is null or unset, nothing is substituted, otherwise the expansion of WORD is substituted.
257 |
258 | #### Slicing
259 |
260 | - `${PARAM:OFFSET}` :: All characters after OFFSET. Note: -ve OFFSET is from end.
261 | - `${PARAM:OFFSET:LENGTH}` :: Slice characters after OFFSET for LENGTH.
262 | - `${@:OFFSET}` :: `@` = use positional parameters. OFFSET from start.
263 | - `${@:OFFSET:LENGTH}` :: Slice parameters from OFFSET for LENGTH.
264 |
265 | #### Counting
266 |
267 | - `${#PARAM}` :: Length of PARAM in chars.
268 |
269 | #### Substitution
270 |
271 | - `${PARAM/PATTERN/STRING}` :: Longest match of PATTERN is replaced with STRING. Pattern: `#` = PARAM start. @,* apply to positional params.
272 | - `${PARAM#WORD}` :: WORD is pattern ('?','*' wildcards). Shortest matching pattern deleted from string start.
273 | - `${PARAM##WORD}` :: As above, but longest matching pattern deleted from string start.
274 | - `${PARAM%WORD}` :: WORD is pattern ('?','*' wildcards). Shortest matching pattern deleted from string end.
275 | - `${PARAM%%WORD}` :: As above, but longest matching pattern deleted from string end.
276 | - `${PARAM^PATTERN}` :: Modify case of PARAM where pattern matched. Make upper case first char.
277 | - `${PARAM^^PATTERN}` :: As above. Make upper case all char.
278 | - `${PARAM,PATTERN}` :: As above. Make lower case first char.
279 | - `${PARAM,,PATTERN}` :: As above. Make lower case all chars.
280 |
281 | ### Useful
282 |
283 | * `SCRIPTPATH=$(cd $(dirname $0); pwd -P)` - Path of current script.
284 |
285 | #### set
286 |
287 | ```bash
288 | set -o errexit -o nounset
289 | ```
290 |
291 | - errexit :: stop executing if any errors occur, by default bash will just continue past any errors
292 | to run the next command
293 | - nounset :: stop executing if an unset variable is encountered, by default bash will use an empty
294 | string for the value of such variables.
295 |
296 |
297 | Date
298 | ----
299 |
300 | `date +"%FORMAT"` used to display or set date and time. Command:
301 |
302 | date "+DATE: %Y-%m-%d%nTIME: %H:%M:%S"
303 |
304 | displays:
305 |
306 | ```raw
307 | DATE: 1987-11-21
308 | TIME: 13:36:16
309 | ```
310 |
311 |
312 | %FORMAT String | Description
313 | -------------- | -----------
314 | `%%` | a literal %
315 | `%a` | locale’s abbreviated weekday name (e.g., Sun)
316 | `%A` | locale’s full weekday name (e.g., Sunday)
317 | `%b` | locale’s abbreviated month name (e.g., Jan)
318 | `%B` | locale’s full month name (e.g., January)
319 | `%c` | locale’s date and time (e.g., Thu Mar 3 23:05:25 2005)
320 | `%C` | century; like %Y, except omit last two digits (e.g., 21)
321 | `%d` | day of month (e.g, 01)
322 | `%D` | date; same as %m/%d/%y
323 | `%e` | day of month, space padded; same as %_d
324 | `%F` | full date; same as %Y-%m-%d
325 | `%g` | last two digits of year of ISO week number (see %G)
326 | `%G` | year of ISO week number (see %V); normally useful only with %V
327 | `%h` | same as %b
328 | `%H` | hour (00..23)
329 | `%I` | hour (01..12)
330 | `%j` | day of year (001..366)
331 | `%k` | hour ( 0..23)
332 | `%l` | hour ( 1..12)
333 | `%m` | month (01..12)
334 | `%M` | minute (00..59)
335 | `%n` | a newline
336 | `%N` | nanoseconds (000000000..999999999)
337 | `%p` | locale’s equivalent of either AM or PM; blank if not known
338 | `%P` | like %p, but lower case
339 | `%r` | locale’s 12-hour clock time (e.g., 11:11:04 PM)
340 | `%R` | 24-hour hour and minute; same as %H:%M
341 | `%s` | seconds since 1970-01-01 00:00:00 UTC
342 | `%S` | second (00..60)
343 | `%t` | a tab
344 | `%T` | time; same as %H:%M:%S
345 | `%u` | day of week (1..7); 1 is Monday
346 | `%U` | week number of year, with Sunday as first day of week (00..53)
347 | `%V` | ISO week number, with Monday as first day of week (01..53)
348 | `%w` | day of week (0..6); 0 is Sunday
349 | `%W` | week number of year, with Monday as first day of week (00..53)
350 | `%x` | locale’s date representation (e.g., 12/31/99)
351 | `%X` | locale’s time representation (e.g., 23:13:48)
352 | `%y` | last two digits of year (00..99)
353 | `%Y` | year
354 | `%z` | +hhmm numeric timezone (e.g., -0400)
355 | `%:z` | +hh:mm numeric timezone (e.g., -04:00)
356 | `%::z` | +hh:mm:ss numeric time zone (e.g., -04:00:00)
357 | `%:::z` | numeric time zone with : to necessary precision (e.g., -04, +05:30)
358 | `%Z` | alphabetic time zone abbreviation (e.g., EDT)
359 |
360 |
361 | Keyboard
362 | --------
363 |
364 | Shortcut | Comment
365 | ------------------------------ | -----------------------------------------
366 | CTRL + A | move to beginning of line
367 | CTRL + B | moves backward one character
368 | CTRL + C | halts the current command
369 | CTRL + D | deletes one character backward or logs out of current session, similar to exit
370 | CTRL + E | moves to end of line
371 | CTRL + F | moves forward one character
372 | CTRL + G | aborts the current editing command and ring the terminal bell
373 | CTRL + J | same as RETURN
374 | CTRL + K | deletes (kill) forward to end of line
375 | CTRL + L | clears screen and redisplay the line
376 | CTRL + M | same as RETURN
377 | CTRL + N | next line in command history
378 | CTRL + O | same as RETURN, then displays next line in history file
379 | CTRL + P | previous line in command history
380 | CTRL + R | searches backward
381 | CTRL + S | searches forward
382 | CTRL + T | transposes two characters
383 | CTRL + U | kills backward from point to the beginning of line
384 | CTRL + V | makes the next character typed verbatim
385 | CTRL + W | kills the word behind the cursor
386 | CTRL + X | lists the possible filename completefions of the current word
387 | CTRL + Y | retrieves (yank) last item killed
388 | CTRL + Z | stops the current command, resume with fg in the foreground or bg in the background
389 |
390 |
391 | Tips
392 | ----
393 |
394 | ### History
395 |
396 | Config (`.bashrc`):
397 |
398 | shopt -s histappend
399 | shopt -s cmdhist
400 | export HISTCONTROL="erasedups:ignoreboth" # ignore duplicates
401 | export HISTIGNORE="&:[ ]*:exit"
402 | export HISTFILESIZE=500000
403 | export HISTSIZE=10000
404 |
405 | Top 10 commands used:
406 |
407 | history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -nr | head
408 |
409 | ### Navigation
410 |
411 | Takes you to the previous directory you were in:
412 |
413 | cd -
414 |
415 | List only subdirectoies in current one:
416 |
417 | ls -d */
418 |
419 | ### Renaming
420 |
421 | Renaming/moving files with suffixes quickly:
422 |
423 | cp /home/foo/realllylongname.cpp{,-old}
424 |
425 | This expands to:
426 |
427 | cp /home/foo/realllylongname.cpp /home/foo/realllylongname.cpp-old
428 |
429 | ### Repeat
430 |
431 | Another favorite:
432 |
433 | `!!` and `!?` (matching) repeats your last command. E.g.
434 |
435 | ```bash
436 | !! # repeat
437 | sudo !!
438 | !?foo # repeat last command starting with "foo"
439 | ```
440 |
441 | Print last command:
442 |
443 | !!:p
444 | !?foo?:p # print last command starting with "foo"
445 |
446 | `^search^replace` takes the last command applying a search and replace:
447 |
448 | $ ehco foo bar baz
449 | bash: ehco: command not found
450 | $ ^ehco^echo
451 | foo bar baz
452 |
453 | Run command with the previous command's arguments:
454 |
455 | $ mkdir /tmp/new
456 | $ cd !!:*
457 |
458 |
459 | ### Sources
460 |
461 | - Stack Overflow [favourite BASH tricks](http://stackoverflow.com/q/68372/3233)
462 |
463 |
464 | Notes
465 | -----
466 |
467 |
468 |
469 | #### spe1
470 |
471 | ```bash
472 | VAR=${1:-'default'}
473 | ```
474 |
475 |
476 |
--------------------------------------------------------------------------------
/sheets/textmate.md:
--------------------------------------------------------------------------------
1 |
2 | Textmate 2
3 | ==========
4 |
5 |
6 | Regular Expressions
7 | -------------------
8 |
9 | Regular-Expressions.info
10 | A.M. Kuchling’s Regular Expression HOWTO
11 | Steve Mansour’s A Tao of Regular Expressions
12 | Jeffrey Friedl’s Mastering Regular Expressions (book)
13 |
14 | Here is a list of places where TextMate makes use of regular expressions:
15 |
16 | - Filtering which files should be shown in folder references (added to projects) is done by
17 | providing regular expressions.
18 | - Find and Find in Project both allow regular expression replacements.
19 | - Folding markers are found via regular expressions.
20 | - Indentation calculations are based on regular expression matches.
21 | - Language grammars are basically a tree (with cycles) that have regular expressions in each node.
22 | - Snippets allow regular expression replacements to be applied to variables and (in realtime)
23 | mirrored placeholders.
24 |
25 | Regex Syntax
26 | ------------
27 |
28 | TextMate uses the Oniguruma regular expression library by K. Kosako. Oniguruma Regular Expressions
29 | Version 5.6.0 2007/04/03
30 |
31 | syntax: ONIG_SYNTAX_RUBY (default)
32 |
33 | ### Syntax elements
34 |
35 | - `\` :: escape (enable or disable meta character meaning)
36 | - `|` :: alternation
37 | - `(...)` :: group
38 | - `[...]` :: character class
39 |
40 |
41 | #### Characters
42 |
43 | - `\t` :: horizontal tab (0x09)
44 | - `\v` :: vertical tab (0x0B)
45 | - `\n` :: newline (0x0A)
46 | - `\r` :: return (0x0D)
47 | - `\b` :: back space (0x08)
48 | - `\f` :: form feed (0x0C)
49 | - `\a` :: bell (0x07)
50 | - `\e` :: escape (0x1B)
51 | - `\nnn` :: octal char (encoded byte value)
52 | - `\xHH` :: hexadecimal char (encoded byte value)
53 | - `\x{7HHHHHHH}` :: wide hexadecimal char (character code point value)
54 | - `\cx` :: control char (character code point value)
55 | - `\C-x` :: control char (character code point value)
56 | - `\M-x` :: meta (x|0x80) (character code point value)
57 | - `\M-\C-x` :: meta control char (character code point value)
58 |
59 | `* \b` is effective in character class `[...]` only
60 |
61 |
62 | #### Character types
63 |
64 | - `.` :: any character (except newline)
65 | - `\w` :: word character
66 | Not Unicode: alphanumeric, "_" and multibyte char.
67 | Unicode: General_Category -- (Letter|Mark|Number|Connector_Punctuation)
68 | - `\W` :: non word char
69 |
70 | - `\s` :: whitespace char
71 | Not Unicode: `\t`, `\n`, `\v`, `\f`, `\r`, `\x20`
72 | Unicode:
73 | `0009`, `000A`, `000B`, `000C`, `000D`, `0085(NEL)`,
74 | General_Category -- Line_Separator
75 | -- Paragraph_Separator
76 | -- Space_Separator
77 | - `\S` :: non whitespace char
78 | - `\d` :: decimal digit char
79 | Unicode: General_Category -- Decimal_Number
80 | - `\D` :: non decimal digit char
81 | - `\h` :: hexadecimal digit char [0-9a-fA-F]
82 | - `\H` :: non hexadecimal digit char
83 |
84 |
85 | ##### Character Property
86 |
87 | * `\p{property-name}`
88 | * `\p{^property-name}` (negative)
89 | * `\P{property-name}` (negative)
90 |
91 | property-name:
92 |
93 | ```raw
94 | + works on all encodings
95 | Alnum, Alpha, Blank, Cntrl, Digit, Graph, Lower,
96 | Print, Punct, Space, Upper, XDigit, Word, ASCII,
97 |
98 | + works on EUC_JP, Shift_JIS
99 | Hiragana, Katakana
100 |
101 | + works on UTF8, UTF16, UTF32
102 | Any, Assigned, C, Cc, Cf, Cn, Co, Cs, L, Ll, Lm, Lo, Lt, Lu,
103 | M, Mc, Me, Mn, N, Nd, Nl, No, P, Pc, Pd, Pe, Pf, Pi, Po, Ps,
104 | S, Sc, Sk, Sm, So, Z, Zl, Zp, Zs,
105 | Arabic, Armenian, Bengali, Bopomofo, Braille, Buginese,
106 | Buhid, Canadian_Aboriginal, Cherokee, Common, Coptic,
107 | Cypriot, Cyrillic, Deseret, Devanagari, Ethiopic, Georgian,
108 | Glagolitic, Gothic, Greek, Gujarati, Gurmukhi, Han, Hangul,
109 | Hanunoo, Hebrew, Hiragana, Inherited, Kannada, Katakana,
110 | Kharoshthi, Khmer, Lao, Latin, Limbu, Linear_B, Malayalam,
111 | Mongolian, Myanmar, New_Tai_Lue, Ogham, Old_Italic, Old_Persian,
112 | Oriya, Osmanya, Runic, Shavian, Sinhala, Syloti_Nagri, Syriac,
113 | Tagalog, Tagbanwa, Tai_Le, Tamil, Telugu, Thaana, Thai, Tibetan,
114 | Tifinagh, Ugaritic, Yi
115 | ```
116 |
117 |
118 | ### Quantifier
119 |
120 | #### greedy
121 |
122 | - `?` :: 1 or 0 times
123 | - `*` :: 0 or more times
124 | - `+` :: 1 or more times
125 | - `{n,m}` :: at least n but not more than m times
126 | - `{n,}` :: at least n times
127 | - `{,n}` :: at least 0 but not more than n times (`{0,n}`)
128 | - `{n}` :: n times
129 |
130 | #### reluctant
131 |
132 | - `??` :: 1 or 0 times
133 | - `*?` :: 0 or more times
134 | - `+?` :: 1 or more times
135 | - `{n,m}?` :: at least n but not more than m times
136 | - `{n,}?` :: at least n times
137 | - `{,n}?` :: at least 0 but not more than n times (== `{0,n}?`)
138 |
139 | #### possessive (greedy and does not backtrack after repeated)
140 |
141 | - `?+` :: 1 or 0 times
142 | - `*+` :: 0 or more times
143 | - `++` :: 1 or more times
144 |
145 | (`{n,m}+`, `{n,}+`, `{n}+` are possessive op. in ONIG_SYNTAX_JAVA only) ex. /a*+/ === /(?>a*)/
146 |
147 |
148 | ### Anchors
149 |
150 | - `^` :: beginning of the line
151 | - `$` :: end of the line
152 | - `\b` :: word boundary
153 | - `\B` :: not word boundary
154 | - `\A` :: beginning of string
155 | - `\Z` :: end of string, or before newline at the end
156 | - `\z` :: end of string
157 | - `\G` :: matching start position
158 |
159 |
160 | ### Character class
161 |
162 | - `^...` :: negative class (lowest precedence operator)
163 | - `x-y` :: range from x to y
164 | - `[...]` :: set (character class in character class)
165 | - `..&&..` :: intersection (low precedence at the next of `^`)
166 |
167 | ex. [a-w&&[^c-g]z] ==> ([a-w] AND ([^c-g] OR z)) ==> [abh-w]
168 |
169 | If you want to use `[`, `-`, `]` as a normal character in a character class,
170 | you should escape these characters by `\`.
171 |
172 | ```text
173 | POSIX bracket ([:xxxxx:], negate [:^xxxxx:])
174 |
175 | Not Unicode Case:
176 |
177 | alnum alphabet or digit char
178 | alpha alphabet
179 | ascii code value: [0 - 127]
180 | blank \t, \x20
181 | cntrl
182 | digit 0-9
183 | graph include all of multibyte encoded characters
184 | lower
185 | print include all of multibyte encoded characters
186 | punct
187 | space \t, \n, \v, \f, \r, \x20
188 | upper
189 | xdigit 0-9, a-f, A-F
190 | word alphanumeric, "_" and multibyte characters
191 |
192 |
193 | Unicode Case:
194 |
195 | alnum Letter | Mark | Decimal_Number
196 | alpha Letter | Mark
197 | ascii 0000 - 007F
198 | blank Space_Separator | 0009
199 | cntrl Control | Format | Unassigned | Private_Use | Surrogate
200 | digit Decimal_Number
201 | graph [[:^space:]] && ^Control && ^Unassigned && ^Surrogate
202 | lower Lowercase_Letter
203 | print [[:graph:]] | [[:space:]]
204 | punct Connector_Punctuation | Dash_Punctuation | Close_Punctuation |
205 | Final_Punctuation | Initial_Punctuation | Other_Punctuation |
206 | Open_Punctuation
207 | space Space_Separator | Line_Separator | Paragraph_Separator |
208 | 0009 | 000A | 000B | 000C | 000D | 0085
209 | upper Uppercase_Letter
210 | xdigit 0030 - 0039 | 0041 - 0046 | 0061 - 0066
211 | (0-9, a-f, A-F)
212 | word Letter | Mark | Decimal_Number | Connector_Punctuation
213 | ```
214 |
215 |
216 | ### Extended groups
217 |
218 | - `(?#...)` :: comment
219 |
220 | - `(?imx-imx)` :: option on/off
221 | i: ignore case
222 | m: multi-line (dot(.) match newline)
223 | x: extended form
224 | - `(?imx-imx:subexp)` :: option on/off for subexp
225 |
226 | - `(?:subexp)` :: not captured group
227 | - `(subexp)` :: captured group
228 |
229 | - `(?=subexp)` :: look-ahead
230 | - `(?!subexp)` :: negative look-ahead
231 | - `(?<=subexp)` :: look-behind
232 | - `(?
233 | Subexp of look-behind must be fixed character length.
234 | But different character length is allowed in top level
235 | alternatives only.
236 | ex. (?<=a|bc) is OK. (?<=aaa(?:b|cd)) is not allowed.
237 |
238 | In negative-look-behind, captured group isn't allowed,
239 | but shy group(?:) is allowed.
240 |
241 | - `(?>subexp)` :: atomic group, don't backtrack in subexp.
242 | - `(?subexp)`, `(?'name'subexp)` :: define named group
243 | (All characters of the name must be a word character.)
244 |
245 | Not only a name but a number is assigned like a captured
246 | group.
247 |
248 | Assigning the same name as two or more subexps is allowed.
249 | In this case, a subexp call can not be performed although
250 | the back reference is possible.
251 |
252 |
253 | ### Back reference
254 |
255 | - `\n` :: back reference by group number (n >= 1)
256 | - `\k` :: back reference by group name
257 | - `\k'name'` :: back reference by group name
258 |
259 | In the back reference by the multiplex definition name,
260 | a subexp with a large number is referred to preferentially.
261 | (When not matched, a group of the small number is referred to.)
262 |
263 | Back reference by group number is *forbidden* if named group is defined
264 | in the pattern and ONIG_OPTION_CAPTURE_GROUP is not setted.
265 |
266 | Back reference with nest level:
267 |
268 | - `\k` - n: 0, 1, 2, ...
269 | - `\k` - n: 0, 1, 2, ...
270 | - `\k'name+n'` - n: 0, 1, 2, ...
271 | - `\k'name-n'` - n: 0, 1, 2, ...
272 |
273 | Destinate relative nest level from back reference position.
274 |
275 | ```
276 | /\A(?|.|(?:(?.)\g\k))\z/.match("reer")
277 | ```
278 |
279 | ```
280 | r = Regexp.compile(<<'__REGEXP__'.strip, Regexp::EXTENDED)
281 | (? \g \g* \g ){0}
282 | (? < \g \s* > ){0}
283 | (? [a-zA-Z_:]+ ){0}
284 | (? [^<&]+ (\g | [^<&]+)* ){0}
285 | (? \k >){0}
286 | \g
287 | __REGEXP__
288 |
289 | p r.match('fbbbf').captures
290 | ```
291 |
292 |
293 | ### Subexp call
294 |
295 | ("Tanaka Akira special")
296 |
297 | - `\g` :: call by group name
298 | - `\g'name'` :: call by group name
299 | - `\g` :: call by group number (n >= 1)
300 | - `\g'n'` :: call by group number (n >= 1)
301 |
302 | left-most recursive call is not allowed.
303 |
304 | (?a|\gb) => error
305 | (?a|b\gc) => OK
306 |
307 | Call by group number is forbidden if named group is defined in the pattern and
308 | `ONIG_OPTION_CAPTURE_GROUP` is not setted.
309 |
310 | If the option status of called group is different from calling position then the group's option is
311 | effective. eg. `(?-i:\g)(?i:(?a)){0}` match to "A"
312 |
313 |
314 | ### Captured group
315 |
316 | Behavior of the no-named group (...) changes with the following conditions.
317 | (But named group is not changed.)
318 |
319 | case 1. /.../ (named group is not used, no option)
320 |
321 | (...) is treated as a captured group.
322 |
323 | case 2. /.../g (named group is not used, 'g' option)
324 |
325 | (...) is treated as a no-captured group (?:...).
326 |
327 | case 3. /..(?..)../ (named group is used, no option)
328 |
329 | (...) is treated as a no-captured group (?:...).
330 | numbered-backref/call is not allowed.
331 |
332 | case 4. /..(?..)../G (named group is used, 'G' option)
333 |
334 | (...) is treated as a captured group.
335 | numbered-backref/call is allowed.
336 |
337 | where
338 | g: ONIG_OPTION_DONT_CAPTURE_GROUP
339 | G: ONIG_OPTION_CAPTURE_GROUP
340 |
341 | ('g' and 'G' options are argued in ruby-dev ML)
342 |
343 |
344 | Regex notes
345 | -----------
346 |
347 | ```raw
348 | A-1. Syntax depend options
349 |
350 | + ONIG_SYNTAX_RUBY
351 | (?m): dot(.) match newline
352 |
353 | + ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA
354 | (?s): dot(.) match newline
355 | (?m): ^ match after newline, $ match before newline
356 |
357 |
358 | A-2. Original extensions
359 |
360 | + hexadecimal digit char type \h, \H
361 | + named group (?...), (?'name'...)
362 | + named backref \k
363 | + subexp call \g, \g
364 |
365 |
366 | A-3. Lacked features compare with perl 5.8.0
367 |
368 | + \N{name}
369 | + \l,\u,\L,\U, \X, \C
370 | + (?{code})
371 | + (??{code})
372 | + (?(condition)yes-pat|no-pat)
373 |
374 | * \Q...\E
375 | This is effective on ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA.
376 |
377 |
378 | A-4. Differences with Japanized GNU regex(version 0.12) of Ruby 1.8
379 |
380 | + add character property (\p{property}, \P{property})
381 | + add hexadecimal digit char type (\h, \H)
382 | + add look-behind
383 | (?<=fixed-char-length-pattern), (?>]/ in EUC-JP encoding.
395 | + effect range of isolated option is to next ')'.
396 | ex. (?:(?i)a|b) is interpreted as (?:(?i:a|b)), not (?:(?i:a)|b).
397 | + isolated option is not transparent to previous pattern.
398 | ex. a(?i)* is a syntax error pattern.
399 | + allowed incompleted left brace as an usual string.
400 | ex. /{/, /({)/, /a{2,3/ etc...
401 | + negative POSIX bracket [:^xxxx:] is supported.
402 | + POSIX bracket [:ascii:] is added.
403 | + repeat of look-ahead is not allowed.
404 | ex. /(?=a)*/, /(?!b){5}/
405 | + Ignore case option is effective to numbered character.
406 | ex. /\x61/i =~ "A"
407 | + In the range quantifier, the number of the minimum is omissible.
408 | /a{,n}/ == /a{0,n}/
409 | The simultanious abbreviation of the number of times of the minimum
410 | and the maximum is not allowed. (/a{,}/)
411 | + /a{n}?/ is not a non-greedy operator.
412 | /a{n}?/ == /(?:a{n})?/
413 | + invalid back reference is checked and cause error.
414 | /\1/, /(a)\2/
415 | + Zero-length match in infinite repeat stops the repeat,
416 | then changes of the capture group status are checked as stop condition.
417 | /(?:()|())*\1\2/ =~ ""
418 | /(?:\1a|())*/ =~ "a"
419 |
420 |
421 | A-5. Disabled functions by default syntax
422 |
423 | + capture history
424 |
425 | (?@...) and (?@...)
426 |
427 | ex. /(?@a)*/.match("aaa") ==> [<0-1>, <1-2>, <2-3>]
428 |
429 | see sample/listcap.c file.
430 |
431 |
432 | A-6. Problems
433 |
434 | + Invalid encoding byte sequence is not checked in UTF-8.
435 |
436 | * Invalid first byte is treated as a character.
437 | /./u =~ "\xa3"
438 |
439 | * Incomplete byte sequence is not checked.
440 | /\w+/ =~ "a\xf3\x8ec"
441 |
442 | ```
443 |
444 | 20.4 Replacement String Syntax (Format Strings)
445 |
446 | When you perform a regular expression replace, the replace string is interpreted as a format string
447 | which can reference captures, perform case foldings, do conditional insertions (based on capture
448 | registers) and support a minimal amount of escape sequences.
449 |
450 | 20.4.1 Captures
451 |
452 | To reference a capture, use $n where n is the capture register number. Using $0 means the entire
453 | match.
454 |
455 | Example:
456 |
457 | Find:
458 | Replace:
459 | 20.4.2 Case Foldings
460 |
461 | It is possible to convert the next character to upper or lowercase by prepending it with \u or \l.
462 | This is mainly useful when the next character stems from a capture register. Example:
463 |
464 | Find: ()(.*?)()
465 | Replace: $1\u$2$3
466 |
467 | You can also convert a longer sequence to upper or lowercase by using \U or \L and then \E to
468 | disable the case folding again. Example:
469 |
470 | Find: ()(.*?)()
471 | Replace: $1\U$2\E$3
472 | 20.4.3 Conditional Insertions
473 |
474 | There are times where the replacements depends on whether or not something was matched. This can be
475 | done using (?«n»:«insertion») to insert «insertion» if capture «n» was matched. You can also use
476 | (?«n»:«insertion»:«otherwise») to have «otherwise» inserted when capture «n» was not matched.
477 |
478 | To make a capture conditional either place it in an alternation, e.g. foo|(bar)|fud or append a
479 | question mark to it: (bar)?. Note that (.*) will result in a match, even when zero characters are
480 | matched, so use (.+)? instead.
481 |
482 | So for example if we wish to truncate text to eight words and insert ellipsis only if there were
483 | more than eight words, we can use:
484 |
485 | Find: (\w+(?:\W+\w+){,7})\W*(.+)?
486 | Replace: $1(?2:…)
487 |
488 | Here we first match a word (\w+) followed by up to seven words ((?:\W+\w+){,7}) each preceded by
489 | non-word characters (spacing). Then optionally put anything following that (separated by non-word
490 | characters) into capture register 2 ((.+)?).
491 |
492 | The replacement first inserts the (up to) eight words matched ($1) and then only if capture 2
493 | matched something, ellipsis ((?2:…)).
494 |
495 | 20.4.4 Escape Codes
496 |
497 | In addition to the case folding escape codes, you can insert a newline character with \n, a tab
498 | character with \t and a dollar sign with \$.
499 |
--------------------------------------------------------------------------------
/html/marked.min.js:
--------------------------------------------------------------------------------
1 | /**
2 | * marked - a markdown parser
3 | * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
4 | * https://github.com/chjj/marked
5 | */
6 | (function(){var block={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:noop,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:noop,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:noop,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};block.bullet=/(?:[*+-]|\d+\.)/;block.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;block.item=replace(block.item,"gm")(/bull/g,block.bullet)();block.list=replace(block.list)(/bull/g,block.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+block.def.source+")")();block.blockquote=replace(block.blockquote)("def",block.def)();block._tag="(?!(?:"+"a|em|strong|small|s|cite|q|dfn|abbr|data|time|code"+"|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo"+"|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b";block.html=replace(block.html)("comment",//)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/])*?>/)(/tag/g,block._tag)();block.paragraph=replace(block.paragraph)("hr",block.hr)("heading",block.heading)("lheading",block.lheading)("blockquote",block.blockquote)("tag","<"+block._tag)("def",block.def)();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=replace(block.paragraph)("(?!","(?!"+block.gfm.fences.source.replace("\\1","\\2")+"|"+block.list.source.replace("\\1","\\3")+"|")();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables}else{this.rules=block.gfm}}}Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src)};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");return this.token(src,true)};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,""),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:"space"})}}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,"");this.tokens.push({type:"code",text:!this.options.pedantic?cap.replace(/\n+$/,""):cap});continue}if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"code",lang:cap[2],text:cap[3]||""});continue}if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});continue}if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/\n$/,"").split("\n")};for(i=0;i ?/gm,"");this.token(cap,top,true);this.tokens.push({type:"blockquote_end"});continue}if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:"list_start",ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i1&&b.length>1)){src=cap.slice(i+1).join("\n")+src;i=l-1}}loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==="\n";if(!loose)loose=next}this.tokens.push({type:loose?"loose_item_start":"list_item_start"});this.token(item,false,bq);this.tokens.push({type:"list_item_end"})}this.tokens.push({type:"list_end"});continue}if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&(cap[1]==="pre"||cap[1]==="script"||cap[1]==="style"),text:cap[0]});continue}if(!bq&&top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue}if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(i=0;i])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/;inline.link=replace(inline.link)("inside",inline._inside)("href",inline._href)();inline.reflink=replace(inline.reflink)("inside",inline._inside)();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)("]|","~]|")("|","|https?://|")()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new Error("Tokens array requires a `links` property.")}if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks}else{this.rules=inline.gfm}}else if(this.options.pedantic){this.rules=inline.pedantic}}InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src)};InlineLexer.prototype.output=function(src){var out="",link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue}if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==="@"){text=cap[1].charAt(6)===":"?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle("mailto:")+text}else{text=escape(cap[1]);href=text}out+=this.renderer.link(href,null,text);continue}if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue}if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^/i.test(cap[0])){this.inLink=false}src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0];continue}if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue}if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g," ");link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue}this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue}if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue}if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue}if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue}if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue}if(src){throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}}return out};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!=="!"?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out="",l=text.length,i=0,ch;for(;i.5){ch="x"+ch.toString(16)}out+=""+ch+";"}return out};function Renderer(options){this.options=options||{}}Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out}}if(!lang){return"