File: utils.c

package info (click to toggle)
latex2rtf 2.3.18a-3
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye
  • size: 9,384 kB
  • sloc: ansic: 20,424; makefile: 660; sh: 478; perl: 22
file content (788 lines) | stat: -rwxr-xr-x 21,810 bytes parent folder | download | duplicates (5)
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

/*
 * utils.c - handy routines
 * 
 * Copyright (C) 1995-2002 The Free Software Foundation
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 * 
 * This program 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 General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * 
 * This file is available from http://sourceforge.net/projects/latex2rtf/
 * 
 * Authors: 1995-1997 Ralf Schlatterbeck 1998-2000 Georg Lehner 2001-2002 Scott
 * Prahl
 */
#if defined(NOSTDERR)
#define ERROUT stdout
#else
#define ERROUT stderr
#endif 

#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#ifdef UNIX
# include <sys/types.h>
# include <sys/stat.h>
# include <unistd.h>
#else
# include <stdio.h>
#endif

#include "cfg.h"
#include "main.h"
#include "utils.h"
#include "parser.h"

/******************************************************************************
 purpose:  returns true if n is odd
******************************************************************************/
int odd(long n)
{
    return (int) (n & 1);
}

/******************************************************************************
 purpose:  returns true if n is even
******************************************************************************/
int even(long n)
{
    return (int) (!(n & 1));
}

/******************************************************************************
 purpose:  rounds to nearest integer. round() in math.h is not always present
 *****************************************************************************/
double my_rint(double nr)
{
  double f = floor(nr);
  double c = ceil(nr);
  return (((c-nr) >= (nr-f)) ? f :c);
}

/******************************************************************************
 purpose: this works with overlapping pointers ... the C standard says that
   strcpy can do anything it likes for this case (which it happens to
   do under Fedora 
******************************************************************************/
char *my_strcpy(char *dest, const char *src)
{
   char *save = dest;
   while ( (*dest++ = *src++) );
   return save;
} 


/******************************************************************************
 purpose:  count the number of occurences of the string t in the string s
******************************************************************************/
int strstr_count(const char *s, char *t)
{
    int n = 0;
    size_t len;
    char *p;

    if (t == NULL || s == NULL)
        return n;

    len = strlen(t);
    p = strstr(s, t);

    while (p) {
        n++;
        p = strstr(p + len - 1, t);
    }

    return n;
}

/******************************************************************************
 purpose:  returns a new string having n characters from src terminated with
           '\0' at the end.  (so the length is n+1)
******************************************************************************/
char *my_strndup(const char *src, size_t n)
{
    char *dst;

    dst = (char *) calloc(n + 1, sizeof(char));
    if (dst == NULL)
        return NULL;

    strncpy(dst, src, n);

    return dst;
}

/******************************************************************************
 purpose:  returns a new string consisting of s+t
******************************************************************************/
char *strdup_together(const char *s, const char *t)
{
    char *both;
    size_t siz;
    
    if (s == NULL) {
        if (t == NULL)
            return NULL;
        return strdup(t);
    }
    if (t == NULL)
        return strdup(s);

    if (0) diagnostics(1, "'%s' + '%s'", s, t);
    siz = strlen(s) + strlen(t) + 1;
    both = (char *) malloc(siz);

    if (both == NULL)
        diagnostics(ERROR, "Could not allocate memory for both strings.");

    my_strlcpy(both, s, siz);
    my_strlcat(both, t, siz);

    return both;
}

/******************************************************************************
 purpose:  returns a new string consisting of s+t+u
******************************************************************************/
char *strdup_together3(const char *s, const char *t, const char *u)
{
    char *two, *three;
    two = strdup_together(s,t);
    three = strdup_together(two,u);
    free(two);
    return three;
}

/******************************************************************************
 purpose:  returns a new string consisting of s+t+u+v
******************************************************************************/
char *strdup_together4(const char *s, const char *t, const char *u, const char *v)
{
    char *four, *three;
    three = strdup_together3(s,t,u);
    four = strdup_together(three,v);
    free(three);
    return four;
}

/******************************************************************************
 purpose:  duplicates a string but removes TeX  %comment\n
******************************************************************************/
char *strdup_nocomments(const char *s)
{
    char *p, *duplicate;

    if (s == NULL)
        return NULL;

    duplicate = (char *) malloc(strlen(s) + 1);
    p = duplicate;

    while (*s) {
        while (*s == '%') {     /* remove comment */
            s++;                /* one char past % */
            while (*s && *s != '\n')
                s++;            /* find end of line */
            if (*s == '\0')
                goto done;
            s++;                /* first char after comment */
        }
        *p = *s;
        p++;
        s++;
    }
  done:
    *p = '\0';
    return duplicate;
}

/******************************************************************************
 purpose:  duplicates a string without including spaces or newlines
******************************************************************************/
char *strdup_noblanks(const char *s)
{
    char *p, *duplicate;

    if (s == NULL)
        return NULL;
    while (*s == ' ' || *s == '\n')
        s++;                    /* skip to non blank */
    duplicate = (char *) malloc(strlen(s) + 1);
    p = duplicate;
    while (*s) {
        *p = *s;
        if (*p != ' ' && *p != '\n')
            p++;                /* increment if non-blank */
        s++;
    }
    *p = '\0';
    return duplicate;
}

/*************************************************************************
purpose: duplicate text with only a..z A..Z 0..9 and _
**************************************************************************/
char *strdup_nobadchars(const char *text)
{
    char *duplicate, *s;

    duplicate = strdup_noblanks(text);
    s = duplicate;

    while (*s) {
        if (!('a' <= *s && *s <= 'z') && !('A' <= *s && *s <= 'Z') && !('0' <= *s && *s <= '9'))
            *s = '_';
        s++;
    }

    return duplicate;
}

/******************************************************************************
 purpose:  duplicates a string without newlines and CR replaced by '\n' or '\r'
******************************************************************************/
char *strdup_printable(const char *s)
{
    char *duplicate;
    int i;
    
    if (s == NULL) return NULL;

    duplicate = (char *) malloc(2*strlen(s));

    i=0;
    while (*s) {
        if (*s=='\r') {
            duplicate[i++]='\\';
            duplicate[i++]='r';
         } else if (*s=='\n') {
            duplicate[i++]='\\';
            duplicate[i++]='n';
         } else if (*s=='\t') {
            duplicate[i++]='\\';
            duplicate[i++]='t';
         } else 
            duplicate[i++]=*s;
         s++;
    }
    duplicate[i]='\0';
        
    return duplicate;
}

/******************************************************************************
 purpose:  duplicates a string without newlines and CR replaced by '\n' or '\r'
******************************************************************************/
void strncpy_printable(char* dst, char *src, int n)
{
    int i=0;
    
    if (dst == NULL)
        return;

    while (i<n-1 && *src) {

        if (*src=='\r') {
            dst[i++]='\\';
            dst[i++]='r';
         } else if (*src=='\n') {
            dst[i++]='\\';
            dst[i++]='n';
         } else if (*src=='\t') {
            dst[i++]='\\';
            dst[i++]='t';
         } else 
            dst[i++]=*src;
         src++;
    }
    
    dst[i]='\0';
}

/******************************************************************************
 purpose:  duplicates a string without spaces or newlines at front or end
******************************************************************************/
char *strdup_noendblanks(const char *s)
{
    char *p, *t;

    if (s == NULL)
        return NULL;
    if (*s == '\0')
        return strdup("");

    /* find pointer to first non-space character in string */
    t = (char *) s;
    while (*t == ' ' || *t == '\n')
        t++;                    /* first non blank char */

    /* find pointer to last non-space character in string */
    p = (char *) s + strlen(s) - 1;
    while (p >= t && (*p == ' ' || *p == '\n'))
        p--;                    /* last non blank char */

    if (t > p)
        return strdup("");
    return my_strndup(t, (size_t) (p - t + 1));
}

/******************************************************************************
 purpose:  replaces all occurences of target in s with blanks
******************************************************************************/
void str_blank_out(char *s, const char *target)
{
    char *p;
    int i, n;

    if (s == NULL || target == NULL || *target == '\0')
        return;
    
    n = strlen(target);
    p = strstr(s,target);
    while (p) {
        for (i=0; i<n; i++) 
            p[i] = ' ';
        p = strstr(p+n,target);
    }
}

/******************************************************************************
 purpose:  deletes all occurences of target in s
******************************************************************************/
void str_delete(char *s, const char *target)
{
    char *p;
    int n;
    if (s == NULL || target == NULL || *target == '\0') return;   
    
    n = strlen(target);
    p = s;
    while ((p = strstr(p,target))) 
        p = my_strcpy(p,p+n);
}

/******************************************************************************
  purpose: return a copy of tag from \label{tag} in the string text
 ******************************************************************************/
char *ExtractLabelTag(const char *text)
{
    char *s, *label_with_spaces, *label;

    s = strstr(text, "\\label{");
    if (!s)
        s = strstr(text, "\\label ");
    if (!s)
        return NULL;

    s += strlen("\\label");
    PushSource(NULL, s);
    label_with_spaces = getBraceParam();
    PopSource();
    label = strdup_nobadchars(label_with_spaces);
    free(label_with_spaces);

    diagnostics(4, "LabelTag = <%s>", (label) ? label : "missing");
    return label;
}

/**************************************************************************
 purpose: provide functionality of getBraceParam() for strings
 
        if s contains "aaa {stuff}cdef", then  
            parameter = getStringBraceParam(&s)
            
          gives
            parameter = "stuff"
            s="cdef"

     \alpha\beta   --->  "\beta"             \bar \alpha   --->  "\alpha"
           ^                                     ^
     \bar{text}    --->  "text"              \bar text     --->  "t"
         ^                                       ^
    _\alpha        ---> "\alpha"             _{\alpha}     ---> "\alpha"
     ^                                        ^
    _2             ---> "2"                  _{2}          ---> "2"
     ^                                        ^
 ******************************************************************************/
char *getStringBraceParam(char **s)

{
    char *p_start, *p, *parameter, last;
    int braces;
    
    if (*s == NULL) return strdup("");
    
    /* skip white space ... and one possible newline*/
    while (**s == ' ') (*s)++;
    if (**s == '\n') {
        while (**s == ' ') (*s)++;
    }
    
    p_start = *s;

    /* return simple command like \alpha */
    if (**s == '\\') {
        do { (*s)++; } while (isalpha(**s));
    diagnostics(1,"getstringbraceparam \\ before='%s'", *s);
        return my_strndup(p_start,(*s)-p_start);
    }
    
    /* no brace ... advance one and return next character */
    if (**s != '{' ) {
        (*s)++; 
        return my_strndup(p_start,1);
     }
    
    /* usual case, return contents between braces */
    p_start++;
    p=p_start;  
    last = '\0';
    braces = 1;
    while (*p != '\0' && braces > 0) {
        if (*p == '{' && last != '\\')
            braces++;
        if (*p == '}' && last != '\\')
            braces--;
        last = *p;
        p++;
    }
    
    parameter = my_strndup(p_start, p-p_start-1);
    *s = p;

    diagnostics(6,"Extract parameter=<%s> after=<%s>", parameter, *s); 
    
    return parameter;
    
}


/******************************************************************************
  purpose: remove 'tag{contents}' from text and return contents
           note that tag should typically be "\\caption"
 ******************************************************************************/
char *ExtractAndRemoveTag(char *tag, char *text)
{
    char *s, *contents, *start=NULL;

    if (text==NULL || *text=='\0') return NULL;
    
    s = text;
    diagnostics(5, "target tag = <%s>", tag);
    diagnostics(5, "original text = <%s>", text);

    while (s) {                 /* find start of caption */
        start = strstr(s, tag);
        if (!start)
            return NULL;
        s = start + strlen(tag);
        if (*s == ' ' || *s == '{')
            break;
    }

    contents = getStringBraceParam(&s);
    if (contents == NULL) return NULL;
    
    /* erase "tag{contents}" */
    do
        *start++ = *s++;
    while (*s);               
    *start = '\0';

    diagnostics(5, "final contents = <%s>", contents);
    diagnostics(5, "final text = <%s>", text);

    return contents;
}

/* this extracts a comma-delimited, key-value pair from the string s
   the string is untouched, and the return value from the function is
   a pointer to the next character in the string to be parsed to get
   the next pair.
   
   EXAMPLE: s= "  option=param,singleoptionname,opt2=crazy"
   first  iteration return="singleoptionname,opt2=crazy", key="option", value="param"
   second iteration return="opt2=crazy", key="singleoptionname", value=NULL
   third  iteration return=NULL, key="opt2", value="crazy"
*/  
   
char * keyvalue_pair(char *s, char **key, char **value)
{
    char *k, *v;    
    *key = NULL;
    *value = NULL;
    if (s==NULL) return NULL;
        
    /* skip any blanks at start */
    while (*s == ' ') s++;

    if (*s=='\0') return NULL;  /*possibly all blanks*/
    
    /* find the end of the key */
    k = s;
    while (*k != '=' && *k != ',' && *k != '\0') 
        k++;
        
    /* allocate and copy string into the key */
    *key = my_strndup(s, k-s);
    
    if (*k == '\0') return NULL;
    
    if (*k == ',') return k+1;
    
    /* '=' found, now parse value */
    s = k+1;
    
    /* skip any blanks at start */
    while (*s == ' ') s++;
    
    /* find the end of the value */
    v = s;
    while (*v != ',' && *v != '\0') {
        if (*v == '{')
        while (*(++v) != '}')
            ;
        else
        v++;
    }
    /* allocate and copy this into the value */
    *value = my_strndup(s, v-s);
    
    if (*v == '\0') return NULL;
    return v+1;
}

int getStringDimension(char *s)
{
    int size = 0;
    
    if (s != NULL) {
        PushSource(NULL, s);
        size = getDimension();
        PopSource();
    }
    
    diagnostics(5, "getStringDimension fore '%s' is %d twips", s, size);
    return size;
}

void show_string(int level, const char *s, const char *label)
{
    int width=100;
    long i;
    char c;
    long len;
    
    if (g_verbosity_level<level) return;
        
    if (s == NULL) {
        diagnostics(WARNING, "\n%s: NULL",label);
        return;
    }
        
    len = strlen(s);
    fprintf(ERROUT, "\n%s: ", label);

    for (i=0; i<len; i++) {
    
        if (i==width)
            fprintf(ERROUT, "\n%-*d: ", (int) strlen(label), (int) strlen(s));
        else if (i>1 && i % width == 0) 
            fprintf(ERROUT, "\n%s: ",label);
        c = s[i];
        if (c == '\n') c = '=';
        if (c == '\0') c = '*';
        fprintf(ERROUT,"%c",c);
    }
}

/* these next two routines fall under the copyright banner below.  The
names of the routines have had 'my_' prepended to avoid conflicting
with existing versions in string.h  */

/*
 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Copy src to string dst of size siz.  At most siz-1 characters
 * will be copied.  Always NUL terminates (unless siz == 0).
 * Returns strlen(src); if retval >= siz, truncation occurred.
 */
size_t
my_strlcpy(char *dst, const char *src, size_t siz)
{
        char *d = dst;
        const char *s = src;
        size_t n = siz;

        /* Copy as many bytes as will fit */
        if (n != 0) {
                while (--n != 0) {
                        if ((*d++ = *s++) == '\0')
                                break;
                }
        }

        /* Not enough room in dst, add NUL and traverse rest of src */
        if (n == 0) {
                if (siz != 0)
                        *d = '\0';                /* NUL-terminate dst */
                while (*s++)
                        ;
        }

        return(s - src - 1);        /* count does not include NUL */
}

/*
 * Appends src to string dst of size siz (unlike strncat, siz is the
 * full size of dst, not space left).  At most siz-1 characters
 * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
 * Returns strlen(src) + MIN(siz, strlen(initial dst)).
 * If retval >= siz, truncation occurred.
 */
size_t
my_strlcat(char *dst, const char *src, size_t siz)
{
        char *d = dst;
        const char *s = src;
        size_t n = siz;
        size_t dlen;

        /* Find the end of dst and adjust bytes left but don't go past end */
        while (n-- != 0 && *d != '\0')
                d++;
        dlen = d - dst;
        n = siz - dlen;

        if (n == 0)
                return(dlen + strlen(s));
        while (*s != '\0') {
                if (n != 1) {
                        *d++ = *s;
                        n--;
                }
                s++;
        }
        *d = '\0';

        return(dlen + (s - src));        /* count does not include NUL */
}


/*
 * handy litte portable file existance check
 */
int file_exists(char *fname)
{
    int result = FALSE;
#ifdef UNIX
    struct stat fStat;
    result = (stat(fname,&fStat) == 0);
#else
    FILE *f = fopen(fname,"rb");
    if (NULL != f) {
        result = TRUE;
        fclose(f);
    }
#endif
    diagnostics(5,"file_exists(%s) returns %d",fname,result);
    return result;
}

#define CR (char) 0x0d
#define LF (char) 0x0a

int my_fgetc(FILE *f)
{
    int c;
    
    c = fgetc(f);
    if (feof(f)) return '\0';
        
    if (c==CR) {
        c = fgetc(f);
        if (c == LF) return '\n';
        ungetc(c,f);
        return '\n';
    } 
    
    if (c == LF ) return '\n';
    if (c =='\t') return ' ';
    
    return c;
}

/* fgets function that honors '\' at end of line 

      \harvardcite{aharanov1995}{Aharanov, Whitehead, Kelemen \harvardand \
      Spiegelman}{Aharanov et~al.}{1995}
      
   returns number of characters read
*/

char * my_fgets(char *buffer, int maxBuffer, FILE *f) 
{
    int i;
    int cLast = '\0';
    
    if (f == NULL || feof(f)) return NULL;
    
    for (i=0; i<maxBuffer; i++) {
        buffer[i] = my_fgetc(f);
    
        if (buffer[i] == '\0') return buffer;
        
        /* skip TeX comments */
        while (buffer[i] == '%' && cLast != '\\' && buffer[i] != '\0') {
        	do {
        		buffer[i] = my_fgetc(f);
        	} while (buffer[i] == '\0' || buffer[i] == '\n');
        	
        	if (buffer[i] == '\0') return buffer;
        	do {
        		buffer[i] = my_fgetc(f);
        	} while (buffer[i] == '\0' || buffer[i] == ' ');
        	if (buffer[i] == '\0') return buffer;
        	
        }

        if (buffer[i] == '\n') {
            if (cLast == '\\')
                buffer[i] = ' ';  /* replace backslash-newline with backslash-space */
            else 
                break;
        } 
        cLast = buffer[i];
    }
        
    buffer[i] = '\0';
    return buffer;
}