about summary refs log blame commit diff stats
path: root/src/types/cell.nim
blob: 8820f3512a7626396d0e6dd2cd391d2525541eeb (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
                  
                     

    
                     






               
 
                  

                       
                            
 


                            
 


                                   
 


                                               
                
                   
 



                          








                                                                                
                                                
                                                  
 



                                                        
                                                              






                           

 
                                                   
                                                                        
 
                                   
                         
 
                                              
                                                            



                                 
         

          
                                                                        





                                   
                                                                            




                               
import types/color
import utils/strwidth

type
  FormatFlags* = enum
    ffBold
    ffItalic
    ffUnderline
    ffReverse
    ffStrike
    ffOverline
    ffBlink

  Format* = object
    fgcolor*: CellColor
    bgcolor*: CellColor
    flags*: set[FormatFlags]

  SimpleFormatCell* = object
    format*: Format
    pos*: int

  SimpleFlexibleLine* = object
    str*: string
    formats*: seq[SimpleFormatCell]

  SimpleFlexibleGrid* = seq[SimpleFlexibleLine]

  FixedCell* = object
    str*: string
    format*: Format

  FixedGrid* = object
    width*, height*: int
    cells*: seq[FixedCell]

proc `[]=`*(grid: var FixedGrid; i: int; cell: FixedCell) = grid.cells[i] = cell
proc `[]=`*(grid: var FixedGrid; i: BackwardsIndex; cell: FixedCell) =
  grid.cells[i] = cell
proc `[]`*(grid: var FixedGrid; i: int): var FixedCell = grid.cells[i]
proc `[]`*(grid: var FixedGrid; i: BackwardsIndex): var FixedCell =
  grid.cells[i]
proc `[]`*(grid: FixedGrid; i: int): FixedCell = grid.cells[i]
proc `[]`*(grid: FixedGrid; i: BackwardsIndex): FixedCell = grid.cells[i]

proc len*(grid: FixedGrid): int = grid.cells.len
proc high*(grid: FixedGrid): int = grid.cells.high

iterator items*(grid: FixedGrid): FixedCell {.inline.} =
  for cell in grid.cells:
    yield cell

const FormatCodes*: array[FormatFlags, tuple[s, e: uint8]] = [
  ffBold: (1u8, 22u8),
  ffItalic: (3u8, 23u8),
  ffUnderline: (4u8, 24u8),
  ffReverse: (7u8, 27u8),
  ffStrike: (9u8, 29u8),
  ffOverline: (53u8, 55u8),
  ffBlink: (5u8, 25u8),
]

func newFixedGrid*(w: int; h: int = 1): FixedGrid =
  return FixedGrid(width: w, height: h, cells: newSeq[FixedCell](w * h))

func width*(cell: FixedCell): int =
  return cell.str.width()

# Get the first format cell after pos, if any.
func findFormatN*(line: SimpleFlexibleLine; pos: int): int =
  var i = 0
  while i < line.formats.len:
    if line.formats[i].pos > pos:
      break
    inc i
  return i

func findFormat*(line: SimpleFlexibleLine; pos: int): SimpleFormatCell =
  let i = line.findFormatN(pos) - 1
  if i != -1:
    result = line.formats[i]
  else:
    result.pos = -1

func findNextFormat*(line: SimpleFlexibleLine; pos: int): SimpleFormatCell =
  let i = line.findFormatN(pos)
  if i < line.formats.len:
    result = line.formats[i]
  else:
    result.pos = -1
ced substitution expressions' href='/ahoang/Nim/commit/lib/pure/subexes.nim?h=devel&id=b336bf4039f3bc428f0a6690bf448f1e0b447c4b'>b336bf403 ^
43bddf62d ^
1639de0a4 ^

c36421f8e ^
22db40e5e ^
d18e18060 ^
1639de0a4 ^
c36421f8e ^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411

 
                                  
                                         




                                                   
                                                                  
  
                                     

















                                                                 



                                                                    

                                                   
                                                                 

    
                                       




                                                       
                        
                                             
 
                                      



         
                                                       





                            
                                                                   

















                                                                          
                               












                                                                            
                                                                            
                
 
                                                                        



                              
                                                                              

                                        
                                                                        


                      
                                                                 













                                                                   
                                                          








                                             
           



































                                                       
                                                                             


                   
 



















                                                    
 
                                                                           


             
         

                      


                                          



























                                                        
           
























                                                             
 






                                                      
                                 






                                                             
 







                                                                           
 









                                                                              
         





                                


                                                                            
 
                               

                                                                             
                   
 
                                                                       

                                                               
                     









                                  
                                                                          







                                                                         
                                                               




                                                       
                                                                               







                                                                         


                  
                              


                                                             
                                    


                                                  
                                      















                                                                           
 




                                                                      
 
                                                                                                      
                       

                
 

                                                                                            
                         
                         

                           
                                        
 
                                                                       
 
                                                                             
 
                                                  
 

                                                                                    
                         
          
                   
                                             
                            
#
#
#            Nim's Runtime Library
#        (c) Copyright 2012 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## Nim support for `substitution expressions`:idx: (`subex`:idx:).
##
## .. include:: ../../doc/subexes.txt
##

{.push debugger:off .} # the user does not want to trace a part
                       # of the standard library!

from strutils import parseInt, cmpIgnoreStyle, Digits
include "system/inclrtl"


proc findNormalized(x: string, inArray: openarray[string]): int =
  var i = 0
  while i < high(inArray):
    if cmpIgnoreStyle(x, inArray[i]) == 0: return i
    inc(i, 2) # incrementing by 1 would probably lead to a
              # security hole...
  return -1

type
  SubexError* = object of ValueError ## exception that is raised for
                                     ## an invalid subex

{.deprecated: [EInvalidSubex: SubexError].}

proc raiseInvalidFormat(msg: string) {.noinline.} =
  raise newException(SubexError, "invalid format string: " & msg)

type
  FormatParser = object {.pure, final.}
    when defined(js):
      f: string # we rely on the '\0' terminator
                # which JS's native string doesn't have
    else:
      f: cstring
    num, i, lineLen: int
{.deprecated: [TFormatParser: FormatParser].}

template call(x: stmt) {.immediate.} =
  p.i = i
  x
  i = p.i

template callNoLineLenTracking(x: stmt) {.immediate.} =
  let oldLineLen = p.lineLen
  p.i = i
  x
  i = p.i
  p.lineLen = oldLineLen

proc getFormatArg(p: var FormatParser, a: openArray[string]): int =
  const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'}
  var i = p.i
  var f = p.f
  case f[i]
  of '#':
    result = p.num
    inc i
    inc p.num
  of '1'..'9', '-':
    var j = 0
    var negative = f[i] == '-'
    if negative: inc i
    while f[i] in Digits:
      j = j * 10 + ord(f[i]) - ord('0')
      inc i
    result = if not negative: j-1 else: a.len-j
  of 'a'..'z', 'A'..'Z', '\128'..'\255', '_':
    var name = ""
    while f[i] in PatternChars:
      name.add(f[i])
      inc(i)
    result = findNormalized(name, a)+1
  of '$':
    inc(i)
    call:
      result = getFormatArg(p, a)
    result = parseInt(a[result])-1
  else:
    raiseInvalidFormat("'#', '$', number or identifier expected")
  if result >=% a.len: raiseInvalidFormat("index out of bounds: " & $result)
  p.i = i

proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) {.
  noSideEffect.}

proc emitChar(p: var FormatParser, x: var string, ch: char) {.inline.} =
  x.add(ch)
  if ch == '\L': p.lineLen = 0
  else: inc p.lineLen

proc emitStrLinear(p: var FormatParser, x: var string, y: string) {.inline.} =
  for ch in items(y): emitChar(p, x, ch)

proc emitStr(p: var FormatParser, x: var string, y: string) {.inline.} =
  x.add(y)
  inc p.lineLen, y.len

proc scanQuote(p: var FormatParser, x: var string, toAdd: bool) =
  var i = p.i+1
  var f = p.f
  while true:
    if f[i] == '\'':
      inc i
      if f[i] != '\'': break
      inc i
      if toAdd: emitChar(p, x, '\'')
    elif f[i] == '\0': raiseInvalidFormat("closing \"'\" expected")
    else:
      if toAdd: emitChar(p, x, f[i])
      inc i
  p.i = i

proc scanBranch(p: var FormatParser, a: openArray[string],
                x: var string, choice: int) =
  var i = p.i
  var f = p.f
  var c = 0
  var elsePart = i
  var toAdd = choice == 0
  while true:
    case f[i]
    of ']': break
    of '|':
      inc i
      elsePart = i
      inc c
      if toAdd: break
      toAdd = choice == c
    of '\'':
      call: scanQuote(p, x, toAdd)
    of '\0': raiseInvalidFormat("closing ']' expected")
    else:
      if toAdd:
        if f[i] == '$':
          inc i
          call: scanDollar(p, a, x)
        else:
          emitChar(p, x, f[i])
          inc i
      else:
        inc i
  if not toAdd and choice >= 0:
    # evaluate 'else' part:
    var last = i
    i = elsePart
    while true:
      case f[i]
      of '|', ']': break
      of '\'':
        call: scanQuote(p, x, true)
      of '$':
        inc i
        call: scanDollar(p, a, x)
      else:
        emitChar(p, x, f[i])
        inc i
    i = last
  p.i = i+1

proc scanSlice(p: var FormatParser, a: openarray[string]): tuple[x, y: int] =
  var slice = false
  var i = p.i
  var f = p.f

  if f[i] == '{': inc i
  else: raiseInvalidFormat("'{' expected")
  if f[i] == '.' and f[i+1] == '.':
    inc i, 2
    slice = true
  else:
    call: result.x = getFormatArg(p, a)
    if f[i] == '.' and f[i+1] == '.':
      inc i, 2
      slice = true
  if slice:
    if f[i] != '}':
      call: result.y = getFormatArg(p, a)
    else:
      result.y = high(a)
  else:
    result.y = result.x
  if f[i] != '}': raiseInvalidFormat("'}' expected")
  inc i
  p.i = i

proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) =
  var i = p.i
  var f = p.f
  case f[i]
  of '$':
    emitChar p, s, '$'
    inc i
  of '*':
    for j in 0..a.high: emitStr p, s, a[j]
    inc i
  of '{':
    call:
      let (x, y) = scanSlice(p, a)
    for j in x..y: emitStr p, s, a[j]
  of '[':
    inc i
    var start = i
    call: scanBranch(p, a, s, -1)
    var x: int
    if f[i] == '{':
      inc i
      call: x = getFormatArg(p, a)
      if f[i] != '}': raiseInvalidFormat("'}' expected")
      inc i
    else:
      call: x = getFormatArg(p, a)
    var last = i
    let choice = parseInt(a[x])
    i = start
    call: scanBranch(p, a, s, choice)
    i = last
  of '\'':
    var sep = ""
    callNoLineLenTracking: scanQuote(p, sep, true)
    if f[i] == '~':
      # $' '~{1..3}
      # insert space followed by 1..3 if not empty
      inc i
      call:
        let (x, y) = scanSlice(p, a)
      var L = 0
      for j in x..y: inc L, a[j].len
      if L > 0:
        emitStrLinear p, s, sep
        for j in x..y: emitStr p, s, a[j]
    else:
      block StringJoin:
        block OptionalLineLengthSpecifier:
          var maxLen = 0
          case f[i]
          of '0'..'9':
            while f[i] in Digits:
              maxLen = maxLen * 10 + ord(f[i]) - ord('0')
              inc i
          of '$':
            # do not skip the '$' here for `getFormatArg`!
            call:
              maxLen = getFormatArg(p, a)
          else: break OptionalLineLengthSpecifier
          var indent = ""
          case f[i]
          of 'i':
            inc i
            callNoLineLenTracking: scanQuote(p, indent, true)

            call:
              let (x, y) = scanSlice(p, a)
            if maxLen < 1: emitStrLinear(p, s, indent)
            var items = 1
            emitStr p, s, a[x]
            for j in x+1..y:
              emitStr p, s, sep
              if items >= maxLen:
                emitStrLinear p, s, indent
                items = 0
              emitStr p, s, a[j]
              inc items
          of 'c':
            inc i
            callNoLineLenTracking: scanQuote(p, indent, true)

            call:
              let (x, y) = scanSlice(p, a)
            if p.lineLen + a[x].len > maxLen: emitStrLinear(p, s, indent)
            emitStr p, s, a[x]
            for j in x+1..y:
              emitStr p, s, sep
              if p.lineLen + a[j].len > maxLen: emitStrLinear(p, s, indent)
              emitStr p, s, a[j]

          else: raiseInvalidFormat("unit 'c' (chars) or 'i' (items) expected")
          break StringJoin

        call:
          let (x, y) = scanSlice(p, a)
        emitStr p, s, a[x]
        for j in x+1..y:
          emitStr p, s, sep
          emitStr p, s, a[j]
  else:
    call:
      var x = getFormatArg(p, a)
    emitStr p, s, a[x]
  p.i = i


type
  Subex* = distinct string ## string that contains a substitution expression

{.deprecated: [TSubex: Subex].}

proc subex*(s: string): Subex =
  ## constructs a *substitution expression* from `s`. Currently this performs
  ## no syntax checking but this may change in later versions.
  result = Subex(s)

proc addf*(s: var string, formatstr: Subex, a: varargs[string, `$`]) {.
           noSideEffect, rtl, extern: "nfrmtAddf".} =
  ## The same as ``add(s, formatstr % a)``, but more efficient.
  var p: FormatParser
  p.f = formatstr.string
  var i = 0
  while i < len(formatstr.string):
    if p.f[i] == '$':
      inc i
      call: scanDollar(p, a, s)
    else:
      emitChar(p, s, p.f[i])
      inc(i)

proc `%` *(formatstr: Subex, a: openarray[string]): string {.noSideEffect,
  rtl, extern: "nfrmtFormatOpenArray".} =
  ## The `substitution`:idx: operator performs string substitutions in
  ## `formatstr` and returns a modified `formatstr`. This is often called
  ## `string interpolation`:idx:.
  ##
  result = newStringOfCap(formatstr.string.len + a.len shl 4)
  addf(result, formatstr, a)

proc `%` *(formatstr: Subex, a: string): string {.noSideEffect,
  rtl, extern: "nfrmtFormatSingleElem".} =
  ## This is the same as ``formatstr % [a]``.
  result = newStringOfCap(formatstr.string.len + a.len)
  addf(result, formatstr, [a])

proc format*(formatstr: Subex, a: varargs[string, `$`]): string {.noSideEffect,
  rtl, extern: "nfrmtFormatVarargs".} =
  ## The `substitution`:idx: operator performs string substitutions in
  ## `formatstr` and returns a modified `formatstr`. This is often called
  ## `string interpolation`:idx:.
  ##
  result = newStringOfCap(formatstr.string.len + a.len shl 4)
  addf(result, formatstr, a)

{.pop.}

when isMainModule:
  from strutils import replace

  proc `%`(formatstr: string, a: openarray[string]): string =
    result = newStringOfCap(formatstr.len + a.len shl 4)
    addf(result, formatstr.Subex, a)

  proc `%`(formatstr: string, a: string): string =
    result = newStringOfCap(formatstr.len + a.len)
    addf(result, formatstr.Subex, [a])


  doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c"
  doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] ==
           "The cat eats fish."


  doAssert "$[abc|def]# $3 $# $#" % ["17", "b", "c"] == "def c b c"
  doAssert "$[abc|def]# $3 $# $#" % ["1", "b", "c"] == "def c b c"
  doAssert "$[abc|def]# $3 $# $#" % ["0", "b", "c"] == "abc c b c"
  doAssert "$[abc|def|]# $3 $# $#" % ["17", "b", "c"] == " c b c"

  doAssert "$[abc|def|]# $3 $# $#" % ["-9", "b", "c"] == " c b c"
  doAssert "$1($', '{2..})" % ["f", "a", "b"] == "f(a, b)"

  doAssert "$[$1($', '{2..})|''''|fg'$3']1" % ["7", "a", "b"] == "fg$3"

  doAssert "$[$#($', '{#..})|''''|$3]1" % ["0", "a", "b"] == "0(a, b)"
  doAssert "$' '~{..}" % "" == ""
  doAssert "$' '~{..}" % "P0" == " P0"
  doAssert "${$1}" % "1" == "1"
  doAssert "${$$-1} $$1" % "1" == "1 $1"

  doAssert(("$#($', '10c'\n    '{#..})" % ["doAssert", "longishA", "longish"]).replace(" \n", "\n") ==
           """doAssert(
    longishA,
    longish)""")

  doAssert(("type MyEnum* = enum\n  $', '2i'\n  '{..}" % ["fieldA",
    "fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"]).replace(" \n", "\n") ==
    strutils.unindent("""
      type MyEnum* = enum
        fieldA, fieldB,
        FiledClkad, fieldD,
        fieldE, longishFieldName""", 6))

  doAssert subex"$1($', '{2..})" % ["f", "a", "b", "c"] == "f(a, b, c)"

  doAssert subex"$1 $[files|file|files]{1} copied" % ["1"] == "1 file copied"

  doAssert subex"$['''|'|''''|']']#" % "0" == "'|"

  doAssert((subex("type\n  Enum = enum\n    $', '40c'\n    '{..}") % [
    "fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"]).replace(" \n", "\n") ==
    strutils.unindent("""
      type
        Enum = enum
          fieldNameA, fieldNameB, fieldNameC,
          fieldNameD""", 6))