Action

insert.js function()

Posted by RoyRogers, Last update over 4 years ago

Save script to iCloud Drive /Library/Scripts/
as insert.js
And reuse in other scripts with statement:
require('insert.js')

Library function, not to be run on its own!

Steps

  • script (disabled)

    // insert.js
    // RV 2020-03-10 at 18:51
    
    // Save to iCloud Drive '/Library/Scripts/insert.js'
    // And reuse in other scripts with statement:
    // require('insert.js')
    // Uses two spaces for indentation!
    
    function insert(code, move, len) {
      // Smart indent block
      let range = editor.getSelectedRange();
      let lnRange = editor.getSelectedLineRange();
      let before = editor.getTextInRange(lnRange[0], range[0] - lnRange[0]);
      indent = ' '.repeat(before.length);
      
      // no selection
      let lines = code.split('\n');
      let newLines = [];
      let prefix = '';
      
      
      if (before.match(/\S/)) prefix = '\n' + indent;
      m = before.match(/([ \t]*)\}/)
      if (m) {
      	  indent = m[1];
        prefix = '';
      }
      if (len == 0) move += indent.length;
      newLines.push(prefix + [lines[0]]); // First line
      for (line of lines.slice(1)) {
        newLines.push(indent + line);
      }
      editor.setSelectedText(newLines.join('\n'));
      editor.setSelectedRange(range[0] + move + prefix.length, len);  
    }
      
    

Options

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