Debian Codegraph @

c.c

raw
1 /**************************************************************************
2 * This program is Copyright (C) 1986-2002 by Jonathan Payne. JOVE is *
3 * provided by Jonathan and Jovehacks without charge and without *
4 * warranty. You may copy, modify, and/or distribute JOVE, provided that *
5 * this notice is included in all the source files and documentation. *
6 **************************************************************************/
7
8 /* Contains commands for C mode. Paren matching routines are in here. */
9
10 #include "jove.h"
11 #include "re.h"
12 #include "c.h"
13 #include "jctype.h"
14 #include "disp.h"
15 #include "delete.h"
16 #include "insert.h"
17 #include "fmt.h"
18 #include "marks.h"
19 #include "misc.h"
20 #include "move.h"
21 #include "para.h"
22
23 private void
24 FindMatch(int);
25
26 private jbool
27 backslashed(char *lp, int cpos)
28 {
29 int cnt = 0;
30
31 while (cpos > 0 && lp[--cpos] == '\\')
32 cnt += 1;
33 return (cnt % 2) != 0;
34 }
35
36 private const char p_types[] = "(){}[]";
37 private int mp_kind;
38 #define MP_OKAY 0
39 #define MP_MISMATCH 1
40 #define MP_UNBALANCED 2
41 #define MP_INCOMMENT 3
42
43 void
44 mp_error(void)
45 {
46 switch (mp_kind) {
47 case MP_MISMATCH:
48 message("[Mismatched parentheses]");
49 break;
50
51 case MP_UNBALANCED:
52 message("[Unbalanced parenthesis]");
53 break;
54
55 case MP_INCOMMENT:
56 message("[Inside a comment]");
57 break;
58
59 case MP_OKAY:
60 default:
61 return;
62 }
63 rbell();
64 }
65
66 /* Search from the current position for the paren that matches p_type.
67 * Search in the direction dir. If can_mismatch is YES then it is okay
68 * to have mismatched parens. If stop_early is YES then when an open
69 * paren is found at the beginning of a line, it is assumed that there
70 * is no point in backing up further. This is so when you hit tab or
71 * LineFeed outside, in-between procedure/function definitions, it won't
72 * sit there searching all the way to the beginning of the file for a
73 * match that doesn't exist. {forward,backward}-s-expression are the
74 * only ones that insist on getting the "true" story.
75 */
76 Bufpos *
77 m_paren(DAPchar p_type, int dir, jbool can_mismatch, jbool can_stop)
78 {
79 static Bufpos ret;
80 Bufpos savedot;
81 struct RE_block re_blk;
82 int count = 0;
83 char c = '\0'; /* avoid uninitialized complaint from gcc -W */
84 char
85 p_match, /* kind of paren matching p_type */
86 quote_c = '\0';
87 int c_char;
88 int in_comment = -1; /* -1, YES, or NO */
89 jbool stopped = NO;
90
91 REcompile(MajorMode(CMODE)? "[(){}[\\]/\"']" : "[(){}[\\]\"]",
92 YES, &re_blk);
93 {
94 const char *cp = strchr(p_types, p_type);
95
96 if (cp == NULL) {
97 complain("[Cannot match %c's]", p_type);
98 /* NOTREACHED */
99 }
100 p_match = cp[dir];
101 }
102 DOTsave(&savedot);
103
104 /* To make things a little faster I avoid copying lines into
105 * linebuf by setting curline and curchar by hand. Warning:
106 * this is slightly to very risky. When I did this there were
107 * lots of problems with procedures that expect the contents of
108 * curline to be in linebuf.
109 */
110 do {
111 Bufpos *sp = docompiled(dir, &re_blk);
112 char *lp;
113
114 if (sp == NULL)
115 break;
116
117 lp = lbptr(sp->p_line);
118
119 curline = sp->p_line;
120 curchar = sp->p_char; /* here's where I cheat */
121
122 c_char = curchar;
123 if (dir == FORWARD)
124 c_char -= 1;
125 if (backslashed(lp, c_char))
126 continue;
127
128 c = lp[c_char];
129 /* check if this is a comment (if we're not inside quotes) */
130 if (quote_c == '\0' && c == '/') {
131 int new_ic = in_comment; /* -1, YES, or NO */
132
133 /* close comment */
134 if ((c_char != 0) && lp[c_char - 1] == '*') {
135 new_ic = (dir == FORWARD) ? NO : YES;
136 if (new_ic == NO && in_comment == -1) {
137 count = 0;
138 quote_c = '\0';
139 }
140 } else if (lp[c_char + 1] == '*') {
141 new_ic = (dir == FORWARD) ? YES : NO;
142 if (new_ic == NO && in_comment == -1) {
143 count = 0;
144 quote_c = '\0';
145 }
146 }
147 in_comment = new_ic;
148 }
149 if (in_comment == YES)
150 continue;
151
152 if (c == '"' || c == '\'') {
153 if (quote_c == c)
154 quote_c = '\0';
155 else if (quote_c == '\0')
156 quote_c = c;
157 }
158 if (quote_c != '\0')
159 continue;
160
161 if (jisopenp(c)) {
162 count += dir;
163 if (c_char == 0 && can_stop && count >= 0) {
164 stopped = YES;
165 break;
166 }
167 } else if (jisclosep(c)) {
168 count -= dir;
169 }
170 } while (count >= 0);
171
172 ret.p_line = curline;
173 ret.p_char = curchar;
174
175 curline = savedot.p_line;
176 curchar = savedot.p_char; /* here's where I undo it */
177
178 if (count >= 0)
179 mp_kind = MP_UNBALANCED;
180 else if (c != p_match)
181 mp_kind = MP_MISMATCH;
182 else
183 mp_kind = MP_OKAY;
184
185 /* If we stopped (which means we were allowed to stop) and there
186 * was an error, we clear the error so no error message is printed.
187 * An error should be printed ONLY when we are sure about the fact,
188 * namely we didn't stop prematurely HOPING that it was the right
189 * answer.
190 */
191 if (stopped && mp_kind != MP_OKAY) {
192 mp_kind = MP_OKAY;
193 return NULL;
194 }
195 if (mp_kind == MP_OKAY || (mp_kind == MP_MISMATCH && can_mismatch))
196 return &ret;
197
198 return NULL;
199 }
200
201 private void
202 do_expr(int dir, jbool skip_words)
203 {
204 char syntax = (dir == FORWARD) ? C_BRA : C_KET;
205
206 if (dir == BACKWARD)
207 b_char(1);
208 for (;;) {
209 char c = linebuf[curchar];
210
211 if (!skip_words && jisident(c)) {
212 for (;;) {
213 if (dir == FORWARD? c == '\0' : bolp())
214 break;
215
216 curchar += dir;
217 if (!jisident(linebuf[curchar])) {
218 if (dir == BACKWARD)
219 curchar += 1;
220 break;
221 }
222 }
223 break;
224 }
225 /*
226 * BUG ALERT! The following test ought not to recognise brackets inside
227 * comments or quotes
228 */
229 if (has_syntax(c, syntax)) {
230 FindMatch(dir);
231 break;
232 }
233 f_char(dir);
234 if (eobp() || bobp())
235 return;
236 }
237 }
238
239 void
240 FSexpr(void)
241 {
242 int num = arg_value();
243
244 if (num < 0) {
245 negate_arg();
246 BSexpr();
247 }
248 while (--num >= 0)
249 do_expr(FORWARD, NO);
250 }
251
252 void
253 FList(void)
254 {
255 int num = arg_value();
256
257 if (num < 0) {
258 negate_arg();
259 BList();
260 }
261 while (--num >= 0)
262 do_expr(FORWARD, YES);
263 }
264
265 void
266 BSexpr(void)
267 {
268 int num = arg_value();
269
270 if (num < 0) {
271 negate_arg();
272 FSexpr();
273 }
274 while (--num >= 0)
275 do_expr(BACKWARD, NO);
276 }
277
278 void
279 BList(void)
280 {
281 int num = arg_value();
282
283 if (num < 0) {
284 negate_arg();
285 FList();
286 }
287 while (--num >= 0)
288 do_expr(BACKWARD, YES);
289 }
290
291 void
292 BUpList(void)
293 {
294 int num = arg_value();
295 Bufpos *mp;
296
297 if (num < 0) {
298 negate_arg();
299 FDownList();
300 }
301 while (--num >= 0) {
302 mp = m_paren(')', BACKWARD, YES, YES);
303 if (mp == NULL)
304 mp_error();
305 else
306 SetDot(mp);
307 }
308 }
309
310 void
311 FDownList(void)
312 {
313 int num = arg_value();
314 Bufpos *sp;
315 static const char sstr[] = "[{([\\])}]";
316
317 if (num < 0) {
318 negate_arg();
319 BUpList();
320 }
321 while (--num >= 0) {
322 /*
323 * BUG ALERT! The following test ought not to recognise brackets inside
324 * comments or quotes
325 */
326 sp = dosearch(sstr, FORWARD, YES);
327 if (sp == NULL || jisclosep(lcontents(sp->p_line)[sp->p_char - 1])) {
328 complain("[No contained expression]");
329 /* NOTREACHED */
330 }
331 SetDot(sp);
332 }
333 }
334
335 /* Move to the matching brace or paren depending on the current position
336 * in the buffer.
337 */
338 private void
339 FindMatch(int dir)
340 {
341 Bufpos *bp;
342 char c = linebuf[curchar];
343
344 if (strchr(p_types, c) == NULL || backslashed(linebuf, curchar)) {
345 complain((char *)NULL);
346 /* NOTREACHED */
347 }
348 if (dir == FORWARD)
349 f_char(1);
350 bp = m_paren(c, dir, YES, NO);
351 if (dir == FORWARD)
352 b_char(1);
353 if (bp != NULL)
354 SetDot(bp);
355 mp_error(); /* if there is an error the user wants to
356 know about it */
357 }
358
359 #define ALIGN_ARGS (-1)
360
361 /* If CArgIndent == ALIGN_ARGS then the indentation routine will
362 * indent a continued line by lining it up with the first argument.
363 * Otherwise, it will indent CArgIndent characters past the indent
364 * of the first line of the procedure call.
365 */
366 int CArgIndent = ALIGN_ARGS; /* VAR: how to indent arguments to C functions */
367
368 /* indent for C code */
369 Bufpos *
370 c_indent(jbool brace)
371 {
372 Bufpos *bp;
373 int new_indent = 0,
374 current_indent,
375 increment = brace? 0 : CIndIncrmt;
376
377 /* Find matching paren, which may be a mismatch now. If it
378 * is not a matching curly brace then it is a paren (most likely).
379 * In that case we try to line up the arguments to a procedure
380 * or inside an of statement.
381 */
382 if ((bp = m_paren('}', BACKWARD, YES, YES)) != NULL) {
383 Bufpos save;
384 int matching_indent;
385
386 DOTsave(&save);
387 SetDot(bp); /* go to matching paren */
388 ToIndent();
389 matching_indent = calc_pos(linebuf, curchar);
390 SetDot(bp);
391 switch (linebuf[curchar]) {
392 case '{':
393 new_indent = matching_indent;
394 if (!bolp()) {
395 b_char(1);
396 /* If we're not within the indent then we
397 * can assume that there is either a C keyword
398 * line DO on the line before the brace, or
399 * there is a parenthesized expression. If
400 * that's the case we want to go backward
401 * over that to the beginning of the expression
402 * so that we can get the correct indent for
403 * this matching brace. This handles wrapped
404 * if statements, etc.
405 */
406 if (!within_indent()) {
407 Bufpos savematch;
408
409 savematch = *bp;
410
411 do_expr(BACKWARD, NO);
412 ToIndent();
413 new_indent = calc_pos(linebuf, curchar);
414
415 /* do_expr() calls b_paren, which
416 * returns a pointer to a structure,
417 * and that pointer is in BP so we
418 * have to save away the matching
419 * paren and restore it in the
420 * following line ... sigh
421 */
422 *bp = savematch;
423 }
424 }
425 if (!brace)
426 new_indent += (increment - (new_indent % increment));
427 break;
428
429 case '(':
430 if (CArgIndent == ALIGN_ARGS) {
431 f_char(1);
432 new_indent = calc_pos(linebuf, curchar);
433 } else
434 new_indent = matching_indent + CArgIndent;
435 break;
436 }
437 SetDot(&save);
438 }
439
440 /* new_indent is the "correct" place to indent. Now we check to
441 * see if what we consider as the correct place to indent is to
442 * the LEFT of where we already are. If it is, and we are NOT
443 * handling a brace, then we assume that the person wants to tab
444 * in further than what we think is right (for some reason) and
445 * so we allow that.
446 */
447 ToIndent();
448 current_indent = calc_pos(linebuf, curchar);
449 if (!brace && new_indent <= current_indent)
450 new_indent = current_indent + (increment - (current_indent % increment));
451 Bol();
452 DelWtSpace(); /* nice uniform Tabs*Space* */
453 n_indent(new_indent);
454
455 return bp;
456 }
457
458 private void
459 re_indent(int incr)
460 {
461 LinePtr l1, l2, lp;
462 int c1, c2;
463 Mark *m = CurMark();
464 Bufpos savedot;
465
466 DOTsave(&savedot);
467 l1 = curline;
468 c1 = curchar;
469 l2 = m->m_line;
470 c2 = m->m_char;
471 (void) fixorder(&l1, &c1, &l2, &c2);
472 for (lp = l1; lp != l2->l_next; lp = lp->l_next) {
473 int indent;
474
475 SetLine(lp);
476 ToIndent();
477 indent = calc_pos(linebuf, curchar);
478 if (indent != 0 || linebuf[0] != '\0')
479 n_indent(indent + incr);
480 }
481 SetDot(&savedot);
482 }
483
484 void
485 LRShift(void)
486 {
487 re_indent(-arg_or_default(CIndIncrmt));
488 }
489
490 void
491 RRShift(void)
492 {
493 re_indent(arg_or_default(CIndIncrmt));
494 }
495
496 #ifdef CMT_FMT
497
498 char CmtFmt[80] = "/*%n%! * %c%!%n */"; /* VAR: comment format */
499
500 /* Strip leading and trailing white space. Skip over any imbedded '\n's. */
501
502 private void
503 strip_c(char *from, char *to)
504 {
505 char *fr_p = from,
506 *to_p = to,
507 c;
508
509 while ((c = *fr_p) == '\n' || jiswhite(c))
510 fr_p += 1;
511 while ((c = *fr_p) != '\0') {
512 if (c != '\n')
513 *to_p++ = c;
514 fr_p += 1;
515 }
516 while (to_p > to && jiswhite(to_p[-1]))
517 to_p -= 1;
518 *to_p = '\0';
519 }
520
521 # define CMT_STR_BOUND 20
522
523 private char open_c[CMT_STR_BOUND], /* the open comment format string */
524 open_pat[CMT_STR_BOUND], /* the search pattern for open comment */
525 l_header[CMT_STR_BOUND], /* the prefix for each comment line */
526 l_trailer[CMT_STR_BOUND], /* the suffix ... */
527 close_c[CMT_STR_BOUND],
528 close_pat[CMT_STR_BOUND];
529
530 private jbool nl_in_close_c;
531
532 /* Fill in the data structures above from the format string. Don't return
533 * if there's trouble.
534 */
535 private void
536 parse_cmt_fmt(void)
537 {
538
539 static char *const component[] = {
540 open_c,
541 l_header,
542 l_trailer,
543 close_c
544 };
545 char *fmtp = CmtFmt,
546 *const *c_body = component,
547 *body_p = *c_body,
548 *body_limit = body_p + CMT_STR_BOUND - 1,
549 c;
550 int comp_no = 0;
551
552 /* pick apart the comment string */
553 nl_in_close_c = NO;
554 while ((c = *fmtp++) != '\0') {
555 if (c == '%') {
556 switch(c = *fmtp++) {
557 case 'n':
558 switch (comp_no) {
559 case 0:
560 break;
561 case 3:
562 nl_in_close_c = YES;
563 break;
564 default:
565 complain("%%n not allowed in line header or trailer: %s",
566 fmtp - 2);
567 /* NOTREACHED */
568 }
569 c = '\n';
570 break;
571 case 't':
572 c = '\t';
573 break;
574 case '%':
575 break;
576 case '!':
577 case 'c':
578 if (++comp_no == elemsof(component)) {
579 complain("too many components");
580 /* NOTREACHED */
581 }
582 if ((c=='c') != (comp_no==2)) {
583 complain("wrong separator: %%%c", c);
584 /* NOTREACHED */
585 }
586 *body_p++ = '\0';
587 body_p = *++c_body;
588 body_limit = body_p + CMT_STR_BOUND - 1;
589 continue;
590 default:
591 complain("[Unknown comment escape: %%%c]", c);
592 /*NOTREACHED*/
593 }
594 }
595 if (body_p >= body_limit) {
596 complain("component too long");
597 /* NOTREACHED */
598 }
599 *body_p++ = c;
600 }
601 *body_p = '\0';
602 while (++comp_no != elemsof(component))
603 **++c_body = '\0';
604 /* make search patterns */
605 strip_c(open_c, open_pat);
606 strip_c(close_c, close_pat);
607 }
608
609 void
610 FillComment(void)
611 {
612 int saveRMargin,
613 indent_pos;
614 jbool found_close;
615 char *trimmed_header; /* l_header without leading spaces */
616 int trimmed_header_len, /* length without leading or trailing spaces */
617 trailer_len;
618 char *cp;
619 Bufpos open_c_pt,
620 close_c_pt,
621 tmp_bp,
622 *match_o,
623 *match_c;
624 Mark *close_c_mark, /* end of comment (we may terminate it) */
625 *open_c_mark, /* start of comment (reference to curmark) */
626 *savedot;
627
628 parse_cmt_fmt();
629 /* Figure out if we're "inside" a comment.
630 * First look back for opening comment symbol.
631 */
632 if ((match_o = dosearch(open_pat, BACKWARD, NO)) == NULL) {
633 complain("No opening %s to match to.", open_pat);
634 /* NOTREACHED */
635 }
636 open_c_pt = *match_o;
637 if ((match_c = dosearch(close_pat, BACKWARD, NO)) != NULL
638 && inorder(open_c_pt.p_line, open_c_pt.p_char,
639 match_c->p_line, match_c->p_char)) {
640 complain("[Must be between %s and %s to re-format]",
641 open_pat, close_pat);
642 /* NOTREACHED */
643 }
644
645 /* Now look forward for closing comment symbol.
646 * This involves looking forward for the next opening too.
647 */
648 if ((match_o = dosearch(open_pat, FORWARD, NO)) != NULL) {
649 tmp_bp = *match_o;
650 match_o = &tmp_bp;
651 }
652 match_c = dosearch(close_pat, FORWARD, NO);
653
654 /* If we found the right close comment symbol, we format
655 * up to it; otherwise we format up to dot. We have found the
656 * close if we found (looking forward) a close not preceded by
657 * an open.
658 */
659 found_close = match_c != NULL
660 && (match_o == NULL
661 || inorder(match_c->p_line, match_c->p_char,
662 match_o->p_line, match_o->p_char));
663
664 if (found_close) {
665 close_c_pt = *match_c;
666 } else {
667 close_c_pt.p_line = curline;
668 close_c_pt.p_char = curchar;
669 }
670
671 SetDot(&open_c_pt);
672 set_mark(); /* user visible mark! */
673 open_c_mark = curmark;
674 indent_pos = calc_pos(linebuf, curchar);
675
676 /* move to end; delete close if it exists */
677 SetDot(&close_c_pt);
678 CopyRegion(); /* enable yank-pop for undo */
679 if (found_close) {
680 del_char(BACKWARD, (int)strlen(close_pat), NO);
681 DelWtSpace();
682 if (bolp())
683 del_char(BACKWARD, 1, NO);
684 }
685 close_c_mark = MakeMark(curline, curchar);
686
687 /* Separate the comment body from anything preceeding it.
688 * Delete separator later.
689 */
690 ToMark(open_c_mark);
691 LineInsert(1);
692 DelWtSpace();
693 Bol();
694
695 /* insert comment open string */
696 for (cp = open_c; *cp!='\0'; cp++) {
697 if (*cp == '\n') {
698 if (!eolp())
699 LineInsert(1);
700 else
701 line_move(FORWARD, 1, NO);
702 } else if (jiswhite(*cp)) {
703 if (linebuf[curchar] != *cp)
704 insert_c(*cp, 1);
705 } else {
706 /* Since we matched the open comment string
707 * on this line, we don't need to worry about
708 * crossing line boundaries.
709 */
710 curchar += 1;
711 }
712 }
713 savedot = MakeMark(curline, curchar);
714
715 /* We need to strip the line header pattern of leading
716 * white space since we need to match the line after all of
717 * its leading whitespace is gone. We also need to note
718 * how long that string is without counting trailing whitespace.
719 */
720 for (cp = l_header; jiswhite(*cp); cp++)
721 ;
722 trimmed_header = cp;
723 for (trimmed_header_len = strlen(cp)
724 ; trimmed_header_len > 0 && jiswhite(cp[trimmed_header_len - 1])
725 ; trimmed_header_len--)
726 ;
727
728 trailer_len = strlen(l_trailer);
729
730 /* Strip each comment line of the open and close comment line strings
731 * before reformatting it.
732 * Any whitespace at the end of the open line string is optional.
733 * This allows empty comment lines (paragraph separators) without
734 * trailing whitespace.
735 */
736 for (;;) {
737 Bol();
738 DelWtSpace();
739 if (trimmed_header_len) {
740 int hmw = numcomp(linebuf, trimmed_header);
741
742 if (hmw >= trimmed_header_len)
743 del_char(FORWARD, hmw, NO);
744 }
745
746 if (trailer_len) {
747 Eol();
748 if (curchar > trailer_len
749 && strncmp(&linebuf[curchar - trailer_len],
750 l_trailer, (size_t)trailer_len)==0)
751 del_char(BACKWARD, trailer_len, NO);
752 }
753 if (curline == close_c_mark->m_line)
754 break;
755
756 line_move(FORWARD, 1, NO);
757 }
758
759 /* Now that comment decoration is gone, use normal fill
760 * routine to format body.
761 * Adjust RMargin to allow for decoration to be added back,
762 * but always allow at least 10 characters (arbitrary).
763 */
764
765 do_set_mark(savedot->m_line, savedot->m_char); /* user visible mark! */
766 DelMark(savedot);
767 ToMark(close_c_mark);
768 saveRMargin = RMargin;
769 RMargin = jmax(10,
770 saveRMargin - (int)strlen(l_header) - trailer_len - indent_pos + 2);
771 do_rfill(NO); /* justify from mark through point */
772 RMargin = saveRMargin;
773 PopMark(); /* get back to the start of the comment; discard mark */
774
775 /* redecorate newly filled comment text */
776 for (;;) {
777 if (curline != open_c_mark->m_line->l_next) {
778 /* Not first line: insert line header.
779 * Slightly tricky: preserve interesting leading
780 * whitespace in line (n_indent would eat it).
781 */
782 Bol();
783 ins_str(trimmed_header);
784 Bol();
785 n_indent(indent_pos + (int)(trimmed_header - l_header));
786 }
787 Eol();
788 if (trailer_len == 0)
789 DelWtSpace();
790
791 if (curline == close_c_mark->m_line)
792 break;
793
794 /* not last line: insert line trailer */
795 ins_str(l_trailer);
796 line_move(FORWARD, 1, NO);
797 }
798
799 if (nl_in_close_c) {
800 /* since NewLine is included in comment close,
801 * add line trailer first
802 */
803 ins_str(l_trailer);
804 }
805
806 /* handle the close comment symbol */
807 DelMark(close_c_mark);
808 DelWtSpace();
809 /* if the addition of the close symbol would cause the line
810 * to be too long, put the close symbol on the next line.
811 */
812 if (!nl_in_close_c
813 && (int)strlen(close_c) + calc_pos(linebuf, curchar) > RMargin)
814 {
815 LineInsert(1);
816 n_indent(indent_pos);
817 }
818 for (cp = close_c; *cp; cp++) {
819 if (*cp == '\n') {
820 LineInsert(1);
821 n_indent(indent_pos);
822 } else {
823 insert_c(*cp, 1);
824 }
825 }
826 ExchPtMark();
827 Eol();
828 del_char(FORWARD, 1, NO); /* Delete separator added earlier */
829 this_cmd = UNDOABLECMD; /* allow yank-pop to undo */
830 }
831
832 #endif /* CMT_FMT */