Error newText.replace is not a function (in a command)


#1

Thanks to this answer I wrote this command which replaces the double blank lines by a single one.

But it triggers: TypeError: newText.replace is not a function

atom.commands.add 'atom-text-editor', 'custom:double-blank-line', ->
  editor = atom.workspace.getActiveTextEditor()
  regMatch=/^(\s*\n){2,}/  #regex must be enclosed /btw/
  regReplace=/\n/
  editor.scan(regMatch, (match) -> match.replace(regReplace))
  alert('done!')

ps: To run it from the context menu, I also added

atom.contextMenu.add {
    "atom-text-editor": [{
      label: "test"
      submenu: [
        {label: 'remove double blank line'
        command:'custom:double-blank-line'}
      ]
    }]
  }

#2

Should the argument to replace() be a string rather than a regex?

  newStr='\n'
  editor.scan(regMatch, (match) -> match.replace(newStr))

#3

Thanks for your reply rsese! I tried your code, it doesn’t give an error! (Thanks a lot !), but it doesn’t replace the double blank line within the selection, any idea why?

the new code:

atom.commands.add 'atom-text-editor', 'custom:double-blank-line', ->
  editor = atom.workspace.getActiveTextEditor()
  regMatch='^(\s*\n){2,}' 
  regReplace='\n'
  editor.scan(regMatch, (match) -> match.replace(regReplace))
  alert('done!')

#4

Here is the full code explained (answered here):

It should be in the init.coffee

atom.commands.add 'atom-text-editor', 'custom:double-blank-line', ->
  editor = atom.workspace.getActiveTextEditor().getBuffer()
  regMatch=/^(?:\s*\n){2,}/g  
  # it's a regex, so it must be enclosed /btw/  
  # Without the g flag, it'll only test for the first.)
  regReplace='\n' 
  editor.backwardsScan(regMatch, (match) -> match.replace(regReplace))

# this add the label to the context menu:
atom.contextMenu.add {
    "atom-text-editor": [{
      label: "● test"
      submenu: [
        {label: 'remove double blank line'
        command:'custom:double-blank-line'}
        # just another label as an example
        {label: 'Redo', command:'core:redo'} ]
    }]
  }