Retry only for https protocol
[elinks.git] / doc / hacking.txt
blob7b43afe7f5c453d18eb44eedcc823a22354aeb81
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 Inline functions
250 ----------------
252 Various standards and compilers set restrictions on inline functions:
254 - C89 doesn't support them at all.
256 - According to C99 6.7.4p6, if a translation unit declares a function
257   as inline and not static, then it must also define that function.
259 - According to C99 6.7.4p3, an inline definition of a non-static
260   function must not contain any non-const static variables, and must
261   not refer to anything static outside of it.  According to C99
262   6.7.4p6 however, if the function is ever declared without inline or
263   with extern, then its definition is not an inline definition even if
264   the definition includes the inline keyword.
266 - Sun Studio 11 on Solaris 9 does not let non-static inline functions
267   refer to static identifiers.  Unlike C99 6.7.4p3, this seems to
268   apply to all definitions of inline functions, not only inline
269   definitions.  See ELinks bug 1047.
271 - GCC 4.3.1 warns if a function is declared inline after being called.
272   Perhaps it means such calls cannot be inlined.
274 - In C99, a function definition with extern inline means the compiler
275   should inline calls to that function and must also emit out-of-line
276   code that other translation units can call.  In GCC 4.3.1, it
277   instead means the out-of-line definition is elsewhere.
279 So to be portable to all of those, we use inline functions in only
280 these ways:
282 - Define as static inline in a *.c file.  Perhaps declare in that same
283   file.  On C89, we #define inline to nothing.
285 - Define as static inline in a *.h file.  Perhaps declare in that same
286   file.  On C89, we #define inline to nothing, and extra copies of the
287   function may then get emitted but anyway it'll work.
289 - Declare without inline in a *.h file, and define with NONSTATIC_INLINE
290   in a *.c file.  Perhaps also declare with NONSTATIC_INLINE in the same
291   *.c file.  On Sun Studio 11, we #define NONSTATIC_INLINE to nothing.
294 Comments
295 --------
297 Use blank lines frequently to separate chunks of code.  And use magic `/\*` and
298 `*/` to give others an idea about what it does and about possible pitfalls.
299 (Do not use //, as that is not a feature of ANSI C a.k.a. C89.)
301 Keep in mind that if there's an object and verb in the comment (and it is, in
302 most cases), it is a sentence, so it has to start with a capital letter and end
303 with a fullstop ;-).  If you want to share your opinion or investigations, you
304 should sign yourself; e.g.,
306         /* TODO: Move this far away! --pasky */
308 Comments should be written in _ENGLISH_ only.
310 All three following styles of comments are acceptable:
312 ------------------------------------------------------------------------------
314  * Bla bla bla.
315  * blabla?
316  */
318 /* Bla bla bla.
319  * blabla?
320  */
322 /* Bla bla bla.
323  * blabla? */
324 ------------------------------------------------------------------------------
326 The best one usually depends on the actual context.
328 If you describe a structure, make either:
330 ------------------------------------------------------------------------------
331 char *name; /* name of the tag */
332 void (*func)(unsigned char *); /* function hopefully handling the
333                                 * content of the tag */
334 int linebreak; /* needed for break of a line? */
335 ------------------------------------------------------------------------------
339 ------------------------------------------------------------------------------
340 /* Name of the tag */
341 char *name;
342 /* Function hopefully handling the content of the tag */
343 void (*func)(unsigned char *);
345 /* Do we need to break a line? */
346 int linebreak;
347 ------------------------------------------------------------------------------
349 Same if you comment the code.  If the comment is
351         /* then do it now! */
353 place it on the same line as the command, if it's
355         /* We have to parse this crap now, as it is going to be freed in free_crap() */
357 place it on the preceding line.
360 More about style
361 ----------------
363 Note: We use short variables names and stupid examples here, do not take that
364       as a guideline for _REAL_ coding.  Always use descriptive variables
365       names and do not write stupid code ;).
367 General style is:
368 ~~~~~~~~~~~~~~~~~
370 ------------------------------------------------------------------------------
371 [blank line]
372 /* This is a comment about that function */
374 func(int a, int b)
376         int c;
378         c = a * b;
379         if (c) {
380                 int d;
382                 ...
383         } else {
384                 int e;
386                 ...
387         }
389         return (c * d);
391 ------------------------------------------------------------------------------
393 You should observe the following rules:
394 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
396 Always have a blank line before a function declaration or comment.
398 Please add a comment about what the function does.
400 A function's type must be on first line while the function's name is on the
401 second line.
403 If the parameters list exceeds 80 columns then wrap them after a comma to
404 the next line and align them using tabs and/or spaces with the first
405 parameter.
406   
407 .Use:
408 ------------------------------------------------------------------------------
410 func(int p1, int p2, int p3,
411      struct very_long_name_for_a_structure *s,
412      unsigned long last_parameter)
414         int v;
416         ...
418 ------------------------------------------------------------------------------
420 The start of a function's body should be alone on the first column.
422 Always have a blank line after declarations.
424 Always have spaces around operators.
426 .Use:
427 ------------------------------------------------------------------------------
428 c = a * b - (a + b);
429 ------------------------------------------------------------------------------
431 .Instead of:
432 ------------------------------------------------------------------------------
433 c=a*b-(a+b);
434 ------------------------------------------------------------------------------
436 - Keep affectation outside of conditional tests.
438 .Use:
439 ------------------------------------------------------------------------------
440 c = a;
441 if (c == b) {...
442 ------------------------------------------------------------------------------
444 .Instead of:
445 ------------------------------------------------------------------------------
446 if ((c = a) == b) {...
447 ------------------------------------------------------------------------------
449 Never use spaces within ().
451 .Use:
452 ------------------------------------------------------------------------------
453 if (a) ...
454 ------------------------------------------------------------------------------
456 .Instead of:
457 ------------------------------------------------------------------------------
458 if ( a ) ...
459 ------------------------------------------------------------------------------
461 Indent.
463 .Use:
464 ------------------------------------------------------------------------------
465 foreach (a, b)
466         if (a == c)
467                 ...
468         else
469                 ...
470 ------------------------------------------------------------------------------
472 .Instead of:
473 ------------------------------------------------------------------------------
474 foreach(a, b) if (a == c) ...  else ...
475 ------------------------------------------------------------------------------
477 If you have a chain of if () { .. } else if () { .. } else { .. } with longer
478 statements, you can insert a blank line before each else line.
480 Label names should start on the first column and a blank line should be 
481 inserted before it.
483 .Use:
484 -------------------------------------------------------------------------------
485         some_code(aaa);
487 label:
488         some_other_code(bbb);
489 -------------------------------------------------------------------------------
490 .Instead of:
491 -------------------------------------------------------------------------------
492         some_code(aaa);
493         label:
494         some_other_code(bbb);
495 -------------------------------------------------------------------------------
497 Wrap conditions on spaces before operators like && or ||.
499 .Use:
500 -------------------------------------------------------------------------------
501 if (some_very_long_thing1 == some_very_long_thing2
502     && (test1 == test2
503         || some_very_long_thing3 == some_very_long_thing4)) {
504         ....
506 -------------------------------------------------------------------------------
508 Please remove useless spaces or tabs at the end of lines.  Vim has a syntax
509 file called "Whitespace (add)" ...
511 Please keep includes in alphabetical order unless a specific order is required
512 for compilation on weird systems (then please at least make a proper comment
513 about that).
515 Please declare functions without parameters as taking void parameter:
517 .Use:
518 -------------------------------------------------------------------------------
520 func(void)
522         some_code();
524 -------------------------------------------------------------------------------
526 .Instead of:
527 -------------------------------------------------------------------------------
529 func()
531         some_code();
533 -------------------------------------------------------------------------------
535 Please write if (), while (), switch (), for (), .... instead of if(),
536 while(), switch(), for()...  Same thing apply for all iterators and tests
537 (e.g. foreach, foreachback).
539 Please write sizeof(something) instead of sizeof something.
541 Use assert() and assertm() where applicable. It will prevent hidden bugs.
543 Names of enum constants should be in upper case.
545 Please call the charset "utf8" or "UTF8" in identifiers, "UTF-8"
546 elsewhere, and "utf_8" only for compatibility.
548 If you see code in ELinks that doesn't follow these rules, fix it or tell us
549 about it.
551 All the .c files MUST start by a short one-line description:
553         /* <short one-line description> */
555 All the .h files MUST start by an anti-reinclusion ifdef.
556 The macro is
558         EL_<path_relative_to_src:s/[\/.]/_/>.
560 There are obviously exceptions to these rules, but don't make a rule from your
561 exception and be prepared to defend your exception at anytime ;).
564 Coding practices
565 ----------------
567 Use bitfields to store boolean values
568 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
570 If speed is not critical and especially if you are messing with some struct
571 where size might matter, feel encouraged to use bitfields to store boolean (or
572 tristate or tetrastate ;) values (e.g. unsigned int foo:1 for one-bit field).
573 HOWEVER please ALWAYS specify signedness of all such fields. It is very easy
574 to reach the top bit in these cases, and with int foo:1, foo would be either 0
575 or -1, which is probably not what you want.
577 Wrap hard initializations of structures with macros
578 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
580 This should be done if the structure's initializers are going to be spread
581 widely (so that we can grep for them easily), there are massive typecasts
582 needed in most of the initializers, you feel that order of the fields in
583 structure is unstable yet and it is likely to change (and you don't want to
584 change the initializers everytime you do so), or in similar cases.
586 .You can do it like:
587 -------------------------------------------------------------------------------
588 struct example {
589         int a;
590         int b;
591         char *c;
593 #define INIT_EXAMPLE(a, b, c) {a, b, c}
594 #define NULL_EXAMPLE {0, 0, NULL}
596 struct example t[] = {
597         INIT_EXAMPLE(1, 2, "abc"),
598         INIT_EXAMPLE(3, 4, "def"),
599         NULL_EXAMPLE
602 struct example t = NULL_EXAMPLE;
603 -------------------------------------------------------------------------------
605 Please try to keep order of fields
606 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
608 Please try to keep order of fields from max. to min. of size of each type of
609 fields, especially in structures:
611 .Use:
612 -------------------------------------------------------------------------------
613 long a;
614 int b;
615 char c;
616 -------------------------------------------------------------------------------
618 .Instead of:
619 -------------------------------------------------------------------------------
620 char c;
621 int b;
622 long b;
623 -------------------------------------------------------------------------------
625 It will help to reduce memory padding on some architectures. Note that this
626 applies only if this will not affect logical division of the structure. The
627 logical composition always takes precedence over this optimization, modulo
628 some very rare critical structures.
630 Please do not use sizeof(struct item_struct_name)
631 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
633 Instead use sizeof(*item) when possible.
635 -------------------------------------------------------------------------------
636 struct example {
637         int *integers;
638         void **pointers;
641 struct example *item;
642 -------------------------------------------------------------------------------
644 .Use:
645 -------------------------------------------------------------------------------
646 item = mem_alloc(sizeof(*item));
647 memset(item, 0, sizeof(*item));
648 item->integers = mem_calloc(10, sizeof(*item->integers));
649 item->pointers = mem_calloc(10, sizeof(*item->pointers));
650 -------------------------------------------------------------------------------
652 .Instead of:
653 -------------------------------------------------------------------------------
654 item = mem_alloc(sizeof(struct example));
655 memset(item, 0, sizeof(struct example));
656 item->integers = mem_calloc(10, sizeof(int));
657 item->pointers = mem_calloc(10, sizeof(void *));
658 -------------------------------------------------------------------------------
660 The preferred form eases future changes in types, and maintain size vs type
661 coherence.
663 Please postfix defined types with _T
664 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
666 -------------------------------------------------------------------------------
667 typedef int (some_func_T)(void *);
668 typedef long long our_long_T;
669 -------------------------------------------------------------------------------
671 Please use mode_t and S_I???? macros instead of numeric modes
672 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
674 .Use:
675 -------------------------------------------------------------------------------
676 mode_t mode = S_IRWXU | S_IRGRP | S_IROTH;
677 -------------------------------------------------------------------------------
679 .Instead of:
680 -------------------------------------------------------------------------------
681 int mode = 0744;
682 -------------------------------------------------------------------------------
684 Note that S_IREAD, S_IWRITE and S_IEXEC are obsolete, you should use S_IRUSR,
685 S_IWUSR, S_IXUSR instead.
688 Patches
689 -------
691 Please send unified patches only.
693 .The recommended way is:
694 -------------------------------------------------------------------------------
695 cp -a elinks/ elinks+mysuperfeature/
696 cd elinks+mysuperfeature/
697 *clap clap*
698 *clickety clickey*
699 make
700 ./elinks -no-connect
701 *goto clap*
702 cd ..
703 diff -ru elinks/ elinks+mysuperfeature/ >elinks-mysuperfeature.patch
704 -------------------------------------------------------------------------------
706 Please manually remove any bloat like changes in ./configure, whitespace
707 changes etc. ;-).
709 We also accept output from `git diff` :).  The statement about bloat
710 removing above still applies.
712 Big patches are hard to review so if your feature involves a lot of changes
713 please consider splitting it in appropriate bits. Appropriate could mean:
715 - Keep trivial changes like indenting, renaming, fixing comments separate.
717 - Keep movements of (bigger) code snippets separate from changes in them.
719 Note that it makes no sense to separate patches by directories. The
720 important thing is to separate big changes to smaller ones and smaller ones,
721 breaking it to the "thinnest" possible level where the change is still
722 sufficiently self-contained.
725 Advantages of `--enable-debug` configure option
726 -----------------------------------------------
728 Since ELinks 0.4pre11, a memory debugger can be enabled using the
729 `--enable-debug` configure script option.  It may help to find memleaks and more
730 which is why everybody concerned with ELinks develepment should use it:
732 In 0.5 versions `--enable-debug` add some fancy things:
733 - many data integrity checking (see `lists.h`)
734 - hotkey debugging: especially cool for translators, it highlights redundant
735   hotkeys in a menu.  (See also po/perl/README.)
736 - more errors messages
737 - low bug tolerance: it will core dump on some errors instead of just writing
738   an error description.
739 - internal backtrace feature (always enabled if possible)
740 - and more...
742 Before sending a patch, always try to compile and test it with
743 `--enable-debug`, then in normal mode, then in `--fast-mem` mode. If it fails
744 to compile or execute in one of these modes, then rework it.
747 Happy hacking!