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