fwmechanic / k_edit

K Editor for Win32 and Linux
GNU General Public License v3.0
11 stars 0 forks source link

Implement Z Automatic Indentation #6

Open fwmechanic opened 8 years ago

fwmechanic commented 8 years ago

(excerpt from "Z The.95 Percent Program Editor by Steven R. Wood, Yale.U, 1981")

Automatic Indentation

Existing structure-oriented program editors store a program as a parse tree and use a pretty-printer to map the parse tree onto the display. Instead of having the editor play the dominant role in program formatting, we chose to have it "suggest" an indentation amount whenever the newline command is used to enter a line. The indentation is relative to the first non-blank character of the current line. For block-structured languages, the cursor position on the next line is determined as follows:

For BLISS, the backtab token set is: TES, TESN, END, left parenthesis and the tab token set is: SET, NSET, BEGIN, right parenthesis, THEN, ELSE, DO with the last three tokens implicitly opening a block since they have no matching token in the backtab token table. Combined with the rules above, they encourage the following indentation style:

FUNCTION ... BEGIN
   ... ;
   IF ... THEN (
      ... ;
      ... ;
      )
   ELSE
      WHILE ... DO
         ... ;
   ... ;
   END;

The advantages of this scheme are that it is simple (the implementation is only 50 lines of BLISS) and that it is right almost all of the time. Even when this algorithm guesses wrong, it is off by only one tab stop. By disabling the automatic indentation feature, the user can effect his own indentation style by hand.

For languages that are not block-structured (e.g. LISP and APL) the algorithm is even simpler. For LISP, the algorithm places the cursor on the next line, in the column containing the left parenthesis of the last balanced expression, as determined by moving backwards from the end of the current line. This encourages the following indentation style:

(DE FOO (BAR)
        (COND (ATOM BAR)
              (...)
              (T (...)))
        (...))

For APL the indentation algorithm is the same one used for text files, namely maintain the indentation of the current line.