ECMAScript: evaluating onclick, onsubmit etc. done in the right way.
[elinks.git] / doc / hacking.txt
blob2a4979bc202f97fee69b007f4c1223ae08fd2af9
1 Hacking ELinks
2 ==============
4 Welcome, mere mortal, to the realm of evil unindented code, heaps of one or
5 two-letter variables, seas of gotos accompanied with 30-letters labels in Czech
6 language with absolutely no meaning, welcome to the realm of ELinks code!
8 Don't take this file as a law. We may or may not be right in these issues.
10 Motto: I didn't expect someone to look at the source, so it's unreadable.
11        --Mikulas
14 Language files
15 --------------
17 Each UI output should use language files in order to be able to translate the
18 messages to a desired language.  Those language files reside in the po/ subdir. If
19 you want to update a .po file, please read the gettext manual available at
20 <http://www.gnu.org/manual/gettext>. In order to actually use your updates on
21 your own system, you have to have the gettext tools installed.
24 ELinks philosophy
25 -----------------
27 ELinks is based on the philosophy of asynchronism.  That means, you pass a
28 callback to each function, and when the requested task finishes sometime in the
29 unclear future, the callback will be called in order to notify you that you can
30 go on.
32 When you use multiple elinks instances at once, normally only one of them is a
33 'master', and the rest of them are just kinda dumb terminals.  So if you want
34 to test some new feature, you have to start elinks with the '-no-connect'
35 parameter, otherwise it will just connect to an already running elinks and you
36 won't see your great new feature that you just added with such much pain.
38 There are two basic structures in ELinks.  Connection and session - their names
39 should be self-descriptive.  Only note that connections may or may not have
40 sessions attached.  I.e. if you type some URL, then start loading it and then
41 press ACT_BACK (KEY_LEFT), the connection will lose its session.  So you should
42 never pretend that it has one.
44 The UI plainly needs a rewrite as it's extremely ugly ;-).  Cut'n'paste from
45 some existing code and modify appropriately, if you want one :).
47 Some common used functions (e.g., malloc() or free()) have their own clones
48 inside ELinks and you should use them (e.g., mem_alloc() or mem_free()) instead.
50 If you want to have anything else documented here, write a description and send
51 us a patch.
53 Various parts are described either below or in README* file(s) of appropriate
54 directory.
57 HTML parser
58 -----------
60 The following was found in the mailing list archive - Mikulas wrote it:
62 The entry of the parser is parse_html.  This function gets an html source to
63 parse (pointers html and eof) and the functions it should call when it wants to
64 produce output (put_chars, line_break, init, special).  f is a pointer that is
65 passed to that function, head is the HTTP header (for refresh).  The function
66 uses a stack (struct list_head html_stack; it is set up by the caller of
67 parse_html), places formatting info into it, and calls output functions.
68 put_chars to write text, line_break for new line, init (currently unused),
69 special (tags, forms, etc...).  These functions read the parameters from the
70 stack (struct html_element) and do the actual rendering (some while ago, people
71 wanted to use the parser for a graphics browser, so I wrote it so that it could
72 produce graphics output by replacing the output functions).
74 Html renderer is in html_r.c.  html_interpret formats the whole screen.  It
75 calls cached_format_html which formats one document (frame) or returns directly
76 a formatted document from the cache.  cached_format_html then calls
77 format_html, which sets up rendering and calls format_html_part.
78 format_html_part is used for formatting the whole document or formatting parts
79 of tables. It calls parse_html.
81 The rendering functions put_chars_conv, line_break, html_special receive struct
82 part * from the parser.  They render the text or calculate the size of the text
83 (in case of tables).  struct part has a pointer to struct f_data - a structure
84 that holds the actual formatted data.  If the pointer is NULL, rendering
85 functions only calculate size.
88 Documents management
89 --------------------
91 Just a few words regarding the document structures. To understand the code, it
92 is important to note the difference between rendered documents and document
93 views.
95 A document is rendered (or formatted) one time once it is loaded - then it
96 stays formatted in a cache for some time, and whoever opens the document just
97 attaches that formatted document. That is, if you open the same document in
98 three tabs, they all show contents of the same single underlying struct
99 document and family.
101 However, each of the tabs gets own struct document_view. That structure
102 contains information about the currently active link, the position in the document,
103 the size of the viewport, search terms currently highlighted etc. This structure
104 stays around only when the document is displayed in some session, thus its
105 lifespan is always shorter than struct document's. document_view to document
106 mapping is many to one.
108 There is a third structure, struct view_state. This structure contains
109 information about the current link and position, contents of forms fields,
110 and so. Like struct document_view, it contains information specific to
111 a certain view of the document, and the mapping to document is many to one.
112 Unlike document_view, though, its lifespan is much longer. When you chain
113 those view_states up, you get a session history.
116 Lua support
117 -----------
119 Peter Wang wrote this on the mailing list:
121 The parts of the Links-Lua and ELinks code that related to Lua are mostly
122 wrapped inside #ifdef HAVE_LUA ...  #endif conditions, so they're easy to find.
123 And also lua.c.
125 In certain situations, I put some hooks into the C code.  These prepare the C
126 code to run some Lua code, run it, then translate the return values to
127 something meaningful to the C code.  They are really simple, but I had to put
128 in some cruft.
130 .The code implementing the Go To URL dialog box hook :
131 ------------------------------------------------------------------------------
132 void goto_url_with_hook(struct session *ses, unsigned char *url)
134 #ifndef HAVE_LUA
135         goto_url(ses, url);
136 #else
137         lua_State *L = lua_state;
138         int err;
140         lua_getglobal(L, "goto_url_hook");                                 <1>
141         if (lua_isnil(L, -1)) {
142                 lua_pop(L, 1);
143                 goto_url(ses, url);
144                 return;
145         }        
146         lua_pushstring(L, url);                                            <2>
147         if (list_empty(ses->history)) lua_pushnil(L);
148         else lua_pushstring(L, cur_loc(ses)->vs.url);
149          
150         if (prepare_lua(ses)) return;                                      <3>
151         err = lua_call(L, 2, 1);                                           <4>
152         finish_lua();                                                      <5>
153         if (err) return;
154          
155         if (lua_isstring(L, -1))                                           <6>
156                 goto_url(ses, (unsigned char *) lua_tostring(L, -1));
157         else if (!lua_isnil(L, -1))
158                 alert_lua_error("goto_url_hook must return a string or nil");
159         lua_pop(L, 1);
160 #endif
162 ------------------------------------------------------------------------------
164 Quick description of what it does:
166 <1> Get the value named `goto_url_hook' from the Lua state.  If it doesn't
167     exist, the user hasn't installed a hook so continue the normal way.
169 <2> Push the arguments onto the Lua stack for the function call.
170     `goto_url_hook' takes two parameters, the new URL and the current URL, so
171     we push them on.
173 <3> Some stuff to prepare for running Lua.  This is in case, for example, the
174     Lua function contains bugs, we want to trap some of that.  It's supposed to
175     enable a mechanism where ^C will break out of infinite loops and such, but
176     that's not working so good.
178 <4> Call the Lua function, i.e. goto_url_hook
180 <5> Disable the error trapping stuff.
182 <6> Look at the return value of goto_url_hook and do something appropriate.
184 [ If you want to know the lua_* functions, you're going to have to read the
185   Lua API manual ]
188 That's basically all the Links-Lua stuff is, a bunch of hooks that pass
189 arguments to some arbitrary Lua code, then read in return values and interpret
190 them.  But it works because Lua is a programming language, and that enables you
191 to do what you would from C, as long as you stick to the C<->Lua interface.
193 The code to allow binding Lua code to a keypress is slightly different then the
194 hooks, but not much.  Instead of branching off to some C code when a key is
195 pressed, we branch off to some Lua code.
198 Coding style
199 ------------
201 Mikulas once said that 'it was hard to code, so it should be hard to read' -
202 and he drove by this when he was writing links.  However, we do NOT drive by
203 this rule anymore ;-).  We strongly welcome cleanup patches and you have 99%
204 chance that they will be applied, if they are correct.
206 Variable names should be descriptive.  Well, in worst case we'll accept 'i' for
207 index, but if possible don't do even this :).  You should try to declare them
208 on the lowest level possible, so their declaration and initialization will be
209 near their usage and you will also prevent reuse of one variable for two
210 completely different things.  Yes, that's another thing you shouldn't do.  If
211 reasonable, initialize variables during their declaration and don't group too
212 many variables in one line.  ALWAYS make a blank line after the declaration
213 part.
215 Be sure to prefix all local functions with 'static'.
217 Indent shift width is 8 characters--that means one tab character.
219 '{' should be on the same line as conditions near for, if, while, switch etc.,
220 but on separate lines near function headers in function definitions.
222 Please _USE_ one tab instead of 8 spaces!  It makes things easier.
224 Always place spaces around '=', after ',' and - if reasonable - around other
225 operators as well.  You shouldn't make assignments in conditionals:
227 .Use:
228 ------------------------------------------------------------------------------
229 foo = mem_alloc(1234);
230 if (!foo) panic("out of memory");
231 ------------------------------------------------------------------------------
233 .Instead of:
234 ------------------------------------------------------------------------------
235 if (!(foo = mem_alloc(1234))) panic("out of memory");
236 ------------------------------------------------------------------------------
238 Note that thou shalt ALWAYS test for success on everything - we are supposed
239 to die with honor if we are to die!
241 One good point is regarding what language we actually code in. We use C89
242 _exclusively_ (if we don't, we provide a fall-back way for survival in C89
243 environment). ELinks is supposed to work on a large number of more or less
244 weird and ancient systems and we are already used to C89 anyway. The most
245 remarkable implication of no C99 are no C++ (//) comments and declarations
246 at the start of block only.
249 Comments
250 --------
252 Use blank lines frequently to separate chunks of code.  And use magic `/\*` and
253 `*/` to give others an idea about what it does and about possible pitfalls.
254 (Do not use //, as that is not a feature of ANSI C a.k.a. C89.)
256 Keep in mind that if there's an object and verb in the comment (and it is, in
257 most cases), it is a sentence, so it has to start with a capital letter and end
258 with a fullstop ;-).  If you want to share your opinion or investigations, you
259 should sign yourself; e.g.,
261         /* TODO: Move this far away! --pasky */
263 Comments should be written in _ENGLISH_ only.
265 All three following styles of comments are acceptable:
267 ------------------------------------------------------------------------------
269  * Bla bla bla.
270  * blabla?
271  */
273 /* Bla bla bla.
274  * blabla?
275  */
277 /* Bla bla bla.
278  * blabla? */
279 ------------------------------------------------------------------------------
281 The best one usually depends on the actual context.
283 If you describe a structure, make either:
285 ------------------------------------------------------------------------------
286 char *name; /* name of the tag */
287 void (*func)(unsigned char *); /* function hopefully handling the
288                                 * content of the tag */
289 int linebreak; /* needed for break of a line? */
290 ------------------------------------------------------------------------------
294 ------------------------------------------------------------------------------
295 /* Name of the tag */
296 char *name;
297 /* Function hopefully handling the content of the tag */
298 void (*func)(unsigned char *);
300 /* Do we need to break a line? */
301 int linebreak;
302 ------------------------------------------------------------------------------
304 Same if you comment the code.  If the comment is
306         /* then do it now! */
308 place it on the same line as the command, if it's
310         /* We have to parse this crap now, as it is going to be freed in free_crap() */
312 place it on the preceding line.
315 More about style
316 ----------------
318 Note: We use short variables names and stupid examples here, do not take that
319       as a guideline for _REAL_ coding.  Always use descriptive variables
320       names and do not write stupid code ;).
322 General style is:
323 ~~~~~~~~~~~~~~~~~
325 ------------------------------------------------------------------------------
326 [blank line]
327 /* This is a comment about that function */
329 func(int a, int b)
331         int c;
333         c = a * b;
334         if (c) {
335                 int d;
337                 ...
338         } else {
339                 int e;
341                 ...
342         }
344         return (c * d);
346 ------------------------------------------------------------------------------
348 You should observe the following rules:
349 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
351 Always have a blank line before a function declaration or comment.
353 Please add a comment about what the function does.
355 A function's type must be on first line while the function's name is on the
356 second line.
358 If the parameters list exceeds 80 columns then wrap them after a comma to
359 the next line and align them using tabs and/or spaces with the first
360 parameter.
361   
362 .Use:
363 ------------------------------------------------------------------------------
365 func(int p1, int p2, int p3,
366      struct very_long_name_for_a_structure *s,
367      unsigned long last_parameter)
369         int v;
371         ...
373 ------------------------------------------------------------------------------
375 The start of a function's body should be alone on the first column.
377 Always have a blank line after declarations.
379 Always have spaces around operators.
381 .Use:
382 ------------------------------------------------------------------------------
383 c = a * b - (a + b);
384 ------------------------------------------------------------------------------
386 .Instead of:
387 ------------------------------------------------------------------------------
388 c=a*b-(a+b);
389 ------------------------------------------------------------------------------
391 - Keep affectation outside of conditional tests.
393 .Use:
394 ------------------------------------------------------------------------------
395 c = a;
396 if (c == b) {...
397 ------------------------------------------------------------------------------
399 .Instead of:
400 ------------------------------------------------------------------------------
401 if ((c = a) == b) {...
402 ------------------------------------------------------------------------------
404 Never use spaces within ().
406 .Use:
407 ------------------------------------------------------------------------------
408 if (a) ...
409 ------------------------------------------------------------------------------
411 .Instead of:
412 ------------------------------------------------------------------------------
413 if ( a ) ...
414 ------------------------------------------------------------------------------
416 Indent.
418 .Use:
419 ------------------------------------------------------------------------------
420 foreach (a, b)
421         if (a == c)
422                 ...
423         else
424                 ...
425 ------------------------------------------------------------------------------
427 .Instead of:
428 ------------------------------------------------------------------------------
429 foreach(a, b) if (a == c) ...  else ...
430 ------------------------------------------------------------------------------
432 If you have a chain of if () { .. } else if () { .. } else { .. } with longer
433 statements, you can insert a blank line before each else line.
435 Label names should start on the first column and a blank line should be 
436 inserted before it.
438 .Use:
439 -------------------------------------------------------------------------------
440         some_code(aaa);
442 label:
443         some_other_code(bbb);
444 -------------------------------------------------------------------------------
445 .Instead of:
446 -------------------------------------------------------------------------------
447         some_code(aaa);
448         label:
449         some_other_code(bbb);
450 -------------------------------------------------------------------------------
452 Wrap conditions on spaces before operators like && or ||.
454 .Use:
455 -------------------------------------------------------------------------------
456 if (some_very_long_thing1 == some_very_long_thing2
457     && (test1 == test2
458         || some_very_long_thing3 == some_very_long_thing4)) {
459         ....
461 -------------------------------------------------------------------------------
463 Please remove useless spaces or tabs at the end of lines.  Vim has a syntax
464 file called "Whitespace (add)" ...
466 Please keep includes in alphabetical order unless a specific order is required
467 for compilation on weird systems (then please at least make a proper comment
468 about that).
470 Please declare functions without parameters as taking void parameter:
472 .Use:
473 -------------------------------------------------------------------------------
475 func(void)
477         some_code();
479 -------------------------------------------------------------------------------
481 .Instead of:
482 -------------------------------------------------------------------------------
484 func()
486         some_code();
488 -------------------------------------------------------------------------------
490 Please write if (), while (), switch (), for (), .... instead of if(),
491 while(), switch(), for()...  Same thing apply for all iterators and tests
492 (e.g. foreach, foreachback).
494 Please write sizeof(something) instead of sizeof something.
496 Use assert() and assertm() where applicable. It will prevent hidden bugs.
498 Names of enum constants should be in upper case.
500 Please call the charset "utf8" or "UTF8" in identifiers, "UTF-8"
501 elsewhere, and "utf_8" only for compatibility.
503 If you see code in ELinks that doesn't follow these rules, fix it or tell us
504 about it.
506 All the .c files MUST start by a short one-line description:
508         /* <short one-line description> */
510 All the .h files MUST start by an anti-reinclusion ifdef.
511 The macro is
513         EL_<path_relative_to_src:s/[\/.]/_/>.
515 There are obviously exceptions to these rules, but don't make a rule from your
516 exception and be prepared to defend your exception at anytime ;).
519 Coding practices
520 ----------------
522 Use bitfields to store boolean values
523 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525 If speed is not critical and especially if you are messing with some struct
526 where size might matter, feel encouraged to use bitfields to store boolean (or
527 tristate or tetrastate ;) values (e.g. unsigned int foo:1 for one-bit field).
528 HOWEVER please ALWAYS specify signedness of all such fields. It is very easy
529 to reach the top bit in these cases, and with int foo:1, foo would be either 0
530 or -1, which is probably not what you want.
532 Wrap hard initializations of structures with macros
533 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
535 This should be done if the structure's initializers are going to be spread
536 widely (so that we can grep for them easily), there are massive typecasts
537 needed in most of the initializers, you feel that order of the fields in
538 structure is unstable yet and it is likely to change (and you don't want to
539 change the initializers everytime you do so), or in similar cases.
541 .You can do it like:
542 -------------------------------------------------------------------------------
543 struct example {
544         int a;
545         int b;
546         char *c;
548 #define INIT_EXAMPLE(a, b, c) {a, b, c}
549 #define NULL_EXAMPLE {0, 0, NULL}
551 struct example t[] = {
552         INIT_EXAMPLE(1, 2, "abc"),
553         INIT_EXAMPLE(3, 4, "def"),
554         NULL_EXAMPLE
557 struct example t = NULL_EXAMPLE;
558 -------------------------------------------------------------------------------
560 Please try to keep order of fields
561 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
563 Please try to keep order of fields from max. to min. of size of each type of
564 fields, especially in structures:
566 .Use:
567 -------------------------------------------------------------------------------
568 long a;
569 int b;
570 char c;
571 -------------------------------------------------------------------------------
573 .Instead of:
574 -------------------------------------------------------------------------------
575 char c;
576 int b;
577 long b;
578 -------------------------------------------------------------------------------
580 It will help to reduce memory padding on some architectures. Note that this
581 applies only if this will not affect logical division of the structure. The
582 logical composition always takes precedence over this optimization, modulo
583 some very rare critical structures.
585 Please do not use sizeof(struct item_struct_name)
586 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
588 Instead use sizeof(*item) when possible.
590 -------------------------------------------------------------------------------
591 struct example {
592         int *integers;
593         void **pointers;
596 struct example *item;
597 -------------------------------------------------------------------------------
599 .Use:
600 -------------------------------------------------------------------------------
601 item = mem_alloc(sizeof(*item));
602 memset(item, 0, sizeof(*item));
603 item->integers = mem_calloc(10, sizeof(*item->integers));
604 item->pointers = mem_calloc(10, sizeof(*item->pointers));
605 -------------------------------------------------------------------------------
607 .Instead of:
608 -------------------------------------------------------------------------------
609 item = mem_alloc(sizeof(struct example));
610 memset(item, 0, sizeof(struct example));
611 item->integers = mem_calloc(10, sizeof(int));
612 item->pointers = mem_calloc(10, sizeof(void *));
613 -------------------------------------------------------------------------------
615 The preferred form eases future changes in types, and maintain size vs type
616 coherence.
618 Please postfix defined types with _T
619 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
621 -------------------------------------------------------------------------------
622 typedef int (some_func_T)(void *);
623 typedef long long our_long_T;
624 -------------------------------------------------------------------------------
626 Please use mode_t and S_I???? macros instead of numeric modes
627 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
629 .Use:
630 -------------------------------------------------------------------------------
631 mode_t mode = S_IRWXU | S_IRGRP | S_IROTH;
632 -------------------------------------------------------------------------------
634 .Instead of:
635 -------------------------------------------------------------------------------
636 int mode = 0744;
637 -------------------------------------------------------------------------------
639 Note that S_IREAD, S_IWRITE and S_IEXEC are obsolete, you should use S_IRUSR,
640 S_IWUSR, S_IXUSR instead.
643 Patches
644 -------
646 Please send unified patches only.
648 .The recommended way is:
649 -------------------------------------------------------------------------------
650 cp -a elinks/ elinks+mysuperfeature/
651 cd elinks+mysuperfeature/
652 *clap clap*
653 *clickety clickey*
654 make
655 ./elinks -no-connect
656 *goto clap*
657 cd ..
658 diff -ru elinks/ elinks+mysuperfeature/ >elinks-mysuperfeature.patch
659 -------------------------------------------------------------------------------
661 Please manually remove any bloat like changes in ./configure, whitespace
662 changes etc. ;-).
664 We also accept output from `cvs diff -u` :).  The statement about bloat
665 removing above still applies.
667 Big patches are hard to review so if your feature involves a lot of changes
668 please consider splitting it in appropriate bits. Appropriate could mean:
670 - Keep trivial changes like indenting, renaming, fixing comments separate.
672 - Keep movements of (bigger) code snippets separate from changes in them.
674 Note that it makes no sense to separate patches by directories. The
675 important thing is to separate big changes to smaller ones and smaller ones,
676 breaking it to the "thinnest" possible level where the change is still
677 sufficiently self-contained.
680 Advantages of `--enable-debug` configure option
681 -----------------------------------------------
683 Since ELinks 0.4pre11, a memory debugger can be enabled using the
684 `--enable-debug` configure script option.  It may help to find memleaks and more
685 which is why everybody concerned with ELinks develepment should use it:
687 In 0.5 versions `--enable-debug` add some fancy things:
688 - many data integrity checking (see `lists.h`)
689 - hotkey debugging: especially cool for translators, it highlights redundant
690   hotkeys in a menu.  (See also po/perl/README.)
691 - more errors messages
692 - low bug tolerance: it will core dump on some errors instead of just writing
693   an error description.
694 - internal backtrace feature (always enabled if possible)
695 - and more...
697 Before sending a patch, always try to compile and test it with
698 `--enable-debug`, then in normal mode, then in `--fast-mem` mode. If it fails
699 to compile or execute in one of these modes, then rework it.
702 Happy hacking!