Advertisement
rplantiko

Align text lines along occurrences of a pattern

Jul 13th, 2015
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Align selected text lines along occurrences of a given pattern or substring
  2. // During the alignment process, all the pattern occurrences will be deleted
  3.  
  4. /* global  UltraEdit, selectedLines, lineEnd */
  5.  
  6. /* eslint no-shadow:0 */
  7.  
  8. var alignAt        = UltraEdit.getString("Align at pattern (e.g. \\t)",1)
  9. var alignAtPattern = new RegExp( alignAt )
  10.  
  11. // Cut array "selectedLines" into clipboard,
  12. // determine "lineEnd" byte sequence of this document:
  13. // include cutSelection.js
  14.  
  15. var cells = selectedLines.map( function(line) { return line.split(alignAtPattern) } )
  16.  
  17. var colwidths = cells.reduce( function( widths, row ) {
  18.   row.forEach( function(cell,i) {
  19.     if (widths.length < i+1) widths.push(0)
  20.     widths[i] = Math.max(widths[i],cell.length)
  21.     })
  22.   return widths
  23.   }, [])
  24.  
  25. var resultLines = cells.map(
  26.   pad_to( colwidths )
  27.   )
  28.  
  29. // Output - and done
  30. UltraEdit.activeDocument.write( resultLines.join(lineEnd) )
  31.  
  32. //-----------------------------------------------------------------------------------
  33.  
  34.  function pad_to( colwidths ) {
  35.   var spaces = new Array( Math.max.apply(null,colwidths)+1).join(' ')  
  36.   return function( row ) {
  37.     return row.map( function(cell,i){
  38.       return cell+spaces.substr(0,colwidths[i]-cell.length)
  39.       }).join(' ')
  40.     }
  41.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement