Indent в программировании что это
Хочу рассказать об утилите indent, помогающей разметить исходный код пробелами и табуляциями в соответствии с теми или иными стандартами. Программа классическая, входит в состав любого Linux-дистрибутива, в котором установлены пакеты, связанные с разработкой. Но так ли это важно — правильно оформлять исходники?
До тех пор, пока вы пишете «для себя», количество пробелов в начале строки, отступы между функциями и т.п., конечно же, не особо важны. Лишь бы самому автору читать было удобно. Как только появляется необходимость работать в серьезной команде — внешний вид кода приобретает важнейшее значение. Даже если ваша программа работает правильно, ее могут не принять (а значит не оплатить) из-за неправильно оформленных исходников, причем правила у каждого заказчика свои: кто-то хочет, чтобы строки не были слишком длинными, кто-то — чтобы фигурная скобка в операторе if открывалась на следующей строке, кто-то — чтобы на той же самой, кто-то любит начинать строку пробелами, кто-то табуляциями и т.п. Всем этим управляет утилита indent.
«Для себя», например, я пишу программы в собственном стиле, где отступы слева минимальны и оформляются пробелами, а операторы по возможности вытягиваются в одну строку, правая граница которой очень часто оказывается вне экрана. Мне важно видеть что за чем идет, а не мелкие детали, в них я более-менее уверен.
Если же программу будет читать кто-то другой, то ему, напротив, нужно проверить код на вменяемость, так что всё содержимое должно быть видно, пусть и ценой разбивки длинных строк и наличия пустот.
Опций-ключей у indent великое множество. Достаточно посмотреть первые страницы мануала, чтобы увидеть, что конец их перечня их теряется где-то в бесконечности.
Но никто не заставляет учить всё это. Есть наиболее употребляемые опции. Вот, например, как можно оформить исходники в стиле отцов-основателей языка C — Кернигана и Ритчи:
В GUI-средствах разработки, таких как Eclipse, есть встроенные средства проверки оформления кода (Checkstyle). Есть такой модуль и для сборщика ant. Но и indent пока не сдает позиций в деле грамотной разметки текста программ.
Индентация программного кода
Индентация — способ оформления программного кода при помощи отступов таким образом, чтобы структурные блоки было видно наглядно. Зачем нужна индентация:
Кроме того, существуют отдельные языки программирования (Python и несколько производных от него языков), где индентация является обязательной и непосрдественно влияет на выполнение программы. В большинстве языков программирование индентация не является обязательной, однако настоятельно рекомендуется всеми руководствами по написанию программного кода.
Использование индентации
Если вы выделяете блок кода (if, while, foreach и т.п.), то весь код, который находится внутри блока, должен быть на один таб правее, чем основной код.
Если внутри блока выделяется еще один блок, то он должен быть еще на один таб правее.
Скобка, которая закрывает блок, должна быть на том же уровне, что и начало блока. Только обратите внимание, что речь идет не про скобку, открывающую блок, а сам блок (в примере выше это будет if).
Если у нас есть два равноправных блока, например if-else, то они будут на одном уровне.
Таких блоков может быть сколько угодно:
Но не нужно путать со случаем, когда внутри одного из блоков появляется еще один уровень вложенности:
Если же у вас просто последовательность команд, выполняемых последовательно, то они будут на одном уровне.
Даже если они внутри блока:
Если вам нужно добавить отступ нажимаете клавишу Tab на клавиатуре. Если вам нужно сдвинуть уже существующий блок кода вправо, то выделяете блок кода, нажимаете клавишу tab. Если влево, выделяете, нажимаете Shift+Tab. Это работает в любом редакторе, предназначенном для работы с кодом. Редко в каких-то местах может не работать. Использовать для индентации клавишу пробел крайне не рекомендуется.
Перенос в рамках одной команды
Большинство языков программирования допускают переность одну команду на несколько строк. Обычно это делается, если строка становится слишком большой, чтобы влезть на экран монитора. Чаще всего речь идет про вызов функции со сложными аргументами.
Для облегчения читаемости таких вызовов рекомендуется добавлять переносы. В этом случае применяется то же принцип, что и при индентации блоков.
Кроме того, рекомендуется помещать каждый аргумент в отдельную строку. Даже если какой-то из аргументов короткий.
Таким образом, рекомендуется придерживаться правила: либо все аргументы располагаются на одной строке, либо каждый аргумент на отдельной строке. Это делается для того, чтобы при быстром чтении кода было хорошо видно количество и порядок следования аргументов.
Стандарты на индентацию
В настойщий момент существуют два разных подхода к тому, как текстовый редактор должен реализовывать индентацию:
Среди разработчиков ведутся дискуссии, какой способ является более предпочтительным. Единого мнение на этот счет у программистского сообщества так и не сложилось. Как правило, результат выглядит одинаково. Различия могут быть связаны с тем, что символ табуляции в разных ректорах может иметь разную длину. Как правило, во всех редакторах есть настройка, определяющая длину символа табуляции. Настоятельно рекомендуется в рамках одного проекта использовать один стиль индентации (всегда табы или всегда пробелы), иначе при открытии в разных редакторах индентация может нарушаться.
Python табуляция (отступы)
О дна из особенностей Python — для оформления блоков кода вместо привычных фигурных скобок, как в C, C ++, Java или операторных скобок begin … end как в Pascal, используются отступы (или табуляция).
Подробнее о том, какие есть правила расстановки отступов — рассмотрим далее.
Почему табуляция в Питоне так важна?
Что такое отступ? Говоря простыми словами, это просто добавление пробела перед определенным оператором.
Многим программистам жесткое соблюдение отступов может показаться избыточной мерой. Однако именно из-за строго соблюдения правил форматирования, код на Python — чистый, понятный и аккуратный. Отсюда следующие плюсы 👍:
Отступы в языке Python — это способ указать интерпретатору, что оператор (или целая их группа) — это определенный block-комбинация команд для выполнения задачи.
В большинстве других языков, таких как семейство C, Java и прочих для оформления блоков используются фигурные скобки, в Питоне — отступы, для создания которых обычно используются пробелы. Все команды, отделенные от начала строки одним и тем же расстоянием, принадлежат к одному и тому же блоку. Если в нем выделяется еще один блок — используется еще один отступ вправо, и так далее. Рассмотрим это на примере:
def my_small_function(): # [0 пробелов] определение функции со знаком «:» в конце if a > b: # [4 пробела] начало блока условия, располагается внутри функции return a # [8 пробелов] часть блока if else: # [4 пробела] продолжение блока условия, на том же уровне, что и if return b # [8 пробелов] часть блока else print(my_small_function()) # [0 пробелов] вызов функции вне ее блока
💡 По умолчанию в Python используется 4 пробела в качестве отступа
Однако программист может использовать и другое их количество, но не менее одного.
Что нам говорит PEP8?
Для каждого уровня отступов необходимо использовать по 4 пробела.
Строки большой длины должны вертикально выравнивать внутренние элементы, для этого используется неявная линия в скобках или с применением висячего отступа. Во втором случае следует помнить: на первой линии не должны располагаться аргументы, остальные строки располагаются так, чтобы быть продолжением неявной линии.
Примеры кода
👍 Правильное оформление
Расположение закрывающих скобок в конструкциях с многими строками под началом первой строки:
my_list = [ one, two, three, four, five, six, ] result = some_arguments( ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, )
👎 Ошибочное оформление
😐 Выборочное оформление
В многострочных конструкциях закрывающие скобки можно устанавливать на отдельной строке под первым символом (не пробелом) последнего пункта:
some_list = [ one, two, three, four, five, six, ] res = some_arguments( ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, )
Табуляция или пробелы — что использовать? 🤷♂️
Согласно официальной документации, самым предпочтительным способом оформления отступов является использование пробелов, обычно 4
Табуляция может использоваться в случае поддержки готового кода, где все отступы оформлены именно таким способом.
Настройка IDE для работы с отступами
Чтобы при написании кода не задумываться о правильной расстановке пробелов для отступов, в редакторах кода и IDE используется специальный функционал, самостоятельно распознающий место создания отдельных блоков, в результате чего пробелы расставляются автоматически.
Рассмотрим, как можно настроить или изменить такие параметры в самых популярных IDE, когда возникает такая необходимость.
PyCharm
В случае использования интегрированной среды разработки PyCharm для настройки оформления отступов необходимо последовательно перейти по таким пунктам меню:
File → Settings → Editor → Code style → Python
Для настроек параметров есть 3 поля:
VSCode
File → Preferences → Settings
Далее для ускорения в строке поиска ввести tab и установить нужные значения для таких опций:
Ошибки при работе с отступами
При неправильном оформлении отступов интерпретатор Python будет сообщать об ошибках. Таких ошибок может быть несколько, рассмотрим основные.
expected an indented block
Данная ошибка может возникать в случае, когда после оглашения начала блока кода — def, if, while и некоторых других на следующей строке отсутствует отступ. Для ее исправления после начала блока должна быть хотя бы одна вложенная строка с отступом.
Возникает ошибка в том случае, когда перед началом строки есть отступ, но на предыдущей отсутствует оглашение начала блока кода, то есть, нет def, if, elif, else, for или while. Обычно такая ситуация возникает случайно, когда программист ставит слишком много пробелов в начале строки.
Indentationerror: expected an indented block
Ошибка возникает в том случае, когда после оглашения блока кода на следующей строке нет отступа или же сделанные отступы состоят из разного количества пробелов.
Таким образом, отступы в языке программирования Python, в отличие от многих других, играют такую же важную роль, как и служебные слова, так как именно они определяют создание блоков кода. Для каждого indent рекомендуется использовать 4 пробела, однако программист по своему желанию может установить и другое их количество, главное — одинаковое во всем проекте.
Indent в программировании что это
indent [options] [single-input-file] [-o output-file]
DESCRIPTION
The indent program can be used to make code easier to read. It can also convert from one style of writing C to another.
indent understands a substantial amount about the syntax of C, but it also attempts to cope with incomplete and misformed syntax.
In version 1.2 and more recent versions, the GNU style of indenting is the default.
OPTIONS
INVOKING INDENT
As of version 1.3, the format of the indent command is:
In the second form, only one input file is specified. In this case, or when the standard input is used, you may specify an output file after the `-o’ option.
To cause indent to write to standard output, use the `-st’ option. This is only allowed when there is only one input file, or when the standard input is used.
If no input files are named, the standard input is read for input. Also, if a filename named `-‘ is specified, then the standard input is read.
As an example, each of the following commands will input the program `slithy_toves.c’ and write its indented text to `slithy_toves.out’:
Here is another example:
This will indent the program `test/metabolism.c’ using the `-br’ and `-l85′ options, write the output back to `test/metabolism.c’, and write the original contents of `test/metabolism.c’ to a backup file in the directory `test’.
Equivalent invocations using long option names for this example would be:
The format of `.indent.pro’ is simply a list of options, just as they would appear on the command line, separated by white space (tabs, spaces, and newlines). Options in `.indent.pro’ may be surrounded by C or C++ comments, in which case they are ignored.
Command line switches are handled after processing `.indent.pro’. Options specified later override arguments specified earlier, with one exception: Explicitly specified options always override background options (See COMMON STYLES ). You can prevent indent from reading an `.indent.pro’ file by specifying the `-npro’ option.
BACKUP FILES
As of version 1.3, GNU indent makes GNU-style backup files, the same way GNU Emacs does. This means that either simple or numbered backup filenames may be made.
Simple backup file names are generated by appending a suffix to the original file name. The default for this suffix is the one-character string `
‘ (tilde). Thus, the backup file for `python.c’ would be `python.c
Instead of the default, you may specify any string as a suffix by setting the environment variable SIMPLE_BACKUP_SUFFIX to your preferred suffix.
Numbered backup versions of a file `momeraths.c’ look like `momeraths.c.
‘, where 23 is the version of this particular backup. When making a numbered backup of the file `src/momeraths.c’, the backup file will be named `src/momeraths.c.
‘, where V is one greater than the highest version currently existing in the directory `src’. The environment variable VERSION_WIDTH controls the number of digits, using left zero padding when necessary. For instance, setting this variable to «2» will lead to the backup file being named `momeraths.c.
Other versions of indent use the suffix `.BAK’ in naming backup files. This behaviour can be emulated by setting SIMPLE_BACKUP_SUFFIX to `.BAK’.
Note also that other versions of indent make backups in the current directory, rather than in the directory of the source file as GNU indent now does.
COMMON STYLES
There are several common styles of C code, including the GNU style, the Kernighan & Ritchie style, and the original Berkeley style. A style may be selected with a single background option, which specifies a set of values for all other options. However, explicitly specified options always override options implied by a background option.
As of version 1.2, the default style of GNU indent is the GNU style. Thus, it is no longer necessary to specify the option `-gnu’ to obtain this format, although doing so will not cause an error. Option settings which correspond to the GNU style are:
The GNU coding style is that preferred by the GNU project. It is the style that the GNU Emacs C mode encourages and which is used in the C portions of GNU Emacs. (People interested in writing programs for Project GNU should get a copy of «The GNU Coding Standards», which also covers semantic and portability issues such as memory usage, the size of integers, etc.)
The Kernighan & Ritchie style is used throughout their well-known book «The C Programming Language». It is enabled with the `-kr’ option. The Kernighan & Ritchie style corresponds to the following set of options:
Kernighan & Ritchie style does not put comments to the right of code in the same column at all times (nor does it use only one space to the right of the code), so for this style indent has arbitrarily chosen column 33.
The style of the original Berkeley indent may be obtained by specifying `-orig’ (or by specifying `—original’, using the long option name). This style is equivalent to the following settings:
BLANK LINES
Various programming styles use blank lines in different places. indent has a number of options to insert or delete blank lines in specific places.
The `-bad’ option causes indent to force a blank line after every block of declarations. The `-nbad’ option causes indent not to force such blank lines.
The `-bap’ option forces a blank line after every procedure body. The `-nbap’ option forces no such blank line.
The `-sob’ option causes indent to swallow optional blank lines (that is, any optional blank lines present in the input will be removed from the output). If the `-nsob’ is specified, any blank lines present in the input file will be copied to the output file.
—blank-lines-after-declarations
The `-bad’ option forces a blank line after every block of declarations. The `-nbad’ option does not add any such blank lines.
For example, given the input
—blank-lines-after-procedures
The `-bap’ option forces a blank line after every procedure body.
For example, given the input
COMMENTS
indent formats both C and C++ comments. C comments are begun with `/*’, terminated with `*/’ and may contain newline characters. C++ comments begin with the delimiter `//’ and end at the newline.
indent handles comments differently depending upon their context. indent attempts to distinguish between comments which follow statements, comments which follow declarations, comments following preprocessor directives, and comments which are not preceded by code of any sort, i.e., they begin the text of the line (although not neccessarily in column 1).
indent further distinguishes between comments found outside of procedures and aggregates, and those found within them. In particular, comments beginning a line found within a procedure will be indented to the column at which code is currently indented. The exception to this a comment beginning in the leftmost column; such a comment is output at that column.
indent attempts to leave boxed comments unmodified. The general idea of such a comment is that it is enclosed in a rectangle or «box» of stars or dashes to visually set it apart. More precisely, boxed comments are defined as those in which the initial `/*’ is followed immediately by the character `*’, `=’, `_’, or `-‘, or those in which the beginning comment delimiter (`/*’) is on a line by itself, and the following line begins with a `*’ in the same column as the star of the opening delimiter.
Examples of boxed comments are:
indent attempts to leave boxed comments exactly as they are found in the source file. Thus the indentation of the comment is unchanged, and its length is not checked in any way. The only alteration made is that an embedded tab character may be converted into the appropriate number of spaces.
If the `-bbb’ option is specified, all such boxed comments will be preceded by a blank line, unless such a comment is preceded by code.
Comments which are not boxed comments may be formatted, which means that the line is broken to fit within a right margin and left-filled with whitespace. Single newlines are equivalent to a space, but blank lines (two or more newlines in a row) are taken to mean a paragraph break. Formatting of comments which begin after the first column is enabled with the `-fca’ option. To format those beginning in column one, specify `-fc1′. Such formatting is disabled by default.
The right margin for formatting defaults to 78, but may be changed with the `-lc’ option. If the margin specified does not allow the comment to be printed, the margin will be automatically extended for the duration of that comment. The margin is not respected if the comment is not being formatted.
If the code to the left of the comment exceeds the beginning column, the comment column will be extended to the next tabstop column past the end of the code, or in the case of preprocessor directives, to one space past the end of the directive. This extension lasts only for the output of that particular comment.
The `-cdb’ option places the comment delimiters on blank lines. Thus, a single line comment like /* Loving hug */ can be transformed into:
STATEMENTS
The `-br’ or `-bl’ option specifies how to format braces.
The `-br’ option formats statement braces like this:
The `-bl’ option formats them like this:
If you use the `-bl’ option, you may also want to specify the `-bli’ option. This option specifies the number of spaces by which braces are indented. `-bli2′, the default, gives the result shown above. `-bli0′ results in the following:
This causes the while in a do-while loop to cuddle up to the immediately preceding `>’. For example, with `-cdw’ you get the following:
With `-ncdw’ that code would appear as
The `-cli’ option specifies the number of spaces that case labels should be indented to the right of the containing switch statement.
The default gives code like:
Using the `-cli2′ that would become:
If a semicolon is on the same line as a for or while statement, the `-ss’ option will cause a space to be placed before the semicolon. This emphasizes the semicolon, making it clear that the body of the for or while statement is an empty statement. `-nss’ disables this feature.
If the `-cs’ option is specified, indent puts a space after a cast operator.
The `-bs’ option ensures that there is a space between the keyword sizeof and its argument. In some versions, this is known as the `Bill_Shannon’ option.
The `-saf’ option forces a space between an for and the following parenthesis. This is the default.
The `-sai’ option forces a space between an if and the following parenthesis. This is the default.
The `-saw’ option forces a space between an while and the following parenthesis. This is the default.
The `-prs’ option causes all parentheses to be seperated with a space from the what is between them. For example, using `-prs’ results in code like:
DECLARATIONS
By default indent will line up identifiers, in the column specified by the `-di’ option. For example, `-di16′ makes things look like:
Using a small value (such as one or two) for the `-di’ option can be used to cause the identifiers to be placed in the first available position; for example:
The value given to the `-di’ option will still affect variables which are put on separate lines from their types, for example `-di2′ will lead to:
If the `-bc’ option is specified, a newline is forced after each comma in a declaration. For example,
With the `-nbc’ option this would look like
With the `-bfda’ option this would look like
With, in addition, the `-bfde’ option this would look like
The `-psl’ option causes the type of a procedure being defined to be placed on the line before the name of the procedure. This style is required for the etags program to work correctly, as well as some of the c-mode functions of Emacs.
The `-brs’ or `-bls’ option specifies how to format braces in struct declarations. The `-brs’ option formats braces like this:
The `-bls’ option formats them like this:
INDENTATION
With `-lp’ in effect the code looks somewhat clearer:
When a statement is broken in between two or more paren pairs (. ), each extra pair causes the indentation level extra indentation:
The option `-ip N ‘ can be used to set the extra offset per paren. For instance, `-ip0’ would format the above as:
indent assumes that tabs are placed at regular intervals of both input and output character streams. These intervals are by default 8 columns wide, but (as of version 1.2) may be changed by the `-ts’ option. Tabs are treated as the equivalent number of spaces.
The indentation of type declarations in old-style function definitions is controlled by the `-ip’ parameter. This is a numeric parameter specifying how many spaces to indent type declarations. For example, the default `-ip5′ makes definitions look like this:
For compatibility with other versions of indent, the option `-nip’ is provided, which is equivalent to `-ip0′.
ANSI C allows white space to be placed on preprocessor command lines between the character `#’ and the command name. By default, indent removes this space, but specifying the `-lps’ option directs indent to leave this space unmodified. The option `-ppi’ overrides `-nlps’ and `-lps’.
This option can be used to request that preprocessor conditional statements can be indented by to given number of spaces, for example with the option `-ppi 3′
BREAKING LONG LINES
With the option `-l n ‘, or `—line-length n ‘, it is possible to specify the maximum length of a line of C code, not including possible comments that follow it.
When lines become longer then the specified line length, GNU indent tries to break the line at a logical place. This is new as of version 2.1 however and not very intelligent or flexible yet.
Currently there are two options that allows one to interfere with the algorithm that determines where to break a line.
Using the option `-nbbo’ will make it look like this:
The default `-hnl’, however, honours newlines in the input file by giving them the highest possible priority to break lines at. For example, when the input file looks like this:
then using the option `-hnl’, or `—honour-newlines’, together with the previously mentioned `-nbbo’ and `—line-length60′, will cause the output not to be what is given in the last example but instead will prefer to break at the positions where the code was broken in the input file:
DISABLING FORMATTING
More precisely, indent does not attempt to verify the closing delimiter ( */ ) for these C comments, and any whitespace on the line is totally transparent.
It should be noted that the internal state of indent remains unchanged over the course of the unformatted section. Thus, for example, turning off formatting in the middle of a function and continuing it after the end of the function may lead to bizarre results. It is therefore wise to be somewhat modular in selecting code to be left unformatted.
MISCELLANEOUS OPTIONS
The `-v’ option can be used to turn on verbose mode. When in verbose mode, indent reports when it splits one line of input into two more more lines of output, and gives some size statistics at completion.
The `-pmt’ option causes indent to preserve the access and modification times on the output files. Using this option has the advantage that running indent on all source and header files in a project won’t cause make to rebuild all targets. This option is only available on Operating Systems that have the POSIX utime(2) function.
Please report any bugs to bug-indent@gnu.org.
While an attempt was made to get indent working for C++, it will not do a good job on any C++ source except the very simplest.
indent does not look at the given `—line-length’ option when writing comments to the output file. This results often in comments being put far to the right. In order to prohibit indent from joining a broken line that has a comment at the end, make sure that the comments start on the first line of the break.
Comments of the form /*UPPERCASE*/ are not treated as comment but as an identifier, causing them to be joined with the next line. This renders comments of this type useless, unless they are embedded in the code to begin with.
COPYRIGHT
The following copyright notice applies to the indent program. The copyright and copying permissions for this manual appear near the beginning of `indent.texinfo’ and `indent.info’, and near the end of `indent.1′.
Options’ Cross Key
Here is a list of options alphabetized by long option, to help you find the corresponding short option.
RETURN VALUE
FILES
AUTHORS
HISTORY
COPYING
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.