Advertisement
RemcoE33

Richtext

May 19th, 2022
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * Returns definition, example and synonym
  3. * 0 = nothing | 1 = Bold | 2 = Italic | 3 = Underline | 4 = Strikethrough
  4. * Example: =RICHTEXT(,"RemcoE33", 1, " made this", 2)
  5. *
  6. * @param {"RemcoE33", 1, " made this", 2} args
  7. * @return {string} Ritchtext string.
  8. * @customfunction
  9. */
  10. function RICHTEXT(...args){
  11.   if(args.length % 2 != 0){
  12.     throw new Error('You probably forgot an formatting option')
  13.   }
  14.   return args.join("|");
  15. }
  16.  
  17. function setRichText_(args, e) {
  18.   const string = args.reduce((acc, curr, i) => {
  19.     if (i % 2 == 0){
  20.       acc += curr
  21.     }
  22.     return acc
  23.   },"");
  24.  
  25.   console.log(string)
  26.  
  27.   let richText = SpreadsheetApp.newRichTextValue()
  28.     .setText(string)
  29.  
  30.   for(let i = 0; i < args.length; i += 2){
  31.     const str = args[i]
  32.     const type = args[i + 1]
  33.     const start = string.indexOf(str)
  34.     const end = start + str.length
  35.     console.log(str, type, start, end)
  36.     switch (type) {
  37.       case '1':
  38.         const bold = SpreadsheetApp.newTextStyle().setBold(true).build()
  39.         richText.setTextStyle(start, end, bold)
  40.         break;
  41.       case '2':
  42.         const italic = SpreadsheetApp.newTextStyle().setItalic(true).build()
  43.         richText.setTextStyle(start, end, italic)
  44.       break;
  45.       case '3':
  46.         const underline = SpreadsheetApp.newTextStyle().setUnderline(true).build()
  47.         richText.setTextStyle(start, end, underline)
  48.       break;
  49.       case '4':
  50.         const strike = SpreadsheetApp.newTextStyle().setStrikethrough(true).build()
  51.         richText.setTextStyle(start, end, strike)
  52.       break;
  53.     }
  54.   };
  55.  
  56.   e.range.setRichTextValue(richText.build())
  57. }
  58.  
  59. function onEdit(e){
  60.   const range = e.range;
  61.   const formula = range.getFormula()
  62.   const value = range.getValue()
  63.   if(formula.match(/=richtext/gmi) && value != '#ERROR!'){
  64.     const values = value.split("|")
  65.     console.log(values)
  66.     setRichText_(values, e)
  67.   }
  68. }
  69.  
  70.  
  71.  
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement