summary refs log tree commit diff stats
path: root/doc/tut2.txt
blob: b4b29d7cea1f2e301e160bcce0e3f07af3719f8c (plain) (blame)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
=========================
Nimrod Tutorial (Part II)
=========================

:Author: Andreas Rumpf
:Version: |nimrodversion|

.. contents::


Introduction
============

  "With great power comes great responsibility." -- Spiderman

This document is a tutorial for the advanced constructs of the *Nimrod*
programming language.


Pragmas
=======
Pragmas are Nimrod's method to give the compiler additional information/
commands without introducing a massive number of new keywords. Pragmas are
processed during semantic checking. Pragmas are enclosed in the
special ``{.`` and ``.}`` curly dot brackets. This tutorial does not cover
pragmas. See the `manual <manual.html>`_ or `user guide <nimrodc.html>`_ for
a description of the available pragmas.


Object Oriented Programming
===========================

While Nimrod's support for object oriented programming (OOP) is minimalistic,
powerful OOP technics can be used. OOP is seen as *one* way to design a
program, not *the only* way. Often a procedural approach leads to simpler
and more efficient code. In particular, prefering composition over inheritance
is often the better design.


Objects
-------

Like tuples, objects are a means to pack different values together in a
structured way. However, objects provide many features that tuples do not:
They provide inheritance and information hiding. Because objects encapsulate
data, the ``()`` tuple constructor cannot be used to construct objects. So
the order of the object's fields is not as important as it is for tuples. The
programmer should provide a proc to initialize the object (this is called
a *constructor*).

Objects have access to their type at runtime. There is an
``of`` operator that can be used to check the object's type:

.. code-block:: nimrod

  type
    TPerson = object of TObject
      name*: string  # the * means that `name` is accessible from other modules
      age: int       # no * means that the field is hidden from other modules

    TStudent = object of TPerson # TStudent inherits from TPerson
      id: int                    # with an id field

  var
    student: TStudent
    person: TPerson
  assert(student of TStudent) # is true

Object fields that should be visible from outside the defining module, have to
be marked by ``*``. In contrast to tuples, different object types are
never *equivalent*. New object types can only be defined within a type
section.

Inheritance is done with the ``object of`` syntax. Multiple inheritance is
currently not supported. If an object type has no suitable ancestor, ``TObject``
can be used as its ancestor, but this is only a convention.

**Note**: Composition (*has-a* relation) is often preferable to inheritance
(*is-a* relation) for simple code reuse. Since objects are value types in
Nimrod, composition is as efficient as inheritance.


Mutually recursive types
------------------------

Objects, tuples and references can model quite complex data structures which
depend on each other; they are *mutually recursive*. In Nimrod
these types can only be declared within a single type section. (Anything else
would require arbitrary symbol lookahead which slows down compilation.)

Example:

.. code-block:: nimrod
  type
    PNode = ref TNode # a traced reference to a TNode
    TNode = object
      le, ri: PNode   # left and right subtrees
      sym: ref TSym   # leaves contain a reference to a TSym

    TSym = object     # a symbol
      name: string    # the symbol's name
      line: int       # the line the symbol was declared in
      code: PNode     # the symbol's abstract syntax tree


Type conversions
----------------
Nimrod distinguishes between `type casts`:idx: and `type conversions`:idx:.
Casts are done with the ``cast`` operator and force the compiler to
interpret a bit pattern to be of another type.

Type conversions are a much more polite way to convert a type into another:
They preserve the abstract *value*, not necessarily the *bit-pattern*. If a
type conversion is not possible, the compiler complains or an exception is
raised.

The syntax for type conversions is ``destination_type(expression_to_convert)``
(like an ordinary call):

.. code-block:: nimrod
  proc getID(x: TPerson): int =
    return TStudent(x).id

The ``EInvalidObjectConversion`` exception is raised if ``x`` is not a
``TStudent``.


Object variants
---------------
Often an object hierarchy is overkill in certain situations where simple
`variant`:idx: types are needed.

An example:

.. code-block:: nimrod

  # This is an example how an abstract syntax tree could be modeled in Nimrod
  type
    TNodeKind = enum  # the different node types
      nkInt,          # a leaf with an integer value
      nkFloat,        # a leaf with a float value
      nkString,       # a leaf with a string value
      nkAdd,          # an addition
      nkSub,          # a subtraction
      nkIf            # an if statement
    PNode = ref TNode
    TNode = object
      case kind: TNodeKind  # the ``kind`` field is the discriminator
      of nkInt: intVal: int
      of nkFloat: floatVal: float
      of nkString: strVal: string
      of nkAdd, nkSub:
        leftOp, rightOp: PNode
      of nkIf:
        condition, thenPart, elsePart: PNode

  var
    n: PNode
  new(n)  # creates a new node
  n.kind = nkFloat
  n.floatVal = 0.0 # valid, because ``n.kind==nkFloat``

  # the following statement raises an `EInvalidField` exception, because
  # n.kind's value does not fit:
  n.strVal = ""

As can been seen from the example, an advantage to an object hierarchy is that
no conversion between different object types is needed. Yet, access to invalid
object fields raises an exception.


Methods
-------
In ordinary object oriented languages, procedures (also called *methods*) are
bound to a class. This has disadvantages:

* Adding a method to a class the programmer has no control over is
  impossible or needs ugly workarounds.
* Often it is unclear where the method should belong to: is
  ``join`` a string method or an array method?

Nimrod avoids these problems by not assigning methods to a class. All methods
in Nimrod are `multi-methods`:idx:. As we will see later, multi-methods are
distinguished from procs only for dynamic binding purposes.


Method call syntax
------------------

There is a syntactic sugar for calling routines:
The syntax ``obj.method(args)`` can be used instead of ``method(obj, args)``.
If there are no remaining arguments, the parentheses can be omitted:
``obj.len`` (instead of ``len(obj)``).

This `method call syntax`:idx: is not restricted to objects, it can be used
for any type:

.. code-block:: nimrod
  
  echo("abc".len) # is the same as echo(len("abc"))
  echo("abc".toUpper())
  echo({'a', 'b', 'c'}.card)
  stdout.writeln("Hallo") # the same as writeln(stdout, "Hallo")

(Another way to look at the method call syntax is that it provides the missing
postfix notation.)

So "pure object oriented" code is easy to write:

.. code-block:: nimrod
  import strutils
  
  stdout.writeln("Give a list of numbers (separated by spaces): ")
  stdout.write(stdin.readLine.split.each(parseInt).max.`$`)
  stdout.writeln(" is the maximum!")


Properties
----------
As the above example shows, Nimrod has no need for *get-properties*:
Ordinary get-procedures that are called with the *method call syntax* achieve
the same. But setting a value is different; for this a special setter syntax
is needed:

.. code-block:: nimrod
  
  type
    TSocket* = object of TObject
      FHost: int # cannot be accessed from the outside of the module
                 # the `F` prefix is a convention to avoid clashes since
                 # the accessors are named `host`

  proc `host=`*(s: var TSocket, value: int) {.inline.} =
    ## setter of hostAddr
    s.FHost = value
  
  proc host*(s: TSocket): int {.inline.} =
    ## getter of hostAddr
    return s.FHost

  var
    s: TSocket
  s.host = 34  # same as `host=`(s, 34)

(The example also shows ``inline`` procedures.)


The ``[]`` array access operator can be overloaded to provide
`array properties`:idx:\ :

.. code-block:: nimrod
  type
    TVector* = object
      x, y, z: float

  proc `[]=`* (v: var TVector, i: int, value: float) =
    # setter
    case i
    of 0: v.x = value
    of 1: v.y = value
    of 2: v.z = value
    else: assert(false)

  proc `[]`* (v: TVector, i: int): float =
    # getter
    case i
    of 0: result = v.x
    of 1: result = v.y
    of 2: result = v.z
    else: assert(false)

The example is silly, since a vector is better modelled by a tuple which
already provides ``v[]`` access.


Dynamic dispatch
----------------

Procedures always use static dispatch. For dynamic dispatch replace the
``proc`` keyword by ``method``:

.. code-block:: nimrod
  type
    TExpr = object ## abstract base class for an expression
    TLiteral = object of TExpr
      x: int
    TPlusExpr = object of TExpr
      a, b: ref TExpr
      
  method eval(e: ref TExpr): int =
    # override this base method
    quit "to override!"
  
  method eval(e: ref TLiteral): int = return e.x

  method eval(e: ref TPlusExpr): int =
    # watch out: relies on dynamic binding
    return eval(e.a) + eval(e.b)
  
  proc newLit(x: int): ref TLiteral =
    new(result)
    result.x = x
    
  proc newPlus(a, b: ref TExpr): ref TPlusExpr =
    new(result)
    result.a = a
    result.b = b
  
  echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
  
Note that in the example the constructors ``newLit`` and ``newPlus`` are procs
because they should use static binding, but ``eval`` is a method because it
requires dynamic binding.

In a multi-method all parameters that have an object type are used for the
dispatching:

.. code-block:: nimrod

  type
    TThing = object
    TUnit = object of TThing
      x: int
      
  method collide(a, b: TThing) {.inline.} =
    quit "to override!"
    
  method collide(a: TThing, b: TUnit) {.inline.} =
    echo "1"
  
  method collide(a: TUnit, b: TThing) {.inline.} =
    echo "2"
  
  var
    a, b: TUnit
  collide(a, b) # output: 2


As the example demonstrates, invocation of a multi-method cannot be ambiguous:
Collide 2 is preferred over collide 1 because the resolution works from left to
right. Thus ``TUnit, TThing`` is preferred over ``TThing, TUnit``.

**Perfomance note**: Nimrod does not produce a virtual method table, but
generates dispatch trees. This avoids the expensive indirect branch for method
calls and enables inlining. However, other optimizations like compile time
evaluation or dead code elimination do not work with methods.


Exceptions
==========

In Nimrod `exceptions`:idx: are objects. By convention, exception types are
prefixed with an 'E', not 'T'. The ``system`` module defines an exception
hierarchy that you might want to stick to.

Exceptions should be allocated on the heap because their lifetime is unknown.

A convention is that exceptions should be raised in *exceptional* cases:
For example, if a file cannot be opened, this should not raise an
exception since this is quite common (the file may not exist).


Raise statement
---------------
Raising an exception is done with the ``raise`` statement:

.. code-block:: nimrod
  var
    e: ref EOS
  new(e)
  e.msg = "the request to the OS failed"
  raise e

If the ``raise`` keyword is not followed by an expression, the last exception
is *re-raised*.


Try statement
-------------

The `try`:idx: statement handles exceptions:

.. code-block:: nimrod
  # read the first two lines of a text file that should contain numbers
  # and tries to add them
  var
    f: TFile
  if open(f, "numbers.txt"):
    try:
      let a = readLine(f)
      let b = readLine(f)
      echo "sum: ", parseInt(a) + parseInt(b)
    except EOverflow:
      echo "overflow!"
    except EInvalidValue:
      echo "could not convert string to integer"
    except EIO:
      echo "IO error!"
    except:
      echo "Unknown exception!"
      # reraise the unknown exception:
      raise
    finally:
      close(f)

The statements after the ``try`` are executed unless an exception is
raised. Then the appropriate ``except`` part is executed.

The empty ``except`` part is executed if there is an exception that is
not explicitly listed. It is similar to an ``else`` part in ``if``
statements.

If there is a ``finally`` part, it is always executed after the
exception handlers.

The exception is *consumed* in an ``except`` part. If an exception is not
handled, it is propagated through the call stack. This means that often
the rest of the procedure - that is not within a ``finally`` clause -
is not executed (if an exception occurs).


Generics
========

`Generics`:idx: are Nimrod's means to parametrize procs, iterators or types
with `type parameters`:idx:. They are most useful for efficient type safe
containers:

.. code-block:: nimrod
  type
    TBinaryTree[T] = object      # TBinaryTree is a generic type with
                                 # with generic param ``T``
      le, ri: ref TBinaryTree[T] # left and right subtrees; may be nil
      data: T                    # the data stored in a node
    PBinaryTree*[T] = ref TBinaryTree[T] # type that is exported

  proc newNode*[T](data: T): PBinaryTree[T] =
    # constructor for a node
    new(result)
    result.dat = data

  proc add*[T](root: var PBinaryTree[T], n: PBinaryTree[T]) =
    # insert a node into the tree
    if root == nil:
      root = n
    else:
      var it = root
      while it != nil:
        # compare the data items; uses the generic ``cmp`` proc
        # that works for any type that has a ``==`` and ``<`` operator
        var c = cmp(it.data, n.data)
        if c < 0:
          if it.le == nil:
            it.le = n
            return
          it = it.le
        else:
          if it.ri == nil:
            it.ri = n
            return
          it = it.ri

  proc add*[T](root: var PBinaryTree[T], data: T) =
    # convenience proc:
    add(root, newNode(data))

  iterator preorder*[T](root: PBinaryTree[T]): T =
    # Preorder traversal of a binary tree.
    # Since recursive iterators are not yet implemented,
    # this uses an explicit stack (which is more efficient anyway):
    var stack: seq[PBinaryTree[T]] = @[root]
    while stack.len > 0:
      var n = stack.pop()
      while n != nil:
        yield n.data
        add(stack, n.ri)  # push right subtree onto the stack
        n = n.le          # and follow the left pointer
      
  var
    root: PBinaryTree[string] # instantiate a PBinaryTree with ``string``
  add(root, newNode("hallo")) # instantiates ``newNode`` and ``add``
  add(root, "world")          # instantiates the second ``add`` proc
  for str in preorder(root):
    stdout.writeln(str)

The example shows a generic binary tree. Depending on context, the brackets are
used either to introduce type parameters or to instantiate a generic proc,
iterator or type. As the example shows, generics work with overloading: the
best match of ``add`` is used. The built-in ``add`` procedure for sequences
is not hidden and is used in the ``preorder`` iterator.


Templates
=========

Templates are a simple substitution mechanism that operates on Nimrod's
abstract syntax trees. Templates are processed in the semantic pass of the
compiler. They integrate well with the rest of the language and share none
of C's preprocessor macros flaws.

To *invoke* a template, call it like a procedure.

Example:

.. code-block:: nimrod
  template `!=` (a, b: expr): expr =
    # this definition exists in the System module
    not (a == b)

  assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))

The ``!=``, ``>``, ``>=``, ``in``, ``notin``, ``isnot`` operators are in fact
templates: this has the benefit that if you overload the ``==`` operator,
the ``!=`` operator is available automatically and does the right thing. (Except
for IEEE floating point numbers - NaN breaks basic boolean logic.)

``a > b`` is transformed into ``b < a``.
``a in b`` is transformed into ``contains(b, a)``.
``notin`` and ``isnot`` have the obvious meanings.

Templates are especially useful for lazy evaluation purposes. Consider a
simple proc for logging:

.. code-block:: nimrod
  const
    debug = True

  proc log(msg: string) {.inline.} =
    if debug: stdout.writeln(msg)
  
  var
    x = 4
  log("x has the value: " & $x)

This code has a shortcoming: if ``debug`` is set to false someday, the quite
expensive ``$`` and ``&`` operations are still performed! (The argument
evaluation for procedures is *eager*).

Turning the ``log`` proc into a template solves this problem:

.. code-block:: nimrod
  const
    debug = True

  template log(msg: string) =
    if debug: stdout.writeln(msg)
  
  var
    x = 4
  log("x has the value: " & $x)

The parameters' types can be ordinary types or the meta types ``expr``
(stands for *expression*), ``stmt`` (stands for *statement*) or ``typedesc``
(stands for *type description*). If the template has no explicit return type,
``stmt`` is used for consistency with procs and methods.

The template body does not open a new scope. To open a new scope use a ``block``
statement:

.. code-block:: nimrod
  template declareInScope(x: expr, t: typeDesc): stmt {.immediate.} =
    var x: t

  template declareInNewScope(x: expr, t: typeDesc): stmt {.immediate.} =
    # open a new scope:
    block:
      var x: t

  declareInScope(a, int)
  a = 42  # works, `a` is known here
  
  declareInNewScope(b, int)
  b = 42  # does not work, `b` is unknown

(The manual explains why the ``immediate`` pragma is needed for these 
templates.)

If there is a ``stmt`` parameter it should be the last in the template
declaration. The reason is that statements can be passed to a template
via a special ``:`` syntax:

.. code-block:: nimrod

  template withFile(f: expr, filename: string, mode: TFileMode,
                    body: stmt): stmt {.immediate.} =
    block:
      let fn = filename
      var f: TFile
      if open(f, fn, mode):
        try:
          body
        finally:
          close(f)
      else:
        quit("cannot open: " & fn)
      
  withFile(txt, "ttempl3.txt", fmWrite):
    txt.writeln("line 1")
    txt.writeln("line 2")
  
In the example the two ``writeln`` statements are bound to the ``body``
parameter. The ``withFile`` template contains boilerplate code and helps to
avoid a common bug: to forget to close the file. Note how the
``let fn = filename`` statement ensures that ``filename`` is evaluated only
once.


Macros
======

Macros enable advanced compile-time code transformations, but they
cannot change Nimrod's syntax. However, this is no real restriction because
Nimrod's syntax is flexible enough anyway.

To write a macro, one needs to know how the Nimrod concrete syntax is converted
to an abstract syntax tree (AST). The AST is documented in the
`macros <macros.html>`_ module.

There are two ways to invoke a macro:
(1) invoking a macro like a procedure call (`expression macros`:idx:)
(2) invoking a macro with the special ``macrostmt``
    syntax (`statement macros`:idx:)


Expression Macros
-----------------

The following example implements a powerful ``debug`` command that accepts a
variable number of arguments (this cannot be done with templates):

.. code-block:: nimrod
  # to work with Nimrod syntax trees, we need an API that is defined in the
  # ``macros`` module:
  import macros

  macro debug(n: expr): stmt =
    # `n` is a Nimrod AST that contains the whole macro expression
    # this macro returns a list of statements:
    result = newNimNode(nnkStmtList, n)
    # iterate over any argument that is passed to this macro:
    for i in 1..n.len-1:
      # add a call to the statement list that writes the expression;
      # `toStrLit` converts an AST to its string representation:
      result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
      # add a call to the statement list that writes ": "
      result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
      # add a call to the statement list that writes the expressions value:
      result.add(newCall("writeln", newIdentNode("stdout"), n[i]))

  var
    a: array[0..10, int]
    x = "some string"
  a[0] = 42
  a[1] = 45

  debug(a[0], a[1], x)

The macro call expands to:

.. code-block:: nimrod
  write(stdout, "a[0]")
  write(stdout, ": ")
  writeln(stdout, a[0])

  write(stdout, "a[1]")
  write(stdout, ": ")
  writeln(stdout, a[1])

  write(stdout, "x")
  write(stdout, ": ")
  writeln(stdout, x)



Statement Macros
----------------

Statement macros are defined just as expression macros. However, they are
invoked by an expression following a colon.

The following example outlines a macro that generates a lexical analyzer from
regular expressions:

.. code-block:: nimrod

  macro case_token(n: stmt): stmt =
    # creates a lexical analyzer from regular expressions
    # ... (implementation is an exercise for the reader :-)
    nil

  case_token: # this colon tells the parser it is a macro statement
  of r"[A-Za-z_]+[A-Za-z_0-9]*":
    return tkIdentifier
  of r"0-9+":
    return tkInteger
  of r"[\+\-\*\?]+":
    return tkOperator
  else:
    return tkUnknown
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


                   
                      
                        



                                                                            
                                                          











                                                                    
                                                    




                                                                  
                                                    
                                                          
                                                     
                                                       






                                                                       
                                                   


                                                               
                                                        





                                                                                  
                                                   














                                                                
                                                             
                                                                  
                                                          





                                                              
                                                   






                                                                
                                                      
                                                  
                                                      












                                                                       
                                                        










                                                                                 

                                                            
                                                          
                                                    
                                                                
                                                 
                                                          
                                                       












                                                                
                                                    

                                                           
                                                  








                                                                
                                                               








                                                                            
                                                    
                                                         
                                                     




                                                                            
                                                     







                                                               
                                                      











                                                                  
                                                               


                                                           
                                                     
                                                                    
                                                     

                                                           
                                                         
                                                         
                                                    






                                                             
                                                       





                                                            
                                                   
 
                                      
                                         
                                            

                                       
                                                                    
                                           



                                                             
                       
#ifndef LYRCFILE_H
#define LYRCFILE_H

#ifndef LYSTRUCTS_H
#include <LYStructs.h>
#endif /* LYSTRUCTS_H */

/* configuration-variable names to share with LYReadCFG.c and LYOptions.c */
#define RC_ACCEPT_ALL_COOKIES           "accept_all_cookies"
#define RC_ALERTSECS                    "alertsecs"
#define RC_ALWAYS_RESUBMIT_POSTS        "always_resubmit_posts"
#define RC_ALWAYS_TRUSTED_EXEC          "always_trusted_exec"
#define RC_ANONFTP_PASSWORD             "anonftp_password"
#define RC_ASSUMED_COLOR                "assumed_color"
#define RC_ASSUMED_DOC_CHARSET_CHOICE   "assumed_doc_charset_choice"
#define RC_ASSUME_CHARSET               "assume_charset"
#define RC_ASSUME_LOCAL_CHARSET         "assume_local_charset"
#define RC_ASSUME_UNREC_CHARSET         "assume_unrec_charset"
#define RC_AUTO_UNCACHE_DIRLISTS        "auto_uncache_dirlists"
#define RC_BIBP_BIBHOST                 "bibp_bibhost"
#define RC_BIBP_GLOBALSERVER            "bibp_globalserver"
#define RC_BLOCK_MULTI_BOOKMARKS        "block_multi_bookmarks"
#define RC_BOLD_H1                      "bold_h1"
#define RC_BOLD_HEADERS                 "bold_headers"
#define RC_BOLD_NAME_ANCHORS            "bold_name_anchors"
#define RC_BOOKMARK_FILE                "bookmark_file"
#define RC_BZIP2_PATH                   "bzip2_path"
#define RC_CASE_SENSITIVE_ALWAYS_ON     "case_sensitive_always_on"
#define RC_CASE_SENSITIVE_SEARCHING     "case_sensitive_searching"
#define RC_CHARACTER_SET                "character_set"
#define RC_CHARSETS_DIRECTORY           "charsets_directory"
#define RC_CHARSET_SWITCH_RULES         "charset_switch_rules"
#define RC_CHECKMAIL                    "checkmail"
#define RC_CHMOD_PATH                   "chmod_path"
#define RC_COLLAPSE_BR_TAGS             "collapse_br_tags"
#define RC_COLOR                        "color"
#define RC_COLOR_STYLE                  "color_style"
#define RC_COMPRESS_PATH                "compress_path"
#define RC_CONNECT_TIMEOUT              "connect_timeout"
#define RC_COOKIE_ACCEPT_DOMAINS        "cookie_accept_domains"
#define RC_COOKIE_FILE                  "cookie_file"
#define RC_COOKIE_LOOSE_INVALID_DOMAINS "cookie_loose_invalid_domains"
#define RC_COOKIE_QUERY_INVALID_DOMAINS "cookie_query_invalid_domains"
#define RC_COOKIE_REJECT_DOMAINS        "cookie_reject_domains"
#define RC_COOKIE_SAVE_FILE             "cookie_save_file"
#define RC_COOKIE_STRICT_INVALID_DOMAIN "cookie_strict_invalid_domains"
#define RC_COPY_PATH                    "copy_path"
#define RC_CSO_PROXY                    "cso_proxy"
#define RC_CSWING_PATH                  "cswing_path"
#define RC_DEFAULT_BOOKMARK_FILE        "default_bookmark_file"
#define RC_DEFAULT_CACHE_SIZE           "default_cache_size"
#define RC_DEFAULT_COLORS               "default_colors"
#define RC_DEFAULT_EDITOR               "default_editor"
#define RC_DEFAULT_INDEX_FILE           "default_index_file"
#define RC_DEFAULT_KEYPAD_MODE          "default_keypad_mode"
#define RC_DEFAULT_KEYPAD_MODE_NUMARO   "default_keypad_mode_is_numbers_as_arrows"
#define RC_DEFAULT_USER_MODE            "default_user_mode"
#define RC_DEFAULT_VIRTUAL_MEMORY_SIZE  "default_virtual_memory_size"
#define RC_DEFINE RC_XLOADIMAGE_COMMAND "XLOADIMAGE_COMMAND"
#define RC_DELAYSECS                    "delaysecs"
#define RC_DIRED_MENU                   "dired_menu"
#define RC_DIR_LIST_ORDER               "dir_list_order"
#define RC_DIR_LIST_STYLE               "dir_list_style"
#define RC_DISPLAY                      "display"
#define RC_DISPLAY_CHARSET_CHOICE       "display_charset_choice"
#define RC_DOWNLOADER                   "downloader"
#define RC_EMACS_KEYS                   "emacs_keys"
#define RC_EMACS_KEYS_ALWAYS_ON         "emacs_keys_always_on"
#define RC_ENABLE_LYNXRC                "enable_lynxrc"
#define RC_ENABLE_SCROLLBACK            "enable_scrollback"
#define RC_EXTERNAL                     "external"
#define RC_FILE_EDITOR                  "file_editor"
#define RC_FILE_SORTING_METHOD          "file_sorting_method"
#define RC_FINGER_PROXY                 "finger_proxy"
#define RC_FOCUS_WINDOW                 "focus_window"
#define RC_FORCE_8BIT_TOUPPER           "force_8bit_toupper"
#define RC_FORCE_COOKIE_PROMPT          "force_cookie_prompt"
#define RC_FORCE_EMPTY_HREFLESS_A       "force_empty_hrefless_a"
#define RC_FORCE_SSL_COOKIES_SECURE     "force_ssl_cookies_secure"
#define RC_FORCE_SSL_PROMPT             "force_ssl_prompt"
#define RC_FORMS_OPTIONS                "forms_options"
#define RC_FTP_PASSIVE                  "ftp_passive"
#define RC_FTP_PROXY                    "ftp_proxy"
#define RC_GLOBAL_EXTENSION_MAP         "global_extension_map"
#define RC_GLOBAL_MAILCAP               "global_mailcap"
#define RC_GOPHER_PROXY                 "gopher_proxy"
#define RC_GOTOBUFFER                   "gotobuffer"
#define RC_GZIP_PATH                    "gzip_path"
#define RC_HELPFILE                     "helpfile"
#define RC_HIDDEN_LINK_MARKER           "hidden_link_marker"
#define RC_HISTORICAL_COMMENTS          "historical_comments"
#define RC_HTMLSRC_ATTRNAME_XFORM       "htmlsrc_attrname_xform"
#define RC_HTMLSRC_TAGNAME_XFORM        "htmlsrc_tagname_xform"
#define RC_HTTPS_PROXY                  "https_proxy"
#define RC_HTTP_PROXY                   "http_proxy"
#define RC_INCLUDE                      "include"
#define RC_INFLATE_PATH                 "inflate_path"
#define RC_INFOSECS                     "infosecs"
#define RC_INSTALL_PATH                 "install_path"
#define RC_JUMPBUFFER                   "jumpbuffer"
#define RC_JUMPFILE                     "jumpfile"
#define RC_JUMP_PROMPT                  "jump_prompt"
#define RC_JUSTIFY                      "justify"
#define RC_JUSTIFY_MAX_VOID_PERCENT     "justify_max_void_percent"
#define RC_KBLAYOUT                     "kblayout"
#define RC_KEYBOARD_LAYOUT              "keyboard_layout"
#define RC_KEYMAP                       "keymap"
#define RC_KEYPAD_MODE                  "keypad_mode"
#define RC_LEFTARROW_IN_TEXTFLD_PROMPT  "leftarrow_in_textfield_prompt"
#define RC_LINEEDIT_MODE                "lineedit_mode"
#define RC_LIST_FORMAT                  "list_format"
#define RC_LIST_NEWS_DATES              "list_news_dates"
#define RC_LIST_NEWS_NUMBERS            "list_news_numbers"
#define RC_LOCALE_CHARSET               "locale_charset"
#define RC_LOCALHOST_ALIAS              "localhost_alias"
#define RC_LOCAL_DOMAIN                 "local_domain"
#define RC_LOCAL_EXECUTION_LINKS_ALWAYS "local_execution_links_always_on"
#define RC_LOCAL_EXECUTION_LINKS_LOCAL  "local_execution_links_on_but_not_remote"
#define RC_LYNXCGI_DOCUMENT_ROOT        "lynxcgi_document_root"
#define RC_LYNXCGI_ENVIRONMENT          "lynxcgi_environment"
#define RC_LYNX_HOST_NAME               "lynx_host_name"
#define RC_LYNX_SIG_FILE                "lynx_sig_file"
#define RC_MAIL_ADRS                    "mail_adrs"
#define RC_MAIL_SYSTEM_ERROR_LOGGING    "mail_system_error_logging"
#define RC_MAKE_LINKS_FOR_ALL_IMAGES    "make_links_for_all_images"
#define RC_MAKE_PSEUDO_ALTS_FOR_INLINES "make_pseudo_alts_for_inlines"
#define RC_MAX_COOKIES_BUFFER		"max_cookies_buffer"
#define RC_MAX_COOKIES_DOMAIN		"max_cookies_domain"
#define RC_MAX_COOKIES_GLOBAL		"max_cookies_global"
#define RC_MESSAGESECS                  "messagesecs"
#define RC_MINIMAL_COMMENTS             "minimal_comments"
#define RC_MKDIR_PATH                   "mkdir_path"
#define RC_MULTI_BOOKMARK               "multi_bookmark"
#define RC_MULTI_BOOKMARK_SUPPORT       "multi_bookmark_support"
#define RC_MV_PATH                      "mv_path"
#define RC_NCR_IN_BOOKMARKS             "ncr_in_bookmarks"
#define RC_NESTED_TABLES                "nested_tables"
#define RC_NEWSPOST_PROXY               "newspost_proxy"
#define RC_NEWSREPLY_PROXY              "newsreply_proxy"
#define RC_NEWS_CHUNK_SIZE              "news_chunk_size"
#define RC_NEWS_MAX_CHUNK               "news_max_chunk"
#define RC_NEWS_POSTING                 "news_posting"
#define RC_NEWS_PROXY                   "news_proxy"
#define RC_NNTPSERVER                   "nntpserver"
#define RC_NNTP_PROXY                   "nntp_proxy"
#define RC_NONRESTARTING_SIGWINCH       "nonrestarting_sigwinch"
#define RC_NO_DOT_FILES                 "no_dot_files"
#define RC_NO_FILE_REFERER              "no_file_referer"
#define RC_NO_FORCED_CORE_DUMP          "no_forced_core_dump"
#define RC_NO_FROM_HEADER               "no_from_header"
#define RC_NO_ISMAP_IF_USEMAP           "no_ismap_if_usemap"
#define RC_NO_MARGINS                   "no_margins"
#define RC_NO_PROXY                     "no_proxy"
#define RC_NO_REFERER_HEADER            "no_referer_header"
#define RC_NO_TABLE_CENTER              "no_table_center"
#define RC_NO_TITLE                     "no_title"
#define RC_NUMBER_FIELDS_ON_LEFT        "number_fields_on_left"
#define RC_NUMBER_LINKS_ON_LEFT         "number_links_on_left"
#define RC_OUTGOING_MAIL_CHARSET        "outgoing_mail_charset"
#define RC_PARTIAL                      "partial"
#define RC_PARTIAL_THRES                "partial_thres"
#define RC_PERSISTENT_COOKIES           "persistent_cookies"
#define RC_PERSONAL_EXTENSION_MAP       "personal_extension_map"
#define RC_PERSONAL_MAILCAP             "personal_mailcap"
#define RC_PERSONAL_MAIL_ADDRESS        "personal_mail_address"
#define RC_PREFERRED_CHARSET            "preferred_charset"
#define RC_PREFERRED_MEDIA_TYPES        "preferred_media_types"
#define RC_PREFERRED_ENCODING           "preferred_encoding"
#define RC_PREFERRED_LANGUAGE           "preferred_language"
#define RC_PREPEND_BASE_TO_SOURCE       "prepend_base_to_source"
#define RC_PREPEND_CHARSET_TO_SOURCE    "prepend_charset_to_source"
#define RC_PRETTYSRC                    "prettysrc"
#define RC_PRETTYSRC_SPEC               "prettysrc_spec"
#define RC_PRETTYSRC_VIEW_NO_ANCHOR_NUM "prettysrc_view_no_anchor_numbering"
#define RC_PRINTER                      "printer"
#define RC_QUIT_DEFAULT_YES             "quit_default_yes"
#define RC_RAW_MODE                     "raw_mode"
#define RC_REFERER_WITH_QUERY           "referer_with_query"
#define RC_REPLAYSECS                   "replaysecs"
#define RC_REUSE_TEMPFILES              "reuse_tempfiles"
#define RC_RLOGIN_PATH                  "rlogin_path"
#define RC_RM_PATH                      "rm_path"
#define RC_RULE                         "rule"
#define RC_RULESFILE                    "rulesfile"
#define RC_RUN_ALL_EXECUTION_LINKS      "run_all_execution_links"
#define RC_RUN_EXECUTION_LINKS_LOCAL    "run_execution_links_on_local_files"
#define RC_SAVE_SPACE                   "save_space"
#define RC_SCAN_FOR_BURIED_NEWS_REFS    "scan_for_buried_news_refs"
#define RC_SCREEN_SIZE                  "screen_size"
#define RC_SCROLLBAR                    "scrollbar"
#define RC_SCROLLBAR_ARROW              "scrollbar_arrow"
#define RC_SEEK_FRAG_AREA_IN_CUR        "seek_frag_area_in_cur"
#define RC_SEEK_FRAG_MAP_IN_CUR         "seek_frag_map_in_cur"
#define RC_SELECT_POPUPS                "select_popups"
#define RC_SET_COOKIES                  "set_cookies"
#define RC_SHOW_COLOR                   "show_color"
#define RC_SHOW_CURSOR                  "show_cursor"
#define RC_SHOW_DOTFILES                "show_dotfiles"
#define RC_SHOW_KB_NAME                 "show_kb_name"
#define RC_SHOW_KB_RATE                 "show_kb_rate"
#define RC_SNEWSPOST_PROXY              "snewspost_proxy"
#define RC_SNEWSREPLY_PROXY             "snewsreply_proxy"
#define RC_SNEWS_PROXY                  "snews_proxy"
#define RC_SOFT_DQUOTES                 "soft_dquotes"
#define RC_SOURCE_CACHE                 "source_cache"
#define RC_SOURCE_CACHE_FOR_ABORTED     "source_cache_for_aborted"
#define RC_STARTFILE                    "startfile"
#define RC_STRIP_DOTDOT_URLS            "strip_dotdot_urls"
#define RC_SUBSTITUTE_UNDERSCORES       "substitute_underscores"
#define RC_SUB_BOOKMARKS                "sub_bookmarks"
#define RC_SUFFIX                       "suffix"
#define RC_SUFFIX_ORDER                 "suffix_order"
#define RC_SYSLOG_REQUESTED_URLS        "syslog_requested_urls"
#define RC_SYSLOG_TEXT                  "syslog_text"
#define RC_SYSTEM_EDITOR                "system_editor"
#define RC_SYSTEM_MAIL                  "system_mail"
#define RC_SYSTEM_MAIL_FLAGS            "system_mail_flags"
#define RC_TAGSOUP                      "tagsoup"
#define RC_TAR_PATH                     "tar_path"
#define RC_TELNET_PATH                  "telnet_path"
#define RC_TEXTFIELDS_NEED_ACTIVATION   "textfields_need_activation"
#define RC_TIMEOUT                      "timeout"
#define RC_TN3270_PATH                  "tn3270_path"
#define RC_TOUCH_PATH                   "touch_path"
#define RC_TRIM_INPUT_FIELDS            "trim_input_fields"
#define RC_TRUSTED_EXEC                 "trusted_exec"
#define RC_TRUSTED_LYNXCGI              "trusted_lynxcgi"
#define RC_UNCOMPRESS_PATH              "uncompress_path"
#define RC_UNDERLINE_LINKS              "underline_links"
#define RC_UNZIP_PATH                   "unzip_path"
#define RC_UPLOADER                     "uploader"
#define RC_URL_DOMAIN_PREFIXES          "url_domain_prefixes"
#define RC_URL_DOMAIN_SUFFIXES          "url_domain_suffixes"
#define RC_USERAGENT                    "useragent"
#define RC_USER_MODE                    "user_mode"
#define RC_USE_FIXED_RECORDS            "use_fixed_records"
#define RC_USE_MOUSE                    "use_mouse"
#define RC_USE_SELECT_POPUPS            "use_select_popups"
#define RC_UUDECODE_PATH                "uudecode_path"
#define RC_VERBOSE_IMAGES               "verbose_images"
#define RC_VIEWER                       "viewer"
#define RC_VISITED_LINKS                "visited_links"
#define RC_VI_KEYS                      "vi_keys"
#define RC_VI_KEYS_ALWAYS_ON            "vi_keys_always_on"
#define RC_WAIS_PROXY                   "wais_proxy"
#define RC_XLOADIMAGE_COMMAND           "xloadimage_command"
#define RC_ZCAT_PATH                    "zcat_path"
#define RC_ZIP_PATH                     "zip_path"

extern Config_Enum tbl_force_prompt[];
extern Config_Enum tbl_keypad_mode[];
extern Config_Enum tbl_multi_bookmarks[];
extern Config_Enum tbl_preferred_encoding[];
extern Config_Enum tbl_preferred_media[];
extern Config_Enum tbl_transfer_rate[];
extern Config_Enum tbl_user_mode[];

extern BOOL LYgetEnum(Config_Enum * table, char *name, int *result);
extern BOOL will_save_rc(const char *name);
extern const char *LYputEnum(Config_Enum * table, int value);
extern int enable_lynxrc(char *value);
extern int get_tagsoup(char *value);
extern int save_rc(FILE *);
extern void read_rc(FILE *);

#endif /* LYRCFILE_H */