diff --git a/nbs/00_core.ipynb b/nbs/00_core.ipynb index 359bf4f..a0db286 100644 --- a/nbs/00_core.ipynb +++ b/nbs/00_core.ipynb @@ -3274,13 +3274,19 @@ " \"Format multiline comments by replacing multiline comment [CI] by newline and adding indentation\"\n", " split_s = s.split(\"\\n\")\n", " split_out = []\n", + " comment_indentation = None\n", " for sp in split_s: # loop on query lines\n", + " comment_start = re.search(r\"\\/\\*\", sp)\n", + " if comment_start:\n", + " comment_indentation = comment_start.start() + 3\n", " if re.search(r\"\\[CI\\]\", sp):\n", - " indentation = re.search(r\"\\/\\*\", sp).start() + 3\n", + " indentation = comment_indentation if comment_indentation is not None else 0\n", " sp_indent = re.sub(r\"\\[CI\\]\", \"\\n\" + \" \" * indentation, sp)\n", " split_out.append(sp_indent)\n", " else:\n", " split_out.append(sp)\n", + " if re.search(r\"\\*\\/\", sp):\n", + " comment_indentation = None\n", " s = \"\\n\".join(split_out)\n", " return s" ] diff --git a/nbs/99_additional_tests.ipynb b/nbs/99_additional_tests.ipynb index aec8e75..d9db9a0 100644 --- a/nbs/99_additional_tests.ipynb +++ b/nbs/99_additional_tests.ipynb @@ -139,6 +139,46 @@ ")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Multiline comment with an inline comment marker" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "SELECT 1\n", + "/*\n", + " --\n", + " */\n" + ] + } + ], + "source": [ + "assert_and_print(\n", + " format_sql(\"\"\"\n", + "select 1\n", + "/*\n", + "--\n", + "*/\n", + "\"\"\"),\n", + "\"\"\"\n", + "SELECT 1\n", + "/*\n", + " --\n", + " */\n", + "\"\"\".strip()\n", + ")" + ] + }, { "cell_type": "markdown", "metadata": {}, diff --git a/sql_formatter/core.py b/sql_formatter/core.py index ab3c3fb..7d9ce4d 100644 --- a/sql_formatter/core.py +++ b/sql_formatter/core.py @@ -421,13 +421,19 @@ def format_multiline_comments(s): "Format multiline comments by replacing multiline comment [CI] by newline and adding indentation" split_s = s.split("\n") split_out = [] + comment_indentation = None for sp in split_s: # loop on query lines + comment_start = re.search(r"\/\*", sp) + if comment_start: + comment_indentation = comment_start.start() + 3 if re.search(r"\[CI\]", sp): - indentation = re.search(r"\/\*", sp).start() + 3 + indentation = comment_indentation if comment_indentation is not None else 0 sp_indent = re.sub(r"\[CI\]", "\n" + " " * indentation, sp) split_out.append(sp_indent) else: split_out.append(sp) + if re.search(r"\*\/", sp): + comment_indentation = None s = "\n".join(split_out) return s @@ -482,4 +488,4 @@ def format_sql(s, semicolon=False, max_len=82): subquery_pos = extract_outer_subquery(s) # remove whitespace between word and parenthesis s = re.sub(r"\s*\)", ")", s) - return s \ No newline at end of file + return s