Find the number of spaces for the next line of indentation
(code)
| 142 | raise |
| 143 | |
| 144 | def find_next_indent(code): |
| 145 | """Find the number of spaces for the next line of indentation""" |
| 146 | tokens = list(partial_tokens(code)) |
| 147 | if tokens[-1].type == tokenize.ENDMARKER: |
| 148 | tokens.pop() |
| 149 | if not tokens: |
| 150 | return 0 |
| 151 | while (tokens[-1].type in {tokenize.DEDENT, tokenize.NEWLINE, tokenize.COMMENT}): |
| 152 | tokens.pop() |
| 153 | |
| 154 | if tokens[-1].type == INCOMPLETE_STRING: |
| 155 | # Inside a multiline string |
| 156 | return 0 |
| 157 | |
| 158 | # Find the indents used before |
| 159 | prev_indents = [0] |
| 160 | def _add_indent(n): |
| 161 | if n != prev_indents[-1]: |
| 162 | prev_indents.append(n) |
| 163 | |
| 164 | tokiter = iter(tokens) |
| 165 | for tok in tokiter: |
| 166 | if tok.type in {tokenize.INDENT, tokenize.DEDENT}: |
| 167 | _add_indent(tok.end[1]) |
| 168 | elif (tok.type == tokenize.NL): |
| 169 | try: |
| 170 | _add_indent(next(tokiter).start[1]) |
| 171 | except StopIteration: |
| 172 | break |
| 173 | |
| 174 | last_indent = prev_indents.pop() |
| 175 | |
| 176 | # If we've just opened a multiline statement (e.g. 'a = ['), indent more |
| 177 | if tokens[-1].type == IN_MULTILINE_STATEMENT: |
| 178 | if tokens[-2].exact_type in {tokenize.LPAR, tokenize.LSQB, tokenize.LBRACE}: |
| 179 | return last_indent + 4 |
| 180 | return last_indent |
| 181 | |
| 182 | if tokens[-1].exact_type == tokenize.COLON: |
| 183 | # Line ends with colon - indent |
| 184 | return last_indent + 4 |
| 185 | |
| 186 | if last_indent: |
| 187 | # Examine the last line for dedent cues - statements like return or |
| 188 | # raise which normally end a block of code. |
| 189 | last_line_starts = 0 |
| 190 | for i, tok in enumerate(tokens): |
| 191 | if tok.type == tokenize.NEWLINE: |
| 192 | last_line_starts = i + 1 |
| 193 | |
| 194 | last_line_tokens = tokens[last_line_starts:] |
| 195 | names = [t.string for t in last_line_tokens if t.type == tokenize.NAME] |
| 196 | if names and names[0] in {'raise', 'return', 'pass', 'break', 'continue'}: |
| 197 | # Find the most recent indentation less than the current level |
| 198 | for indent in reversed(prev_indents): |
| 199 | if indent < last_indent: |
| 200 | return indent |
| 201 |
no test coverage detected