Propogate colors to new windows on opening (744294)
[nedit.git] / source / smartIndent.c
blob0622f872466a4b23e63d6d7414c2559ed89c576f
1 static const char CVSID[] = "$Id: smartIndent.c,v 1.27 2003/05/09 17:43:48 edg Exp $";
2 /*******************************************************************************
3 * *
4 * smartIndent.c -- Maintain, and allow user to edit, macros for smart indent *
5 * *
6 * Copyright (C) 1999 Mark Edel *
7 * *
8 * This is free software; you can redistribute it and/or modify it under the *
9 * terms of the GNU General Public License as published by the Free Software *
10 * Foundation; either version 2 of the License, or (at your option) any later *
11 * version. *
12 * *
13 * This software is distributed in the hope that it will be useful, but WITHOUT *
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
15 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
16 * for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License along with *
19 * software; if not, write to the Free Software Foundation, Inc., 59 Temple *
20 * Place, Suite 330, Boston, MA 02111-1307 USA *
21 * *
22 * Nirvana Text Editor *
23 * July, 1997 *
24 * *
25 * Written by Mark Edel *
26 * *
27 *******************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 #include "../config.h"
31 #endif
33 #include "smartIndent.h"
34 #include "textBuf.h"
35 #include "nedit.h"
36 #include "text.h"
37 #include "preferences.h"
38 #include "interpret.h"
39 #include "macro.h"
40 #include "window.h"
41 #include "parse.h"
42 #include "shift.h"
43 #include "help.h"
44 #include "../util/DialogF.h"
45 #include "../util/misc.h"
47 #include <stdio.h>
48 #include <string.h>
49 #include <limits.h>
51 #include <Xm/Xm.h>
52 #ifdef VMS
53 #include "../util/VMSparam.h"
54 #else
55 #ifndef __MVS__
56 #include <sys/param.h>
57 #endif
58 #endif /*VMS*/
59 #include <Xm/Xm.h>
60 #include <Xm/Form.h>
61 #include <Xm/Text.h>
62 #include <Xm/LabelG.h>
63 #include <Xm/PushB.h>
64 #include <Xm/RowColumn.h>
65 #include <Xm/SeparatoG.h>
66 #include <Xm/PanedW.h>
68 #ifdef HAVE_DEBUG_H
69 #include "../debug.h"
70 #endif
73 static char MacroEndBoundary[] = "--End-of-Macro--";
75 typedef struct {
76 char *lmName;
77 char *initMacro;
78 char *newlineMacro;
79 char *modMacro;
80 } smartIndentRec;
82 typedef struct {
83 Program *newlineMacro;
84 int inNewLineMacro;
85 Program *modMacro;
86 int inModMacro;
87 } windowSmartIndentData;
89 /* Smart indent macros dialog information */
90 static struct {
91 Widget shell;
92 Widget lmOptMenu;
93 Widget lmPulldown;
94 Widget initMacro;
95 Widget newlineMacro;
96 Widget modMacro;
97 char *langModeName;
98 } SmartIndentDialog = {NULL,NULL,NULL,NULL,NULL,NULL,NULL};
100 /* Common smart indent macros dialog information */
101 static struct {
102 Widget shell;
103 Widget text;
104 } CommonDialog = {NULL,NULL};
106 static int NSmartIndentSpecs = 0;
107 static smartIndentRec *SmartIndentSpecs[MAX_LANGUAGE_MODES];
108 static char *CommonMacros = NULL;
110 static void executeNewlineMacro(WindowInfo *window,smartIndentCBStruct *cbInfo);
111 static void executeModMacro(WindowInfo *window,smartIndentCBStruct *cbInfo);
112 static void insertShiftedMacro(textBuffer *buf, char *macro);
113 static int isDefaultIndentSpec(smartIndentRec *indentSpec);
114 static smartIndentRec *findIndentSpec(const char *modeName);
115 static char *ensureNewline(char *string);
116 static int loadDefaultIndentSpec(char *lmName);
117 static int siParseError(char *stringStart, char *stoppedAt, char *message);
118 static void destroyCB(Widget w, XtPointer clientData, XtPointer callData);
119 static void langModeCB(Widget w, XtPointer clientData, XtPointer callData);
120 static void commonDialogCB(Widget w, XtPointer clientData, XtPointer callData);
121 static void lmDialogCB(Widget w, XtPointer clientData, XtPointer callData);
122 static void okCB(Widget w, XtPointer clientData, XtPointer callData);
123 static void applyCB(Widget w, XtPointer clientData, XtPointer callData);
124 static void checkCB(Widget w, XtPointer clientData, XtPointer callData);
125 static void restoreCB(Widget w, XtPointer clientData, XtPointer callData);
126 static void deleteCB(Widget w, XtPointer clientData, XtPointer callData);
127 static void dismissCB(Widget w, XtPointer clientData, XtPointer callData);
128 static void helpCB(Widget w, XtPointer clientData, XtPointer callData);
129 static int checkSmartIndentDialogData(void);
130 static smartIndentRec *getSmartIndentDialogData(void);
131 static void setSmartIndentDialogData(smartIndentRec *is);
132 static void comDestroyCB(Widget w, XtPointer clientData, XtPointer callData);
133 static void comOKCB(Widget w, XtPointer clientData, XtPointer callData);
134 static void comApplyCB(Widget w, XtPointer clientData, XtPointer callData);
135 static void comCheckCB(Widget w, XtPointer clientData, XtPointer callData);
136 static void comRestoreCB(Widget w, XtPointer clientData, XtPointer callData);
137 static void comDismissCB(Widget w, XtPointer clientData, XtPointer callData);
138 static int updateSmartIndentCommonData(void);
139 static int checkSmartIndentCommonDialogData(void);
140 static int updateSmartIndentData(void);
141 static char *readSIMacro(char **inPtr);
142 static smartIndentRec *copyIndentSpec(smartIndentRec *is);
143 static void freeIndentSpec(smartIndentRec *is);
144 static int indentSpecsDiffer(smartIndentRec *is1, smartIndentRec *is2);
146 #define N_DEFAULT_INDENT_SPECS 4
147 static smartIndentRec DefaultIndentSpecs[N_DEFAULT_INDENT_SPECS] = {
148 {"C",
149 "# C Macros and tuning parameters are shared with C++, and are declared\n\
150 # in the common section. Press Common / Shared Initialization above.\n",
151 "return cFindSmartIndentDist($1)\n",
152 "if ($2 == \"}\" || $2 == \"{\" || $2 == \"#\")\n\
153 cBraceOrPound($1, $2)\n"},
154 {"C++",
155 "# C++ Macros and tuning parameters are shared with C, and are declared\n\
156 # in the common section. Press Common / Shared Initialization above.\n",
157 "return cFindSmartIndentDist($1)\n",
158 "if ($2 == \"}\" || $2 == \"{\" || $2 == \"#\")\n\
159 cBraceOrPound($1, $2)\n"},
160 {"Python",
161 "# Number of characters in a normal indent level. May be a number, or the\n\
162 # string \"default\", meaning, guess the value from the current tab settings.\n\
163 $pyIndentDist = \"default\"\n",
164 "if (get_range($1-1, $1) != \":\")\n\
165 return -1\n\
166 return measureIndent($1) + defaultIndent($pyIndentDist)\n", NULL},
167 {"Matlab",
168 "# Number of spaces to indent \"case\" statements\n\
169 $caseDepth = 2\n\
170 define matlabNewlineMacro\n\
171 {\n\
172 if ($em_tab_dist == -1)\n\
173 tabsize = $tab_dist\n\
174 else\n\
175 tabsize = $em_tab_dist\n\
176 startLine = startOfLine($1)\n\
177 indentLevel = measureIndent($1)\n\
179 # If this line is continued on next, return default:\n\
180 lastLine = get_range(startLine, $1)\n\
181 if (search_string(lastLine, \"...\", 0) != -1) {\n\
182 if ($n_args == 2)\n\
183 return matlabNewlineMacro(startLine - 1, 1)\n\
184 else {\n\
185 return -1\n\
186 }\n\
187 }\n\
189 # Correct the indentLevel if this was a continued line.\n\
190 while (startLine > 1)\n\
191 {\n\
192 endLine = startLine - 1\n\
193 startLine = startOfLine(endLine)\n\
194 lastLine = get_range(startLine, endLine)\n\
195 # No \"...\" means we've found the root\n\
196 if (search_string(lastLine, \"...\", 0) == -1) {\n\
197 startLine = endLine + 1\n\
198 break\n\
199 }\n\
200 }\n\
201 indentLevel = measureIndent(startLine)\n\
203 # Get the first word of the indentLevel line\n\
204 FWend = search(\">|\\n\", startLine + indentLevel, \"regex\")\n\
205 # This search fails on EOF\n\
206 if (FWend == -1)\n\
207 FWend = $1\n\
209 firstWord = get_range(startLine + indentLevel, FWend)\n\
211 # How shall we change the indent level based on the first word?\n\
212 if (search_string(firstWord, \\\n\
213 \"<for>|<function>|<if>|<switch>|<try>|<while>\", 0, \"regex\") == 0) {\n\
214 return indentLevel + tabsize\n\
215 }\n\
216 else if ((firstWord == \"end\") || (search_string(firstWord, \\\n\
217 \"<case>|<catch>|<else>|<elseif>|<otherwise>\", 0, \"regex\") == 0)) {\n\
218 # Get the last indent level \n\
219 if (startLine > 0) # avoid infinite loop\n\
220 last_indent = matlabNewlineMacro(startLine - 1, 1)\n\
221 else\n\
222 last_indent = indentLevel\n\
224 # Re-indent this line\n\
225 if ($n_args == 1) {\n\
226 if (firstWord == \"case\" || firstWord == \"otherwise\")\n\
227 replace_range(startLine, startLine + indentLevel, \\\n\
228 makeIndentString(last_indent - tabsize + $caseDepth))\n\
229 else\n\
230 replace_range(startLine, startLine + indentLevel, \\\n\
231 makeIndentString(last_indent - tabsize))\n\
232 }\n\
234 if (firstWord == \"end\") {\n\
235 return max(last_indent - tabsize, 0)\n\
236 }\n\
237 else {\n\
238 return last_indent\n\
239 }\n\
240 } \n\
241 else {\n\
242 return indentLevel\n\
243 }\n\
244 }", "return matlabNewlineMacro($1)\n", NULL}
247 static char DefaultCommonMacros[] = "#\n\
248 # C/C++ Style/tuning parameters\n\
249 #\n\
251 # Number of characters in a normal indent level. May be a number, or the\n\
252 # string \"default\", meaning, guess the value from the current tab settings.\n\
253 $cIndentDist = \"default\"\n\
255 # Number of characters in a line continuation. May be a number or the\n\
256 # string \"default\", meaning, guess the value from the current tab settings.\n\
257 $cContinuationIndent = \"default\"\n\
259 # How far back from the current position to search for an anchoring position\n\
260 # on which to base indent. When no reliable indicators of proper indent level\n\
261 # can be found within the requested distance, reverts to plain auto indent.\n\
262 $cMaxSearchBackLines = 10\n\
264 #\n\
265 # Find the start of the line containing position $1\n\
266 #\n\
267 define startOfLine {\n\
269 for (i=$1-1; ; i--) {\n\
270 if (i <= 0)\n\
271 return 0\n\
272 if (get_character(i) == \"\\n\")\n\
273 return i + 1\n\
274 }\n\
275 }\n\
277 #\n\
278 # Find the indent level of the line containing character position $1\n\
279 #\n\
280 define measureIndent {\n\
282 # measure the indentation to the first non-white character on the line\n\
283 indent = 0\n\
284 for (i=startOfLine($1); i < $text_length; i++) {\n\
285 c = get_character(i)\n\
286 if (c != \" \" && c != \"\\t\")\n\
287 break\n\
288 if (c == \"\\t\")\n\
289 indent += $tab_dist - (indent % $tab_dist)\n\
290 else\n\
291 indent++\n\
292 }\n\
293 return indent\n\
294 }\n\
296 #\n\
297 # Make a string to produce an indent of $1 characters\n\
298 #\n\
299 define makeIndentString {\n\
301 if ($use_tabs) {\n\
302 nTabs = $1 / $tab_dist\n\
303 nSpaces = $1 % $tab_dist\n\
304 } else {\n\
305 nTabs = 0\n\
306 nSpaces = $1\n\
307 }\n\
308 indentString = \"\"\n\
309 for (i=0; i<nTabs; i++)\n\
310 indentString = indentString \"\\t\"\n\
311 for (i=0; i<nSpaces; i++)\n\
312 indentString = indentString \" \"\n\
313 return indentString\n\
314 }\n\
316 #\n\
317 # If $1 is a number, just pass it on. If it is the string \"default\",\n\
318 # figure out a reasonable indent distance for a structured languages\n\
319 # like C, based on how tabs are set.\n\
320 #\n\
321 define defaultIndent {\n\
323 if ($1 != \"default\")\n\
324 return $1\n\
325 if ($em_tab_dist != -1)\n\
326 return $em_tab_dist\n\
327 if ($tab_dist <= 8)\n\
328 return $tab_dist\n\
329 return 4\n\
330 }\n\
332 #\n\
333 # If $1 is a number, just pass it on. If it is the string \"default\",\n\
334 # figure out a reasonable amount of indentation for continued lines\n\
335 # based on how tabs are set.\n\
336 #\n\
337 define defaultContIndent {\n\
339 if ($1 != \"default\")\n\
340 return $1\n\
341 if ($em_tab_dist != -1)\n\
342 return $em_tab_dist * 2\n\
343 if ($tab_dist <= 8)\n\
344 return $tab_dist * 2\n\
345 return 8\n\
346 }\n\
348 #\n\
349 # Find the end of the conditional part of if/while/for, by looking for balanced\n\
350 # parenthesis between $1 and $2. returns -1 if parens don't balance before\n\
351 # $2, or if no parens are found\n\
352 #\n\
353 define findBalancingParen {\n\
355 openParens = 0\n\
356 parensFound = 0\n\
357 for (i=$1; i<$2; i++) {\n\
358 c = get_character(i)\n\
359 if (c == \"(\") {\n\
360 openParens++\n\
361 parensFound = 1\n\
362 } else if (c == \")\")\n\
363 openParens--\n\
364 else if (!parensFound && c != \" \" && c != \"\\t\")\n\
365 return -1\n\
366 if (parensFound && openParens <=0)\n\
367 return i+1\n\
368 }\n\
369 return -1\n\
370 }\n\
372 #\n\
373 # Skip over blank space and comments and preprocessor directives from position\n\
374 # $1 to a maximum of $2.\n\
375 # if $3 is non-zero, newlines are considered blank space as well. Return -1\n\
376 # if the maximum position ($2) is hit mid-comment or mid-directive\n\
377 #\n\
378 define cSkipBlankSpace {\n\
380 for (i=$1; i<$2; i++) {\n\
381 c = get_character(i)\n\
382 if (c == \"/\") {\n\
383 if (i+1 >= $2)\n\
384 return i\n\
385 if (get_character(i+1) == \"*\") {\n\
386 for (i=i+1; ; i++) {\n\
387 if (i+1 >= $2)\n\
388 return -1\n\
389 if (get_character(i) == \"*\" && get_character(i+1) == \"/\") {\n\
390 i++\n\
391 break\n\
392 }\n\
393 }\n\
394 } else if (get_character(i+1) == \"/\") {\n\
395 for (i=i+1; i<$2; i++) {\n\
396 if (get_character(i) == \"\\n\") {\n\
397 if (!$3)\n\
398 return i\n\
399 break\n\
400 }\n\
401 }\n\
402 }\n\
403 } else if (c == \"#\" && $3) {\n\
404 for (i=i+1; ; i++) {\n\
405 if (i >= $2) {\n\
406 if (get_character(i-1) == \"\\\\\")\n\
407 return -1\n\
408 else\n\
409 break\n\
410 }\n\
411 if (get_character(i) == \"\\n\" && get_character(i-1) != \"\\\\\")\n\
412 break\n\
413 }\n\
414 } else if (!(c == \" \" || c == \"\\t\" || ($3 && c==\"\\n\")))\n\
415 return i\n\
416 }\n\
417 return $2\n\
418 }\n\
420 #\n\
421 # Search backward for an anchor point: a line ending brace, or semicolon\n\
422 # or case statement, followed (ignoring blank lines and comments) by what we\n\
423 # assume is a properly indented line, a brace on a line by itself, or a case\n\
424 # statement. Returns the position of the first non-white, non comment\n\
425 # character on the line. returns -1 if an anchor position can't be found\n\
426 # before $cMaxSearchBackLines.\n\
427 #\n\
428 define cFindIndentAnchorPoint {\n\
430 nLines = 0\n\
431 anchorPos = $1\n\
432 for (i=$1-1; i>0; i--) {\n\
433 c = get_character(i)\n\
434 if (c == \";\" || c == \"{\" || c == \"}\" || c == \":\") {\n\
436 # Verify that it's line ending\n\
437 lineEnd = cSkipBlankSpace(i+1, $1, 0)\n\
438 if (lineEnd == -1 || \\\n\
439 (lineEnd != $text_length && get_character(lineEnd) != \"\\n\"))\n\
440 continue\n\
442 # if it's a colon, it's only meaningful if \"case\" begins the line\n\
443 if (c == \":\") {\n\
444 lineStart = startOfLine(i)\n\
445 caseStart = cSkipBlankSpace(lineStart, lineEnd, 0)\n\
446 if (get_range(caseStart, caseStart+4) != \"case\")\n\
447 continue\n\
448 delim = get_character(caseStart+4)\n\
449 if (delim!=\" \" && delim!=\"\\t\" && delim!=\"(\" && delim!=\":\")\n\
450 continue\n\
451 isCase = 1\n\
452 } else\n\
453 isCase = 0\n\
455 # Move forward past blank lines and comment lines to find\n\
456 # non-blank, non-comment line-start\n\
457 anchorPos = cSkipBlankSpace(lineEnd, $1, 1)\n\
459 # Accept if it's before the requested position, otherwise\n\
460 # continue further back in the file and try again\n\
461 if (anchorPos != -1 && anchorPos < $1)\n\
462 break\n\
464 # A case statement by itself is an acceptable anchor\n\
465 if (isCase)\n\
466 return caseStart\n\
468 # A brace on a line by itself is an acceptable anchor, even\n\
469 # if it doesn't follow a semicolon or another brace\n\
470 if (c == \"{\" || c == \"}\") {\n\
471 for (j = i-1; ; j--) {\n\
472 if (j == 0)\n\
473 return i\n\
474 ch = get_character(j)\n\
475 if (ch == \"\\n\")\n\
476 return i\n\
477 if (ch != \"\\t\" && ch != \" \")\n\
478 break\n\
479 }\n\
480 }\n\
482 } else if (c == \"\\n\")\n\
483 if (++nLines > $cMaxSearchBackLines)\n\
484 return -1\n\
485 }\n\
486 if (i <= 0)\n\
487 return -1\n\
488 return anchorPos\n\
489 }\n\
491 #\n\
492 # adjust the indent on a line about to recive either a right or left brace\n\
493 # or pound (#) character ($2) following position $1\n\
494 #\n\
495 define cBraceOrPound {\n\
497 # Find start of the line, and make sure there's nothing but white-space\n\
498 # before the character. If there's anything before it, do nothing\n\
499 for (i=$1-1; ; i--) {\n\
500 if (i < 0) {\n\
501 lineStart = 0\n\
502 break\n\
503 }\n\
504 c = get_character(i)\n\
505 if (c == \"\\n\") {\n\
506 lineStart = i + 1\n\
507 break\n\
508 }\n\
509 if (c != \" \" && c != \"\\t\")\n\
510 return\n\
511 }\n\
513 # If the character was a pound, drag it all the way to the left margin\n\
514 if ($2 == \"#\") {\n\
515 replace_range(lineStart, $1, \"\")\n\
516 return\n\
517 }\n\
519 # Find the position on which to base the indent\n\
520 indent = cFindSmartIndentDist($1 - 1, \"noContinue\")\n\
521 if (indent == -1)\n\
522 return\n\
524 # Adjust the indent if it's a right brace (left needs no adjustment)\n\
525 if ($2 == \"}\") {\n\
526 indent -= defaultIndent($cIndentDist)\n\
527 if (indent < 0)\n\
528 indent = 0\n\
529 }\n\
531 # Replace the current indent with the new indent string\n\
532 insertStr = makeIndentString(indent)\n\
533 replace_range(lineStart, $1, insertStr)\n\
534 }\n\
536 #\n\
537 # Find Smart Indent Distance for a newline character inserted at $1,\n\
538 # or return -1 to give up. Adding the optional argument \"noContinue\"\n\
539 # will stop the routine from inserting line continuation indents\n\
540 #\n\
541 define cFindSmartIndentDist {\n\
543 # Find a known good indent to base the new indent upon\n\
544 anchorPos = cFindIndentAnchorPoint($1)\n\
545 if (anchorPos == -1)\n\
546 return -1\n\
548 # Find the indentation of that line\n\
549 anchorIndent = measureIndent(anchorPos)\n\
551 # Look for special keywords which affect indent (for, if, else while, do)\n\
552 # and modify the continuation indent distance to the normal indent\n\
553 # distance when a completed statement of this type occupies the line.\n\
554 if ($n_args >= 2 && $2 == \"noContinue\") {\n\
555 continueIndent = 0\n\
556 $allowSemi = 0\n\
557 } else\n\
558 continueIndent = cCalcContinueIndent(anchorPos, $1)\n\
560 # Move forward from anchor point, ignoring comments and blank lines,\n\
561 # remembering the last non-white, non-comment character. If $1 is\n\
562 # in the middle of a comment, give up\n\
563 lastChar = get_character(anchorPos)\n\
564 if (anchorPos < $1) {\n\
565 for (i=anchorPos;;) {\n\
566 i = cSkipBlankSpace(i, $1, 1)\n\
567 if (i == -1)\n\
568 return -1\n\
569 if (i >= $1)\n\
570 break\n\
571 lastChar = get_character(i++)\n\
572 }\n\
573 }\n\
575 # Return the new indent based on the type of the last character.\n\
576 # In a for stmt, however, last character may be a semicolon and not\n\
577 # signal the end of the statement\n\
578 if (lastChar == \"{\")\n\
579 return anchorIndent + defaultIndent($cIndentDist)\n\
580 else if (lastChar == \"}\")\n\
581 return anchorIndent\n\
582 else if (lastChar == \";\") {\n\
583 if ($allowSemi)\n\
584 return anchorIndent + continueIndent\n\
585 else\n\
586 return anchorIndent\n\
587 } else if (lastChar == \":\" && get_range(anchorPos, anchorPos+4) == \"case\")\n\
588 return anchorIndent + defaultIndent($cIndentDist)\n\
589 return anchorIndent + continueIndent\n\
590 }\n\
592 #\n\
593 # Calculate the continuation indent distance for statements not ending in\n\
594 # semicolons or braces. This is not necessarily $continueIndent. It may\n\
595 # be adjusted if the statement contains if, while, for, or else.\n\
596 #\n\
597 # As a side effect, also return $allowSemi to help distinguish statements\n\
598 # which might contain an embedded semicolon, which should not be interpreted\n\
599 # as an end of statement character.\n\
600 #\n\
601 define cCalcContinueIndent {\n\
603 anchorPos = $1\n\
604 maxPos = $2\n\
606 # Figure out if the anchor is on a keyword which changes indent. A special\n\
607 # case is made for elses nested in after braces\n\
608 anchorIsFor = 0\n\
609 $allowSemi = 0\n\
610 if (get_character(anchorPos) == \"}\") {\n\
611 for (i=anchorPos+1; i<maxPos; i++) {\n\
612 c = get_character(i)\n\
613 if (c != \" \" && c != \"\\t\")\n\
614 break\n\
615 }\n\
616 if (get_range(i, i+4) == \"else\") {\n\
617 keywordEnd = i + 4\n\
618 needsBalancedParens = 0\n\
619 } else\n\
620 return defaultContIndent($cContinuationIndent)\n\
621 } else if (get_range(anchorPos, anchorPos + 4) == \"else\") {\n\
622 keywordEnd = anchorPos + 4\n\
623 needsBalancedParens = 0\n\
624 } else if (get_range(anchorPos, anchorPos + 2) == \"do\") {\n\
625 keywordEnd = anchorPos + 2\n\
626 needsBalancedParens = 0\n\
627 } else if (get_range(anchorPos, anchorPos + 3) == \"for\") {\n\
628 keywordEnd = anchorPos + 3\n\
629 anchorIsFor = 1\n\
630 needsBalancedParens = 1\n\
631 } else if (get_range(anchorPos, anchorPos + 2) == \"if\") {\n\
632 keywordEnd = anchorPos + 2\n\
633 needsBalancedParens = 1\n\
634 } else if (get_range(anchorPos, anchorPos + 5) == \"while\") {\n\
635 keywordEnd = anchorPos + 5\n\
636 needsBalancedParens = 1\n\
637 } else\n\
638 return defaultContIndent($cContinuationIndent)\n\
640 # If the keyword must be followed balanced parenthesis, find the end of\n\
641 # the statement by following balanced parens. If the parens aren't\n\
642 # balanced by maxPos, continue the condition. In the special case of\n\
643 # the for keyword, a semicolon can end the line and the caller should be\n\
644 # signaled to allow that\n\
645 if (needsBalancedParens) {\n\
646 stmtEnd = findBalancingParen(keywordEnd, maxPos)\n\
647 if (stmtEnd == -1) {\n\
648 $allowSemi = anchorIsFor\n\
649 return defaultContIndent($cContinuationIndent)\n\
650 }\n\
651 } else\n\
652 stmtEnd = keywordEnd\n\
654 # check if the statement ends the line\n\
655 lineEnd = cSkipBlankSpace(stmtEnd, maxPos, 0)\n\
656 if (lineEnd == -1) # ends in comment or preproc\n\
657 return -1\n\
658 if (lineEnd == maxPos) # maxPos happens at stmt end\n\
659 return defaultIndent($cIndentDist)\n\
660 c = get_character(lineEnd)\n\
661 if (c != \"\\n\") # something past last paren on line,\n\
662 return defaultIndent($cIndentDist) # probably quoted or extra braces\n\
664 # stmt contintinues beyond matching paren && newline, we're in\n\
665 # the conditional part, calculate the continue indent distance\n\
666 # recursively, based on the anchor point of the new line\n\
667 newAnchor = cSkipBlankSpace(lineEnd+1, maxPos, 1)\n\
668 if (newAnchor == -1)\n\
669 return -1\n\
670 if (newAnchor == maxPos)\n\
671 return defaultIndent($cIndentDist)\n\
672 return cCalcContinueIndent(newAnchor, maxPos) + defaultIndent($cIndentDist)\n\
673 }\n\
677 ** Turn on smart-indent (well almost). Unfortunately, this doesn't do
678 ** everything. It requires that the smart indent callback (SmartIndentCB)
679 ** is already attached to all of the text widgets in the window, and that the
680 ** smartIndent resource must be turned on in the widget. These are done
681 ** separately, because they are required per-text widget, and therefore must
682 ** be repeated whenever a new text widget is created within this window
683 ** (a split-window command).
685 void BeginSmartIndent(WindowInfo *window, int warn)
687 windowSmartIndentData *winData;
688 smartIndentRec *indentMacros;
689 char *modeName, *stoppedAt, *errMsg;
690 static int initialized;
692 /* Find the window's language mode. If none is set, warn the user */
693 modeName = LanguageModeName(window->languageMode);
694 if (modeName == NULL)
696 if (warn)
698 DialogF(DF_WARN, window->shell, 1, "Smart Indent",
699 "No language-specific mode has been set for this file.\n\n"
700 "To use smart indent in this window, please select a\n"
701 "language from the Preferences -> Language Modes menu.",
702 "Dismiss");
704 return;
707 /* Look up the appropriate smart-indent macros for the language */
708 indentMacros = findIndentSpec(modeName);
709 if (indentMacros == NULL)
711 if (warn)
713 DialogF(DF_WARN, window->shell, 1, "Smart Indent",
714 "Smart indent is not available in languagemode\n%s.\n\n"
715 "You can create new smart indent macros in the\n"
716 "Preferences -> Default Settings -> Smart Indent\n"
717 "dialog, or choose a different language mode from:\n"
718 "Preferences -> Language Mode.", "Dismiss", modeName);
720 return;
723 /* Make sure that the initial macro file is loaded before we execute
724 any of the smart-indent macros. Smart-indent macros may reference
725 routines defined in that file. */
726 ReadMacroInitFile(window);
728 /* Compile and run the common and language-specific initialization macros
729 (Note that when these return, the immediate commands in the file have not
730 necessarily been executed yet. They are only SCHEDULED for execution) */
731 if (!initialized) {
732 if (!ReadMacroString(window, CommonMacros,
733 "smart indent common initialization macros"))
734 return;
735 initialized = True;
737 if (indentMacros->initMacro != NULL) {
738 if (!ReadMacroString(window, indentMacros->initMacro,
739 "smart indent initialization macro"))
740 return;
743 /* Compile the newline and modify macros and attach them to the window */
744 winData = (windowSmartIndentData *)XtMalloc(sizeof(windowSmartIndentData));
745 winData->inNewLineMacro = 0;
746 winData->inModMacro = 0;
747 winData->newlineMacro = ParseMacro(indentMacros->newlineMacro, &errMsg,
748 &stoppedAt);
749 if (winData->newlineMacro == NULL) {
750 ParseError(window->shell, indentMacros->newlineMacro, stoppedAt,
751 "newline macro", errMsg);
752 return;
754 if (indentMacros->modMacro == NULL)
755 winData->modMacro = NULL;
756 else {
757 winData->modMacro = ParseMacro(indentMacros->modMacro, &errMsg,
758 &stoppedAt);
759 if (winData->modMacro == NULL) {
760 ParseError(window->shell, indentMacros->modMacro, stoppedAt,
761 "smart indent modify macro", errMsg);
762 return;
765 window->smartIndentData = (void *)winData;
768 void EndSmartIndent(WindowInfo *window)
770 windowSmartIndentData *winData =
771 (windowSmartIndentData *)window->smartIndentData;
773 if (winData == NULL)
774 return;
776 /* Free programs and allocated data */
777 if (winData->modMacro != NULL)
778 FreeProgram(winData->modMacro);
779 FreeProgram(winData->newlineMacro);
780 XtFree((char *)winData);
781 window->smartIndentData = NULL;
785 ** Returns true if there are smart indent macros for a named language
787 int SmartIndentMacrosAvailable(char *languageModeName)
789 return findIndentSpec(languageModeName) != NULL;
793 ** Attaches to the text widget's smart-indent callback to invoke a user
794 ** defined macro when the text widget requires an indent (not just when the
795 ** user types a newline, but also when the widget does an auto-wrap with
796 ** auto-indent on), or the user types some other character.
798 void SmartIndentCB(Widget w, XtPointer clientData, XtPointer callData)
800 WindowInfo *window = (WindowInfo *)clientData;
801 smartIndentCBStruct *cbInfo = (smartIndentCBStruct *)callData;
803 if (window->smartIndentData == NULL)
804 return;
805 if (cbInfo->reason == CHAR_TYPED)
806 executeModMacro(window, cbInfo);
807 else if (cbInfo->reason == NEWLINE_INDENT_NEEDED)
808 executeNewlineMacro(window, cbInfo);
812 ** Run the newline macro with information from the smart-indent callback
813 ** structure passed by the widget
815 static void executeNewlineMacro(WindowInfo *window, smartIndentCBStruct *cbInfo)
817 windowSmartIndentData *winData =
818 (windowSmartIndentData *)window->smartIndentData;
819 /* posValue probably shouldn't be static due to re-entrance issues <slobasso> */
820 static DataValue posValue = {INT_TAG, {0}};
821 DataValue result;
822 RestartData *continuation;
823 char *errMsg;
824 int stat;
826 /* Beware of recursion: the newline macro may insert a string which
827 triggers the newline macro to be called again and so on. Newline
828 macros shouldn't insert strings, but nedit must not crash either if
829 they do. */
830 if (winData->inNewLineMacro)
831 return;
833 /* Call newline macro with the position at which to add newline/indent */
834 posValue.val.n = cbInfo->pos;
835 ++(winData->inNewLineMacro);
836 stat = ExecuteMacro(window, winData->newlineMacro, 1, &posValue, &result,
837 &continuation, &errMsg);
839 /* Don't allow preemption or time limit. Must get return value */
840 while (stat == MACRO_TIME_LIMIT)
841 stat = ContinueMacro(continuation, &result, &errMsg);
843 --(winData->inNewLineMacro);
844 /* Collect Garbage. Note that the mod macro does not collect garbage,
845 (because collecting per-line is more efficient than per-character)
846 but GC now depends on the newline macro being mandatory */
847 SafeGC();
849 /* Process errors in macro execution */
850 if (stat == MACRO_PREEMPT || stat == MACRO_ERROR)
852 DialogF(DF_ERR, window->shell, 1, "Smart Indent",
853 "Error in smart indent macro:\n%s", "Dismiss",
854 stat == MACRO_ERROR
855 ? errMsg
856 : "dialogs and shell commands not permitted");
857 EndSmartIndent(window);
858 return;
861 /* Validate and return the result */
862 if (result.tag != INT_TAG || result.val.n < -1 || result.val.n > 1000)
864 DialogF(DF_ERR, window->shell, 1, "Smart Indent",
865 "Smart indent macros must return\ninteger indent distance",
866 "Dismiss");
867 EndSmartIndent(window);
868 return;
871 cbInfo->indentRequest = result.val.n;
875 Boolean InSmartIndentMacros(WindowInfo *window) {
876 windowSmartIndentData *winData =
877 (windowSmartIndentData *)window->smartIndentData;
879 return((winData && (winData->inModMacro || winData->inNewLineMacro)));
883 ** Run the modification macro with information from the smart-indent callback
884 ** structure passed by the widget
886 static void executeModMacro(WindowInfo *window,smartIndentCBStruct *cbInfo)
888 windowSmartIndentData *winData =
889 (windowSmartIndentData *)window->smartIndentData;
890 /* args probably shouldn't be static due to future re-entrance issues <slobasso> */
891 static DataValue args[2] = {{INT_TAG, {0}}, {STRING_TAG, {0}}};
892 /* after 5.2 release remove inModCB and use new winData->inModMacro value */
893 static int inModCB = False;
894 DataValue result;
895 RestartData *continuation;
896 char *errMsg;
897 int stat;
899 /* Check for inappropriate calls and prevent re-entering if the macro
900 makes a buffer modification */
901 if (winData == NULL || winData->modMacro == NULL || inModCB)
902 return;
904 /* Call modification macro with the position of the modification,
905 and the character(s) inserted. Don't allow
906 preemption or time limit. Execution must not overlap or re-enter */
907 args[0].val.n = cbInfo->pos;
908 args[1].val.str = AllocString(strlen(cbInfo->charsTyped) + 1);
909 strcpy(args[1].val.str, cbInfo->charsTyped);
911 inModCB = True;
912 ++(winData->inModMacro);
914 stat = ExecuteMacro(window, winData->modMacro, 3, args, &result,
915 &continuation, &errMsg);
916 while (stat == MACRO_TIME_LIMIT)
917 stat = ContinueMacro(continuation, &result, &errMsg);
919 --(winData->inModMacro);
920 inModCB = False;
922 /* Process errors in macro execution */
923 if (stat == MACRO_PREEMPT || stat == MACRO_ERROR)
925 DialogF(DF_ERR, window->shell, 1, "Smart Indent",
926 "Error in smart indent modification macro:\n%s", "Dismiss",
927 stat == MACRO_ERROR
928 ? errMsg
929 : "dialogs and shell commands not permitted");
930 EndSmartIndent(window);
931 return;
935 void EditSmartIndentMacros(WindowInfo *window)
937 #define BORDER 4
938 Widget form, lmOptMenu, lmForm, lmBtn;
939 Widget okBtn, applyBtn, checkBtn, deleteBtn, commonBtn;
940 Widget dismissBtn, helpBtn, restoreBtn, pane;
941 Widget initForm, newlineForm, modifyForm;
942 Widget initLbl, newlineLbl, modifyLbl;
943 XmString s1;
944 char *lmName;
945 Arg args[20];
946 int n;
948 /* if the dialog is already displayed, just pop it to the top and return */
949 if (SmartIndentDialog.shell != NULL) {
950 RaiseShellWindow(SmartIndentDialog.shell);
951 return;
954 if (LanguageModeName(0) == NULL)
956 DialogF(DF_WARN, window->shell, 1, "Language Mode",
957 "No Language Modes defined", "Dismiss");
958 return;
961 /* Decide on an initial language mode */
962 lmName = LanguageModeName(window->languageMode == PLAIN_LANGUAGE_MODE ? 0 :
963 window->languageMode);
964 SmartIndentDialog.langModeName = XtNewString(lmName);
966 /* Create a form widget in an application shell */
967 n = 0;
968 XtSetArg(args[n], XmNdeleteResponse, XmDO_NOTHING); n++;
969 XtSetArg(args[n], XmNiconName, "NEdit Smart Indent Macros"); n++;
970 XtSetArg(args[n], XmNtitle, "Program Smart Indent Macros"); n++;
971 SmartIndentDialog.shell = CreateShellWithBestVis(APP_NAME, APP_CLASS,
972 applicationShellWidgetClass, TheDisplay, args, n);
973 AddSmallIcon(SmartIndentDialog.shell);
974 form = XtVaCreateManagedWidget("editSmartIndentMacros", xmFormWidgetClass,
975 SmartIndentDialog.shell, XmNautoUnmanage, False,
976 XmNresizePolicy, XmRESIZE_NONE, NULL);
977 XtAddCallback(form, XmNdestroyCallback, destroyCB, NULL);
978 AddMotifCloseCallback(SmartIndentDialog.shell, dismissCB, NULL);
980 lmForm = XtVaCreateManagedWidget("lmForm", xmFormWidgetClass,
981 form,
982 XmNleftAttachment, XmATTACH_POSITION,
983 XmNleftPosition, 1,
984 XmNtopAttachment, XmATTACH_POSITION,
985 XmNtopPosition, 1,
986 XmNrightAttachment, XmATTACH_POSITION,
987 XmNrightPosition, 99, NULL);
989 SmartIndentDialog.lmPulldown = CreateLanguageModeMenu(lmForm, langModeCB,
990 NULL);
991 n = 0;
992 XtSetArg(args[n], XmNspacing, 0); n++;
993 XtSetArg(args[n], XmNmarginWidth, 0); n++;
994 XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
995 XtSetArg(args[n], XmNleftAttachment, XmATTACH_POSITION); n++;
996 XtSetArg(args[n], XmNleftPosition, 50); n++;
997 XtSetArg(args[n], XmNsubMenuId, SmartIndentDialog.lmPulldown); n++;
998 lmOptMenu = XmCreateOptionMenu(lmForm, "langModeOptMenu", args, n);
999 XtManageChild(lmOptMenu);
1000 SmartIndentDialog.lmOptMenu = lmOptMenu;
1002 XtVaCreateManagedWidget("lmLbl", xmLabelGadgetClass, lmForm,
1003 XmNlabelString, s1=XmStringCreateSimple("Language Mode:"),
1004 XmNmnemonic, 'L',
1005 XmNuserData, XtParent(SmartIndentDialog.lmOptMenu),
1006 XmNalignment, XmALIGNMENT_END,
1007 XmNrightAttachment, XmATTACH_POSITION,
1008 XmNrightPosition, 50,
1009 XmNtopAttachment, XmATTACH_FORM,
1010 XmNbottomAttachment, XmATTACH_OPPOSITE_WIDGET,
1011 XmNbottomWidget, lmOptMenu, NULL);
1012 XmStringFree(s1);
1014 lmBtn = XtVaCreateManagedWidget("lmBtn", xmPushButtonWidgetClass, lmForm,
1015 XmNlabelString, s1=MKSTRING("Add / Modify\nLanguage Mode..."),
1016 XmNmnemonic, 'A',
1017 XmNrightAttachment, XmATTACH_FORM,
1018 XmNtopAttachment, XmATTACH_FORM, NULL);
1019 XtAddCallback(lmBtn, XmNactivateCallback, lmDialogCB, NULL);
1020 XmStringFree(s1);
1022 commonBtn = XtVaCreateManagedWidget("commonBtn", xmPushButtonWidgetClass,
1023 lmForm,
1024 XmNlabelString, s1=MKSTRING("Common / Shared\nInitialization..."),
1025 XmNmnemonic, 'C',
1026 XmNleftAttachment, XmATTACH_FORM,
1027 XmNtopAttachment, XmATTACH_FORM, NULL);
1028 XtAddCallback(commonBtn, XmNactivateCallback, commonDialogCB, NULL);
1029 XmStringFree(s1);
1031 okBtn = XtVaCreateManagedWidget("ok", xmPushButtonWidgetClass, form,
1032 XmNlabelString, s1=XmStringCreateSimple("OK"),
1033 XmNleftAttachment, XmATTACH_POSITION,
1034 XmNleftPosition, 1,
1035 XmNrightAttachment, XmATTACH_POSITION,
1036 XmNrightPosition, 13,
1037 XmNbottomAttachment, XmATTACH_FORM,
1038 XmNbottomOffset, BORDER, NULL);
1039 XtAddCallback(okBtn, XmNactivateCallback, okCB, NULL);
1040 XmStringFree(s1);
1042 applyBtn = XtVaCreateManagedWidget("apply", xmPushButtonWidgetClass, form,
1043 XmNlabelString, s1=XmStringCreateSimple("Apply"),
1044 XmNmnemonic, 'y',
1045 XmNleftAttachment, XmATTACH_POSITION,
1046 XmNleftPosition, 13,
1047 XmNrightAttachment, XmATTACH_POSITION,
1048 XmNrightPosition, 26,
1049 XmNbottomAttachment, XmATTACH_FORM,
1050 XmNbottomOffset, BORDER, NULL);
1051 XtAddCallback(applyBtn, XmNactivateCallback, applyCB, NULL);
1052 XmStringFree(s1);
1054 checkBtn = XtVaCreateManagedWidget("check", xmPushButtonWidgetClass, form,
1055 XmNlabelString, s1=XmStringCreateSimple("Check"),
1056 XmNmnemonic, 'k',
1057 XmNleftAttachment, XmATTACH_POSITION,
1058 XmNleftPosition, 26,
1059 XmNrightAttachment, XmATTACH_POSITION,
1060 XmNrightPosition, 39,
1061 XmNbottomAttachment, XmATTACH_FORM,
1062 XmNbottomOffset, BORDER, NULL);
1063 XtAddCallback(checkBtn, XmNactivateCallback, checkCB, NULL);
1064 XmStringFree(s1);
1066 deleteBtn = XtVaCreateManagedWidget("delete", xmPushButtonWidgetClass, form,
1067 XmNlabelString, s1=XmStringCreateSimple("Delete"),
1068 XmNmnemonic, 'D',
1069 XmNleftAttachment, XmATTACH_POSITION,
1070 XmNleftPosition, 39,
1071 XmNrightAttachment, XmATTACH_POSITION,
1072 XmNrightPosition, 52,
1073 XmNbottomAttachment, XmATTACH_FORM,
1074 XmNbottomOffset, BORDER, NULL);
1075 XtAddCallback(deleteBtn, XmNactivateCallback, deleteCB, NULL);
1076 XmStringFree(s1);
1078 restoreBtn = XtVaCreateManagedWidget("restore", xmPushButtonWidgetClass, form,
1079 XmNlabelString, s1=XmStringCreateSimple("Restore Defaults"),
1080 XmNmnemonic, 'f',
1081 XmNleftAttachment, XmATTACH_POSITION,
1082 XmNleftPosition, 52,
1083 XmNrightAttachment, XmATTACH_POSITION,
1084 XmNrightPosition, 73,
1085 XmNbottomAttachment, XmATTACH_FORM,
1086 XmNbottomOffset, BORDER, NULL);
1087 XtAddCallback(restoreBtn, XmNactivateCallback, restoreCB, NULL);
1088 XmStringFree(s1);
1090 dismissBtn = XtVaCreateManagedWidget("dismiss", xmPushButtonWidgetClass,
1091 form,
1092 XmNlabelString, s1=XmStringCreateSimple("Dismiss"),
1093 XmNleftAttachment, XmATTACH_POSITION,
1094 XmNleftPosition, 73,
1095 XmNrightAttachment, XmATTACH_POSITION,
1096 XmNrightPosition, 86,
1097 XmNbottomAttachment, XmATTACH_FORM,
1098 XmNbottomOffset, BORDER, NULL);
1099 XtAddCallback(dismissBtn, XmNactivateCallback, dismissCB, NULL);
1100 XmStringFree(s1);
1102 helpBtn = XtVaCreateManagedWidget("help", xmPushButtonWidgetClass,
1103 form,
1104 XmNlabelString, s1=XmStringCreateSimple("Help"),
1105 XmNmnemonic, 'H',
1106 XmNleftAttachment, XmATTACH_POSITION,
1107 XmNleftPosition, 86,
1108 XmNrightAttachment, XmATTACH_POSITION,
1109 XmNrightPosition, 99,
1110 XmNbottomAttachment, XmATTACH_FORM,
1111 XmNbottomOffset, BORDER, NULL);
1112 XtAddCallback(helpBtn, XmNactivateCallback, helpCB, NULL);
1113 XmStringFree(s1);
1115 pane = XtVaCreateManagedWidget("pane", xmPanedWindowWidgetClass, form,
1116 XmNleftAttachment, XmATTACH_POSITION,
1117 XmNleftPosition, 1,
1118 XmNrightAttachment, XmATTACH_POSITION,
1119 XmNrightPosition, 99,
1120 XmNtopAttachment, XmATTACH_WIDGET,
1121 XmNtopWidget, lmForm,
1122 XmNbottomAttachment, XmATTACH_WIDGET,
1123 XmNbottomWidget, okBtn, NULL);
1124 /* XmNmarginWidth, 0, XmNmarginHeight, 0, XmNseparatorOn, False,
1125 XmNspacing, 3, XmNsashIndent, -2, */
1127 initForm = XtVaCreateManagedWidget("initForm", xmFormWidgetClass,
1128 pane, NULL);
1129 initLbl = XtVaCreateManagedWidget("initLbl", xmLabelGadgetClass, initForm,
1130 XmNlabelString, s1=XmStringCreateSimple(
1131 "Language Specific Initialization Macro Commands and Definitions"),
1132 XmNmnemonic, 'I', NULL);
1133 XmStringFree(s1);
1134 n = 0;
1135 XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++;
1136 XtSetArg(args[n], XmNrows, 5); n++;
1137 XtSetArg(args[n], XmNcolumns, 80); n++;
1138 XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
1139 XtSetArg(args[n], XmNtopWidget, initLbl); n++;
1140 XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
1141 XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
1142 XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
1143 SmartIndentDialog.initMacro = XmCreateScrolledText(initForm,
1144 "initMacro", args, n);
1145 AddMouseWheelSupport(SmartIndentDialog.initMacro);
1146 XtManageChild(SmartIndentDialog.initMacro);
1147 RemapDeleteKey(SmartIndentDialog.initMacro);
1148 XtVaSetValues(initLbl, XmNuserData, SmartIndentDialog.initMacro, NULL);
1150 newlineForm = XtVaCreateManagedWidget("newlineForm", xmFormWidgetClass,
1151 pane, NULL);
1152 newlineLbl = XtVaCreateManagedWidget("newlineLbl", xmLabelGadgetClass,
1153 newlineForm,
1154 XmNlabelString, s1=XmStringCreateSimple("Newline Macro"),
1155 XmNmnemonic, 'N', NULL);
1156 XmStringFree(s1);
1157 XtVaCreateManagedWidget("newlineArgsLbl", xmLabelGadgetClass,
1158 newlineForm, XmNalignment, XmALIGNMENT_END,
1159 XmNlabelString, s1=XmStringCreateSimple(
1160 "($1 is insert position, return indent request or -1)"),
1161 XmNrightAttachment, XmATTACH_FORM, NULL);
1162 XmStringFree(s1);
1163 n = 0;
1164 XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++;
1165 XtSetArg(args[n], XmNrows, 5); n++;
1166 XtSetArg(args[n], XmNcolumns, 80); n++;
1167 XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
1168 XtSetArg(args[n], XmNtopWidget, newlineLbl); n++;
1169 XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
1170 XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
1171 XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
1172 SmartIndentDialog.newlineMacro = XmCreateScrolledText(newlineForm,
1173 "newlineMacro", args, n);
1174 AddMouseWheelSupport(SmartIndentDialog.newlineMacro);
1175 XtManageChild(SmartIndentDialog.newlineMacro);
1176 RemapDeleteKey(SmartIndentDialog.newlineMacro);
1177 XtVaSetValues(newlineLbl, XmNuserData, SmartIndentDialog.newlineMacro,NULL);
1179 modifyForm = XtVaCreateManagedWidget("modifyForm", xmFormWidgetClass,
1180 pane, NULL);
1181 modifyLbl = XtVaCreateManagedWidget("modifyLbl", xmLabelGadgetClass,
1182 modifyForm, XmNlabelString,s1=XmStringCreateSimple("Type-in Macro"),
1183 XmNmnemonic, 'M', NULL);
1184 XmStringFree(s1);
1185 XtVaCreateManagedWidget("modifyArgsLbl", xmLabelGadgetClass,
1186 modifyForm, XmNalignment, XmALIGNMENT_END,
1187 XmNlabelString, s1=XmStringCreateSimple(
1188 "($1 is position, $2 is character just inserted)"),
1189 XmNrightAttachment, XmATTACH_FORM, NULL);
1190 XmStringFree(s1);
1191 n = 0;
1192 XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++;
1193 XtSetArg(args[n], XmNrows, 5); n++;
1194 XtSetArg(args[n], XmNcolumns, 80); n++;
1195 XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
1196 XtSetArg(args[n], XmNtopWidget, modifyLbl); n++;
1197 XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
1198 XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
1199 XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
1200 SmartIndentDialog.modMacro = XmCreateScrolledText(modifyForm,
1201 "modifyMacro", args, n);
1202 AddMouseWheelSupport(SmartIndentDialog.modMacro);
1203 XtManageChild(SmartIndentDialog.modMacro);
1204 RemapDeleteKey(SmartIndentDialog.modMacro);
1205 XtVaSetValues(modifyLbl, XmNuserData, SmartIndentDialog.modMacro, NULL);
1207 /* Set initial default button */
1208 XtVaSetValues(form, XmNdefaultButton, okBtn, NULL);
1209 XtVaSetValues(form, XmNcancelButton, dismissBtn, NULL);
1211 /* Handle mnemonic selection of buttons and focus to dialog */
1212 AddDialogMnemonicHandler(form, FALSE);
1214 /* Fill in the dialog information for the selected language mode */
1215 setSmartIndentDialogData(findIndentSpec(lmName));
1216 SetLangModeMenu(SmartIndentDialog.lmOptMenu,SmartIndentDialog.langModeName);
1218 /* Realize all of the widgets in the new dialog */
1219 RealizeWithoutForcingPosition(SmartIndentDialog.shell);
1222 static void destroyCB(Widget w, XtPointer clientData, XtPointer callData)
1224 XtFree(SmartIndentDialog.langModeName);
1225 SmartIndentDialog.shell = NULL;
1228 static void langModeCB(Widget w, XtPointer clientData, XtPointer callData)
1230 char *modeName;
1231 int i, resp;
1232 static smartIndentRec emptyIndentSpec = {NULL, NULL, NULL, NULL};
1233 smartIndentRec *oldMacros, *newMacros;
1235 /* Get the newly selected mode name. If it's the same, do nothing */
1236 XtVaGetValues(w, XmNuserData, &modeName, NULL);
1237 if (!strcmp(modeName, SmartIndentDialog.langModeName))
1238 return;
1240 /* Find the original macros */
1241 for (i=0; i<NSmartIndentSpecs; i++)
1242 if (!strcmp(SmartIndentDialog.langModeName,SmartIndentSpecs[i]->lmName))
1243 break;
1244 oldMacros = i == NSmartIndentSpecs ? &emptyIndentSpec : SmartIndentSpecs[i];
1246 /* Check if the macros have changed, if so allow user to apply, discard,
1247 or cancel */
1248 newMacros = getSmartIndentDialogData();
1249 if (indentSpecsDiffer(oldMacros, newMacros))
1251 resp = DialogF(DF_QUES, SmartIndentDialog.shell, 3, "Smart Indent",
1252 "Smart indent macros for language mode\n"
1253 "%s were changed. Apply changes?", "Apply", "Discard",
1254 "Cancel", SmartIndentDialog.langModeName);
1256 if (resp == 3)
1258 SetLangModeMenu(SmartIndentDialog.lmOptMenu,
1259 SmartIndentDialog.langModeName);
1260 return;
1261 } else if (resp == 1)
1263 if (checkSmartIndentDialogData())
1265 if (oldMacros == &emptyIndentSpec)
1267 SmartIndentSpecs[NSmartIndentSpecs++]
1268 = copyIndentSpec(newMacros);
1269 } else
1271 freeIndentSpec(oldMacros);
1272 SmartIndentSpecs[i] = copyIndentSpec(newMacros);
1274 } else
1276 SetLangModeMenu(SmartIndentDialog.lmOptMenu,
1277 SmartIndentDialog.langModeName);
1278 return;
1282 freeIndentSpec(newMacros);
1284 /* Fill the dialog with the new language mode information */
1285 SmartIndentDialog.langModeName = XtNewString(modeName);
1286 setSmartIndentDialogData(findIndentSpec(modeName));
1289 static void lmDialogCB(Widget w, XtPointer clientData, XtPointer callData)
1291 EditLanguageModes();
1294 static void commonDialogCB(Widget w, XtPointer clientData, XtPointer callData)
1296 EditCommonSmartIndentMacro();
1299 static void okCB(Widget w, XtPointer clientData, XtPointer callData)
1301 /* change the macro */
1302 if (!updateSmartIndentData())
1303 return;
1305 /* pop down and destroy the dialog */
1306 XtDestroyWidget(SmartIndentDialog.shell);
1309 static void applyCB(Widget w, XtPointer clientData, XtPointer callData)
1311 /* change the patterns */
1312 updateSmartIndentData();
1315 static void checkCB(Widget w, XtPointer clientData, XtPointer callData)
1317 if (checkSmartIndentDialogData())
1318 DialogF(DF_INF, SmartIndentDialog.shell, 1, "Macro compiled",
1319 "Macros compiled without error", "Dismiss");
1322 static void restoreCB(Widget w, XtPointer clientData, XtPointer callData)
1324 int i;
1325 smartIndentRec *defaultIS;
1327 /* Find the default indent spec */
1328 for (i=0; i<N_DEFAULT_INDENT_SPECS; i++)
1330 if (!strcmp(SmartIndentDialog.langModeName,
1331 DefaultIndentSpecs[i].lmName))
1333 break;
1337 if (i == N_DEFAULT_INDENT_SPECS)
1339 DialogF(DF_WARN, SmartIndentDialog.shell, 1, "Smart Indent",
1340 "There are no default indent macros\nfor language mode %s",
1341 "Dismiss", SmartIndentDialog.langModeName);
1342 return;
1344 defaultIS = &DefaultIndentSpecs[i];
1346 if (DialogF(DF_WARN, SmartIndentDialog.shell, 2, "Discard Changes",
1347 "Are you sure you want to discard\n"
1348 "all changes to smart indent macros\n"
1349 "for language mode %s?", "Discard", "Cancel",
1350 SmartIndentDialog.langModeName) == 2)
1352 return;
1355 /* if a stored version of the indent macros exist, replace them, if not,
1356 add a new one */
1357 for (i=0; i<NSmartIndentSpecs; i++)
1358 if (!strcmp(SmartIndentDialog.langModeName,SmartIndentSpecs[i]->lmName))
1359 break;
1360 if (i < NSmartIndentSpecs) {
1361 freeIndentSpec(SmartIndentSpecs[i]);
1362 SmartIndentSpecs[i] = copyIndentSpec(defaultIS);
1363 } else
1364 SmartIndentSpecs[NSmartIndentSpecs++] = copyIndentSpec(defaultIS);
1366 /* Update the dialog */
1367 setSmartIndentDialogData(defaultIS);
1370 static void deleteCB(Widget w, XtPointer clientData, XtPointer callData)
1372 int i;
1374 if (DialogF(DF_WARN, SmartIndentDialog.shell, 2, "Delete Macros",
1375 "Are you sure you want to delete smart indent\n"
1376 "macros for language mode %s?", "Yes, Delete", "Cancel",
1377 SmartIndentDialog.langModeName) == 2)
1379 return;
1382 /* if a stored version of the pattern set exists, delete it from the list */
1383 for (i=0; i<NSmartIndentSpecs; i++)
1384 if (!strcmp(SmartIndentDialog.langModeName,SmartIndentSpecs[i]->lmName))
1385 break;
1386 if (i < NSmartIndentSpecs) {
1387 freeIndentSpec(SmartIndentSpecs[i]);
1388 memmove(&SmartIndentSpecs[i], &SmartIndentSpecs[i+1],
1389 (NSmartIndentSpecs-1 - i) * sizeof(smartIndentRec *));
1390 NSmartIndentSpecs--;
1393 /* Clear out the dialog */
1394 setSmartIndentDialogData(NULL);
1397 static void dismissCB(Widget w, XtPointer clientData, XtPointer callData)
1399 /* pop down and destroy the dialog */
1400 XtDestroyWidget(SmartIndentDialog.shell);
1403 static void helpCB(Widget w, XtPointer clientData, XtPointer callData)
1405 Help(HELP_SMART_INDENT);
1408 static int checkSmartIndentDialogData(void)
1410 char *widgetText, *errMsg, *stoppedAt;
1411 Program *prog;
1413 /* Check the initialization macro */
1414 if (!TextWidgetIsBlank(SmartIndentDialog.initMacro)) {
1415 widgetText =ensureNewline(XmTextGetString(SmartIndentDialog.initMacro));
1416 if (!CheckMacroString(SmartIndentDialog.shell, widgetText,
1417 "initialization macro", &stoppedAt)) {
1418 XmTextSetInsertionPosition(SmartIndentDialog.initMacro,
1419 stoppedAt - widgetText);
1420 XmProcessTraversal(SmartIndentDialog.initMacro, XmTRAVERSE_CURRENT);
1421 XtFree(widgetText);
1422 return False;
1424 XtFree(widgetText);
1427 /* Test compile the newline macro */
1428 if (TextWidgetIsBlank(SmartIndentDialog.newlineMacro))
1430 DialogF(DF_WARN, SmartIndentDialog.shell, 1, "Smart Indent",
1431 "Newline macro required", "Dismiss");
1432 return False;
1435 widgetText = ensureNewline(XmTextGetString(SmartIndentDialog.newlineMacro));
1436 prog = ParseMacro(widgetText, &errMsg, &stoppedAt);
1437 if (prog == NULL) {
1438 ParseError(SmartIndentDialog.shell, widgetText, stoppedAt,
1439 "newline macro", errMsg);
1440 XmTextSetInsertionPosition(SmartIndentDialog.newlineMacro,
1441 stoppedAt - widgetText);
1442 XmProcessTraversal(SmartIndentDialog.newlineMacro, XmTRAVERSE_CURRENT);
1443 XtFree(widgetText);
1444 return False;
1446 XtFree(widgetText);
1447 FreeProgram(prog);
1449 /* Test compile the modify macro */
1450 if (!TextWidgetIsBlank(SmartIndentDialog.modMacro)) {
1451 widgetText = ensureNewline(XmTextGetString(SmartIndentDialog.modMacro));
1452 prog = ParseMacro(widgetText, &errMsg, &stoppedAt);
1453 if (prog == NULL) {
1454 ParseError(SmartIndentDialog.shell, widgetText, stoppedAt,
1455 "modify macro", errMsg);
1456 XmTextSetInsertionPosition(SmartIndentDialog.modMacro,
1457 stoppedAt - widgetText);
1458 XmProcessTraversal(SmartIndentDialog.modMacro, XmTRAVERSE_CURRENT);
1459 XtFree(widgetText);
1460 return False;
1462 XtFree(widgetText);
1463 FreeProgram(prog);
1465 return True;
1468 static smartIndentRec *getSmartIndentDialogData(void)
1470 smartIndentRec *is;
1472 is = (smartIndentRec *)XtMalloc(sizeof(smartIndentRec));
1473 is->lmName = XtNewString(SmartIndentDialog.langModeName);
1474 is->initMacro = TextWidgetIsBlank(SmartIndentDialog.initMacro) ? NULL :
1475 ensureNewline(XmTextGetString(SmartIndentDialog.initMacro));
1476 is->newlineMacro = TextWidgetIsBlank(SmartIndentDialog.newlineMacro) ? NULL:
1477 ensureNewline(XmTextGetString(SmartIndentDialog.newlineMacro));
1478 is->modMacro = TextWidgetIsBlank(SmartIndentDialog.modMacro) ? NULL :
1479 ensureNewline(XmTextGetString(SmartIndentDialog.modMacro));
1480 return is;
1483 static void setSmartIndentDialogData(smartIndentRec *is)
1485 if (is == NULL) {
1486 XmTextSetString(SmartIndentDialog.initMacro, "");
1487 XmTextSetString(SmartIndentDialog.newlineMacro, "");
1488 XmTextSetString(SmartIndentDialog.modMacro, "");
1489 } else {
1490 if (is->initMacro == NULL)
1491 XmTextSetString(SmartIndentDialog.initMacro, "");
1492 else
1493 XmTextSetString(SmartIndentDialog.initMacro, is->initMacro);
1494 XmTextSetString(SmartIndentDialog.newlineMacro, is->newlineMacro);
1495 if (is->modMacro == NULL)
1496 XmTextSetString(SmartIndentDialog.modMacro, "");
1497 else
1498 XmTextSetString(SmartIndentDialog.modMacro, is->modMacro);
1502 void EditCommonSmartIndentMacro(void)
1504 #define VERT_BORDER 4
1505 Widget form, topLbl;
1506 Widget okBtn, applyBtn, checkBtn;
1507 Widget dismissBtn, restoreBtn;
1508 XmString s1;
1509 Arg args[20];
1510 int n;
1512 /* if the dialog is already displayed, just pop it to the top and return */
1513 if (CommonDialog.shell != NULL) {
1514 RaiseShellWindow(CommonDialog.shell);
1515 return;
1518 /* Create a form widget in an application shell */
1519 n = 0;
1520 XtSetArg(args[n], XmNdeleteResponse, XmDO_NOTHING); n++;
1521 XtSetArg(args[n], XmNiconName, "NEdit Common Smart Indent Macros"); n++;
1522 XtSetArg(args[n], XmNtitle, "Common Smart Indent Macros"); n++;
1523 CommonDialog.shell = CreateShellWithBestVis(APP_NAME, APP_CLASS,
1524 applicationShellWidgetClass, TheDisplay, args, n);
1525 AddSmallIcon(CommonDialog.shell);
1526 form = XtVaCreateManagedWidget("editCommonSIMacros", xmFormWidgetClass,
1527 CommonDialog.shell, XmNautoUnmanage, False,
1528 XmNresizePolicy, XmRESIZE_NONE, NULL);
1529 XtAddCallback(form, XmNdestroyCallback, comDestroyCB, NULL);
1530 AddMotifCloseCallback(CommonDialog.shell, comDismissCB, NULL);
1532 topLbl = XtVaCreateManagedWidget("topLbl", xmLabelGadgetClass, form,
1533 XmNlabelString, s1=XmStringCreateSimple(
1534 "Common Definitions for Smart Indent Macros"),
1535 XmNmnemonic, 'C',
1536 XmNtopAttachment, XmATTACH_FORM,
1537 XmNtopOffset, VERT_BORDER,
1538 XmNleftAttachment, XmATTACH_POSITION,
1539 XmNleftPosition, 1, NULL);
1541 okBtn = XtVaCreateManagedWidget("ok", xmPushButtonWidgetClass, form,
1542 XmNlabelString, s1=XmStringCreateSimple("OK"),
1543 XmNleftAttachment, XmATTACH_POSITION,
1544 XmNleftPosition, 6,
1545 XmNrightAttachment, XmATTACH_POSITION,
1546 XmNrightPosition, 18,
1547 XmNbottomAttachment, XmATTACH_FORM,
1548 XmNbottomOffset, VERT_BORDER, NULL);
1549 XtAddCallback(okBtn, XmNactivateCallback, comOKCB, NULL);
1550 XmStringFree(s1);
1552 applyBtn = XtVaCreateManagedWidget("apply", xmPushButtonWidgetClass, form,
1553 XmNlabelString, s1=XmStringCreateSimple("Apply"),
1554 XmNmnemonic, 'y',
1555 XmNleftAttachment, XmATTACH_POSITION,
1556 XmNleftPosition, 22,
1557 XmNrightAttachment, XmATTACH_POSITION,
1558 XmNrightPosition, 35,
1559 XmNbottomAttachment, XmATTACH_FORM,
1560 XmNbottomOffset, VERT_BORDER, NULL);
1561 XtAddCallback(applyBtn, XmNactivateCallback, comApplyCB, NULL);
1562 XmStringFree(s1);
1564 checkBtn = XtVaCreateManagedWidget("check", xmPushButtonWidgetClass, form,
1565 XmNlabelString, s1=XmStringCreateSimple("Check"),
1566 XmNmnemonic, 'k',
1567 XmNleftAttachment, XmATTACH_POSITION,
1568 XmNleftPosition, 39,
1569 XmNrightAttachment, XmATTACH_POSITION,
1570 XmNrightPosition, 52,
1571 XmNbottomAttachment, XmATTACH_FORM,
1572 XmNbottomOffset, VERT_BORDER, NULL);
1573 XtAddCallback(checkBtn, XmNactivateCallback, comCheckCB, NULL);
1574 XmStringFree(s1);
1576 restoreBtn = XtVaCreateManagedWidget("restore", xmPushButtonWidgetClass,
1577 form,
1578 XmNlabelString, s1=XmStringCreateSimple("Restore Default"),
1579 XmNmnemonic, 'f',
1580 XmNleftAttachment, XmATTACH_POSITION,
1581 XmNleftPosition, 56,
1582 XmNrightAttachment, XmATTACH_POSITION,
1583 XmNrightPosition, 77,
1584 XmNbottomAttachment, XmATTACH_FORM,
1585 XmNbottomOffset, VERT_BORDER, NULL);
1586 XtAddCallback(restoreBtn, XmNactivateCallback, comRestoreCB, NULL);
1587 XmStringFree(s1);
1589 dismissBtn = XtVaCreateManagedWidget("dismiss", xmPushButtonWidgetClass,
1590 form,
1591 XmNlabelString, s1=XmStringCreateSimple("Dismiss"),
1592 XmNleftAttachment, XmATTACH_POSITION,
1593 XmNleftPosition, 81,
1594 XmNrightAttachment, XmATTACH_POSITION,
1595 XmNrightPosition, 94,
1596 XmNbottomAttachment, XmATTACH_FORM,
1597 XmNbottomOffset, VERT_BORDER, NULL);
1598 XtAddCallback(dismissBtn, XmNactivateCallback, comDismissCB, NULL);
1599 XmStringFree(s1);
1601 n = 0;
1602 XtSetArg(args[n], XmNeditMode, XmMULTI_LINE_EDIT); n++;
1603 XtSetArg(args[n], XmNrows, 24); n++;
1604 XtSetArg(args[n], XmNcolumns, 80); n++;
1605 XtSetArg(args[n], XmNvalue, CommonMacros); n++;
1606 XtSetArg(args[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
1607 XtSetArg(args[n], XmNtopWidget, topLbl); n++;
1608 XtSetArg(args[n], XmNleftAttachment, XmATTACH_POSITION); n++;
1609 XtSetArg(args[n], XmNleftPosition, 1); n++;
1610 XtSetArg(args[n], XmNrightAttachment, XmATTACH_POSITION); n++;
1611 XtSetArg(args[n], XmNrightPosition, 99); n++;
1612 XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); n++;
1613 XtSetArg(args[n], XmNbottomWidget, okBtn); n++;
1614 XtSetArg(args[n], XmNbottomOffset, VERT_BORDER); n++;
1615 CommonDialog.text = XmCreateScrolledText(form, "commonText", args, n);
1616 AddMouseWheelSupport(CommonDialog.text);
1617 XtManageChild(CommonDialog.text);
1618 RemapDeleteKey(CommonDialog.text);
1619 XtVaSetValues(topLbl, XmNuserData, CommonDialog.text, NULL);
1621 /* Set initial default button */
1622 XtVaSetValues(form, XmNdefaultButton, okBtn, NULL);
1623 XtVaSetValues(form, XmNcancelButton, dismissBtn, NULL);
1625 /* Handle mnemonic selection of buttons and focus to dialog */
1626 AddDialogMnemonicHandler(form, FALSE);
1628 /* Realize all of the widgets in the new dialog */
1629 RealizeWithoutForcingPosition(CommonDialog.shell);
1632 static void comDestroyCB(Widget w, XtPointer clientData, XtPointer callData)
1634 CommonDialog.shell = NULL;
1637 static void comOKCB(Widget w, XtPointer clientData, XtPointer callData)
1639 /* change the macro */
1640 if (!updateSmartIndentCommonData())
1641 return;
1643 /* pop down and destroy the dialog */
1644 XtDestroyWidget(CommonDialog.shell);
1647 static void comApplyCB(Widget w, XtPointer clientData, XtPointer callData)
1649 /* change the macro */
1650 updateSmartIndentCommonData();
1653 static void comCheckCB(Widget w, XtPointer clientData, XtPointer callData)
1655 if (checkSmartIndentCommonDialogData())
1657 DialogF(DF_INF, CommonDialog.shell, 1, "Macro compiled",
1658 "Macros compiled without error", "Dismiss");
1662 static void comRestoreCB(Widget w, XtPointer clientData, XtPointer callData)
1664 if (DialogF(DF_WARN, CommonDialog.shell, 2, "Discard Changes",
1665 "Are you sure you want to discard all\n"
1666 "changes to common smart indent macros", "Discard", "Cancel") == 2)
1668 return;
1671 /* replace common macros with default */
1672 if (CommonMacros != NULL)
1673 XtFree(CommonMacros);
1674 CommonMacros = XtNewString(DefaultCommonMacros);
1676 /* Update the dialog */
1677 XmTextSetString(CommonDialog.text, CommonMacros);
1680 static void comDismissCB(Widget w, XtPointer clientData, XtPointer callData)
1682 /* pop down and destroy the dialog */
1683 XtDestroyWidget(CommonDialog.shell);
1687 ** Update the smart indent macros being edited in the dialog
1688 ** with the information that the dialog is currently displaying, and
1689 ** apply changes to any window which is currently using the macros.
1691 static int updateSmartIndentCommonData(void)
1693 WindowInfo *window;
1695 /* Make sure the patterns are valid and compile */
1696 if (!checkSmartIndentCommonDialogData())
1697 return False;
1699 /* Get the current data */
1700 CommonMacros = ensureNewline(XmTextGetString(CommonDialog.text));
1702 /* Re-execute initialization macros (macros require a window to function,
1703 since user could theoretically execute an action routine, but it
1704 probably won't be referenced in a smart indent initialization) */
1705 if (!ReadMacroString(WindowList, CommonMacros, "common macros"))
1706 return False;
1708 /* Find windows that are currently using smart indent and
1709 re-initialize the smart indent macros (in case they have initialization
1710 data which depends on common data) */
1711 for (window=WindowList; window!=NULL; window=window->next) {
1712 if (window->indentStyle == SMART_INDENT &&
1713 window->languageMode != PLAIN_LANGUAGE_MODE) {
1714 EndSmartIndent(window);
1715 BeginSmartIndent(window, False);
1719 /* Note that preferences have been changed */
1720 MarkPrefsChanged();
1722 return True;
1725 static int checkSmartIndentCommonDialogData(void)
1727 char *widgetText, *stoppedAt;
1729 if (!TextWidgetIsBlank(CommonDialog.text)) {
1730 widgetText = ensureNewline(XmTextGetString(CommonDialog.text));
1731 if (!CheckMacroString(CommonDialog.shell, widgetText,
1732 "macros", &stoppedAt)) {
1733 XmTextSetInsertionPosition(CommonDialog.text, stoppedAt-widgetText);
1734 XmProcessTraversal(CommonDialog.text, XmTRAVERSE_CURRENT);
1735 XtFree(widgetText);
1736 return False;
1738 XtFree(widgetText);
1740 return True;
1744 ** Update the smart indent macros being edited in the dialog
1745 ** with the information that the dialog is currently displaying, and
1746 ** apply changes to any window which is currently using the macros.
1748 static int updateSmartIndentData(void)
1750 smartIndentRec *newMacros;
1751 WindowInfo *window;
1752 char *lmName;
1753 int i;
1755 /* Make sure the patterns are valid and compile */
1756 if (!checkSmartIndentDialogData())
1757 return False;
1759 /* Get the current data */
1760 newMacros = getSmartIndentDialogData();
1762 /* Find the original macros */
1763 for (i=0; i<NSmartIndentSpecs; i++)
1764 if (!strcmp(SmartIndentDialog.langModeName,SmartIndentSpecs[i]->lmName))
1765 break;
1767 /* If it's a new language, add it at the end, otherwise free the
1768 existing macros and replace it */
1769 if (i == NSmartIndentSpecs) {
1770 SmartIndentSpecs[NSmartIndentSpecs++] = newMacros;
1771 } else {
1772 freeIndentSpec(SmartIndentSpecs[i]);
1773 SmartIndentSpecs[i] = newMacros;
1776 /* Find windows that are currently using this indent specification and
1777 re-do the smart indent macros */
1778 for (window=WindowList; window!=NULL; window=window->next) {
1779 lmName = LanguageModeName(window->languageMode);
1780 if (lmName != NULL && !strcmp(lmName, newMacros->lmName)) {
1781 XtSetSensitive(window->smartIndentItem, True);
1782 if (window->indentStyle == SMART_INDENT &&
1783 window->languageMode != PLAIN_LANGUAGE_MODE) {
1784 EndSmartIndent(window);
1785 BeginSmartIndent(window, False);
1790 /* Note that preferences have been changed */
1791 MarkPrefsChanged();
1793 return True;
1796 static int loadDefaultIndentSpec(char *lmName)
1798 int i;
1800 for (i=0; i<N_DEFAULT_INDENT_SPECS; i++) {
1801 if (!strcmp(lmName, DefaultIndentSpecs[i].lmName)) {
1802 SmartIndentSpecs[NSmartIndentSpecs++] =
1803 copyIndentSpec(&DefaultIndentSpecs[i]);
1804 return True;
1807 return False;
1810 int LoadSmartIndentString(char *inString)
1812 char *errMsg, *inPtr = inString;
1813 smartIndentRec is, *isCopy;
1814 int i;
1816 for (;;) {
1818 /* skip over blank space */
1819 inPtr += strspn(inPtr, " \t\n");
1821 /* finished */
1822 if (*inPtr == '\0')
1823 return True;
1825 /* read language mode name */
1826 is.lmName = ReadSymbolicField(&inPtr);
1827 if (is.lmName == NULL)
1828 return siParseError(inString, inPtr, "language mode name required");
1829 if (!SkipDelimiter(&inPtr, &errMsg)) {
1830 XtFree(is.lmName);
1831 return siParseError(inString, inPtr, errMsg);
1834 /* look for "Default" keyword, and if it's there, return the default
1835 smart indent macros */
1836 if (!strncmp(inPtr, "Default", 7)) {
1837 inPtr += 7;
1838 if (!loadDefaultIndentSpec(is.lmName)) {
1839 XtFree(is.lmName);
1840 return siParseError(inString, inPtr,
1841 "no default smart indent macros");
1843 XtFree(is.lmName);
1844 continue;
1847 /* read the initialization macro (arbitrary text terminated by the
1848 macro end boundary string) */
1849 is.initMacro = readSIMacro(&inPtr);
1850 if (is.initMacro == NULL) {
1851 XtFree(is.lmName);
1852 return siParseError(inString, inPtr,
1853 "no end boundary to initialization macro");
1856 /* read the newline macro */
1857 is.newlineMacro = readSIMacro(&inPtr);
1858 if (is.newlineMacro == NULL) {
1859 XtFree(is.lmName);
1860 XtFree(is.initMacro);
1861 return siParseError(inString, inPtr,
1862 "no end boundary to newline macro");
1865 /* read the modify macro */
1866 is.modMacro = readSIMacro(&inPtr);
1867 if (is.modMacro == NULL) {
1868 XtFree(is.lmName);
1869 XtFree(is.initMacro);
1870 XtFree(is.newlineMacro);
1871 return siParseError(inString, inPtr,
1872 "no end boundary to modify macro");
1875 /* if there's no mod macro, make it null so it won't be executed */
1876 if (is.modMacro[0] == '\0') {
1877 XtFree(is.modMacro);
1878 is.modMacro = NULL;
1881 /* create a new data structure and add/change it in the list */
1882 isCopy = (smartIndentRec *)XtMalloc(sizeof(smartIndentRec));
1883 *isCopy = is;
1884 for (i=0; i<NSmartIndentSpecs; i++) {
1885 if (!strcmp(SmartIndentSpecs[i]->lmName, is.lmName)) {
1886 freeIndentSpec(SmartIndentSpecs[i]);
1887 SmartIndentSpecs[i] = isCopy;
1888 break;
1891 if (i == NSmartIndentSpecs)
1892 SmartIndentSpecs[NSmartIndentSpecs++] = isCopy;
1896 int LoadSmartIndentCommonString(char *inString)
1898 int shiftedLen;
1899 char *inPtr = inString;
1901 /* If called from -import, can replace existing ones */
1902 if (CommonMacros != NULL)
1903 XtFree(CommonMacros);
1905 /* skip over blank space */
1906 inPtr += strspn(inPtr, " \t\n");
1908 /* look for "Default" keyword, and if it's there, return the default
1909 smart common macro */
1910 if (!strncmp(inPtr, "Default", 7)) {
1911 CommonMacros = XtNewString(DefaultCommonMacros);
1912 return True;
1915 /* Remove leading tabs added by writer routine */
1916 CommonMacros = ShiftText(inPtr, SHIFT_LEFT, True, 8, 8, &shiftedLen);
1917 return True;
1921 ** Read a macro (arbitrary text terminated by the macro end boundary string)
1922 ** from the position pointed to by *inPtr, trim off added tabs and return an
1923 ** allocated copy of the string, and advance *inPtr to the end of the macro.
1924 ** Returns NULL if the macro end boundary string is not found.
1926 static char *readSIMacro(char **inPtr)
1928 char *retStr, *macroStr, *macroEnd;
1929 int shiftedLen;
1931 /* Strip leading newline */
1932 if (**inPtr == '\n')
1933 (*inPtr)++;
1935 /* Find the end of the macro */
1936 macroEnd = strstr(*inPtr, MacroEndBoundary);
1937 if (macroEnd == NULL)
1938 return NULL;
1940 /* Copy the macro */
1941 macroStr = XtMalloc(macroEnd - *inPtr + 1);
1942 strncpy(macroStr, *inPtr, macroEnd - *inPtr);
1943 macroStr[macroEnd - *inPtr] = '\0';
1945 /* Remove leading tabs added by writer routine */
1946 *inPtr = macroEnd + strlen(MacroEndBoundary);
1947 retStr = ShiftText(macroStr, SHIFT_LEFT, True, 8, 8, &shiftedLen);
1948 XtFree(macroStr);
1949 return retStr;
1952 static smartIndentRec *copyIndentSpec(smartIndentRec *is)
1954 smartIndentRec *ris = (smartIndentRec *)XtMalloc(sizeof(smartIndentRec));
1955 ris->lmName = XtNewString(is->lmName);
1956 ris->initMacro = XtNewString(is->initMacro);
1957 ris->newlineMacro = XtNewString(is->newlineMacro);
1958 ris->modMacro = XtNewString(is->modMacro);
1959 return ris;
1962 static void freeIndentSpec(smartIndentRec *is)
1964 XtFree(is->lmName);
1965 if (is->initMacro != NULL) XtFree(is->initMacro);
1966 XtFree(is->newlineMacro);
1967 if (is->modMacro != NULL)XtFree(is->modMacro);
1970 static int indentSpecsDiffer(smartIndentRec *is1, smartIndentRec *is2)
1972 return AllocatedStringsDiffer(is1->initMacro, is2->initMacro) ||
1973 AllocatedStringsDiffer(is1->newlineMacro, is2->newlineMacro) ||
1974 AllocatedStringsDiffer(is1->modMacro, is2->modMacro);
1977 static int siParseError(char *stringStart, char *stoppedAt, char *message)
1979 return ParseError(NULL, stringStart, stoppedAt,
1980 "smart indent specification", message);
1983 char *WriteSmartIndentString(void)
1985 int i;
1986 smartIndentRec *sis;
1987 textBuffer *outBuf;
1988 char *outStr, *escapedStr;
1990 outBuf = BufCreate();
1991 for (i=0; i<NSmartIndentSpecs; i++) {
1992 sis = SmartIndentSpecs[i];
1993 BufInsert(outBuf, outBuf->length, "\t");
1994 BufInsert(outBuf, outBuf->length, sis->lmName);
1995 BufInsert(outBuf, outBuf->length, ":");
1996 if (isDefaultIndentSpec(sis))
1997 BufInsert(outBuf, outBuf->length, "Default\n");
1998 else {
1999 insertShiftedMacro(outBuf, sis->initMacro);
2000 insertShiftedMacro(outBuf, sis->newlineMacro);
2001 insertShiftedMacro(outBuf, sis->modMacro);
2005 /* Get the output string, and lop off the trailing newline */
2006 outStr = BufGetRange(outBuf, 0, outBuf->length > 0 ? outBuf->length-1 : 0);
2007 BufFree(outBuf);
2009 /* Protect newlines and backslashes from translation by the resource
2010 reader */
2011 escapedStr = EscapeSensitiveChars(outStr);
2012 XtFree(outStr);
2013 return escapedStr;
2016 char *WriteSmartIndentCommonString(void)
2018 int len;
2019 char *outStr, *escapedStr;
2021 if (!strcmp(CommonMacros, DefaultCommonMacros))
2022 return XtNewString("Default");
2023 if (CommonMacros == NULL)
2024 return XtNewString("");
2026 /* Shift the macro over by a tab to keep .nedit file bright and clean */
2027 outStr = ShiftText(CommonMacros, SHIFT_RIGHT, True, 8, 8, &len);
2029 /* Protect newlines and backslashes from translation by the resource
2030 reader */
2031 escapedStr = EscapeSensitiveChars(outStr);
2032 XtFree(outStr);
2034 /* If there's a trailing escaped newline, remove it */
2035 len = strlen(escapedStr);
2036 if (len > 1 && escapedStr[len-1] == '\n' && escapedStr[len-2] == '\\')
2037 escapedStr[len-2] = '\0';
2038 return escapedStr;
2042 ** Insert macro text "macro" into buffer "buf" shifted right by 8 characters
2043 ** (so it looks nice in the .nedit file), and terminated with a macro-end-
2044 ** boundary string.
2046 static void insertShiftedMacro(textBuffer *buf, char *macro)
2048 char *shiftedMacro;
2049 int shiftedLen;
2051 if (macro != NULL) {
2052 shiftedMacro = ShiftText(macro, SHIFT_RIGHT, True, 8, 8, &shiftedLen);
2053 BufInsert(buf, buf->length, shiftedMacro);
2054 XtFree(shiftedMacro);
2056 BufInsert(buf, buf->length, "\t");
2057 BufInsert(buf, buf->length, MacroEndBoundary);
2058 BufInsert(buf, buf->length, "\n");
2061 static int isDefaultIndentSpec(smartIndentRec *indentSpec)
2063 int i;
2065 for (i=0; i<N_DEFAULT_INDENT_SPECS; i++)
2066 if (!strcmp(indentSpec->lmName, DefaultIndentSpecs[i].lmName))
2067 return !indentSpecsDiffer(indentSpec, &DefaultIndentSpecs[i]);
2068 return False;
2071 static smartIndentRec *findIndentSpec(const char *modeName)
2073 int i;
2075 if (modeName == NULL)
2076 return NULL;
2078 for (i=0; i<NSmartIndentSpecs; i++)
2079 if (!strcmp(modeName, SmartIndentSpecs[i]->lmName))
2080 return SmartIndentSpecs[i];
2081 return NULL;
2085 ** If "string" is not terminated with a newline character, return a
2086 ** reallocated string which does end in a newline (otherwise, just pass on
2087 ** string as function value). (The macro language requires newline terminators
2088 ** for statements, but the text widget doesn't force it like the NEdit text
2089 ** buffer does, so this might avoid some confusion.)
2091 static char *ensureNewline(char *string)
2093 char *newString;
2094 int length;
2096 if (string == NULL)
2097 return NULL;
2098 length = strlen(string);
2099 if (length == 0 || string[length-1] == '\n')
2100 return string;
2101 newString = XtMalloc(length + 2);
2102 strcpy(newString, string);
2103 newString[length] = '\n';
2104 newString[length+1] = '\0';
2105 XtFree(string);
2106 return newString;
2110 ** Returns True if there are smart indent macros, or potential macros
2111 ** not yet committed in the smart indent dialog for a language mode,
2113 int LMHasSmartIndentMacros(const char *languageMode)
2115 if (findIndentSpec(languageMode) != NULL)
2116 return True;
2117 return SmartIndentDialog.shell!=NULL && !strcmp(SmartIndentDialog.langModeName,
2118 languageMode);
2122 ** Change the language mode name of smart indent macro sets for language
2123 ** "oldName" to "newName" in both the stored macro sets, and the pattern set
2124 ** currently being edited in the dialog.
2126 void RenameSmartIndentMacros(const char *oldName, const char *newName)
2128 int i;
2130 for (i=0; i<NSmartIndentSpecs; i++) {
2131 if (!strcmp(oldName, SmartIndentSpecs[i]->lmName)) {
2132 XtFree(SmartIndentSpecs[i]->lmName);
2133 SmartIndentSpecs[i]->lmName = XtNewString(newName);
2136 if (SmartIndentDialog.shell != NULL) {
2137 if (!strcmp(SmartIndentDialog.langModeName, oldName)) {
2138 XtFree(SmartIndentDialog.langModeName);
2139 SmartIndentDialog.langModeName = XtNewString(newName);
2145 ** If a smart indent dialog is up, ask to have the option menu for
2146 ** chosing language mode updated (via a call to CreateLanguageModeMenu)
2148 void UpdateLangModeMenuSmartIndent(void)
2150 Widget oldMenu;
2152 if (SmartIndentDialog.shell == NULL)
2153 return;
2155 oldMenu = SmartIndentDialog.lmPulldown;
2156 SmartIndentDialog.lmPulldown = CreateLanguageModeMenu(
2157 XtParent(XtParent(oldMenu)), langModeCB, NULL);
2158 XtVaSetValues(XmOptionButtonGadget(SmartIndentDialog.lmOptMenu),
2159 XmNsubMenuId, SmartIndentDialog.lmPulldown, NULL);
2160 SetLangModeMenu(SmartIndentDialog.lmOptMenu, SmartIndentDialog.langModeName);
2162 XtDestroyWidget(oldMenu);