Navigation Menu

Skip to content

Code Style Guide

Eric Nielsen edited this page Jan 12, 2022 · 7 revisions

These are the code style guidelines that should be followed when contributing to Zim.

Indentation

2 spaces.

When using line continuations, indent with 2 extra spaces:

for x in a very very very very very very very very very very very very very \
    very long line; do
  print ${x}
done

Line length

Be reasonable. Keeping within 80 characters is recommended, 120 is the maximum.

Variables

Wrap your variables in ${curly} ${braces}.

Use ${snake_case} for your variable names.

Use existing variables whenever possible:

-print "$(whoami) in $(pwd)"
+print "${USER} in ${PWD}"

Limit the scope of variables to local when within a function.

When declaring a global variable, be explicit and do it using typeset -g. This avoids warnings when WARN_CREATE_GLOBAL is set:

-: ${VAR=1}
+if (( ! ${+VAR} )) typeset -g VAR=1

Flow logic

For short single commands, prefer one-liners:

  • Short for form: for x (foo bar) print ${x}
  • Short if form: if [[ -d ${dir} ]] cd ${dir} (Only applicable when the test part is delimited, such as by [[ ]] or (( )). See the Zsh manual.)

Otherwise just place ; do or ; then on the same line as while, for ... in or if.

Use (( )) for arithmetic conditions, and [[ ]] for other condition evaluations. Don't use [ ].

With arithmetic conditions:

  • Don't use $ in front of variables: (( var > 1 ))
  • Unless some substitution is needed: (( ${#var} > 1 ))

Functions

Use POSIX syntax:

-function foo {
+foo() {
   print bar
 }

NOTE: There is a difference between this and ksh style, but unless you know what it is and you're sure you need it, use POSIX.

Misc

Don't use backticks ` to execute something in a subshell. $(print "use parentheses")

Clone this wiki locally