I managed to make some slight progress. Need to fix the regexes capturing ,;)
, even though I have tried to tell them not to, trim some white spaces and extract some functionality into functions (my limited coffeescript knowledge didn’t include how to build a function). The implementation below produces the result further below.
atom.commands.add 'atom-text-editor', 'custom:docstring', ->
editor = atom.workspace.getActiveTextEditor()
editor.selectLinesContainingCursors()
text = editor.getSelectedText()
editor.moveUp()
text = text.replace /function /, ""
kwarg_split = text.split ";" # kwargs come after a ;
if kwarg_split.length == 1 # Didn't find kwargs
# editor.insertText("if -- no kwargs")
kwargs = ""
args = text.match( / *([\w\s\:=]+?)[;,\)]/g ) # Match the first paren (, then match everything that ends with either of , ; )
if args == null # Found no args either
arg_text = ""
else
arg_text = "\# Arguments\n"
for arg in args
arg_text = "#{arg_text}- `#{arg}` \n"
kwarg_text = ""
else
# editor.insertText("else -- found kwargs")
arg_text = kwarg_split[0]
args = arg_text.match( / *([\w\s\:=]+?)[;,\)]/g )
if args == null # Found no args
arg_text = ""
else
arg_text = "\# Arguments\n"
for arg in args
arg_text = "#{arg_text}- `#{arg}` \n"
kwarg_text = kwarg_split[1]
kwargs = kwarg_text.match( / *([\w\s\:=]+)[;,\)]/g )
kwarg_text = "\n\# Keyword Arguments\n"
for arg in kwargs
kwarg_text = "#{kwarg_text}- `#{arg}` \n"
# editor.insertText(name)
docstring = "\"\"\"\n #{text}\n#{arg_text}#{kwarg_text}\n\"\"\""
editor.insertText(docstring)
editor.moveUp(2)
editor.moveToBeginningOfLine()
Result
"""
long(mandatory, optional=3, typerestricted::Int = 3; kwarg = 5)
# Arguments
- `mandatory,`
- ` optional=3,`
# Keyword Arguments
- ` kwarg = 5)`
"""
function long(mandatory, optional=3, typerestricted::Int = 3; kwarg = 5)
end
"""
short(a)
# Arguments
- `a)`
"""
function short(a)
end
"""
noargs()
"""
function noargs()
end
"""
typeannotated()::Int
"""
function typeannotated()::Int
1
end
"""
wherefun(a::T) where T
# Arguments
- `a::T)`
"""
function wherefun(a::T) where T
end
"""
long1(mandatory, optional=3, typerestricted::Int = 3; kwarg = 5) = "Hej"
# Arguments
- `mandatory,`
- ` optional=3,`
# Keyword Arguments
- ` kwarg = 5)`
"""
long1(mandatory, optional=3, typerestricted::Int = 3; kwarg = 5) = "Hej"