Action

JS Comment

Posted by RoyRogers, Last update about 4 years ago

Toggles comments of single or multiple lines.
Sets tags at original indenting.
Does not comment blank lines.

Note! Will not comment lines on higher blocks (less indented than first selected line)!
Will not work well with mixed indenting (mix of spaces and tabs)

Steps

  • script

    // JS Comments
    // 2020-03-10 at 17:06 EST
    
    // Togle JS comments and keep original indents
    // Note! Does not comment blank lines!
    
    let tag = "// " // set to prefered tag
    let lnRange = editor.getSelectedLineRange();
    let text = editor.getTextInRange(lnRange[0],lnRange[1]);
    let selRange = editor.getSelectedRange();
    let offset = 0;
    let newText = '';
    let pos = selRange[0] - lnRange[0];
    let len = text.length;
    let sel = selRange[1]
    let selPos = selRange[0];
    let selLen = selRange[1];
    
    main: {
      let re = new RegExp('^[ \t]*' + tag, '');
    
      // Check if first line already has tag:
      if (text.match(re)) {
        // Removing comment tags:
        let re = new RegExp('^([ \t]*)' + tag, 'gm');
        newText = text.replace(re, '$1')
        selLen = text.length;
        selPos = lnRange[0];
        offset = 0;
        if (len = 3) offset = -pos ; 
        if (sel > 0) sel = newText.length;
      } else if (sel == 0 && !text.match(/\S/)) {
        // blank line
        newText = tag;
        offset = 3;
      } else if (sel == 0) {
        // Text unselected, cursor at left margin:
        // alert(text);
        newText = text.replace(/^([ \t]*)(.*)/, '$1// $2')
        selPos = lnRange[0];
        selLen = text.length;
      } else {
        // Text selected:
        m = text.match(/^([ \t]+)/);
        if (m) {
          let indent = m[1];
          let re = new RegExp('^' + indent, 'gm');
          newText = text.replace(re, indent + tag);
        } else {
          let re = new RegExp('^(.+)', 'gm');
          newText = text.replace(re, '// $1');
        }
        
        // newText = text.replace(/^([ \t]*)(\S.*)$/gm, '$1// $2')
        selPos = lnRange[0];
        selLen = text.length;
        sel = newText.length;
      }
    
      // update text and set new selection:
      editor.setTextInRange(selPos, selLen, newText);
      editor.setSelectedRange(selRange[0] + offset, sel);
    
    }
    
    

Options

  • After Success Nothing
    Notification Error
    Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.