summaryrefslogtreecommitdiff
path: root/ch01/ex21-entab.c
blob: 1282c61b277bbfc39ef5f5746b0b80348540d13f (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
#include <stdio.h>

#define TABSTOP 8  /* number of columns between tab stops */
#define DEBUG   0  /* display tabs and spaces explicitly */

#define SYM_SP  '.'  /* visible space for debugging */
#define SYM_TAB '~'  /* visible tab for debugging */

void puttab(void);
void putspace(int len);


/* replace blanks by proper tabs */
int main()
{
    int c;       /* current character */
    int offset;  /* position inside current tab stop */
    int nspace;  /* number of spaces */

    if (DEBUG) {
        printf("# debug mode is on\n");
        printf("# displaying spaces and tabs explicitly\n");
        printf("# space -> %c\n", SYM_SP);
        printf("# tab   -> %c\n", SYM_TAB);
    }

    offset = nspace = 0;
    while ((c = getchar()) != EOF) {
        ++offset;

        if (c == ' ')
            ++nspace;
        else if (c == '\t') {
            puttab();
            offset = nspace = 0;
        } else if (nspace) {
            putspace(nspace);
            nspace = 0;
        }

        if (offset == TABSTOP) {
            if (nspace)
                puttab();
            offset = nspace = 0;
        }

        if (c == '\n') {
            if (nspace)
                putspace(nspace);
            offset = nspace = 0;
        }

        if (c != ' ' && c != '\t')
            putchar(c);
    }

    if (nspace)
        putspace(nspace);

    return 0;
}

/* print a tab */
void puttab(void)
{
    int c;

    if (DEBUG)
        c = SYM_TAB;
    else
        c = '\t';

    putchar(c);
}

/* print len spaces */
void putspace(int len)
{
    int i;
    int c;

    if (DEBUG)
        c = SYM_SP;
    else
        c = ' ';

    for (i = 0; i < len; ++i)
        putchar(c);
}