bryan kennedy
bryan kennedy

Reputation: 7209

Convert JS line comments to spaced block comments in IntelliJ IDEA

I'm working in IntelliJ IDEA cleaning up some Javascript code to match a code style standard.

My goal is to change this:

// A comment
// About some things
// That spans multiple lines

into this:

 /**
  * A comment
  * About some things
  * That spans multiple lines
  */

...without having to manually edit each and every comment block.

I know that IntelliJ has a Comment with Block Comment feature, but when I select a block and use that I can only get it to generate this:

/*A comment
About some things
That spans multiple lines*/

Does IntelliJ support the JSDoc style of comments?

Upvotes: 3

Views: 534

Answers (2)

Amin Ya
Amin Ya

Reputation: 1958

You can do this using Regex and programming. Here is my Julia function that does the trick both for multi-line comments and single-line comments:

function comment2jsdoc(text)

  # match multi-line comment
  firstline_m = match( r"(\/\/.*\n)(?:\/\/.*\n)+", text)
  if firstline_m !== nothing

    # add /** and */
    text = replace(text, r"(\/\/.*\n)+\/\/.*\n" => s"/** \n \0 */ \n")

    # replace // with *
    while match( r"((?:\/\/.*\n)+)\/\/(.*\n)", text) !== nothing
      text = replace(text, r"((?:\/\/.*\n)+)\/\/(.*\n)" => s"\1 * \2")
    end

    # replace first line
    firstline_cap = firstline_m.captures[1]
    text = replace(text,  firstline_cap => "* $(firstline_cap[3:end])")
  end

  # match single-line comment
  while match(r"\/\/(.*)\n(?!\/\/.*\n)", text) !== nothing
    text = replace(text, r"\/\/(.*)\n(?!\/\/.*\n)" => s"/** \1 */")
  end

  return text
end

For example:

text = """
// A comment
// About some things
// That spans multiple lines

// single line
"""

text = comment2jsdoc(text)
println(text)

will result in:

/**
 *  A comment
 *  About some things
 *  That spans multiple lines
 */

/**  single line */

You can also read/write the text from/to a file:

# read file:
text = Base.read("path/to/file", String)

text = comment2jsdoc(text)

# write file
Base.write("path/to/file", text)

Upvotes: 2

yole
yole

Reputation: 97288

There is no feature in IntelliJ IDEA that could automatically convert an existing sequence of end-of-line comments into a JSDoc comment. To perform such a conversion automatically, you can write a simple plugin, or just write a script that would perform the conversion when invoked from the command line.

Upvotes: 2

Related Questions