/*
##      ##  #######   ########   ########        ##      ## ########      ###     ########   
##  ##  ## ##     ##  ##     ##  ##     ##       ##  ##  ## ##     ##    ## ##    ##     ##  
##  ##  ## ##     ##  ##     ##  ##     ##       ##  ##  ## ##     ##   ##   ##   ##     ##  
##  ##  ## ##     ##  ########   ##     ##       ##  ##  ## ########   ##     ##  ########   
##  ##  ## ##     ##  ##   ##    ##     ##       ##  ##  ## ##   ##    #########  ##         
##  ##  ## ##     ##  ##    ##   ##     ##       ##  ##  ## ##    ##   ##     ##  ##         
 ###  ###   #######   ##     ##  ########         ###  ###  ##     ##  ##     ##  ##         

Version: 2.0

Release date: June 7th 2014

Author: Josip

Description: 
Hard break the text at predefined column position. The default is column 75 but you can change that in the plugin file (variable WORD_WRAP_AT at the top of the file).

Instalation:
Unzip the "Word wrap" directory into the plugins directory.

Deployment:
Hit Ctrl+E,B to copy wrapped text. If nothing is selected the whole text is used.
*/



var WORD_WRAP_AT = 75;
var SHORTCUT_KEY = "B"; // use ctrl+E,B
var NOTICE_S = "Copy wrapped at ";



/*
########   ##    ##   ########   ########   ##    ##   
##         ###   ##      ##      ##     ##   ##  ##    
##         ####  ##      ##      ##     ##    ####     
######     ## ## ##      ##      ########      ##      
##         ##  ####      ##      ##   ##       ##      
##         ##   ###      ##      ##    ##      ##      
########   ##    ##      ##      ##     ##     ##      
*/
monkey.add_extendedShortcutFiredE(function(object, eventargs) {
  if (eventargs.extendedKey == SHORTCUT_KEY) {
    copyWrapped((monkey.selectionLength <= 0) ? monkey.text : monkey.selectedText);
  }
});


function copyWrapped(t) {
  var wraped = wordwrap(t, WORD_WRAP_AT, "\n", true);
  System.Windows.Forms.Clipboard.SetText(wraped);
  monkey.showNotice(NOTICE_S + WORD_WRAP_AT.toString(), true, false);
}


function wordwrap(str, int_width, str_break, cut) {
  var m = ((arguments.length >= 2) ? arguments[1] : 60);
  var b = ((arguments.length >= 3) ? arguments[2] : "\n");
  var c = ((arguments.length >= 4) ? arguments[3] : false);

  var i, j, l, s, r;

  str += '';

  if (m < 1) {
    return str;
  }

  for (i = -1, l = (r = str.split(/\r\n|\n|\r/)).length; ++i < l; r[i] += s) {
    for (s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")) {
      j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    }
  }
  return trimBlanks(r.join("\n"));
}



function trimBlanks(str) {
  return str.replace(/^ +| +$/mg, "");
}