summaryrefslogtreecommitdiffstats
path: root/kspread/kspread_functions_text.cpp
blob: 5a8dccf69a5a9d6da80fce6198644f2f9e49226f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/* This file is part of the KDE project
   Copyright (C) 1998-2002 The KSpread Team
                           www.koffice.org/kspread
   Copyright (C) 2005 Tomas Mecir <mecirt@gmail.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/


// built-in text functions
// please keep it in alphabetical order

#include <tqregexp.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <math.h>

#include "functions.h"
#include "valuecalc.h"
#include "valueconverter.h"

using namespace KSpread;

// Functions DOLLAR and FIXED convert data to double, hence they will not
// support arbitrary precision, when it will be introduced.

// prototypes
Value func_char (valVector args, ValueCalc *calc, FuncExtra *);
Value func_clean (valVector args, ValueCalc *calc, FuncExtra *);
Value func_code (valVector args, ValueCalc *calc, FuncExtra *);
Value func_compare (valVector args, ValueCalc *calc, FuncExtra *);
Value func_concatenate (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dollar (valVector args, ValueCalc *calc, FuncExtra *);
Value func_exact (valVector args, ValueCalc *calc, FuncExtra *);
Value func_find (valVector args, ValueCalc *calc, FuncExtra *);
Value func_fixed (valVector args, ValueCalc *calc, FuncExtra *);
Value func_left (valVector args, ValueCalc *calc, FuncExtra *);
Value func_len (valVector args, ValueCalc *calc, FuncExtra *);
Value func_lower (valVector args, ValueCalc *calc, FuncExtra *);
Value func_mid (valVector args, ValueCalc *calc, FuncExtra *);
Value func_proper (valVector args, ValueCalc *calc, FuncExtra *);
Value func_regexp (valVector args, ValueCalc *calc, FuncExtra *);
Value func_regexpre (valVector args, ValueCalc *calc, FuncExtra *);
Value func_replace (valVector args, ValueCalc *calc, FuncExtra *);
Value func_rept (valVector args, ValueCalc *calc, FuncExtra *);
Value func_rot (valVector args, ValueCalc *calc, FuncExtra *);
Value func_right (valVector args, ValueCalc *calc, FuncExtra *);
Value func_search (valVector args, ValueCalc *calc, FuncExtra *);
Value func_sleek (valVector args, ValueCalc *calc, FuncExtra *);
Value func_substitute (valVector args, ValueCalc *calc, FuncExtra *);
Value func_t (valVector args, ValueCalc *calc, FuncExtra *);
Value func_text (valVector args, ValueCalc *calc, FuncExtra *);
Value func_toggle (valVector args, ValueCalc *calc, FuncExtra *);
Value func_trim (valVector args, ValueCalc *calc, FuncExtra *);
Value func_upper (valVector args, ValueCalc *calc, FuncExtra *);
Value func_value (valVector args, ValueCalc *calc, FuncExtra *);

// registers all text functions
void RegisterTextFunctions()
{
  FunctionRepository* repo = FunctionRepository::self();
  Function *f;

  // one-parameter functions
  f = new Function ("CHAR", func_char);
  repo->add (f);
  f = new Function ("CLEAN", func_clean);
  repo->add (f);
  f = new Function ("CODE", func_code);
  repo->add (f);
  f = new Function ("LEN", func_len);
  repo->add (f);
  f = new Function ("LOWER", func_lower);
  repo->add (f);
  f = new Function ("PROPER", func_proper);
  repo->add (f);
  f = new Function ("ROT", func_rot);
  repo->add (f);
  f = new Function ("SLEEK", func_sleek);
  repo->add (f);
  f = new Function ("T", func_t);
  repo->add (f);
  f = new Function ("TOGGLE", func_toggle);
  repo->add (f);
  f = new Function ("TRIM", func_trim);
  repo->add (f);
  f = new Function ("UPPER", func_upper);
  repo->add (f);
  f = new Function ("VALUE", func_value);
  repo->add (f);
  
  // other functions
  f = new Function ("COMPARE", func_compare);
  f->setParamCount (3);
  repo->add (f);
  f = new Function ("CONCATENATE", func_concatenate);
  f->setParamCount (1, -1);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DOLLAR", func_dollar);
  f->setParamCount (1, 2);
  repo->add (f);
  f = new Function ("EXACT", func_exact);
  f->setParamCount (2);
  repo->add (f);
  f = new Function ("FIND", func_find);
  f->setParamCount (2, 3);
  repo->add (f);
  f = new Function ("FIXED", func_fixed);
  f->setParamCount (1, 3);
  repo->add (f);
  f = new Function ("LEFT", func_left);
  f->setParamCount (2);
  repo->add (f);
  f = new Function ("MID", func_mid);
  f->setParamCount (2, 3);
  repo->add (f);
  f = new Function ("REGEXP", func_regexp);
  f->setParamCount (2, 4);
  repo->add (f);
  f = new Function ("REGEXPRE", func_regexpre);
  f->setParamCount (3);
  repo->add (f);
  f = new Function ("REPLACE", func_replace);
  f->setParamCount (4);
  repo->add (f);
  f = new Function ("REPT", func_rept);
  f->setParamCount (2);
  repo->add (f);
  f = new Function ("RIGHT", func_right);
  f->setParamCount (2);
  repo->add (f);
  f = new Function ("SEARCH", func_search);
  f->setParamCount (2, 3);
  repo->add (f);
  f = new Function ("SUBSTITUTE", func_substitute);
  f->setParamCount (3, 4);
  repo->add (f);
  f = new Function ("TEXT", func_text);
  f->setParamCount (1, 2);
  repo->add (f);
}


// Function: CHAR
Value func_char (valVector args, ValueCalc *calc, FuncExtra *)
{
  int val = calc->conv()->asInteger (args[0]).asInteger ();
  return Value (TQString (TQChar (val)));
}

// Function: CLEAN
Value func_clean (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str (calc->conv()->asString (args[0]).asString());
  TQString result;
  TQChar   c;
  int     i;
  int     l = str.length();
  
  for (i = 0; i < l; ++i)
  {
    c = str[i];
    if (c.isPrint())
      result += c;
  }
  
  return Value (result);
}

// Function: CODE
Value func_code (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str (calc->conv()->asString (args[0]).asString());
  if (str.length() <= 0)
     return Value::errorVALUE();

  return Value (str[0].unicode());
}

// Function: COMPARE
Value func_compare (valVector args, ValueCalc *calc, FuncExtra *)
{
  int  result = 0;
  bool exact = calc->conv()->asBoolean (args[2]).asBoolean();

  TQString s1 = calc->conv()->asString (args[0]).asString();
  TQString s2 = calc->conv()->asString (args[1]).asString();

  if (!exact)
    result = s1.lower().localeAwareCompare(s2.lower());
  else
    result = s1.localeAwareCompare(s2);

  if (result < 0)
    result = -1;
  else if (result > 0)
    result = 1;

  return Value (result);
}

void func_concatenate_helper (Value val, ValueCalc *calc,
    TQString& tmp)
{
  if (val.isArray()) {
    for (unsigned int row = 0; row < val.rows(); ++row)
      for (unsigned int col = 0; col < val.columns(); ++col)
        func_concatenate_helper (val.element (col, row), calc, tmp);
  } else
    tmp += calc->conv()->asString (val).asString();
}

// Function: CONCATENATE
Value func_concatenate (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString tmp;
  for (unsigned int i = 0; i < args.count(); ++i)
    func_concatenate_helper (args[i], calc, tmp);
  
  return Value (tmp);
}

// Function: DOLLAR
Value func_dollar (valVector args, ValueCalc *calc, FuncExtra *)
{
  // ValueConverter doesn't support money directly, hence we need to
  // use the locale. This code has the same effect as the output
  // of ValueFormatter for money format.
  
  // This function converts data to double/int, hence it won't support
  // larger precision.
  
  double value = calc->conv()->asFloat (args[0]).asFloat();
  int precision = 2;
  if (args.count() == 2)
    precision = calc->conv()->asInteger (args[1]).asInteger();

  // do round, because formatMoney doesn't
  value = floor (value * pow (10.0, precision) + 0.5) / pow (10.0, precision);
  
  TDELocale *locale = calc->conv()->locale();
  TQString s = locale->formatMoney (value, locale->currencySymbol(), precision);
  
  return Value (s);
}

// Function: EXACT
Value func_exact (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString s1 = calc->conv()->asString (args[0]).asString();
  TQString s2 = calc->conv()->asString (args[1]).asString();
  bool exact = (s1 == s2);
  return Value (exact);
}

// Function: FIND
Value func_find (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString find_text, within_text;
  int start_num = 1;

  find_text = calc->conv()->asString (args[0]).asString();
  within_text = calc->conv()->asString (args[1]).asString();
  if (args.count() == 3)
    start_num = calc->conv()->asInteger (args[2]).asInteger();

  // conforms to Excel behaviour
  if (start_num <= 0) return Value::errorVALUE();
  if (start_num > (int)within_text.length()) return Value::errorVALUE();

  int pos = within_text.find (find_text, start_num - 1);
  if( pos < 0 ) return Value::errorNA();

  return Value (pos + 1);
}

// Function: FIXED
Value func_fixed (valVector args, ValueCalc *calc, FuncExtra *)
{
  // uses double, hence won't support big precision

  int decimals = 2;
  bool no_commas = false;

  double number = calc->conv()->asFloat (args[0]).asFloat();
  if (args.count() > 1)
    decimals = calc->conv()->asInteger (args[1]).asInteger();
  if (args.count() == 3)
    no_commas = calc->conv()->asBoolean (args[2]).asBoolean();

  TQString result;
  TDELocale *locale = calc->conv()->locale();

  // unfortunately, we can't just use TDELocale::formatNumber because
  // * if decimals < 0, number is rounded
  // * if no_commas is true, thousand separators shouldn't show up

  if( decimals < 0 )
  {
    decimals = -decimals;
    number = floor( number/pow(10.0,decimals)+0.5 ) * pow(10.0,decimals);
    decimals = 0;
  }

  bool neg = number < 0;
  result = TQString::number( neg ? -number:number, 'f', decimals );

  int pos = result.find('.');
  if (pos == -1) pos = result.length();
    else result.replace(pos, 1, locale->decimalSymbol());
  if( !no_commas )
    while (0 < (pos -= 3))
      result.insert(pos, locale->thousandsSeparator());

  result.prepend( neg ? locale->negativeSign():
    locale->positiveSign() );

  return Value (result);
}

// Function: LEFT
Value func_left (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str = calc->conv()->asString (args[0]).asString();
  int nb = 1;
  if (args.count() == 2)
    nb = calc->conv()->asInteger (args[1]).asInteger();
  
  return Value (str.left (nb));
}

// Function: LEN
Value func_len (valVector args, ValueCalc *calc, FuncExtra *)
{
  int nb = calc->conv()->asString (args[0]).asString().length();
  return Value (nb);
}

// Function: LOWER
Value func_lower (valVector args, ValueCalc *calc, FuncExtra *)
{
  return Value (calc->conv()->asString (args[0]).asString().lower());
}

// Function: MID
Value func_mid (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str = calc->conv()->asString (args[0]).asString();
  int pos = calc->conv()->asInteger (args[1]).asInteger();
  uint len = 0xffffffff;
  if (args.count() == 3)
    len = (uint) calc->conv()->asInteger (args[2]).asInteger();
  
  // Excel compatible
  pos--;

  return Value (str.mid (pos, len));
}

// Function: PROPER
Value func_proper (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str = calc->conv()->asString (args[0]).asString().lower();
    
  TQChar f;
  bool  first = true;

  for (unsigned int i = 0; i < str.length(); ++i)
  {
    if (first)
    {
      f = str[i];
      if (f.isNumber())
        continue;

      f = f.upper();

      str[i] = f;
      first = false;

      continue;
    }

    if (str[i] == ' ' || str[i] == '-')
      first = true;
  }

  return Value (str);
}

// Function: REGEXP
Value func_regexp (valVector args, ValueCalc *calc, FuncExtra *)
{
  // ensure that we got a valid regular expression
  TQRegExp exp (calc->conv()->asString (args[1]).asString());
  if (!exp.isValid ())
    return Value::errorVALUE();
  
  TQString s = calc->conv()->asString (args[0]).asString();
  TQString defText;
  if (args.count() > 2)
    defText = calc->conv()->asString (args[2]).asString();
  int bkref = 0;
  if (args.count() == 4)
    bkref = calc->conv()->asInteger (args[3]).asInteger();
  if (bkref < 0)   // strange back-reference
    return Value::errorVALUE();

  TQString returnValue;
  
  int pos = exp.search (s);
  if (pos == -1)
    returnValue = defText;
  else
    returnValue = exp.cap (bkref);

  return Value (returnValue);
}

// Function: REGEXPRE
Value func_regexpre (valVector args, ValueCalc *calc, FuncExtra *)
{
  // ensure that we got a valid regular expression
  TQRegExp exp (calc->conv()->asString (args[1]).asString());
  if (!exp.isValid ())
    return Value::errorVALUE();
  
  TQString s = calc->conv()->asString (args[0]).asString();
  TQString str = calc->conv()->asString (args[2]).asString();

  int pos = 0;
  while ((pos = exp.search (s, pos)) != -1)
  {
    int i = exp.matchedLength();
    s = s.replace (pos, i, str);
    pos += str.length();
  }

  return Value (s);
}

// Function: REPLACE
Value func_replace (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString text = calc->conv()->asString (args[0]).asString();
  int pos = calc->conv()->asInteger (args[1]).asInteger();
  int len = calc->conv()->asInteger (args[2]).asInteger();
  TQString new_text = calc->conv()->asString (args[3]).asString();
  
  if (pos < 0) pos = 0;
  
  TQString result = text.replace (pos-1, len, new_text);
  return Value (result);
}

// Function: REPT
Value func_rept (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString s = calc->conv()->asString (args[0]).asString();
  int nb = calc->conv()->asInteger (args[1]).asInteger();
  
  TQString result;
  for (int i = 0; i < nb; i++) result += s;
  return Value (result);
}

// Function: RIGHT
Value func_right (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str = calc->conv()->asString (args[0]).asString();
  int nb = 1;
  if (args.count() == 2)
    nb = calc->conv()->asInteger (args[1]).asInteger();
  
  return Value (str.right (nb));
}

// Function: ROT
Value func_rot (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString text = calc->conv()->asString (args[0]).asString();

  for( unsigned i=0; i<text.length(); i++ )
  {
    unsigned c = text[i].upper().unicode();
    if( ( c >= 'A' ) && ( c <= 'M' ) )
      text[i] = TQChar( text[i].unicode() + 13);
    if( ( c >= 'N' ) && ( c <= 'Z' ) )
      text[i] = TQChar( text[i].unicode() - 13);
  }

  return Value (text);
}

// Function: SEARCH
Value func_search (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString find_text = calc->conv()->asString (args[0]).asString();
  TQString within_text = calc->conv()->asString (args[1]).asString();
  int start_num = 1;
  if (args.count() == 3)
    start_num = calc->conv()->asInteger (args[2]).asInteger();

  // conforms to Excel behaviour
  if (start_num <= 0) return Value::errorVALUE();
  if (start_num > (int)within_text.length()) return Value::errorVALUE();

  // use globbing feature of TQRegExp
  TQRegExp regex( find_text, false, true );
  int pos = within_text.find( regex, start_num-1 );
  if( pos < 0 ) return Value::errorNA();

  return Value (pos + 1);
}

// Function: SLEEK
Value func_sleek (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str = calc->conv()->asString (args[0]).asString();
  TQString result;
  TQChar   c;
  int     i;
  int     l = str.length();

  for (i = 0; i < l; ++i)
  {
    c = str[i];
    if (!c.isSpace())
      result += c;
  }

  return Value (result);
}

// Function: SUBSTITUTE
Value func_substitute (valVector args, ValueCalc *calc, FuncExtra *)
{
  int num = 1;
  bool all = true;

  if (args.count() == 4)
  {
    num = calc->conv()->asInteger (args[3]).asInteger();
    all = false;
  }
  
  TQString text = calc->conv()->asString (args[0]).asString();
  TQString old_text = calc->conv()->asString (args[1]).asString();
  TQString new_text = calc->conv()->asString (args[2]).asString();

  if( num <= 0 ) return Value::errorVALUE();
  if (old_text.length() == 0) return Value (text);

  TQString result = text;

  int p = result.find (old_text);
  while ((p != -1) && (num > 0))
  {
    result.replace( p, old_text.length(), new_text );
    // find another location, starting straight after the replaced text
    p = result.find (old_text, p + new_text.length());
    if( !all ) num--;
  }

  return Value (result);
}

// Function: T
Value func_t (valVector args, ValueCalc *calc, FuncExtra *)
{
  return calc->conv()->asString (args[0]);
}

// Function: TEXT
Value func_text (valVector args, ValueCalc *calc, FuncExtra *)
{
  //Currently the same as the T function ...
  //Second parameter is format_text. It is currently ignored.
  return calc->conv()->asString (args[0]);
}

// Function: TOGGLE
Value func_toggle (valVector args, ValueCalc *calc, FuncExtra *)
{
  TQString str = calc->conv()->asString (args[0]).asString();
  int i;
  int l = str.length();

  for (i = 0; i < l; ++i)
  {
    TQChar c = str[i];
    TQChar lc = c.lower();
    TQChar uc = c.upper();

    if (c == lc) // it is in lowercase
      str[i] = c.upper();
    else if (c == uc) // it is in uppercase
      str[i] = c.lower();
  }

  return Value (str);
}

// Function: TRIM
Value func_trim (valVector args, ValueCalc *calc, FuncExtra *)
{
  return Value (
      calc->conv()->asString (args[0]).asString().simplifyWhiteSpace());
}

// Function: UPPER
Value func_upper (valVector args, ValueCalc *calc, FuncExtra *)
{
  return Value (calc->conv()->asString (args[0]).asString().upper());
}

// Function: VALUE
Value func_value (valVector args, ValueCalc *calc, FuncExtra *)
{
  // same as the N function
  return calc->conv()->asFloat (args[0]);
}