blob: 923faf9bcae8cc325fe03ca7b25ef82e03d3f167 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * ex_cmds2.c: some more functions for command line commands
12 */
13
14#if defined(WIN32) && defined(FEAT_CSCOPE)
15# include <io.h>
16#endif
17
18#include "vim.h"
19
20#if defined(WIN32) && defined(FEAT_CSCOPE)
21# include <fcntl.h>
22#endif
23
24#include "version.h"
25
26static void cmd_source __ARGS((char_u *fname, exarg_T *eap));
27
Bram Moolenaar05159a02005-02-26 23:04:13 +000028#ifdef FEAT_EVAL
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +000029/* Growarray to store info about already sourced scripts.
Bram Moolenaar05159a02005-02-26 23:04:13 +000030 * For Unix also store the dev/ino, so that we don't have to stat() each
31 * script when going through the list. */
32typedef struct scriptitem_S
33{
34 char_u *sn_name;
35# ifdef UNIX
36 int sn_dev;
37 ino_t sn_ino;
38# endif
39# ifdef FEAT_PROFILE
40 int sn_prof_on; /* TRUE when script is/was profiled */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +000041 int sn_pr_force; /* forceit: profile functions in this script */
Bram Moolenaar05159a02005-02-26 23:04:13 +000042 proftime_T sn_pr_child; /* time set when going into first child */
43 int sn_pr_nest; /* nesting for sn_pr_child */
44 /* profiling the script as a whole */
45 int sn_pr_count; /* nr of times sourced */
46 proftime_T sn_pr_total; /* time spend in script + children */
47 proftime_T sn_pr_self; /* time spend in script itself */
48 proftime_T sn_pr_start; /* time at script start */
49 proftime_T sn_pr_children; /* time in children after script start */
50 /* profiling the script per line */
51 garray_T sn_prl_ga; /* things stored for every line */
52 proftime_T sn_prl_start; /* start time for current line */
53 proftime_T sn_prl_children; /* time spent in children for this line */
54 proftime_T sn_prl_wait; /* wait start time for current line */
55 int sn_prl_idx; /* index of line being timed; -1 if none */
56 int sn_prl_execed; /* line being timed was executed */
57# endif
58} scriptitem_T;
59
60static garray_T script_items = {0, 0, sizeof(scriptitem_T), 4, NULL};
61#define SCRIPT_ITEM(id) (((scriptitem_T *)script_items.ga_data)[(id) - 1])
62
63# ifdef FEAT_PROFILE
64/* Struct used in sn_prl_ga for every line of a script. */
65typedef struct sn_prl_S
66{
67 int snp_count; /* nr of times line was executed */
68 proftime_T sn_prl_total; /* time spend in a line + children */
69 proftime_T sn_prl_self; /* time spend in a line itself */
70} sn_prl_T;
71
72# define PRL_ITEM(si, idx) (((sn_prl_T *)(si)->sn_prl_ga.ga_data)[(idx)])
73# endif
74#endif
75
Bram Moolenaar071d4272004-06-13 20:20:40 +000076#if defined(FEAT_EVAL) || defined(PROTO)
77static int debug_greedy = FALSE; /* batch mode debugging: don't save
78 and restore typeahead. */
79
80/*
81 * do_debug(): Debug mode.
82 * Repeatedly get Ex commands, until told to continue normal execution.
83 */
84 void
85do_debug(cmd)
86 char_u *cmd;
87{
88 int save_msg_scroll = msg_scroll;
89 int save_State = State;
90 int save_did_emsg = did_emsg;
91 int save_cmd_silent = cmd_silent;
92 int save_msg_silent = msg_silent;
93 int save_emsg_silent = emsg_silent;
94 int save_redir_off = redir_off;
95 tasave_T typeaheadbuf;
96# ifdef FEAT_EX_EXTRA
97 int save_ex_normal_busy;
98# endif
99 int n;
100 char_u *cmdline = NULL;
101 char_u *p;
102 char *tail = NULL;
103 static int last_cmd = 0;
104#define CMD_CONT 1
105#define CMD_NEXT 2
106#define CMD_STEP 3
107#define CMD_FINISH 4
108#define CMD_QUIT 5
109#define CMD_INTERRUPT 6
110
111#ifdef ALWAYS_USE_GUI
112 /* Can't do this when there is no terminal for input/output. */
113 if (!gui.in_use)
114 {
115 /* Break as soon as possible. */
116 debug_break_level = 9999;
117 return;
118 }
119#endif
120
121 /* Make sure we are in raw mode and start termcap mode. Might have side
122 * effects... */
123 settmode(TMODE_RAW);
124 starttermcap();
125
126 ++RedrawingDisabled; /* don't redisplay the window */
127 ++no_wait_return; /* don't wait for return */
128 did_emsg = FALSE; /* don't use error from debugged stuff */
129 cmd_silent = FALSE; /* display commands */
130 msg_silent = FALSE; /* display messages */
131 emsg_silent = FALSE; /* display error messages */
132 redir_off = TRUE; /* don't redirect debug commands */
133
134 State = NORMAL;
135#ifdef FEAT_SNIFF
136 want_sniff_request = 0; /* No K_SNIFF wanted */
137#endif
138
139 if (!debug_did_msg)
140 MSG(_("Entering Debug mode. Type \"cont\" to continue."));
141 if (sourcing_name != NULL)
142 msg(sourcing_name);
143 if (sourcing_lnum != 0)
Bram Moolenaar555b2802005-05-19 21:08:39 +0000144 smsg((char_u *)_("line %ld: %s"), (long)sourcing_lnum, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145 else
Bram Moolenaar555b2802005-05-19 21:08:39 +0000146 smsg((char_u *)_("cmd: %s"), cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147
148 /*
149 * Repeat getting a command and executing it.
150 */
151 for (;;)
152 {
153 msg_scroll = TRUE;
154 need_wait_return = FALSE;
155#ifdef FEAT_SNIFF
156 ProcessSniffRequests();
157#endif
158 /* Save the current typeahead buffer and replace it with an empty one.
159 * This makes sure we get input from the user here and don't interfere
160 * with the commands being executed. Reset "ex_normal_busy" to avoid
161 * the side effects of using ":normal". Save the stuff buffer and make
162 * it empty. */
163# ifdef FEAT_EX_EXTRA
164 save_ex_normal_busy = ex_normal_busy;
165 ex_normal_busy = 0;
166# endif
167 if (!debug_greedy)
168 save_typeahead(&typeaheadbuf);
169
170 cmdline = getcmdline_prompt('>', NULL, 0);
171
172 if (!debug_greedy)
173 restore_typeahead(&typeaheadbuf);
174# ifdef FEAT_EX_EXTRA
175 ex_normal_busy = save_ex_normal_busy;
176# endif
177
178 cmdline_row = msg_row;
179 if (cmdline != NULL)
180 {
181 /* If this is a debug command, set "last_cmd".
182 * If not, reset "last_cmd".
183 * For a blank line use previous command. */
184 p = skipwhite(cmdline);
185 if (*p != NUL)
186 {
187 switch (*p)
188 {
189 case 'c': last_cmd = CMD_CONT;
190 tail = "ont";
191 break;
192 case 'n': last_cmd = CMD_NEXT;
193 tail = "ext";
194 break;
195 case 's': last_cmd = CMD_STEP;
196 tail = "tep";
197 break;
198 case 'f': last_cmd = CMD_FINISH;
199 tail = "inish";
200 break;
201 case 'q': last_cmd = CMD_QUIT;
202 tail = "uit";
203 break;
204 case 'i': last_cmd = CMD_INTERRUPT;
205 tail = "nterrupt";
206 break;
207 default: last_cmd = 0;
208 }
209 if (last_cmd != 0)
210 {
211 /* Check that the tail matches. */
212 ++p;
213 while (*p != NUL && *p == *tail)
214 {
215 ++p;
216 ++tail;
217 }
218 if (ASCII_ISALPHA(*p))
219 last_cmd = 0;
220 }
221 }
222
223 if (last_cmd != 0)
224 {
225 /* Execute debug command: decided where to break next and
226 * return. */
227 switch (last_cmd)
228 {
229 case CMD_CONT:
230 debug_break_level = -1;
231 break;
232 case CMD_NEXT:
233 debug_break_level = ex_nesting_level;
234 break;
235 case CMD_STEP:
236 debug_break_level = 9999;
237 break;
238 case CMD_FINISH:
239 debug_break_level = ex_nesting_level - 1;
240 break;
241 case CMD_QUIT:
242 got_int = TRUE;
243 debug_break_level = -1;
244 break;
245 case CMD_INTERRUPT:
246 got_int = TRUE;
247 debug_break_level = 9999;
248 /* Do not repeat ">interrupt" cmd, continue stepping. */
249 last_cmd = CMD_STEP;
250 break;
251 }
252 break;
253 }
254
255 /* don't debug this command */
256 n = debug_break_level;
257 debug_break_level = -1;
258 (void)do_cmdline(cmdline, getexline, NULL,
259 DOCMD_VERBOSE|DOCMD_EXCRESET);
260 debug_break_level = n;
261
262 vim_free(cmdline);
263 }
264 lines_left = Rows - 1;
265 }
266 vim_free(cmdline);
267
268 --RedrawingDisabled;
269 --no_wait_return;
270 redraw_all_later(NOT_VALID);
271 need_wait_return = FALSE;
272 msg_scroll = save_msg_scroll;
273 lines_left = Rows - 1;
274 State = save_State;
275 did_emsg = save_did_emsg;
276 cmd_silent = save_cmd_silent;
277 msg_silent = save_msg_silent;
278 emsg_silent = save_emsg_silent;
279 redir_off = save_redir_off;
280
281 /* Only print the message again when typing a command before coming back
282 * here. */
283 debug_did_msg = TRUE;
284}
285
286/*
287 * ":debug".
288 */
289 void
290ex_debug(eap)
291 exarg_T *eap;
292{
293 int debug_break_level_save = debug_break_level;
294
295 debug_break_level = 9999;
296 do_cmdline_cmd(eap->arg);
297 debug_break_level = debug_break_level_save;
298}
299
300static char_u *debug_breakpoint_name = NULL;
301static linenr_T debug_breakpoint_lnum;
302
303/*
304 * When debugging or a breakpoint is set on a skipped command, no debug prompt
305 * is shown by do_one_cmd(). This situation is indicated by debug_skipped, and
306 * debug_skipped_name is then set to the source name in the breakpoint case. If
307 * a skipped command decides itself that a debug prompt should be displayed, it
308 * can do so by calling dbg_check_skipped().
309 */
310static int debug_skipped;
311static char_u *debug_skipped_name;
312
313/*
314 * Go to debug mode when a breakpoint was encountered or "ex_nesting_level" is
315 * at or below the break level. But only when the line is actually
316 * executed. Return TRUE and set breakpoint_name for skipped commands that
317 * decide to execute something themselves.
318 * Called from do_one_cmd() before executing a command.
319 */
320 void
321dbg_check_breakpoint(eap)
322 exarg_T *eap;
323{
324 char_u *p;
325
326 debug_skipped = FALSE;
327 if (debug_breakpoint_name != NULL)
328 {
329 if (!eap->skip)
330 {
331 /* replace K_SNR with "<SNR>" */
332 if (debug_breakpoint_name[0] == K_SPECIAL
333 && debug_breakpoint_name[1] == KS_EXTRA
334 && debug_breakpoint_name[2] == (int)KE_SNR)
335 p = (char_u *)"<SNR>";
336 else
337 p = (char_u *)"";
Bram Moolenaar555b2802005-05-19 21:08:39 +0000338 smsg((char_u *)_("Breakpoint in \"%s%s\" line %ld"),
339 p,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 debug_breakpoint_name + (*p == NUL ? 0 : 3),
341 (long)debug_breakpoint_lnum);
342 debug_breakpoint_name = NULL;
343 do_debug(eap->cmd);
344 }
345 else
346 {
347 debug_skipped = TRUE;
348 debug_skipped_name = debug_breakpoint_name;
349 debug_breakpoint_name = NULL;
350 }
351 }
352 else if (ex_nesting_level <= debug_break_level)
353 {
354 if (!eap->skip)
355 do_debug(eap->cmd);
356 else
357 {
358 debug_skipped = TRUE;
359 debug_skipped_name = NULL;
360 }
361 }
362}
363
364/*
365 * Go to debug mode if skipped by dbg_check_breakpoint() because eap->skip was
366 * set. Return TRUE when the debug mode is entered this time.
367 */
368 int
369dbg_check_skipped(eap)
370 exarg_T *eap;
371{
372 int prev_got_int;
373
374 if (debug_skipped)
375 {
376 /*
377 * Save the value of got_int and reset it. We don't want a previous
378 * interruption cause flushing the input buffer.
379 */
380 prev_got_int = got_int;
381 got_int = FALSE;
382 debug_breakpoint_name = debug_skipped_name;
383 /* eap->skip is TRUE */
384 eap->skip = FALSE;
385 (void)dbg_check_breakpoint(eap);
386 eap->skip = TRUE;
387 got_int |= prev_got_int;
388 return TRUE;
389 }
390 return FALSE;
391}
392
393/*
394 * The list of breakpoints: dbg_breakp.
395 * This is a grow-array of structs.
396 */
397struct debuggy
398{
399 int dbg_nr; /* breakpoint number */
400 int dbg_type; /* DBG_FUNC or DBG_FILE */
401 char_u *dbg_name; /* function or file name */
402 regprog_T *dbg_prog; /* regexp program */
403 linenr_T dbg_lnum; /* line number in function or file */
Bram Moolenaar05159a02005-02-26 23:04:13 +0000404 int dbg_forceit; /* ! used */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000405};
406
407static garray_T dbg_breakp = {0, 0, sizeof(struct debuggy), 4, NULL};
Bram Moolenaar05159a02005-02-26 23:04:13 +0000408#define BREAKP(idx) (((struct debuggy *)dbg_breakp.ga_data)[idx])
409#define DEBUGGY(gap, idx) (((struct debuggy *)gap->ga_data)[idx])
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410static int last_breakp = 0; /* nr of last defined breakpoint */
411
Bram Moolenaar05159a02005-02-26 23:04:13 +0000412#ifdef FEAT_PROFILE
413/* Profiling uses file and func names similar to breakpoints. */
414static garray_T prof_ga = {0, 0, sizeof(struct debuggy), 4, NULL};
415#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416#define DBG_FUNC 1
417#define DBG_FILE 2
418
Bram Moolenaar05159a02005-02-26 23:04:13 +0000419static int dbg_parsearg __ARGS((char_u *arg, garray_T *gap));
420static linenr_T debuggy_find __ARGS((int file,char_u *fname, linenr_T after, garray_T *gap, int *fp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421
422/*
Bram Moolenaar05159a02005-02-26 23:04:13 +0000423 * Parse the arguments of ":profile", ":breakadd" or ":breakdel" and put them
424 * in the entry just after the last one in dbg_breakp. Note that "dbg_name"
425 * is allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 * Returns FAIL for failure.
427 */
428 static int
Bram Moolenaar05159a02005-02-26 23:04:13 +0000429dbg_parsearg(arg, gap)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 char_u *arg;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000431 garray_T *gap; /* either &dbg_breakp or &prof_ga */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432{
433 char_u *p = arg;
434 char_u *q;
435 struct debuggy *bp;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +0000436 int here = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437
Bram Moolenaar05159a02005-02-26 23:04:13 +0000438 if (ga_grow(gap, 1) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 return FAIL;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000440 bp = &DEBUGGY(gap, gap->ga_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441
442 /* Find "func" or "file". */
443 if (STRNCMP(p, "func", 4) == 0)
444 bp->dbg_type = DBG_FUNC;
445 else if (STRNCMP(p, "file", 4) == 0)
446 bp->dbg_type = DBG_FILE;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000447 else if (
448#ifdef FEAT_PROFILE
449 gap != &prof_ga &&
450#endif
451 STRNCMP(p, "here", 4) == 0)
Bram Moolenaarf4b8e572004-06-24 15:53:16 +0000452 {
453 if (curbuf->b_ffname == NULL)
454 {
455 EMSG(_(e_noname));
456 return FAIL;
457 }
458 bp->dbg_type = DBG_FILE;
459 here = TRUE;
460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 else
462 {
463 EMSG2(_(e_invarg2), p);
464 return FAIL;
465 }
466 p = skipwhite(p + 4);
467
468 /* Find optional line number. */
Bram Moolenaarf4b8e572004-06-24 15:53:16 +0000469 if (here)
470 bp->dbg_lnum = curwin->w_cursor.lnum;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000471 else if (
472#ifdef FEAT_PROFILE
473 gap != &prof_ga &&
474#endif
475 VIM_ISDIGIT(*p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476 {
477 bp->dbg_lnum = getdigits(&p);
478 p = skipwhite(p);
479 }
480 else
481 bp->dbg_lnum = 0;
482
483 /* Find the function or file name. Don't accept a function name with (). */
Bram Moolenaarf4b8e572004-06-24 15:53:16 +0000484 if ((!here && *p == NUL)
485 || (here && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 || (bp->dbg_type == DBG_FUNC && strstr((char *)p, "()") != NULL))
487 {
488 EMSG2(_(e_invarg2), arg);
489 return FAIL;
490 }
491
492 if (bp->dbg_type == DBG_FUNC)
493 bp->dbg_name = vim_strsave(p);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +0000494 else if (here)
495 bp->dbg_name = vim_strsave(curbuf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 else
497 {
498 /* Expand the file name in the same way as do_source(). This means
499 * doing it twice, so that $DIR/file gets expanded when $DIR is
500 * "~/dir". */
501#ifdef RISCOS
502 q = mch_munge_fname(p);
503#else
504 q = expand_env_save(p);
505#endif
506 if (q == NULL)
507 return FAIL;
508#ifdef RISCOS
509 p = mch_munge_fname(q);
510#else
511 p = expand_env_save(q);
512#endif
513 vim_free(q);
514 if (p == NULL)
515 return FAIL;
Bram Moolenaar843ee412004-06-30 16:16:41 +0000516 if (*p != '*')
517 {
518 bp->dbg_name = fix_fname(p);
519 vim_free(p);
520 }
521 else
522 bp->dbg_name = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523#ifdef MACOS_CLASSIC
524 if (bp->dbg_name != NULL)
525 slash_n_colon_adjust(bp->dbg_name);
526#endif
527 }
528
529 if (bp->dbg_name == NULL)
530 return FAIL;
531 return OK;
532}
533
534/*
535 * ":breakadd".
536 */
537 void
538ex_breakadd(eap)
539 exarg_T *eap;
540{
541 struct debuggy *bp;
542 char_u *pat;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000543 garray_T *gap;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544
Bram Moolenaar05159a02005-02-26 23:04:13 +0000545 gap = &dbg_breakp;
546#ifdef FEAT_PROFILE
547 if (eap->cmdidx == CMD_profile)
548 gap = &prof_ga;
549#endif
550
551 if (dbg_parsearg(eap->arg, gap) == OK)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552 {
Bram Moolenaar05159a02005-02-26 23:04:13 +0000553 bp = &DEBUGGY(gap, gap->ga_len);
554 bp->dbg_forceit = eap->forceit;
555
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556 pat = file_pat_to_reg_pat(bp->dbg_name, NULL, NULL, FALSE);
557 if (pat != NULL)
558 {
559 bp->dbg_prog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
560 vim_free(pat);
561 }
562 if (pat == NULL || bp->dbg_prog == NULL)
563 vim_free(bp->dbg_name);
564 else
565 {
566 if (bp->dbg_lnum == 0) /* default line number is 1 */
567 bp->dbg_lnum = 1;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000568#ifdef FEAT_PROFILE
569 if (eap->cmdidx != CMD_profile)
570#endif
571 {
572 DEBUGGY(gap, gap->ga_len).dbg_nr = ++last_breakp;
573 ++debug_tick;
574 }
575 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 }
577 }
578}
579
580/*
581 * ":debuggreedy".
582 */
583 void
584ex_debuggreedy(eap)
585 exarg_T *eap;
586{
587 if (eap->addr_count == 0 || eap->line2 != 0)
588 debug_greedy = TRUE;
589 else
590 debug_greedy = FALSE;
591}
592
593/*
Bram Moolenaard9fba312005-06-26 22:34:35 +0000594 * ":breakdel" and ":profdel".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595 */
596 void
597ex_breakdel(eap)
598 exarg_T *eap;
599{
600 struct debuggy *bp, *bpi;
601 int nr;
602 int todel = -1;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000603 int del_all = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604 int i;
605 linenr_T best_lnum = 0;
Bram Moolenaard9fba312005-06-26 22:34:35 +0000606 garray_T *gap;
607
608 gap = &dbg_breakp;
609#ifdef FEAT_PROFILE
610 if (eap->cmdidx == CMD_profdel)
611 gap = &prof_ga;
612#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613
614 if (vim_isdigit(*eap->arg))
615 {
616 /* ":breakdel {nr}" */
617 nr = atol((char *)eap->arg);
Bram Moolenaard9fba312005-06-26 22:34:35 +0000618 for (i = 0; i < gap->ga_len; ++i)
619 if (DEBUGGY(gap, i).dbg_nr == nr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 {
621 todel = i;
622 break;
623 }
624 }
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000625 else if (*eap->arg == '*')
626 {
627 todel = 0;
628 del_all = TRUE;
629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 else
631 {
632 /* ":breakdel {func|file} [lnum] {name}" */
Bram Moolenaard9fba312005-06-26 22:34:35 +0000633 if (dbg_parsearg(eap->arg, gap) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 return;
Bram Moolenaard9fba312005-06-26 22:34:35 +0000635 bp = &DEBUGGY(gap, gap->ga_len);
636 for (i = 0; i < gap->ga_len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {
Bram Moolenaard9fba312005-06-26 22:34:35 +0000638 bpi = &DEBUGGY(gap, i);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000639 if (bp->dbg_type == bpi->dbg_type
640 && STRCMP(bp->dbg_name, bpi->dbg_name) == 0
641 && (bp->dbg_lnum == bpi->dbg_lnum
642 || (bp->dbg_lnum == 0
643 && (best_lnum == 0
644 || bpi->dbg_lnum < best_lnum))))
645 {
646 todel = i;
647 best_lnum = bpi->dbg_lnum;
648 }
649 }
650 vim_free(bp->dbg_name);
651 }
652
653 if (todel < 0)
654 EMSG2(_("E161: Breakpoint not found: %s"), eap->arg);
655 else
Bram Moolenaard9fba312005-06-26 22:34:35 +0000656 {
657 while (gap->ga_len > 0)
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000658 {
Bram Moolenaard9fba312005-06-26 22:34:35 +0000659 vim_free(DEBUGGY(gap, todel).dbg_name);
660 vim_free(DEBUGGY(gap, todel).dbg_prog);
661 --gap->ga_len;
662 if (todel < gap->ga_len)
663 mch_memmove(&DEBUGGY(gap, todel), &DEBUGGY(gap, todel + 1),
664 (gap->ga_len - todel) * sizeof(struct debuggy));
665#ifdef FEAT_PROFILE
666 if (eap->cmdidx == CMD_breakdel)
667#endif
668 ++debug_tick;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000669 if (!del_all)
670 break;
671 }
Bram Moolenaard9fba312005-06-26 22:34:35 +0000672
673 /* If all breakpoints were removed clear the array. */
674 if (gap->ga_len == 0)
675 ga_clear(gap);
676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677}
678
679/*
680 * ":breaklist".
681 */
682/*ARGSUSED*/
683 void
684ex_breaklist(eap)
685 exarg_T *eap;
686{
687 struct debuggy *bp;
688 int i;
689
690 if (dbg_breakp.ga_len == 0)
691 MSG(_("No breakpoints defined"));
692 else
693 for (i = 0; i < dbg_breakp.ga_len; ++i)
694 {
695 bp = &BREAKP(i);
696 smsg((char_u *)_("%3d %s %s line %ld"),
697 bp->dbg_nr,
698 bp->dbg_type == DBG_FUNC ? "func" : "file",
699 bp->dbg_name,
700 (long)bp->dbg_lnum);
701 }
702}
703
704/*
705 * Find a breakpoint for a function or sourced file.
706 * Returns line number at which to break; zero when no matching breakpoint.
707 */
708 linenr_T
709dbg_find_breakpoint(file, fname, after)
710 int file; /* TRUE for a file, FALSE for a function */
711 char_u *fname; /* file or function name */
712 linenr_T after; /* after this line number */
713{
Bram Moolenaar05159a02005-02-26 23:04:13 +0000714 return debuggy_find(file, fname, after, &dbg_breakp, NULL);
715}
716
717#if defined(FEAT_PROFILE) || defined(PROTO)
718/*
719 * Return TRUE if profiling is on for a function or sourced file.
720 */
721 int
722has_profiling(file, fname, fp)
723 int file; /* TRUE for a file, FALSE for a function */
724 char_u *fname; /* file or function name */
725 int *fp; /* return: forceit */
726{
727 return (debuggy_find(file, fname, (linenr_T)0, &prof_ga, fp)
728 != (linenr_T)0);
729}
730#endif
731
732/*
733 * Common code for dbg_find_breakpoint() and has_profiling().
734 */
735 static linenr_T
736debuggy_find(file, fname, after, gap, fp)
737 int file; /* TRUE for a file, FALSE for a function */
738 char_u *fname; /* file or function name */
739 linenr_T after; /* after this line number */
740 garray_T *gap; /* either &dbg_breakp or &prof_ga */
741 int *fp; /* if not NULL: return forceit */
742{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 struct debuggy *bp;
744 int i;
745 linenr_T lnum = 0;
746 regmatch_T regmatch;
747 char_u *name = fname;
748 int prev_got_int;
749
Bram Moolenaar05159a02005-02-26 23:04:13 +0000750 /* Return quickly when there are no breakpoints. */
751 if (gap->ga_len == 0)
752 return (linenr_T)0;
753
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754 /* Replace K_SNR in function name with "<SNR>". */
755 if (!file && fname[0] == K_SPECIAL)
756 {
757 name = alloc((unsigned)STRLEN(fname) + 3);
758 if (name == NULL)
759 name = fname;
760 else
761 {
762 STRCPY(name, "<SNR>");
763 STRCPY(name + 5, fname + 3);
764 }
765 }
766
Bram Moolenaar05159a02005-02-26 23:04:13 +0000767 for (i = 0; i < gap->ga_len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768 {
Bram Moolenaar05159a02005-02-26 23:04:13 +0000769 /* Skip entries that are not useful or are for a line that is beyond
770 * an already found breakpoint. */
771 bp = &DEBUGGY(gap, i);
772 if (((bp->dbg_type == DBG_FILE) == file && (
773#ifdef FEAT_PROFILE
774 gap == &prof_ga ||
775#endif
776 (bp->dbg_lnum > after && (lnum == 0 || bp->dbg_lnum < lnum)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 {
778 regmatch.regprog = bp->dbg_prog;
779 regmatch.rm_ic = FALSE;
780 /*
Bram Moolenaar05159a02005-02-26 23:04:13 +0000781 * Save the value of got_int and reset it. We don't want a
782 * previous interruption cancel matching, only hitting CTRL-C
783 * while matching should abort it.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784 */
785 prev_got_int = got_int;
786 got_int = FALSE;
787 if (vim_regexec(&regmatch, name, (colnr_T)0))
Bram Moolenaar05159a02005-02-26 23:04:13 +0000788 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789 lnum = bp->dbg_lnum;
Bram Moolenaar05159a02005-02-26 23:04:13 +0000790 if (fp != NULL)
791 *fp = bp->dbg_forceit;
792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793 got_int |= prev_got_int;
794 }
795 }
796 if (name != fname)
797 vim_free(name);
798
799 return lnum;
800}
801
802/*
803 * Called when a breakpoint was encountered.
804 */
805 void
806dbg_breakpoint(name, lnum)
807 char_u *name;
808 linenr_T lnum;
809{
810 /* We need to check if this line is actually executed in do_one_cmd() */
811 debug_breakpoint_name = name;
812 debug_breakpoint_lnum = lnum;
813}
Bram Moolenaar05159a02005-02-26 23:04:13 +0000814
815
816# if defined(FEAT_PROFILE) || defined(PROTO)
817/*
818 * Functions for profiling.
819 */
820static void script_do_profile __ARGS((scriptitem_T *si));
821static void script_dump_profile __ARGS((FILE *fd));
822static proftime_T prof_wait_time;
823
824/*
825 * Set the time in "tm" to zero.
826 */
827 void
828profile_zero(tm)
829 proftime_T *tm;
830{
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000831# ifdef WIN3264
832 tm->QuadPart = 0;
833# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000834 tm->tv_usec = 0;
835 tm->tv_sec = 0;
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000836# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000837}
838
839/*
840 * Store the current time in "tm".
841 */
842 void
843profile_start(tm)
844 proftime_T *tm;
845{
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000846# ifdef WIN3264
847 QueryPerformanceCounter(tm);
848# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000849 gettimeofday(tm, NULL);
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000850# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000851}
852
853/*
854 * Compute the elapsed time from "tm" till now and store in "tm".
855 */
856 void
857profile_end(tm)
858 proftime_T *tm;
859{
860 proftime_T now;
861
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000862# ifdef WIN3264
863 QueryPerformanceCounter(&now);
864 tm->QuadPart = now.QuadPart - tm->QuadPart;
865# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000866 gettimeofday(&now, NULL);
867 tm->tv_usec = now.tv_usec - tm->tv_usec;
868 tm->tv_sec = now.tv_sec - tm->tv_sec;
869 if (tm->tv_usec < 0)
870 {
871 tm->tv_usec += 1000000;
872 --tm->tv_sec;
873 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000874# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000875}
876
877/*
878 * Subtract the time "tm2" from "tm".
879 */
880 void
881profile_sub(tm, tm2)
882 proftime_T *tm, *tm2;
883{
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000884# ifdef WIN3264
885 tm->QuadPart -= tm2->QuadPart;
886# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000887 tm->tv_usec -= tm2->tv_usec;
888 tm->tv_sec -= tm2->tv_sec;
889 if (tm->tv_usec < 0)
890 {
891 tm->tv_usec += 1000000;
892 --tm->tv_sec;
893 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000894# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000895}
896
897/*
898 * Add the time "tm2" to "tm".
899 */
900 void
901profile_add(tm, tm2)
902 proftime_T *tm, *tm2;
903{
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000904# ifdef WIN3264
905 tm->QuadPart += tm2->QuadPart;
906# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000907 tm->tv_usec += tm2->tv_usec;
908 tm->tv_sec += tm2->tv_sec;
909 if (tm->tv_usec >= 1000000)
910 {
911 tm->tv_usec -= 1000000;
912 ++tm->tv_sec;
913 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000914# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000915}
916
917/*
918 * Get the current waittime.
919 */
920 void
921profile_get_wait(tm)
922 proftime_T *tm;
923{
924 *tm = prof_wait_time;
925}
926
927/*
928 * Subtract the passed waittime since "tm" from "tma".
929 */
930 void
931profile_sub_wait(tm, tma)
932 proftime_T *tm, *tma;
933{
934 proftime_T tm3 = prof_wait_time;
935
936 profile_sub(&tm3, tm);
937 profile_sub(tma, &tm3);
938}
939
940/*
941 * Return TRUE if "tm1" and "tm2" are equal.
942 */
943 int
944profile_equal(tm1, tm2)
945 proftime_T *tm1, *tm2;
946{
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000947# ifdef WIN3264
948 return (tm1->QuadPart == tm2->QuadPart);
949# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000950 return (tm1->tv_usec == tm2->tv_usec && tm1->tv_sec == tm2->tv_sec);
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000951# endif
952}
953
954/*
955 * Return <0, 0 or >0 if "tm1" < "tm2", "tm1" == "tm2" or "tm1" > "tm2"
956 */
957 int
958profile_cmp(tm1, tm2)
959 proftime_T *tm1, *tm2;
960{
961# ifdef WIN3264
962 return (int)(tm2->QuadPart - tm1->QuadPart);
963# else
964 if (tm1->tv_sec == tm2->tv_sec)
965 return tm2->tv_usec - tm1->tv_usec;
966 return tm2->tv_sec - tm1->tv_sec;
967# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000968}
969
970/*
971 * Return a string that represents a time.
972 * Uses a static buffer!
973 */
974 char *
975profile_msg(tm)
976 proftime_T *tm;
977{
978 static char buf[50];
979
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000980# ifdef WIN3264
981 LARGE_INTEGER fr;
982
983 QueryPerformanceFrequency(&fr);
984 sprintf(buf, "%10.6lf", (double)tm->QuadPart / (double)fr.QuadPart);
985# else
Bram Moolenaar05159a02005-02-26 23:04:13 +0000986 sprintf(buf, "%3ld.%06ld", (long)tm->tv_sec, (long)tm->tv_usec);
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +0000987#endif
Bram Moolenaar05159a02005-02-26 23:04:13 +0000988 return buf;
989}
990
991static char_u *profile_fname = NULL;
992
993/*
994 * ":profile cmd args"
995 */
996 void
997ex_profile(eap)
998 exarg_T *eap;
999{
1000 char_u *e;
1001 int len;
1002
1003 e = skiptowhite(eap->arg);
1004 len = e - eap->arg;
1005 e = skipwhite(e);
1006
1007 if (len == 5 && STRNCMP(eap->arg, "start", 5) == 0 && *e != NUL)
1008 {
1009 vim_free(profile_fname);
1010 profile_fname = vim_strsave(e);
1011 do_profiling = TRUE;
1012 profile_zero(&prof_wait_time);
1013 set_vim_var_nr(VV_PROFILING, 1L);
1014 }
1015 else if (!do_profiling)
1016 EMSG(_("E750: First use :profile start <fname>"));
1017 else
1018 {
1019 /* The rest is similar to ":breakadd". */
1020 ex_breakadd(eap);
1021 }
1022}
1023
1024/*
1025 * Dump the profiling info.
1026 */
1027 void
1028profile_dump()
1029{
1030 FILE *fd;
1031
1032 if (profile_fname != NULL)
1033 {
1034 fd = fopen((char *)profile_fname, "w");
1035 if (fd == NULL)
1036 EMSG2(_(e_notopen), profile_fname);
1037 else
1038 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00001039 script_dump_profile(fd);
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001040 func_dump_profile(fd);
Bram Moolenaar05159a02005-02-26 23:04:13 +00001041 fclose(fd);
1042 }
1043 }
1044}
1045
1046/*
1047 * Start profiling script "fp".
1048 */
1049 static void
1050script_do_profile(si)
1051 scriptitem_T *si;
1052{
1053 si->sn_pr_count = 0;
1054 profile_zero(&si->sn_pr_total);
1055 profile_zero(&si->sn_pr_self);
1056
1057 ga_init2(&si->sn_prl_ga, sizeof(sn_prl_T), 100);
1058 si->sn_prl_idx = -1;
1059 si->sn_prof_on = TRUE;
1060 si->sn_pr_nest = 0;
1061}
1062
1063/*
1064 * save time when starting to invoke another script or function.
1065 */
1066 void
1067script_prof_save(tm)
1068 proftime_T *tm; /* place to store wait time */
1069{
1070 scriptitem_T *si;
1071
1072 if (current_SID > 0 && current_SID <= script_items.ga_len)
1073 {
1074 si = &SCRIPT_ITEM(current_SID);
1075 if (si->sn_prof_on && si->sn_pr_nest++ == 0)
1076 profile_start(&si->sn_pr_child);
1077 }
1078 profile_get_wait(tm);
1079}
1080
1081/*
1082 * Count time spent in children after invoking another script or function.
1083 */
1084 void
1085script_prof_restore(tm)
1086 proftime_T *tm;
1087{
1088 scriptitem_T *si;
1089
1090 if (current_SID > 0 && current_SID <= script_items.ga_len)
1091 {
1092 si = &SCRIPT_ITEM(current_SID);
1093 if (si->sn_prof_on && --si->sn_pr_nest == 0)
1094 {
1095 profile_end(&si->sn_pr_child);
1096 profile_sub_wait(tm, &si->sn_pr_child); /* don't count wait time */
1097 profile_add(&si->sn_pr_children, &si->sn_pr_child);
1098 profile_add(&si->sn_prl_children, &si->sn_pr_child);
1099 }
1100 }
1101}
1102
1103static proftime_T inchar_time;
1104
1105/*
1106 * Called when starting to wait for the user to type a character.
1107 */
1108 void
1109prof_inchar_enter()
1110{
1111 profile_start(&inchar_time);
1112}
1113
1114/*
1115 * Called when finished waiting for the user to type a character.
1116 */
1117 void
1118prof_inchar_exit()
1119{
1120 profile_end(&inchar_time);
1121 profile_add(&prof_wait_time, &inchar_time);
1122}
1123
1124/*
1125 * Dump the profiling results for all scripts in file "fd".
1126 */
1127 static void
1128script_dump_profile(fd)
1129 FILE *fd;
1130{
1131 int id;
1132 scriptitem_T *si;
1133 int i;
1134 FILE *sfd;
1135 sn_prl_T *pp;
1136
1137 for (id = 1; id <= script_items.ga_len; ++id)
1138 {
1139 si = &SCRIPT_ITEM(id);
1140 if (si->sn_prof_on)
1141 {
1142 fprintf(fd, "SCRIPT %s\n", si->sn_name);
1143 if (si->sn_pr_count == 1)
1144 fprintf(fd, "Sourced 1 time\n");
1145 else
1146 fprintf(fd, "Sourced %d times\n", si->sn_pr_count);
1147 fprintf(fd, "Total time: %s\n", profile_msg(&si->sn_pr_total));
1148 fprintf(fd, " Self time: %s\n", profile_msg(&si->sn_pr_self));
1149 fprintf(fd, "\n");
1150 fprintf(fd, "count total (s) self (s)\n");
1151
1152 sfd = fopen((char *)si->sn_name, "r");
1153 if (sfd == NULL)
1154 fprintf(fd, "Cannot open file!\n");
1155 else
1156 {
1157 for (i = 0; i < si->sn_prl_ga.ga_len; ++i)
1158 {
1159 if (vim_fgets(IObuff, IOSIZE, sfd))
1160 break;
1161 pp = &PRL_ITEM(si, i);
1162 if (pp->snp_count > 0)
1163 {
1164 fprintf(fd, "%5d ", pp->snp_count);
1165 if (profile_equal(&pp->sn_prl_total, &pp->sn_prl_self))
1166 fprintf(fd, " ");
1167 else
1168 fprintf(fd, "%s ", profile_msg(&pp->sn_prl_total));
1169 fprintf(fd, "%s ", profile_msg(&pp->sn_prl_self));
1170 }
1171 else
1172 fprintf(fd, " ");
1173 fprintf(fd, "%s", IObuff);
1174 }
1175 fclose(sfd);
1176 }
1177 fprintf(fd, "\n");
1178 }
1179 }
1180}
1181
1182/*
1183 * Return TRUE when a function defined in the current script should be
1184 * profiled.
1185 */
1186 int
1187prof_def_func()
1188{
Bram Moolenaar53180ce2005-07-05 21:48:14 +00001189 if (current_SID > 0)
1190 return SCRIPT_ITEM(current_SID).sn_pr_force;
1191 return FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001192}
1193
1194# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195#endif
1196
1197/*
1198 * If 'autowrite' option set, try to write the file.
1199 * Careful: autocommands may make "buf" invalid!
1200 *
1201 * return FAIL for failure, OK otherwise
1202 */
1203 int
1204autowrite(buf, forceit)
1205 buf_T *buf;
1206 int forceit;
1207{
1208 if (!(p_aw || p_awa) || !p_write
1209#ifdef FEAT_QUICKFIX
1210 /* never autowrite a "nofile" or "nowrite" buffer */
1211 || bt_dontwrite(buf)
1212#endif
1213 || (!forceit && buf->b_p_ro) || buf->b_ffname == NULL)
1214 return FAIL;
1215 return buf_write_all(buf, forceit);
1216}
1217
1218/*
1219 * flush all buffers, except the ones that are readonly
1220 */
1221 void
1222autowrite_all()
1223{
1224 buf_T *buf;
1225
1226 if (!(p_aw || p_awa) || !p_write)
1227 return;
1228 for (buf = firstbuf; buf; buf = buf->b_next)
1229 if (bufIsChanged(buf) && !buf->b_p_ro)
1230 {
1231 (void)buf_write_all(buf, FALSE);
1232#ifdef FEAT_AUTOCMD
1233 /* an autocommand may have deleted the buffer */
1234 if (!buf_valid(buf))
1235 buf = firstbuf;
1236#endif
1237 }
1238}
1239
1240/*
1241 * return TRUE if buffer was changed and cannot be abandoned.
1242 */
1243/*ARGSUSED*/
1244 int
1245check_changed(buf, checkaw, mult_win, forceit, allbuf)
1246 buf_T *buf;
1247 int checkaw; /* do autowrite if buffer was changed */
1248 int mult_win; /* check also when several wins for the buf */
1249 int forceit;
1250 int allbuf; /* may write all buffers */
1251{
1252 if ( !forceit
1253 && bufIsChanged(buf)
1254 && (mult_win || buf->b_nwindows <= 1)
1255 && (!checkaw || autowrite(buf, forceit) == FAIL))
1256 {
1257#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1258 if ((p_confirm || cmdmod.confirm) && p_write)
1259 {
1260 buf_T *buf2;
1261 int count = 0;
1262
1263 if (allbuf)
1264 for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next)
1265 if (bufIsChanged(buf2)
1266 && (buf2->b_ffname != NULL
1267# ifdef FEAT_BROWSE
1268 || cmdmod.browse
1269# endif
1270 ))
1271 ++count;
1272# ifdef FEAT_AUTOCMD
1273 if (!buf_valid(buf))
1274 /* Autocommand deleted buffer, oops! It's not changed now. */
1275 return FALSE;
1276# endif
1277 dialog_changed(buf, count > 1);
1278# ifdef FEAT_AUTOCMD
1279 if (!buf_valid(buf))
1280 /* Autocommand deleted buffer, oops! It's not changed now. */
1281 return FALSE;
1282# endif
1283 return bufIsChanged(buf);
1284 }
1285#endif
1286 EMSG(_(e_nowrtmsg));
1287 return TRUE;
1288 }
1289 return FALSE;
1290}
1291
1292#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
1293
1294#if defined(FEAT_BROWSE) || defined(PROTO)
1295/*
1296 * When wanting to write a file without a file name, ask the user for a name.
1297 */
1298 void
1299browse_save_fname(buf)
1300 buf_T *buf;
1301{
1302 if (buf->b_fname == NULL)
1303 {
1304 char_u *fname;
1305
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001306 fname = do_browse(BROWSE_SAVE, (char_u *)_("Save As"),
1307 NULL, NULL, NULL, NULL, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 if (fname != NULL)
1309 {
1310 if (setfname(buf, fname, NULL, TRUE) == OK)
1311 buf->b_flags |= BF_NOTEDITED;
1312 vim_free(fname);
1313 }
1314 }
1315}
1316#endif
1317
1318/*
1319 * Ask the user what to do when abondoning a changed buffer.
1320 * Must check 'write' option first!
1321 */
1322 void
1323dialog_changed(buf, checkall)
1324 buf_T *buf;
1325 int checkall; /* may abandon all changed buffers */
1326{
1327 char_u buff[IOSIZE];
1328 int ret;
1329 buf_T *buf2;
1330
Bram Moolenaar82cf9b62005-06-07 21:09:25 +00001331 dialog_msg(buff, _("Save changes to \"%s\"?"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332 (buf->b_fname != NULL) ?
1333 buf->b_fname : (char_u *)_("Untitled"));
1334 if (checkall)
1335 ret = vim_dialog_yesnoallcancel(VIM_QUESTION, NULL, buff, 1);
1336 else
1337 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1338
1339 if (ret == VIM_YES)
1340 {
1341#ifdef FEAT_BROWSE
1342 /* May get file name, when there is none */
1343 browse_save_fname(buf);
1344#endif
1345 if (buf->b_fname != NULL) /* didn't hit Cancel */
1346 (void)buf_write_all(buf, FALSE);
1347 }
1348 else if (ret == VIM_NO)
1349 {
1350 unchanged(buf, TRUE);
1351 }
1352 else if (ret == VIM_ALL)
1353 {
1354 /*
1355 * Write all modified files that can be written.
1356 * Skip readonly buffers, these need to be confirmed
1357 * individually.
1358 */
1359 for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next)
1360 {
1361 if (bufIsChanged(buf2)
1362 && (buf2->b_ffname != NULL
1363#ifdef FEAT_BROWSE
1364 || cmdmod.browse
1365#endif
1366 )
1367 && !buf2->b_p_ro)
1368 {
1369#ifdef FEAT_BROWSE
1370 /* May get file name, when there is none */
1371 browse_save_fname(buf2);
1372#endif
1373 if (buf2->b_fname != NULL) /* didn't hit Cancel */
1374 (void)buf_write_all(buf2, FALSE);
1375#ifdef FEAT_AUTOCMD
1376 /* an autocommand may have deleted the buffer */
1377 if (!buf_valid(buf2))
1378 buf2 = firstbuf;
1379#endif
1380 }
1381 }
1382 }
1383 else if (ret == VIM_DISCARDALL)
1384 {
1385 /*
1386 * mark all buffers as unchanged
1387 */
1388 for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next)
1389 unchanged(buf2, TRUE);
1390 }
1391}
1392#endif
1393
1394/*
1395 * Return TRUE if the buffer "buf" can be abandoned, either by making it
1396 * hidden, autowriting it or unloading it.
1397 */
1398 int
1399can_abandon(buf, forceit)
1400 buf_T *buf;
1401 int forceit;
1402{
1403 return ( P_HID(buf)
1404 || !bufIsChanged(buf)
1405 || buf->b_nwindows > 1
1406 || autowrite(buf, forceit) == OK
1407 || forceit);
1408}
1409
1410/*
1411 * Return TRUE if any buffer was changed and cannot be abandoned.
1412 * That changed buffer becomes the current buffer.
1413 */
1414 int
1415check_changed_any(hidden)
1416 int hidden; /* Only check hidden buffers */
1417{
1418 buf_T *buf;
1419 int save;
1420#ifdef FEAT_WINDOWS
1421 win_T *wp;
1422#endif
1423
1424 for (;;)
1425 {
1426 /* check curbuf first: if it was changed we can't abandon it */
1427 if (!hidden && curbufIsChanged())
1428 buf = curbuf;
1429 else
1430 {
1431 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1432 if ((!hidden || buf->b_nwindows == 0) && bufIsChanged(buf))
1433 break;
1434 }
1435 if (buf == NULL) /* No buffers changed */
1436 return FALSE;
1437
1438 if (check_changed(buf, p_awa, TRUE, FALSE, TRUE) && buf_valid(buf))
1439 break; /* didn't save - still changes */
1440 }
1441
1442 exiting = FALSE;
1443#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1444 /*
1445 * When ":confirm" used, don't give an error message.
1446 */
1447 if (!(p_confirm || cmdmod.confirm))
1448#endif
1449 {
1450 /* There must be a wait_return for this message, do_buffer()
1451 * may cause a redraw. But wait_return() is a no-op when vgetc()
1452 * is busy (Quit used from window menu), then make sure we don't
1453 * cause a scroll up. */
1454 if (vgetc_busy)
1455 {
1456 msg_row = cmdline_row;
1457 msg_col = 0;
1458 msg_didout = FALSE;
1459 }
1460 if (EMSG2(_("E162: No write since last change for buffer \"%s\""),
1461 buf_spname(buf) != NULL ? (char_u *)buf_spname(buf) :
1462 buf->b_fname))
1463 {
1464 save = no_wait_return;
1465 no_wait_return = FALSE;
1466 wait_return(FALSE);
1467 no_wait_return = save;
1468 }
1469 }
1470
1471#ifdef FEAT_WINDOWS
1472 /* Try to find a window that contains the buffer. */
1473 if (buf != curbuf)
1474 for (wp = firstwin; wp != NULL; wp = wp->w_next)
1475 if (wp->w_buffer == buf)
1476 {
1477 win_goto(wp);
1478# ifdef FEAT_AUTOCMD
1479 /* Paranoia: did autocms wipe out the buffer with changes? */
1480 if (!buf_valid(buf))
1481 return TRUE;
1482# endif
1483 break;
1484 }
1485#endif
1486
1487 /* Open the changed buffer in the current window. */
1488 if (buf != curbuf)
1489 set_curbuf(buf, DOBUF_GOTO);
1490
1491 return TRUE;
1492}
1493
1494/*
1495 * return FAIL if there is no file name, OK if there is one
1496 * give error message for FAIL
1497 */
1498 int
1499check_fname()
1500{
1501 if (curbuf->b_ffname == NULL)
1502 {
1503 EMSG(_(e_noname));
1504 return FAIL;
1505 }
1506 return OK;
1507}
1508
1509/*
1510 * flush the contents of a buffer, unless it has no file name
1511 *
1512 * return FAIL for failure, OK otherwise
1513 */
1514 int
1515buf_write_all(buf, forceit)
1516 buf_T *buf;
1517 int forceit;
1518{
1519 int retval;
1520#ifdef FEAT_AUTOCMD
1521 buf_T *old_curbuf = curbuf;
1522#endif
1523
1524 retval = (buf_write(buf, buf->b_ffname, buf->b_fname,
1525 (linenr_T)1, buf->b_ml.ml_line_count, NULL,
1526 FALSE, forceit, TRUE, FALSE));
1527#ifdef FEAT_AUTOCMD
1528 if (curbuf != old_curbuf)
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001529 {
1530 msg_source(hl_attr(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 MSG(_("Warning: Entered other buffer unexpectedly (check autocommands)"));
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001532 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533#endif
1534 return retval;
1535}
1536
1537/*
1538 * Code to handle the argument list.
1539 */
1540
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001541static char_u *do_one_arg __ARGS((char_u *str));
1542static int do_arglist __ARGS((char_u *str, int what, int after));
1543static void alist_check_arg_idx __ARGS((void));
1544static int editing_arg_idx __ARGS((win_T *win));
1545#ifdef FEAT_LISTCMDS
1546static int alist_add_list __ARGS((int count, char_u **files, int after));
1547#endif
1548#define AL_SET 1
1549#define AL_ADD 2
1550#define AL_DEL 3
1551
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001553 * Isolate one argument, taking backticks.
1554 * Changes the argument in-place, puts a NUL after it. Backticks remain.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 * Return a pointer to the start of the next argument.
1556 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001557 static char_u *
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558do_one_arg(str)
1559 char_u *str;
1560{
1561 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001562 int inbacktick;
1563
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 inbacktick = FALSE;
1565 for (p = str; *str; ++str)
1566 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001567 /* When the backslash is used for escaping the special meaning of a
1568 * character we need to keep it until wildcard expansion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 if (rem_backslash(str))
1570 {
1571 *p++ = *str++;
1572 *p++ = *str;
1573 }
1574 else
1575 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001576 /* An item ends at a space not in backticks */
1577 if (!inbacktick && vim_isspace(*str))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001579 if (*str == '`')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 inbacktick ^= TRUE;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001581 *p++ = *str;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 }
1583 }
1584 str = skipwhite(str);
1585 *p = NUL;
1586
1587 return str;
1588}
1589
Bram Moolenaar86b68352004-12-27 21:59:20 +00001590/*
1591 * Separate the arguments in "str" and return a list of pointers in the
1592 * growarray "gap".
1593 */
1594 int
1595get_arglist(gap, str)
1596 garray_T *gap;
1597 char_u *str;
1598{
1599 ga_init2(gap, (int)sizeof(char_u *), 20);
1600 while (*str != NUL)
1601 {
1602 if (ga_grow(gap, 1) == FAIL)
1603 {
1604 ga_clear(gap);
1605 return FAIL;
1606 }
1607 ((char_u **)gap->ga_data)[gap->ga_len++] = str;
1608
1609 /* Isolate one argument, change it in-place, put a NUL after it. */
1610 str = do_one_arg(str);
1611 }
1612 return OK;
1613}
1614
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00001615#if defined(FEAT_QUICKFIX) || (defined(FEAT_SYN_HL) && defined(FEAT_MBYTE)) \
1616 || defined(PROTO)
1617/*
1618 * Parse a list of arguments (file names), expand them and return in
1619 * "fnames[fcountp]".
1620 * Return FAIL or OK.
1621 */
1622 int
1623get_arglist_exp(str, fcountp, fnamesp)
1624 char_u *str;
1625 int *fcountp;
1626 char_u ***fnamesp;
1627{
1628 garray_T ga;
1629 int i;
1630
1631 if (get_arglist(&ga, str) == FAIL)
1632 return FAIL;
1633 i = gen_expand_wildcards(ga.ga_len, (char_u **)ga.ga_data,
1634 fcountp, fnamesp, EW_FILE|EW_NOTFOUND);
1635 ga_clear(&ga);
1636 return i;
1637}
1638#endif
1639
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640#if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
1641/*
1642 * Redefine the argument list.
1643 */
1644 void
1645set_arglist(str)
1646 char_u *str;
1647{
1648 do_arglist(str, AL_SET, 0);
1649}
1650#endif
1651
1652/*
1653 * "what" == AL_SET: Redefine the argument list to 'str'.
1654 * "what" == AL_ADD: add files in 'str' to the argument list after "after".
1655 * "what" == AL_DEL: remove files in 'str' from the argument list.
1656 *
1657 * Return FAIL for failure, OK otherwise.
1658 */
1659/*ARGSUSED*/
1660 static int
1661do_arglist(str, what, after)
1662 char_u *str;
1663 int what;
1664 int after; /* 0 means before first one */
1665{
1666 garray_T new_ga;
1667 int exp_count;
1668 char_u **exp_files;
1669 int i;
1670#ifdef FEAT_LISTCMDS
1671 char_u *p;
1672 int match;
1673#endif
1674
1675 /*
1676 * Collect all file name arguments in "new_ga".
1677 */
Bram Moolenaar86b68352004-12-27 21:59:20 +00001678 if (get_arglist(&new_ga, str) == FAIL)
1679 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680
1681#ifdef FEAT_LISTCMDS
1682 if (what == AL_DEL)
1683 {
1684 regmatch_T regmatch;
1685 int didone;
1686
1687 /*
1688 * Delete the items: use each item as a regexp and find a match in the
1689 * argument list.
1690 */
1691#ifdef CASE_INSENSITIVE_FILENAME
1692 regmatch.rm_ic = TRUE; /* Always ignore case */
1693#else
1694 regmatch.rm_ic = FALSE; /* Never ignore case */
1695#endif
1696 for (i = 0; i < new_ga.ga_len && !got_int; ++i)
1697 {
1698 p = ((char_u **)new_ga.ga_data)[i];
1699 p = file_pat_to_reg_pat(p, NULL, NULL, FALSE);
1700 if (p == NULL)
1701 break;
1702 regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
1703 if (regmatch.regprog == NULL)
1704 {
1705 vim_free(p);
1706 break;
1707 }
1708
1709 didone = FALSE;
1710 for (match = 0; match < ARGCOUNT; ++match)
1711 if (vim_regexec(&regmatch, alist_name(&ARGLIST[match]),
1712 (colnr_T)0))
1713 {
1714 didone = TRUE;
1715 vim_free(ARGLIST[match].ae_fname);
1716 mch_memmove(ARGLIST + match, ARGLIST + match + 1,
1717 (ARGCOUNT - match - 1) * sizeof(aentry_T));
1718 --ALIST(curwin)->al_ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 if (curwin->w_arg_idx > match)
1720 --curwin->w_arg_idx;
1721 --match;
1722 }
1723
1724 vim_free(regmatch.regprog);
1725 vim_free(p);
1726 if (!didone)
1727 EMSG2(_(e_nomatch2), ((char_u **)new_ga.ga_data)[i]);
1728 }
1729 ga_clear(&new_ga);
1730 }
1731 else
1732#endif
1733 {
1734 i = expand_wildcards(new_ga.ga_len, (char_u **)new_ga.ga_data,
1735 &exp_count, &exp_files, EW_DIR|EW_FILE|EW_ADDSLASH|EW_NOTFOUND);
1736 ga_clear(&new_ga);
1737 if (i == FAIL)
1738 return FAIL;
1739 if (exp_count == 0)
1740 {
1741 EMSG(_(e_nomatch));
1742 return FAIL;
1743 }
1744
1745#ifdef FEAT_LISTCMDS
1746 if (what == AL_ADD)
1747 {
1748 (void)alist_add_list(exp_count, exp_files, after);
1749 vim_free(exp_files);
1750 }
1751 else /* what == AL_SET */
1752#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00001753 alist_set(ALIST(curwin), exp_count, exp_files, FALSE, NULL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 }
1755
1756 alist_check_arg_idx();
1757
1758 return OK;
1759}
1760
1761/*
1762 * Check the validity of the arg_idx for each other window.
1763 */
1764 static void
1765alist_check_arg_idx()
1766{
1767#ifdef FEAT_WINDOWS
1768 win_T *win;
1769
1770 for (win = firstwin; win != NULL; win = win->w_next)
1771 if (win->w_alist == curwin->w_alist)
1772 check_arg_idx(win);
1773#else
1774 check_arg_idx(curwin);
1775#endif
1776}
1777
1778/*
Bram Moolenaard4755bb2004-09-02 19:12:26 +00001779 * Return TRUE if window "win" is editing then file at the current argument
1780 * index.
1781 */
1782 static int
1783editing_arg_idx(win)
1784 win_T *win;
1785{
1786 return !(win->w_arg_idx >= WARGCOUNT(win)
1787 || (win->w_buffer->b_fnum
1788 != WARGLIST(win)[win->w_arg_idx].ae_fnum
1789 && (win->w_buffer->b_ffname == NULL
1790 || !(fullpathcmp(
1791 alist_name(&WARGLIST(win)[win->w_arg_idx]),
1792 win->w_buffer->b_ffname, TRUE) & FPC_SAME))));
1793}
1794
1795/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 * Check if window "win" is editing the w_arg_idx file in its argument list.
1797 */
1798 void
1799check_arg_idx(win)
1800 win_T *win;
1801{
Bram Moolenaard4755bb2004-09-02 19:12:26 +00001802 if (WARGCOUNT(win) > 1 && !editing_arg_idx(win))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 {
1804 /* We are not editing the current entry in the argument list.
1805 * Set "arg_had_last" if we are editing the last one. */
1806 win->w_arg_idx_invalid = TRUE;
1807 if (win->w_arg_idx != WARGCOUNT(win) - 1
1808 && arg_had_last == FALSE
1809#ifdef FEAT_WINDOWS
1810 && ALIST(win) == &global_alist
1811#endif
1812 && GARGCOUNT > 0
1813 && win->w_arg_idx < GARGCOUNT
1814 && (win->w_buffer->b_fnum == GARGLIST[GARGCOUNT - 1].ae_fnum
1815 || (win->w_buffer->b_ffname != NULL
1816 && (fullpathcmp(alist_name(&GARGLIST[GARGCOUNT - 1]),
1817 win->w_buffer->b_ffname, TRUE) & FPC_SAME))))
1818 arg_had_last = TRUE;
1819 }
1820 else
1821 {
1822 /* We are editing the current entry in the argument list.
1823 * Set "arg_had_last" if it's also the last one */
1824 win->w_arg_idx_invalid = FALSE;
1825 if (win->w_arg_idx == WARGCOUNT(win) - 1
1826#ifdef FEAT_WINDOWS
1827 && win->w_alist == &global_alist
1828#endif
1829 )
1830 arg_had_last = TRUE;
1831 }
1832}
1833
1834/*
1835 * ":args", ":argslocal" and ":argsglobal".
1836 */
1837 void
1838ex_args(eap)
1839 exarg_T *eap;
1840{
1841 int i;
1842
1843 if (eap->cmdidx != CMD_args)
1844 {
1845#if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS)
1846 alist_unlink(ALIST(curwin));
1847 if (eap->cmdidx == CMD_argglobal)
1848 ALIST(curwin) = &global_alist;
1849 else /* eap->cmdidx == CMD_arglocal */
1850 alist_new();
1851#else
1852 ex_ni(eap);
1853 return;
1854#endif
1855 }
1856
1857 if (!ends_excmd(*eap->arg))
1858 {
1859 /*
1860 * ":args file ..": define new argument list, handle like ":next"
1861 * Also for ":argslocal file .." and ":argsglobal file ..".
1862 */
1863 ex_next(eap);
1864 }
1865 else
1866#if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS)
1867 if (eap->cmdidx == CMD_args)
1868#endif
1869 {
1870 /*
1871 * ":args": list arguments.
1872 */
1873 if (ARGCOUNT > 0)
1874 {
1875 /* Overwrite the command, for a short list there is no scrolling
1876 * required and no wait_return(). */
1877 gotocmdline(TRUE);
1878 for (i = 0; i < ARGCOUNT; ++i)
1879 {
1880 if (i == curwin->w_arg_idx)
1881 msg_putchar('[');
1882 msg_outtrans(alist_name(&ARGLIST[i]));
1883 if (i == curwin->w_arg_idx)
1884 msg_putchar(']');
1885 msg_putchar(' ');
1886 }
1887 }
1888 }
1889#if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS)
1890 else if (eap->cmdidx == CMD_arglocal)
1891 {
1892 garray_T *gap = &curwin->w_alist->al_ga;
1893
1894 /*
1895 * ":argslocal": make a local copy of the global argument list.
1896 */
1897 if (ga_grow(gap, GARGCOUNT) == OK)
1898 for (i = 0; i < GARGCOUNT; ++i)
1899 if (GARGLIST[i].ae_fname != NULL)
1900 {
1901 AARGLIST(curwin->w_alist)[gap->ga_len].ae_fname =
1902 vim_strsave(GARGLIST[i].ae_fname);
1903 AARGLIST(curwin->w_alist)[gap->ga_len].ae_fnum =
1904 GARGLIST[i].ae_fnum;
1905 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 }
1907 }
1908#endif
1909}
1910
1911/*
1912 * ":previous", ":sprevious", ":Next" and ":sNext".
1913 */
1914 void
1915ex_previous(eap)
1916 exarg_T *eap;
1917{
1918 /* If past the last one already, go to the last one. */
1919 if (curwin->w_arg_idx - (int)eap->line2 >= ARGCOUNT)
1920 do_argfile(eap, ARGCOUNT - 1);
1921 else
1922 do_argfile(eap, curwin->w_arg_idx - (int)eap->line2);
1923}
1924
1925/*
1926 * ":rewind", ":first", ":sfirst" and ":srewind".
1927 */
1928 void
1929ex_rewind(eap)
1930 exarg_T *eap;
1931{
1932 do_argfile(eap, 0);
1933}
1934
1935/*
1936 * ":last" and ":slast".
1937 */
1938 void
1939ex_last(eap)
1940 exarg_T *eap;
1941{
1942 do_argfile(eap, ARGCOUNT - 1);
1943}
1944
1945/*
1946 * ":argument" and ":sargument".
1947 */
1948 void
1949ex_argument(eap)
1950 exarg_T *eap;
1951{
1952 int i;
1953
1954 if (eap->addr_count > 0)
1955 i = eap->line2 - 1;
1956 else
1957 i = curwin->w_arg_idx;
1958 do_argfile(eap, i);
1959}
1960
1961/*
1962 * Edit file "argn" of the argument lists.
1963 */
1964 void
1965do_argfile(eap, argn)
1966 exarg_T *eap;
1967 int argn;
1968{
1969 int other;
1970 char_u *p;
Bram Moolenaar34cdc3e2005-05-18 22:24:46 +00001971 int old_arg_idx = curwin->w_arg_idx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972
1973 if (argn < 0 || argn >= ARGCOUNT)
1974 {
1975 if (ARGCOUNT <= 1)
1976 EMSG(_("E163: There is only one file to edit"));
1977 else if (argn < 0)
1978 EMSG(_("E164: Cannot go before first file"));
1979 else
1980 EMSG(_("E165: Cannot go beyond last file"));
1981 }
1982 else
1983 {
1984 setpcmark();
1985#ifdef FEAT_GUI
1986 need_mouse_correct = TRUE;
1987#endif
1988
1989#ifdef FEAT_WINDOWS
1990 if (*eap->cmd == 's') /* split window first */
1991 {
1992 if (win_split(0, 0) == FAIL)
1993 return;
1994# ifdef FEAT_SCROLLBIND
1995 curwin->w_p_scb = FALSE;
1996# endif
1997 }
1998 else
1999#endif
2000 {
2001 /*
2002 * if 'hidden' set, only check for changed file when re-editing
2003 * the same buffer
2004 */
2005 other = TRUE;
2006 if (P_HID(curbuf))
2007 {
2008 p = fix_fname(alist_name(&ARGLIST[argn]));
2009 other = otherfile(p);
2010 vim_free(p);
2011 }
2012 if ((!P_HID(curbuf) || !other)
2013 && check_changed(curbuf, TRUE, !other, eap->forceit, FALSE))
2014 return;
2015 }
2016
2017 curwin->w_arg_idx = argn;
2018 if (argn == ARGCOUNT - 1
2019#ifdef FEAT_WINDOWS
2020 && curwin->w_alist == &global_alist
2021#endif
2022 )
2023 arg_had_last = TRUE;
2024
Bram Moolenaar34cdc3e2005-05-18 22:24:46 +00002025 /* Edit the file; always use the last known line number.
2026 * When it fails (e.g. Abort for already edited file) restore the
2027 * argument index. */
2028 if (do_ecmd(0, alist_name(&ARGLIST[curwin->w_arg_idx]), NULL,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029 eap, ECMD_LAST,
2030 (P_HID(curwin->w_buffer) ? ECMD_HIDE : 0) +
Bram Moolenaar34cdc3e2005-05-18 22:24:46 +00002031 (eap->forceit ? ECMD_FORCEIT : 0)) == FAIL)
2032 curwin->w_arg_idx = old_arg_idx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 /* like Vi: set the mark where the cursor is in the file. */
Bram Moolenaar34cdc3e2005-05-18 22:24:46 +00002034 else if (eap->cmdidx != CMD_argdo)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 setmark('\'');
2036 }
2037}
2038
2039/*
2040 * ":next", and commands that behave like it.
2041 */
2042 void
2043ex_next(eap)
2044 exarg_T *eap;
2045{
2046 int i;
2047
2048 /*
2049 * check for changed buffer now, if this fails the argument list is not
2050 * redefined.
2051 */
2052 if ( P_HID(curbuf)
2053 || eap->cmdidx == CMD_snext
2054 || !check_changed(curbuf, TRUE, FALSE, eap->forceit, FALSE))
2055 {
2056 if (*eap->arg != NUL) /* redefine file list */
2057 {
2058 if (do_arglist(eap->arg, AL_SET, 0) == FAIL)
2059 return;
2060 i = 0;
2061 }
2062 else
2063 i = curwin->w_arg_idx + (int)eap->line2;
2064 do_argfile(eap, i);
2065 }
2066}
2067
2068#ifdef FEAT_LISTCMDS
2069/*
2070 * ":argedit"
2071 */
2072 void
2073ex_argedit(eap)
2074 exarg_T *eap;
2075{
2076 int fnum;
2077 int i;
2078 char_u *s;
2079
2080 /* Add the argument to the buffer list and get the buffer number. */
2081 fnum = buflist_add(eap->arg, BLN_LISTED);
2082
2083 /* Check if this argument is already in the argument list. */
2084 for (i = 0; i < ARGCOUNT; ++i)
2085 if (ARGLIST[i].ae_fnum == fnum)
2086 break;
2087 if (i == ARGCOUNT)
2088 {
2089 /* Can't find it, add it to the argument list. */
2090 s = vim_strsave(eap->arg);
2091 if (s == NULL)
2092 return;
2093 i = alist_add_list(1, &s,
2094 eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1);
2095 if (i < 0)
2096 return;
2097 curwin->w_arg_idx = i;
2098 }
2099
2100 alist_check_arg_idx();
2101
2102 /* Edit the argument. */
2103 do_argfile(eap, i);
2104}
2105
2106/*
2107 * ":argadd"
2108 */
2109 void
2110ex_argadd(eap)
2111 exarg_T *eap;
2112{
2113 do_arglist(eap->arg, AL_ADD,
2114 eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1);
2115#ifdef FEAT_TITLE
2116 maketitle();
2117#endif
2118}
2119
2120/*
2121 * ":argdelete"
2122 */
2123 void
2124ex_argdelete(eap)
2125 exarg_T *eap;
2126{
2127 int i;
2128 int n;
2129
2130 if (eap->addr_count > 0)
2131 {
2132 /* ":1,4argdel": Delete all arguments in the range. */
2133 if (eap->line2 > ARGCOUNT)
2134 eap->line2 = ARGCOUNT;
2135 n = eap->line2 - eap->line1 + 1;
2136 if (*eap->arg != NUL || n <= 0)
2137 EMSG(_(e_invarg));
2138 else
2139 {
2140 for (i = eap->line1; i <= eap->line2; ++i)
2141 vim_free(ARGLIST[i - 1].ae_fname);
2142 mch_memmove(ARGLIST + eap->line1 - 1, ARGLIST + eap->line2,
2143 (size_t)((ARGCOUNT - eap->line2) * sizeof(aentry_T)));
2144 ALIST(curwin)->al_ga.ga_len -= n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 if (curwin->w_arg_idx >= eap->line2)
2146 curwin->w_arg_idx -= n;
2147 else if (curwin->w_arg_idx > eap->line1)
2148 curwin->w_arg_idx = eap->line1;
2149 }
2150 }
2151 else if (*eap->arg == NUL)
2152 EMSG(_(e_argreq));
2153 else
2154 do_arglist(eap->arg, AL_DEL, 0);
2155#ifdef FEAT_TITLE
2156 maketitle();
2157#endif
2158}
2159
2160/*
2161 * ":argdo", ":windo", ":bufdo"
2162 */
2163 void
2164ex_listdo(eap)
2165 exarg_T *eap;
2166{
2167 int i;
2168#ifdef FEAT_WINDOWS
2169 win_T *win;
2170#endif
2171 buf_T *buf;
2172 int next_fnum = 0;
2173#if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL)
2174 char_u *save_ei = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002176 char_u *p_shm_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177
2178#ifndef FEAT_WINDOWS
2179 if (eap->cmdidx == CMD_windo)
2180 {
2181 ex_ni(eap);
2182 return;
2183 }
2184#endif
2185
2186#if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL)
2187 if (eap->cmdidx != CMD_windo)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00002188 /* Don't do syntax HL autocommands. Skipping the syntax file is a
2189 * great speed improvement. */
2190 save_ei = au_event_disable(",Syntax");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191#endif
2192
2193 if (eap->cmdidx == CMD_windo
2194 || P_HID(curbuf)
2195 || !check_changed(curbuf, TRUE, FALSE, eap->forceit, FALSE))
2196 {
2197 /* start at the first argument/window/buffer */
2198 i = 0;
2199#ifdef FEAT_WINDOWS
2200 win = firstwin;
2201#endif
2202 /* set pcmark now */
2203 if (eap->cmdidx == CMD_bufdo)
2204 goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
2205 else
2206 setpcmark();
2207 listcmd_busy = TRUE; /* avoids setting pcmark below */
2208
2209 while (!got_int)
2210 {
2211 if (eap->cmdidx == CMD_argdo)
2212 {
2213 /* go to argument "i" */
2214 if (i == ARGCOUNT)
2215 break;
2216 /* Don't call do_argfile() when already there, it will try
2217 * reloading the file. */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002218 if (curwin->w_arg_idx != i || !editing_arg_idx(curwin))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002219 {
2220 /* Clear 'shm' to avoid that the file message overwrites
2221 * any output from the command. */
2222 p_shm_save = vim_strsave(p_shm);
2223 set_option_value((char_u *)"shm", 0L, (char_u *)"", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 do_argfile(eap, i);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002225 set_option_value((char_u *)"shm", 0L, p_shm_save, 0);
2226 vim_free(p_shm_save);
2227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 if (curwin->w_arg_idx != i)
2229 break;
2230 ++i;
2231 }
2232#ifdef FEAT_WINDOWS
2233 else if (eap->cmdidx == CMD_windo)
2234 {
2235 /* go to window "win" */
2236 if (!win_valid(win))
2237 break;
2238 win_goto(win);
2239 win = win->w_next;
2240 }
2241#endif
2242 else if (eap->cmdidx == CMD_bufdo)
2243 {
2244 /* Remember the number of the next listed buffer, in case
2245 * ":bwipe" is used or autocommands do something strange. */
2246 next_fnum = -1;
2247 for (buf = curbuf->b_next; buf != NULL; buf = buf->b_next)
2248 if (buf->b_p_bl)
2249 {
2250 next_fnum = buf->b_fnum;
2251 break;
2252 }
2253 }
2254
2255 /* execute the command */
2256 do_cmdline(eap->arg, eap->getline, eap->cookie,
2257 DOCMD_VERBOSE + DOCMD_NOWAIT);
2258
2259 if (eap->cmdidx == CMD_bufdo)
2260 {
2261 /* Done? */
2262 if (next_fnum < 0)
2263 break;
2264 /* Check if the buffer still exists. */
2265 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2266 if (buf->b_fnum == next_fnum)
2267 break;
2268 if (buf == NULL)
2269 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002270
2271 /* Go to the next buffer. Clear 'shm' to avoid that the file
2272 * message overwrites any output from the command. */
2273 p_shm_save = vim_strsave(p_shm);
2274 set_option_value((char_u *)"shm", 0L, (char_u *)"", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 goto_buffer(eap, DOBUF_FIRST, FORWARD, next_fnum);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002276 set_option_value((char_u *)"shm", 0L, p_shm_save, 0);
2277 vim_free(p_shm_save);
2278
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 /* If autocommands took us elsewhere, quit here */
2280 if (curbuf->b_fnum != next_fnum)
2281 break;
2282 }
2283
2284 if (eap->cmdidx == CMD_windo)
2285 {
2286 validate_cursor(); /* cursor may have moved */
2287#ifdef FEAT_SCROLLBIND
2288 /* required when 'scrollbind' has been set */
2289 if (curwin->w_p_scb)
2290 do_check_scrollbind(TRUE);
2291#endif
2292 }
2293 }
2294 listcmd_busy = FALSE;
2295 }
2296
2297#if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL)
Bram Moolenaar6ac54292005-02-02 23:07:25 +00002298 if (save_ei != NULL)
2299 {
2300 au_event_restore(save_ei);
2301 apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn,
2302 curbuf->b_fname, TRUE, curbuf);
2303 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304#endif
2305}
2306
2307/*
2308 * Add files[count] to the arglist of the current window after arg "after".
2309 * The file names in files[count] must have been allocated and are taken over.
2310 * Files[] itself is not taken over.
2311 * Returns index of first added argument. Returns -1 when failed (out of mem).
2312 */
2313 static int
2314alist_add_list(count, files, after)
2315 int count;
2316 char_u **files;
2317 int after; /* where to add: 0 = before first one */
2318{
2319 int i;
2320
2321 if (ga_grow(&ALIST(curwin)->al_ga, count) == OK)
2322 {
2323 if (after < 0)
2324 after = 0;
2325 if (after > ARGCOUNT)
2326 after = ARGCOUNT;
2327 if (after < ARGCOUNT)
2328 mch_memmove(&(ARGLIST[after + count]), &(ARGLIST[after]),
2329 (ARGCOUNT - after) * sizeof(aentry_T));
2330 for (i = 0; i < count; ++i)
2331 {
2332 ARGLIST[after + i].ae_fname = files[i];
2333 ARGLIST[after + i].ae_fnum = buflist_add(files[i], BLN_LISTED);
2334 }
2335 ALIST(curwin)->al_ga.ga_len += count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336 if (curwin->w_arg_idx >= after)
2337 ++curwin->w_arg_idx;
2338 return after;
2339 }
2340
2341 for (i = 0; i < count; ++i)
2342 vim_free(files[i]);
2343 return -1;
2344}
2345
2346#endif /* FEAT_LISTCMDS */
2347
2348#ifdef FEAT_EVAL
2349/*
2350 * ":compiler[!] {name}"
2351 */
2352 void
2353ex_compiler(eap)
2354 exarg_T *eap;
2355{
2356 char_u *buf;
2357 char_u *old_cur_comp = NULL;
2358 char_u *p;
2359
2360 if (*eap->arg == NUL)
2361 {
2362 /* List all compiler scripts. */
2363 do_cmdline_cmd((char_u *)"echo globpath(&rtp, 'compiler/*.vim')");
2364 /* ) keep the indenter happy... */
2365 }
2366 else
2367 {
2368 buf = alloc((unsigned)(STRLEN(eap->arg) + 14));
2369 if (buf != NULL)
2370 {
2371 if (eap->forceit)
2372 {
2373 /* ":compiler! {name}" sets global options */
2374 do_cmdline_cmd((char_u *)
2375 "command -nargs=* CompilerSet set <args>");
2376 }
2377 else
2378 {
2379 /* ":compiler! {name}" sets local options.
2380 * To remain backwards compatible "current_compiler" is always
2381 * used. A user's compiler plugin may set it, the distributed
2382 * plugin will then skip the settings. Afterwards set
2383 * "b:current_compiler" and restore "current_compiler". */
2384 old_cur_comp = get_var_value((char_u *)"current_compiler");
2385 if (old_cur_comp != NULL)
2386 old_cur_comp = vim_strsave(old_cur_comp);
2387 do_cmdline_cmd((char_u *)
2388 "command -nargs=* CompilerSet setlocal <args>");
2389 }
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00002390 do_unlet((char_u *)"current_compiler", TRUE);
2391 do_unlet((char_u *)"b:current_compiler", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392
2393 sprintf((char *)buf, "compiler/%s.vim", eap->arg);
2394 if (cmd_runtime(buf, TRUE) == FAIL)
2395 EMSG2(_("E666: compiler not supported: %s"), eap->arg);
2396 vim_free(buf);
2397
2398 do_cmdline_cmd((char_u *)":delcommand CompilerSet");
2399
2400 /* Set "b:current_compiler" from "current_compiler". */
2401 p = get_var_value((char_u *)"current_compiler");
2402 if (p != NULL)
2403 set_internal_string_var((char_u *)"b:current_compiler", p);
2404
2405 /* Restore "current_compiler" for ":compiler {name}". */
2406 if (!eap->forceit)
2407 {
2408 if (old_cur_comp != NULL)
2409 {
2410 set_internal_string_var((char_u *)"current_compiler",
2411 old_cur_comp);
2412 vim_free(old_cur_comp);
2413 }
2414 else
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00002415 do_unlet((char_u *)"current_compiler", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 }
2417 }
2418 }
2419}
2420#endif
2421
2422/*
2423 * ":runtime {name}"
2424 */
2425 void
2426ex_runtime(eap)
2427 exarg_T *eap;
2428{
2429 cmd_runtime(eap->arg, eap->forceit);
2430}
2431
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002432static void source_callback __ARGS((char_u *fname, void *cookie));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002434/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 static void
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002436source_callback(fname, cookie)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 char_u *fname;
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002438 void *cookie;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439{
2440 (void)do_source(fname, FALSE, FALSE);
2441}
2442
2443/*
2444 * Source the file "name" from all directories in 'runtimepath'.
2445 * "name" can contain wildcards.
2446 * When "all" is TRUE, source all files, otherwise only the first one.
2447 * return FAIL when no file could be sourced, OK otherwise.
2448 */
2449 int
2450cmd_runtime(name, all)
2451 char_u *name;
2452 int all;
2453{
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002454 return do_in_runtimepath(name, all, source_callback, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455}
2456
2457/*
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002458 * Find "name" in 'runtimepath'. When found, invoke the callback function for
2459 * it: callback(fname, "cookie")
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 * When "all" is TRUE repeat for all matches, otherwise only the first one is
2461 * used.
2462 * Returns OK when at least one match found, FAIL otherwise.
2463 */
2464 int
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002465do_in_runtimepath(name, all, callback, cookie)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 char_u *name;
2467 int all;
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002468 void (*callback)__ARGS((char_u *fname, void *ck));
2469 void *cookie;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470{
2471 char_u *rtp;
2472 char_u *np;
2473 char_u *buf;
2474 char_u *rtp_copy;
2475 char_u *tail;
2476 int num_files;
2477 char_u **files;
2478 int i;
2479 int did_one = FALSE;
2480#ifdef AMIGA
2481 struct Process *proc = (struct Process *)FindTask(0L);
2482 APTR save_winptr = proc->pr_WindowPtr;
2483
2484 /* Avoid a requester here for a volume that doesn't exist. */
2485 proc->pr_WindowPtr = (APTR)-1L;
2486#endif
2487
2488 /* Make a copy of 'runtimepath'. Invoking the callback may change the
2489 * value. */
2490 rtp_copy = vim_strsave(p_rtp);
2491 buf = alloc(MAXPATHL);
2492 if (buf != NULL && rtp_copy != NULL)
2493 {
2494 if (p_verbose > 1)
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002495 {
2496 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00002497 smsg((char_u *)_("Searching for \"%s\" in \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 (char *)name, (char *)p_rtp);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002499 verbose_leave();
2500 }
Bram Moolenaar34cdc3e2005-05-18 22:24:46 +00002501
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 /* Loop over all entries in 'runtimepath'. */
2503 rtp = rtp_copy;
2504 while (*rtp != NUL && (all || !did_one))
2505 {
2506 /* Copy the path from 'runtimepath' to buf[]. */
2507 copy_option_part(&rtp, buf, MAXPATHL, ",");
2508 if (STRLEN(buf) + STRLEN(name) + 2 < MAXPATHL)
2509 {
2510 add_pathsep(buf);
2511 tail = buf + STRLEN(buf);
2512
2513 /* Loop over all patterns in "name" */
2514 np = name;
2515 while (*np != NUL && (all || !did_one))
2516 {
2517 /* Append the pattern from "name" to buf[]. */
2518 copy_option_part(&np, tail, (int)(MAXPATHL - (tail - buf)),
2519 "\t ");
2520
2521 if (p_verbose > 2)
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002522 {
2523 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00002524 smsg((char_u *)_("Searching for \"%s\""), buf);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002525 verbose_leave();
2526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527
2528 /* Expand wildcards, invoke the callback for each match. */
2529 if (gen_expand_wildcards(1, &buf, &num_files, &files,
2530 EW_FILE) == OK)
2531 {
2532 for (i = 0; i < num_files; ++i)
2533 {
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00002534 (*callback)(files[i], cookie);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 did_one = TRUE;
2536 if (!all)
2537 break;
2538 }
2539 FreeWild(num_files, files);
2540 }
2541 }
2542 }
2543 }
2544 }
2545 vim_free(buf);
2546 vim_free(rtp_copy);
2547 if (p_verbose > 0 && !did_one)
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002548 {
2549 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00002550 smsg((char_u *)_("not found in 'runtimepath': \"%s\""), name);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002551 verbose_leave();
2552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553
2554#ifdef AMIGA
2555 proc->pr_WindowPtr = save_winptr;
2556#endif
2557
2558 return did_one ? OK : FAIL;
2559}
2560
2561#if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
2562/*
2563 * ":options"
2564 */
2565/*ARGSUSED*/
2566 void
2567ex_options(eap)
2568 exarg_T *eap;
2569{
2570 cmd_source((char_u *)SYS_OPTWIN_FILE, NULL);
2571}
2572#endif
2573
2574/*
2575 * ":source {fname}"
2576 */
2577 void
2578ex_source(eap)
2579 exarg_T *eap;
2580{
2581#ifdef FEAT_BROWSE
2582 if (cmdmod.browse)
2583 {
2584 char_u *fname = NULL;
2585
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002586 fname = do_browse(0, (char_u *)_("Source Vim script"), eap->arg,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 NULL, NULL, BROWSE_FILTER_MACROS, NULL);
2588 if (fname != NULL)
2589 {
2590 cmd_source(fname, eap);
2591 vim_free(fname);
2592 }
2593 }
2594 else
2595#endif
2596 cmd_source(eap->arg, eap);
2597}
2598
2599 static void
2600cmd_source(fname, eap)
2601 char_u *fname;
2602 exarg_T *eap;
2603{
2604 if (*fname == NUL)
2605 EMSG(_(e_argreq));
2606
2607 /* ":source!" read vi commands */
2608 else if (eap != NULL && eap->forceit)
2609 /* Need to execute the commands directly when:
2610 * - ":g" command busy
2611 * - after ":argdo", ":windo" or ":bufdo"
2612 * - another command follows
2613 * - inside a loop
2614 */
2615 openscript(fname, global_busy || listcmd_busy || eap->nextcmd != NULL
2616#ifdef FEAT_EVAL
2617 || eap->cstack->cs_idx >= 0
2618#endif
2619 );
2620
2621 /* ":source" read ex commands */
2622 else if (do_source(fname, FALSE, FALSE) == FAIL)
2623 EMSG2(_(e_notopen), fname);
2624}
2625
2626/*
2627 * ":source" and associated commands.
2628 */
2629/*
2630 * Structure used to store info for each sourced file.
2631 * It is shared between do_source() and getsourceline().
2632 * This is required, because it needs to be handed to do_cmdline() and
2633 * sourcing can be done recursively.
2634 */
2635struct source_cookie
2636{
2637 FILE *fp; /* opened file for sourcing */
2638 char_u *nextline; /* if not NULL: line that was read ahead */
2639 int finished; /* ":finish" used */
2640#if defined (USE_CRNL) || defined (USE_CR)
2641 int fileformat; /* EOL_UNKNOWN, EOL_UNIX or EOL_DOS */
2642 int error; /* TRUE if LF found after CR-LF */
2643#endif
2644#ifdef FEAT_EVAL
2645 linenr_T breakpoint; /* next line with breakpoint or zero */
2646 char_u *fname; /* name of sourced file */
2647 int dbg_tick; /* debug_tick when breakpoint was set */
2648 int level; /* top nesting level of sourced file */
2649#endif
2650#ifdef FEAT_MBYTE
2651 vimconv_T conv; /* type of conversion */
2652#endif
2653};
2654
2655#ifdef FEAT_EVAL
2656/*
2657 * Return the address holding the next breakpoint line for a source cookie.
2658 */
2659 linenr_T *
2660source_breakpoint(cookie)
2661 void *cookie;
2662{
2663 return &((struct source_cookie *)cookie)->breakpoint;
2664}
2665
2666/*
2667 * Return the address holding the debug tick for a source cookie.
2668 */
2669 int *
2670source_dbg_tick(cookie)
2671 void *cookie;
2672{
2673 return &((struct source_cookie *)cookie)->dbg_tick;
2674}
2675
2676/*
2677 * Return the nesting level for a source cookie.
2678 */
2679 int
2680source_level(cookie)
2681 void *cookie;
2682{
2683 return ((struct source_cookie *)cookie)->level;
2684}
2685#endif
2686
2687static char_u *get_one_sourceline __ARGS((struct source_cookie *sp));
2688
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689#if defined(WIN32) && defined(FEAT_CSCOPE)
2690static FILE *fopen_noinh_readbin __ARGS((char *filename));
2691
2692/*
2693 * Special function to open a file without handle inheritance.
2694 */
2695 static FILE *
2696fopen_noinh_readbin(filename)
2697 char *filename;
2698{
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00002699 int fd_tmp = mch_open(filename, O_RDONLY | O_BINARY | O_NOINHERIT, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700
2701 if (fd_tmp == -1)
2702 return NULL;
2703 return fdopen(fd_tmp, READBIN);
2704}
2705#endif
2706
2707
2708/*
2709 * do_source: Read the file "fname" and execute its lines as EX commands.
2710 *
2711 * This function may be called recursively!
2712 *
2713 * return FAIL if file could not be opened, OK otherwise
2714 */
2715 int
2716do_source(fname, check_other, is_vimrc)
2717 char_u *fname;
2718 int check_other; /* check for .vimrc and _vimrc */
2719 int is_vimrc; /* call vimrc_found() when file exists */
2720{
2721 struct source_cookie cookie;
2722 char_u *save_sourcing_name;
2723 linenr_T save_sourcing_lnum;
2724 char_u *p;
2725 char_u *fname_exp;
2726 int retval = FAIL;
2727#ifdef FEAT_EVAL
2728 scid_T save_current_SID;
2729 static scid_T last_current_SID = 0;
2730 void *save_funccalp;
2731 int save_debug_break_level = debug_break_level;
Bram Moolenaar05159a02005-02-26 23:04:13 +00002732 scriptitem_T *si = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733# ifdef UNIX
2734 struct stat st;
2735 int stat_ok;
2736# endif
2737#endif
2738#ifdef STARTUPTIME
2739 struct timeval tv_rel;
2740 struct timeval tv_start;
2741#endif
Bram Moolenaar05159a02005-02-26 23:04:13 +00002742#ifdef FEAT_PROFILE
2743 proftime_T wait_start;
2744#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745
2746#ifdef RISCOS
2747 p = mch_munge_fname(fname);
2748#else
2749 p = expand_env_save(fname);
2750#endif
2751 if (p == NULL)
2752 return retval;
2753 fname_exp = fix_fname(p);
2754 vim_free(p);
2755 if (fname_exp == NULL)
2756 return retval;
2757#ifdef MACOS_CLASSIC
2758 slash_n_colon_adjust(fname_exp);
2759#endif
2760 if (mch_isdir(fname_exp))
2761 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00002762 smsg((char_u *)_("Cannot source a directory: \"%s\""), fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763 goto theend;
2764 }
2765
2766#if defined(WIN32) && defined(FEAT_CSCOPE)
2767 cookie.fp = fopen_noinh_readbin((char *)fname_exp);
2768#else
2769 cookie.fp = mch_fopen((char *)fname_exp, READBIN);
2770#endif
2771 if (cookie.fp == NULL && check_other)
2772 {
2773 /*
2774 * Try again, replacing file name ".vimrc" by "_vimrc" or vice versa,
2775 * and ".exrc" by "_exrc" or vice versa.
2776 */
2777 p = gettail(fname_exp);
2778 if ((*p == '.' || *p == '_')
2779 && (STRICMP(p + 1, "vimrc") == 0
2780 || STRICMP(p + 1, "gvimrc") == 0
2781 || STRICMP(p + 1, "exrc") == 0))
2782 {
2783 if (*p == '_')
2784 *p = '.';
2785 else
2786 *p = '_';
2787#if defined(WIN32) && defined(FEAT_CSCOPE)
2788 cookie.fp = fopen_noinh_readbin((char *)fname_exp);
2789#else
2790 cookie.fp = mch_fopen((char *)fname_exp, READBIN);
2791#endif
2792 }
2793 }
2794
2795 if (cookie.fp == NULL)
2796 {
2797 if (p_verbose > 0)
2798 {
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002799 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 if (sourcing_name == NULL)
Bram Moolenaar555b2802005-05-19 21:08:39 +00002801 smsg((char_u *)_("could not source \"%s\""), fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002802 else
2803 smsg((char_u *)_("line %ld: could not source \"%s\""),
Bram Moolenaar555b2802005-05-19 21:08:39 +00002804 sourcing_lnum, fname);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002805 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 }
2807 goto theend;
2808 }
2809
2810 /*
2811 * The file exists.
2812 * - In verbose mode, give a message.
2813 * - For a vimrc file, may want to set 'compatible', call vimrc_found().
2814 */
2815 if (p_verbose > 1)
2816 {
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002817 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 if (sourcing_name == NULL)
Bram Moolenaar555b2802005-05-19 21:08:39 +00002819 smsg((char_u *)_("sourcing \"%s\""), fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 else
2821 smsg((char_u *)_("line %ld: sourcing \"%s\""),
Bram Moolenaar555b2802005-05-19 21:08:39 +00002822 sourcing_lnum, fname);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00002823 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824 }
2825 if (is_vimrc)
2826 vimrc_found();
2827
2828#ifdef USE_CRNL
2829 /* If no automatic file format: Set default to CR-NL. */
2830 if (*p_ffs == NUL)
2831 cookie.fileformat = EOL_DOS;
2832 else
2833 cookie.fileformat = EOL_UNKNOWN;
2834 cookie.error = FALSE;
2835#endif
2836
2837#ifdef USE_CR
2838 /* If no automatic file format: Set default to CR. */
2839 if (*p_ffs == NUL)
2840 cookie.fileformat = EOL_MAC;
2841 else
2842 cookie.fileformat = EOL_UNKNOWN;
2843 cookie.error = FALSE;
2844#endif
2845
2846 cookie.nextline = NULL;
2847 cookie.finished = FALSE;
2848
2849#ifdef FEAT_EVAL
2850 /*
2851 * Check if this script has a breakpoint.
2852 */
2853 cookie.breakpoint = dbg_find_breakpoint(TRUE, fname_exp, (linenr_T)0);
2854 cookie.fname = fname_exp;
2855 cookie.dbg_tick = debug_tick;
2856
2857 cookie.level = ex_nesting_level;
2858#endif
2859#ifdef FEAT_MBYTE
2860 cookie.conv.vc_type = CONV_NONE; /* no conversion */
2861
2862 /* Try reading the first few bytes to check for a UTF-8 BOM. */
2863 {
2864 char_u buf[3];
2865
2866 if (fread((char *)buf, sizeof(char_u), (size_t)3, cookie.fp)
2867 == (size_t)3
2868 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf)
2869 /* Found BOM, setup conversion and skip over it. */
2870 convert_setup(&cookie.conv, (char_u *)"utf-8", p_enc);
2871 else
2872 /* No BOM found, rewind. */
2873 fseek(cookie.fp, 0L, SEEK_SET);
2874 }
2875#endif
2876
2877 /*
2878 * Keep the sourcing name/lnum, for recursive calls.
2879 */
2880 save_sourcing_name = sourcing_name;
2881 sourcing_name = fname_exp;
2882 save_sourcing_lnum = sourcing_lnum;
2883 sourcing_lnum = 0;
2884
2885#ifdef STARTUPTIME
2886 time_push(&tv_rel, &tv_start);
2887#endif
2888
2889#ifdef FEAT_EVAL
Bram Moolenaar05159a02005-02-26 23:04:13 +00002890# ifdef FEAT_PROFILE
2891 if (do_profiling)
2892 prof_child_enter(&wait_start); /* entering a child now */
2893# endif
2894
2895 /* Don't use local function variables, if called from a function.
2896 * Also starts profiling timer for nested script. */
2897 save_funccalp = save_funccal();
2898
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 /*
2900 * Check if this script was sourced before to finds its SID.
2901 * If it's new, generate a new SID.
2902 */
2903 save_current_SID = current_SID;
2904# ifdef UNIX
2905 stat_ok = (mch_stat((char *)fname_exp, &st) >= 0);
2906# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +00002907 for (current_SID = script_items.ga_len; current_SID > 0; --current_SID)
2908 {
2909 si = &SCRIPT_ITEM(current_SID);
2910 if (si->sn_name != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 && (
2912# ifdef UNIX
Bram Moolenaar7c626922005-02-07 22:01:03 +00002913 /* Compare dev/ino when possible, it catches symbolic
2914 * links. Also compare file names, the inode may change
2915 * when the file was edited. */
Bram Moolenaar05159a02005-02-26 23:04:13 +00002916 ((stat_ok && si->sn_dev != -1)
2917 && (si->sn_dev == st.st_dev
2918 && si->sn_ino == st.st_ino)) ||
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919# endif
Bram Moolenaar05159a02005-02-26 23:04:13 +00002920 fnamecmp(si->sn_name, fname_exp) == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 break;
Bram Moolenaar05159a02005-02-26 23:04:13 +00002922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 if (current_SID == 0)
2924 {
2925 current_SID = ++last_current_SID;
Bram Moolenaar05159a02005-02-26 23:04:13 +00002926 if (ga_grow(&script_items, (int)(current_SID - script_items.ga_len))
2927 == FAIL)
2928 goto almosttheend;
2929 while (script_items.ga_len < current_SID)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00002931 ++script_items.ga_len;
2932 SCRIPT_ITEM(script_items.ga_len).sn_name = NULL;
2933# ifdef FEAT_PROFILE
2934 SCRIPT_ITEM(script_items.ga_len).sn_prof_on = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00002937 si = &SCRIPT_ITEM(current_SID);
2938 si->sn_name = fname_exp;
2939 fname_exp = NULL;
2940# ifdef UNIX
2941 if (stat_ok)
2942 {
2943 si->sn_dev = st.st_dev;
2944 si->sn_ino = st.st_ino;
2945 }
2946 else
2947 si->sn_dev = -1;
2948# endif
2949
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 /* Allocate the local script variables to use for this script. */
2951 new_script_vars(current_SID);
2952 }
2953
Bram Moolenaar05159a02005-02-26 23:04:13 +00002954# ifdef FEAT_PROFILE
2955 if (do_profiling)
2956 {
2957 int forceit;
2958
2959 /* Check if we do profiling for this script. */
2960 if (!si->sn_prof_on && has_profiling(TRUE, si->sn_name, &forceit))
2961 {
2962 script_do_profile(si);
2963 si->sn_pr_force = forceit;
2964 }
2965 if (si->sn_prof_on)
2966 {
2967 ++si->sn_pr_count;
2968 profile_start(&si->sn_pr_start);
2969 profile_zero(&si->sn_pr_children);
2970 }
2971 }
2972# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973#endif
2974
2975 /*
2976 * Call do_cmdline, which will call getsourceline() to get the lines.
2977 */
2978 do_cmdline(NULL, getsourceline, (void *)&cookie,
2979 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_REPEAT);
2980
2981 retval = OK;
Bram Moolenaar05159a02005-02-26 23:04:13 +00002982
2983#ifdef FEAT_PROFILE
2984 if (do_profiling)
2985 {
2986 /* Get "si" again, "script_items" may have been reallocated. */
2987 si = &SCRIPT_ITEM(current_SID);
2988 if (si->sn_prof_on)
2989 {
2990 profile_end(&si->sn_pr_start);
2991 profile_sub_wait(&wait_start, &si->sn_pr_start);
2992 profile_add(&si->sn_pr_total, &si->sn_pr_start);
2993 profile_add(&si->sn_pr_self, &si->sn_pr_start);
2994 profile_sub(&si->sn_pr_self, &si->sn_pr_children);
2995 }
2996 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997#endif
2998
2999 if (got_int)
3000 EMSG(_(e_interr));
3001 sourcing_name = save_sourcing_name;
3002 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 if (p_verbose > 1)
3004 {
Bram Moolenaar54ee7752005-05-31 22:22:17 +00003005 verbose_enter();
Bram Moolenaar555b2802005-05-19 21:08:39 +00003006 smsg((char_u *)_("finished sourcing %s"), fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007 if (sourcing_name != NULL)
Bram Moolenaar555b2802005-05-19 21:08:39 +00003008 smsg((char_u *)_("continuing in %s"), sourcing_name);
Bram Moolenaar54ee7752005-05-31 22:22:17 +00003009 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 }
3011#ifdef STARTUPTIME
Bram Moolenaar555b2802005-05-19 21:08:39 +00003012 vim_snprintf(IObuff, IOSIZE, "sourcing %s", fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 time_msg(IObuff, &tv_start);
3014 time_pop(&tv_rel);
3015#endif
3016
3017#ifdef FEAT_EVAL
3018 /*
3019 * After a "finish" in debug mode, need to break at first command of next
3020 * sourced file.
3021 */
3022 if (save_debug_break_level > ex_nesting_level
3023 && debug_break_level == ex_nesting_level)
3024 ++debug_break_level;
3025#endif
3026
Bram Moolenaar05159a02005-02-26 23:04:13 +00003027#ifdef FEAT_EVAL
3028almosttheend:
3029 current_SID = save_current_SID;
3030 restore_funccal(save_funccalp);
3031# ifdef FEAT_PROFILE
3032 if (do_profiling)
3033 prof_child_exit(&wait_start); /* leaving a child now */
3034# endif
3035#endif
3036 fclose(cookie.fp);
3037 vim_free(cookie.nextline);
3038#ifdef FEAT_MBYTE
3039 convert_setup(&cookie.conv, NULL, NULL);
3040#endif
3041
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042theend:
3043 vim_free(fname_exp);
3044 return retval;
3045}
3046
3047#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00003048
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049/*
3050 * ":scriptnames"
3051 */
3052/*ARGSUSED*/
3053 void
3054ex_scriptnames(eap)
3055 exarg_T *eap;
3056{
3057 int i;
3058
Bram Moolenaar05159a02005-02-26 23:04:13 +00003059 for (i = 1; i <= script_items.ga_len && !got_int; ++i)
3060 if (SCRIPT_ITEM(i).sn_name != NULL)
3061 smsg((char_u *)"%3d: %s", i, SCRIPT_ITEM(i).sn_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062}
3063
3064# if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
3065/*
3066 * Fix slashes in the list of script names for 'shellslash'.
3067 */
3068 void
3069scriptnames_slash_adjust()
3070{
3071 int i;
3072
Bram Moolenaar05159a02005-02-26 23:04:13 +00003073 for (i = 1; i <= script_items.ga_len; ++i)
3074 if (SCRIPT_ITEM(i).sn_name != NULL)
3075 slash_adjust(SCRIPT_ITEM(i).sn_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076}
3077# endif
3078
3079/*
3080 * Get a pointer to a script name. Used for ":verbose set".
3081 */
3082 char_u *
3083get_scriptname(id)
3084 scid_T id;
3085{
3086 if (id == SID_MODELINE)
3087 return (char_u *)"modeline";
3088 if (id == SID_CMDARG)
3089 return (char_u *)"--cmd argument";
3090 if (id == SID_CARG)
3091 return (char_u *)"-c argument";
3092 if (id == SID_ENV)
3093 return (char_u *)"environment variable";
Bram Moolenaar05159a02005-02-26 23:04:13 +00003094 return SCRIPT_ITEM(id).sn_name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095}
Bram Moolenaar05159a02005-02-26 23:04:13 +00003096
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00003097# if defined(EXITFREE) || defined(PROTO)
3098 void
3099free_scriptnames()
3100{
3101 int i;
3102
3103 for (i = script_items.ga_len; i > 0; --i)
3104 vim_free(SCRIPT_ITEM(i).sn_name);
3105 ga_clear(&script_items);
3106}
3107# endif
3108
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109#endif
3110
3111#if defined(USE_CR) || defined(PROTO)
3112
3113# if defined(__MSL__) && (__MSL__ >= 22)
3114/*
3115 * Newer version of the Metrowerks library handle DOS and UNIX files
3116 * without help.
3117 * Test with earlier versions, MSL 2.2 is the library supplied with
3118 * Codewarrior Pro 2.
3119 */
3120 char *
3121fgets_cr(s, n, stream)
3122 char *s;
3123 int n;
3124 FILE *stream;
3125{
3126 return fgets(s, n, stream);
3127}
3128# else
3129/*
3130 * Version of fgets() which also works for lines ending in a <CR> only
3131 * (Macintosh format).
3132 * For older versions of the Metrowerks library.
3133 * At least CodeWarrior 9 needed this code.
3134 */
3135 char *
3136fgets_cr(s, n, stream)
3137 char *s;
3138 int n;
3139 FILE *stream;
3140{
3141 int c = 0;
3142 int char_read = 0;
3143
3144 while (!feof(stream) && c != '\r' && c != '\n' && char_read < n - 1)
3145 {
3146 c = fgetc(stream);
3147 s[char_read++] = c;
3148 /* If the file is in DOS format, we need to skip a NL after a CR. I
3149 * thought it was the other way around, but this appears to work... */
3150 if (c == '\n')
3151 {
3152 c = fgetc(stream);
3153 if (c != '\r')
3154 ungetc(c, stream);
3155 }
3156 }
3157
3158 s[char_read] = 0;
3159 if (char_read == 0)
3160 return NULL;
3161
3162 if (feof(stream) && char_read == 1)
3163 return NULL;
3164
3165 return s;
3166}
3167# endif
3168#endif
3169
3170/*
3171 * Get one full line from a sourced file.
3172 * Called by do_cmdline() when it's called from do_source().
3173 *
3174 * Return a pointer to the line in allocated memory.
3175 * Return NULL for end-of-file or some error.
3176 */
3177/* ARGSUSED */
3178 char_u *
3179getsourceline(c, cookie, indent)
3180 int c; /* not used */
3181 void *cookie;
3182 int indent; /* not used */
3183{
3184 struct source_cookie *sp = (struct source_cookie *)cookie;
3185 char_u *line;
3186 char_u *p, *s;
3187
3188#ifdef FEAT_EVAL
3189 /* If breakpoints have been added/deleted need to check for it. */
3190 if (sp->dbg_tick < debug_tick)
3191 {
3192 sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, sourcing_lnum);
3193 sp->dbg_tick = debug_tick;
3194 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003195# ifdef FEAT_PROFILE
3196 if (do_profiling)
3197 script_line_end();
3198# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199#endif
3200 /*
3201 * Get current line. If there is a read-ahead line, use it, otherwise get
3202 * one now.
3203 */
3204 if (sp->finished)
3205 line = NULL;
3206 else if (sp->nextline == NULL)
3207 line = get_one_sourceline(sp);
3208 else
3209 {
3210 line = sp->nextline;
3211 sp->nextline = NULL;
3212 ++sourcing_lnum;
3213 }
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003214#ifdef FEAT_PROFILE
3215 if (line != NULL && do_profiling)
3216 script_line_start();
3217#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218
3219 /* Only concatenate lines starting with a \ when 'cpoptions' doesn't
3220 * contain the 'C' flag. */
3221 if (line != NULL && (vim_strchr(p_cpo, CPO_CONCAT) == NULL))
3222 {
3223 /* compensate for the one line read-ahead */
3224 --sourcing_lnum;
3225 for (;;)
3226 {
3227 sp->nextline = get_one_sourceline(sp);
3228 if (sp->nextline == NULL)
3229 break;
3230 p = skipwhite(sp->nextline);
3231 if (*p != '\\')
3232 break;
3233 s = alloc((int)(STRLEN(line) + STRLEN(p)));
3234 if (s == NULL) /* out of memory */
3235 break;
3236 STRCPY(s, line);
3237 STRCAT(s, p + 1);
3238 vim_free(line);
3239 line = s;
3240 vim_free(sp->nextline);
3241 }
3242 }
3243
3244#ifdef FEAT_MBYTE
3245 if (line != NULL && sp->conv.vc_type != CONV_NONE)
3246 {
3247 /* Convert the encoding of the script line. */
3248 s = string_convert(&sp->conv, line, NULL);
3249 if (s != NULL)
3250 {
3251 vim_free(line);
3252 line = s;
3253 }
3254 }
3255#endif
3256
3257#ifdef FEAT_EVAL
3258 /* Did we encounter a breakpoint? */
3259 if (sp->breakpoint != 0 && sp->breakpoint <= sourcing_lnum)
3260 {
3261 dbg_breakpoint(sp->fname, sourcing_lnum);
3262 /* Find next breakpoint. */
3263 sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, sourcing_lnum);
3264 sp->dbg_tick = debug_tick;
3265 }
3266#endif
3267
3268 return line;
3269}
3270
3271 static char_u *
3272get_one_sourceline(sp)
3273 struct source_cookie *sp;
3274{
3275 garray_T ga;
3276 int len;
3277 int c;
3278 char_u *buf;
3279#ifdef USE_CRNL
3280 int has_cr; /* CR-LF found */
3281#endif
3282#ifdef USE_CR
3283 char_u *scan;
3284#endif
3285 int have_read = FALSE;
3286
3287 /* use a growarray to store the sourced line */
Bram Moolenaar6ac54292005-02-02 23:07:25 +00003288 ga_init2(&ga, 1, 250);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289
3290 /*
3291 * Loop until there is a finished line (or end-of-file).
3292 */
3293 sourcing_lnum++;
3294 for (;;)
3295 {
Bram Moolenaar6ac54292005-02-02 23:07:25 +00003296 /* make room to read at least 120 (more) characters */
3297 if (ga_grow(&ga, 120) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 break;
3299 buf = (char_u *)ga.ga_data;
3300
3301#ifdef USE_CR
3302 if (sp->fileformat == EOL_MAC)
3303 {
Bram Moolenaar86b68352004-12-27 21:59:20 +00003304 if (fgets_cr((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,
3305 sp->fp) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306 break;
3307 }
3308 else
3309#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00003310 if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,
3311 sp->fp) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312 break;
Bram Moolenaar6ac54292005-02-02 23:07:25 +00003313 len = ga.ga_len + (int)STRLEN(buf + ga.ga_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314#ifdef USE_CRNL
3315 /* Ignore a trailing CTRL-Z, when in Dos mode. Only recognize the
3316 * CTRL-Z by its own, or after a NL. */
3317 if ( (len == 1 || (len >= 2 && buf[len - 2] == '\n'))
3318 && sp->fileformat == EOL_DOS
3319 && buf[len - 1] == Ctrl_Z)
3320 {
3321 buf[len - 1] = NUL;
3322 break;
3323 }
3324#endif
3325
3326#ifdef USE_CR
3327 /* If the read doesn't stop on a new line, and there's
3328 * some CR then we assume a Mac format */
3329 if (sp->fileformat == EOL_UNKNOWN)
3330 {
3331 if (buf[len - 1] != '\n' && vim_strchr(buf, '\r') != NULL)
3332 sp->fileformat = EOL_MAC;
3333 else
3334 sp->fileformat = EOL_UNIX;
3335 }
3336
3337 if (sp->fileformat == EOL_MAC)
3338 {
3339 scan = vim_strchr(buf, '\r');
3340
3341 if (scan != NULL)
3342 {
3343 *scan = '\n';
3344 if (*(scan + 1) != 0)
3345 {
3346 *(scan + 1) = 0;
3347 fseek(sp->fp, (long)(scan - buf - len + 1), SEEK_CUR);
3348 }
3349 }
3350 len = STRLEN(buf);
3351 }
3352#endif
3353
3354 have_read = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 ga.ga_len = len;
3356
3357 /* If the line was longer than the buffer, read more. */
Bram Moolenaar86b68352004-12-27 21:59:20 +00003358 if (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\n')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359 continue;
3360
3361 if (len >= 1 && buf[len - 1] == '\n') /* remove trailing NL */
3362 {
3363#ifdef USE_CRNL
3364 has_cr = (len >= 2 && buf[len - 2] == '\r');
3365 if (sp->fileformat == EOL_UNKNOWN)
3366 {
3367 if (has_cr)
3368 sp->fileformat = EOL_DOS;
3369 else
3370 sp->fileformat = EOL_UNIX;
3371 }
3372
3373 if (sp->fileformat == EOL_DOS)
3374 {
3375 if (has_cr) /* replace trailing CR */
3376 {
3377 buf[len - 2] = '\n';
3378 --len;
3379 --ga.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 }
3381 else /* lines like ":map xx yy^M" will have failed */
3382 {
3383 if (!sp->error)
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003384 {
3385 msg_source(hl_attr(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 EMSG(_("W15: Warning: Wrong line separator, ^M may be missing"));
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 sp->error = TRUE;
3389 sp->fileformat = EOL_UNIX;
3390 }
3391 }
3392#endif
3393 /* The '\n' is escaped if there is an odd number of ^V's just
3394 * before it, first set "c" just before the 'V's and then check
3395 * len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo */
3396 for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)
3397 ;
3398 if ((len & 1) != (c & 1)) /* escaped NL, read more */
3399 {
3400 sourcing_lnum++;
3401 continue;
3402 }
3403
3404 buf[len - 1] = NUL; /* remove the NL */
3405 }
3406
3407 /*
3408 * Check for ^C here now and then, so recursive :so can be broken.
3409 */
3410 line_breakcheck();
3411 break;
3412 }
3413
3414 if (have_read)
3415 return (char_u *)ga.ga_data;
3416
3417 vim_free(ga.ga_data);
3418 return NULL;
3419}
3420
Bram Moolenaar05159a02005-02-26 23:04:13 +00003421#if defined(FEAT_PROFILE) || defined(PROTO)
3422/*
3423 * Called when starting to read a script line.
3424 * "sourcing_lnum" must be correct!
3425 * When skipping lines it may not actually be executed, but we won't find out
3426 * until later and we need to store the time now.
3427 */
3428 void
3429script_line_start()
3430{
3431 scriptitem_T *si;
3432 sn_prl_T *pp;
3433
3434 if (current_SID <= 0 || current_SID > script_items.ga_len)
3435 return;
3436 si = &SCRIPT_ITEM(current_SID);
3437 if (si->sn_prof_on && sourcing_lnum >= 1)
3438 {
3439 /* Grow the array before starting the timer, so that the time spend
3440 * here isn't counted. */
3441 ga_grow(&si->sn_prl_ga, (int)(sourcing_lnum - si->sn_prl_ga.ga_len));
3442 si->sn_prl_idx = sourcing_lnum - 1;
3443 while (si->sn_prl_ga.ga_len <= si->sn_prl_idx
3444 && si->sn_prl_ga.ga_len < si->sn_prl_ga.ga_maxlen)
3445 {
3446 /* Zero counters for a line that was not used before. */
3447 pp = &PRL_ITEM(si, si->sn_prl_ga.ga_len);
3448 pp->snp_count = 0;
3449 profile_zero(&pp->sn_prl_total);
3450 profile_zero(&pp->sn_prl_self);
3451 ++si->sn_prl_ga.ga_len;
3452 }
3453 si->sn_prl_execed = FALSE;
3454 profile_start(&si->sn_prl_start);
3455 profile_zero(&si->sn_prl_children);
3456 profile_get_wait(&si->sn_prl_wait);
3457 }
3458}
3459
3460/*
3461 * Called when actually executing a function line.
3462 */
3463 void
3464script_line_exec()
3465{
3466 scriptitem_T *si;
3467
3468 if (current_SID <= 0 || current_SID > script_items.ga_len)
3469 return;
3470 si = &SCRIPT_ITEM(current_SID);
3471 if (si->sn_prof_on && si->sn_prl_idx >= 0)
3472 si->sn_prl_execed = TRUE;
3473}
3474
3475/*
3476 * Called when done with a function line.
3477 */
3478 void
3479script_line_end()
3480{
3481 scriptitem_T *si;
3482 sn_prl_T *pp;
3483
3484 if (current_SID <= 0 || current_SID > script_items.ga_len)
3485 return;
3486 si = &SCRIPT_ITEM(current_SID);
3487 if (si->sn_prof_on && si->sn_prl_idx >= 0
3488 && si->sn_prl_idx < si->sn_prl_ga.ga_len)
3489 {
3490 if (si->sn_prl_execed)
3491 {
3492 pp = &PRL_ITEM(si, si->sn_prl_idx);
3493 ++pp->snp_count;
3494 profile_end(&si->sn_prl_start);
3495 profile_sub_wait(&si->sn_prl_wait, &si->sn_prl_start);
3496 profile_add(&pp->sn_prl_self, &si->sn_prl_start);
3497 profile_add(&pp->sn_prl_total, &si->sn_prl_start);
3498 profile_sub(&pp->sn_prl_self, &si->sn_prl_children);
3499 }
3500 si->sn_prl_idx = -1;
3501 }
3502}
3503#endif
3504
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505/*
3506 * ":scriptencoding": Set encoding conversion for a sourced script.
3507 * Without the multi-byte feature it's simply ignored.
3508 */
3509/*ARGSUSED*/
3510 void
3511ex_scriptencoding(eap)
3512 exarg_T *eap;
3513{
3514#ifdef FEAT_MBYTE
3515 struct source_cookie *sp;
3516 char_u *name;
3517
3518 if (!getline_equal(eap->getline, eap->cookie, getsourceline))
3519 {
3520 EMSG(_("E167: :scriptencoding used outside of a sourced file"));
3521 return;
3522 }
3523
3524 if (*eap->arg != NUL)
3525 {
3526 name = enc_canonize(eap->arg);
3527 if (name == NULL) /* out of memory */
3528 return;
3529 }
3530 else
3531 name = eap->arg;
3532
3533 /* Setup for conversion from the specified encoding to 'encoding'. */
3534 sp = (struct source_cookie *)getline_cookie(eap->getline, eap->cookie);
3535 convert_setup(&sp->conv, name, p_enc);
3536
3537 if (name != eap->arg)
3538 vim_free(name);
3539#endif
3540}
3541
3542#if defined(FEAT_EVAL) || defined(PROTO)
3543/*
3544 * ":finish": Mark a sourced file as finished.
3545 */
3546 void
3547ex_finish(eap)
3548 exarg_T *eap;
3549{
3550 if (getline_equal(eap->getline, eap->cookie, getsourceline))
3551 do_finish(eap, FALSE);
3552 else
3553 EMSG(_("E168: :finish used outside of a sourced file"));
3554}
3555
3556/*
3557 * Mark a sourced file as finished. Possibly makes the ":finish" pending.
3558 * Also called for a pending finish at the ":endtry" or after returning from
3559 * an extra do_cmdline(). "reanimate" is used in the latter case.
3560 */
3561 void
3562do_finish(eap, reanimate)
3563 exarg_T *eap;
3564 int reanimate;
3565{
3566 int idx;
3567
3568 if (reanimate)
3569 ((struct source_cookie *)getline_cookie(eap->getline,
3570 eap->cookie))->finished = FALSE;
3571
3572 /*
3573 * Cleanup (and inactivate) conditionals, but stop when a try conditional
3574 * not in its finally clause (which then is to be executed next) is found.
3575 * In this case, make the ":finish" pending for execution at the ":endtry".
3576 * Otherwise, finish normally.
3577 */
3578 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
3579 if (idx >= 0)
3580 {
3581 eap->cstack->cs_pending[idx] = CSTP_FINISH;
3582 report_make_pending(CSTP_FINISH, NULL);
3583 }
3584 else
3585 ((struct source_cookie *)getline_cookie(eap->getline,
3586 eap->cookie))->finished = TRUE;
3587}
3588
3589
3590/*
3591 * Return TRUE when a sourced file had the ":finish" command: Don't give error
3592 * message for missing ":endif".
3593 * Return FALSE when not sourcing a file.
3594 */
3595 int
3596source_finished(getline, cookie)
3597 char_u *(*getline) __ARGS((int, void *, int));
3598 void *cookie;
3599{
3600 return (getline_equal(getline, cookie, getsourceline)
3601 && ((struct source_cookie *)getline_cookie(
3602 getline, cookie))->finished);
3603}
3604#endif
3605
3606#if defined(FEAT_LISTCMDS) || defined(PROTO)
3607/*
3608 * ":checktime [buffer]"
3609 */
3610 void
3611ex_checktime(eap)
3612 exarg_T *eap;
3613{
3614 buf_T *buf;
3615 int save_no_check_timestamps = no_check_timestamps;
3616
3617 no_check_timestamps = 0;
3618 if (eap->addr_count == 0) /* default is all buffers */
3619 check_timestamps(FALSE);
3620 else
3621 {
3622 buf = buflist_findnr((int)eap->line2);
3623 if (buf != NULL) /* cannot happen? */
3624 (void)buf_check_timestamp(buf, FALSE);
3625 }
3626 no_check_timestamps = save_no_check_timestamps;
3627}
3628#endif
3629
3630#if defined(FEAT_PRINTER) || defined(PROTO)
3631/*
3632 * Printing code (Machine-independent.)
3633 * To implement printing on a platform, the following functions must be
3634 * defined:
3635 *
3636 * int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
3637 * Called once. Code should display printer dialogue (if appropriate) and
3638 * determine printer font and margin settings. Reset has_color if the printer
3639 * doesn't support colors at all.
3640 * Returns FAIL to abort.
3641 *
3642 * int mch_print_begin(prt_settings_T *settings)
3643 * Called to start the print job.
3644 * Return FALSE to abort.
3645 *
3646 * int mch_print_begin_page(char_u *msg)
3647 * Called at the start of each page.
3648 * "msg" indicates the progress of the print job, can be NULL.
3649 * Return FALSE to abort.
3650 *
3651 * int mch_print_end_page()
3652 * Called at the end of each page.
3653 * Return FALSE to abort.
3654 *
3655 * int mch_print_blank_page()
3656 * Called to generate a blank page for collated, duplex, multiple copy
3657 * document. Return FALSE to abort.
3658 *
3659 * void mch_print_end(prt_settings_T *psettings)
3660 * Called at normal end of print job.
3661 *
3662 * void mch_print_cleanup()
3663 * Called if print job ends normally or is abandoned. Free any memory, close
3664 * devices and handles. Also called when mch_print_begin() fails, but not
3665 * when mch_print_init() fails.
3666 *
3667 * void mch_print_set_font(int Bold, int Italic, int Underline);
3668 * Called whenever the font style changes.
3669 *
3670 * void mch_print_set_bg(long bgcol);
3671 * Called to set the background color for the following text. Parameter is an
3672 * RGB value.
3673 *
3674 * void mch_print_set_fg(long fgcol);
3675 * Called to set the foreground color for the following text. Parameter is an
3676 * RGB value.
3677 *
3678 * mch_print_start_line(int margin, int page_line)
3679 * Sets the current position at the start of line "page_line".
3680 * If margin is TRUE start in the left margin (for header and line number).
3681 *
3682 * int mch_print_text_out(char_u *p, int len);
3683 * Output one character of text p[len] at the current position.
3684 * Return TRUE if there is no room for another character in the same line.
3685 *
3686 * Note that the generic code has no idea of margins. The machine code should
3687 * simply make the page look smaller! The header and the line numbers are
3688 * printed in the margin.
3689 */
3690
3691#ifdef FEAT_SYN_HL
3692static const long_u cterm_color_8[8] =
3693{
3694 (long_u)0x000000L, (long_u)0xff0000L, (long_u)0x00ff00L, (long_u)0xffff00L,
3695 (long_u)0x0000ffL, (long_u)0xff00ffL, (long_u)0x00ffffL, (long_u)0xffffffL
3696};
3697
3698static const long_u cterm_color_16[16] =
3699{
3700 (long_u)0x000000L, (long_u)0x0000c0L, (long_u)0x008000L, (long_u)0x004080L,
3701 (long_u)0xc00000L, (long_u)0xc000c0L, (long_u)0x808000L, (long_u)0xc0c0c0L,
3702 (long_u)0x808080L, (long_u)0x6060ffL, (long_u)0x00ff00L, (long_u)0x00ffffL,
3703 (long_u)0xff8080L, (long_u)0xff40ffL, (long_u)0xffff00L, (long_u)0xffffffL
3704};
3705
3706static int current_syn_id;
3707#endif
3708
3709#define PRCOLOR_BLACK (long_u)0
3710#define PRCOLOR_WHITE (long_u)0xFFFFFFL
3711
3712static int curr_italic;
3713static int curr_bold;
3714static int curr_underline;
3715static long_u curr_bg;
3716static long_u curr_fg;
3717static int page_count;
3718
3719/*
3720 * These values determine the print position on a page.
3721 */
3722typedef struct
3723{
3724 int lead_spaces; /* remaining spaces for a TAB */
3725 int print_pos; /* virtual column for computing TABs */
3726 colnr_T column; /* byte column */
3727 linenr_T file_line; /* line nr in the buffer */
3728 long_u bytes_printed; /* bytes printed so far */
3729 int ff; /* seen form feed character */
3730} prt_pos_T;
3731
3732#ifdef FEAT_SYN_HL
3733static long_u darken_rgb __ARGS((long_u rgb));
3734static long_u prt_get_term_color __ARGS((int colorindex));
3735#endif
3736static void prt_set_fg __ARGS((long_u fg));
3737static void prt_set_bg __ARGS((long_u bg));
3738static void prt_set_font __ARGS((int bold, int italic, int underline));
3739static void prt_line_number __ARGS((prt_settings_T *psettings, int page_line, linenr_T lnum));
3740static void prt_header __ARGS((prt_settings_T *psettings, int pagenum, linenr_T lnum));
3741static void prt_message __ARGS((char_u *s));
3742static colnr_T hardcopy_line __ARGS((prt_settings_T *psettings, int page_line, prt_pos_T *ppos));
3743static void prt_get_attr __ARGS((int hl_id, prt_text_attr_T* pattr, int modec));
3744
3745#ifdef FEAT_SYN_HL
3746/*
3747 * If using a dark background, the colors will probably be too bright to show
3748 * up well on white paper, so reduce their brightness.
3749 */
3750 static long_u
3751darken_rgb(rgb)
3752 long_u rgb;
3753{
3754 return ((rgb >> 17) << 16)
3755 + (((rgb & 0xff00) >> 9) << 8)
3756 + ((rgb & 0xff) >> 1);
3757}
3758
3759 static long_u
3760prt_get_term_color(colorindex)
3761 int colorindex;
3762{
3763 /* TODO: Should check for xterm with 88 or 256 colors. */
3764 if (t_colors > 8)
3765 return cterm_color_16[colorindex % 16];
3766 return cterm_color_8[colorindex % 8];
3767}
3768
3769 static void
3770prt_get_attr(hl_id, pattr, modec)
3771 int hl_id;
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003772 prt_text_attr_T *pattr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 int modec;
3774{
3775 int colorindex;
3776 long_u fg_color;
3777 long_u bg_color;
3778 char *color;
3779
3780 pattr->bold = (highlight_has_attr(hl_id, HL_BOLD, modec) != NULL);
3781 pattr->italic = (highlight_has_attr(hl_id, HL_ITALIC, modec) != NULL);
3782 pattr->underline = (highlight_has_attr(hl_id, HL_UNDERLINE, modec) != NULL);
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003783 pattr->undercurl = (highlight_has_attr(hl_id, HL_UNDERCURL, modec) != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784
3785# ifdef FEAT_GUI
3786 if (gui.in_use)
3787 {
3788 bg_color = highlight_gui_color_rgb(hl_id, FALSE);
3789 if (bg_color == PRCOLOR_BLACK)
3790 bg_color = PRCOLOR_WHITE;
3791
3792 fg_color = highlight_gui_color_rgb(hl_id, TRUE);
3793 }
3794 else
3795# endif
3796 {
3797 bg_color = PRCOLOR_WHITE;
3798
3799 color = (char *)highlight_color(hl_id, (char_u *)"fg", modec);
3800 if (color == NULL)
3801 colorindex = 0;
3802 else
3803 colorindex = atoi(color);
3804
3805 if (colorindex >= 0 && colorindex < t_colors)
3806 fg_color = prt_get_term_color(colorindex);
3807 else
3808 fg_color = PRCOLOR_BLACK;
3809 }
3810
3811 if (fg_color == PRCOLOR_WHITE)
3812 fg_color = PRCOLOR_BLACK;
3813 else if (*p_bg == 'd')
3814 fg_color = darken_rgb(fg_color);
3815
3816 pattr->fg_color = fg_color;
3817 pattr->bg_color = bg_color;
3818}
3819#endif /* FEAT_SYN_HL */
3820
3821 static void
3822prt_set_fg(fg)
3823 long_u fg;
3824{
3825 if (fg != curr_fg)
3826 {
3827 curr_fg = fg;
3828 mch_print_set_fg(fg);
3829 }
3830}
3831
3832 static void
3833prt_set_bg(bg)
3834 long_u bg;
3835{
3836 if (bg != curr_bg)
3837 {
3838 curr_bg = bg;
3839 mch_print_set_bg(bg);
3840 }
3841}
3842
3843 static void
3844prt_set_font(bold, italic, underline)
3845 int bold;
3846 int italic;
3847 int underline;
3848{
3849 if (curr_bold != bold
3850 || curr_italic != italic
3851 || curr_underline != underline)
3852 {
3853 curr_underline = underline;
3854 curr_italic = italic;
3855 curr_bold = bold;
3856 mch_print_set_font(bold, italic, underline);
3857 }
3858}
3859
3860/*
3861 * Print the line number in the left margin.
3862 */
3863 static void
3864prt_line_number(psettings, page_line, lnum)
3865 prt_settings_T *psettings;
3866 int page_line;
3867 linenr_T lnum;
3868{
3869 int i;
3870 char_u tbuf[20];
3871
3872 prt_set_fg(psettings->number.fg_color);
3873 prt_set_bg(psettings->number.bg_color);
3874 prt_set_font(psettings->number.bold, psettings->number.italic, psettings->number.underline);
3875 mch_print_start_line(TRUE, page_line);
3876
3877 /* Leave two spaces between the number and the text; depends on
3878 * PRINT_NUMBER_WIDTH. */
3879 sprintf((char *)tbuf, "%6ld", (long)lnum);
3880 for (i = 0; i < 6; i++)
3881 (void)mch_print_text_out(&tbuf[i], 1);
3882
3883#ifdef FEAT_SYN_HL
3884 if (psettings->do_syntax)
3885 /* Set colors for next character. */
3886 current_syn_id = -1;
3887 else
3888#endif
3889 {
3890 /* Set colors and font back to normal. */
3891 prt_set_fg(PRCOLOR_BLACK);
3892 prt_set_bg(PRCOLOR_WHITE);
3893 prt_set_font(FALSE, FALSE, FALSE);
3894 }
3895}
3896
3897static linenr_T printer_page_num;
3898
3899 int
3900get_printer_page_num()
3901{
3902 return printer_page_num;
3903}
3904
3905/*
3906 * Get the currently effective header height.
3907 */
3908 int
3909prt_header_height()
3910{
3911 if (printer_opts[OPT_PRINT_HEADERHEIGHT].present)
3912 return printer_opts[OPT_PRINT_HEADERHEIGHT].number;
3913 return 2;
3914}
3915
3916/*
3917 * Return TRUE if using a line number for printing.
3918 */
3919 int
3920prt_use_number()
3921{
3922 return (printer_opts[OPT_PRINT_NUMBER].present
3923 && TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y');
3924}
3925
3926/*
3927 * Return the unit used in a margin item in 'printoptions'.
3928 * Returns PRT_UNIT_NONE if not recognized.
3929 */
3930 int
3931prt_get_unit(idx)
3932 int idx;
3933{
3934 int u = PRT_UNIT_NONE;
3935 int i;
3936 static char *(units[4]) = PRT_UNIT_NAMES;
3937
3938 if (printer_opts[idx].present)
3939 for (i = 0; i < 4; ++i)
3940 if (STRNICMP(printer_opts[idx].string, units[i], 2) == 0)
3941 {
3942 u = i;
3943 break;
3944 }
3945 return u;
3946}
3947
3948/*
3949 * Print the page header.
3950 */
3951/*ARGSUSED*/
3952 static void
3953prt_header(psettings, pagenum, lnum)
3954 prt_settings_T *psettings;
3955 int pagenum;
3956 linenr_T lnum;
3957{
3958 int width = psettings->chars_per_line;
3959 int page_line;
3960 char_u *tbuf;
3961 char_u *p;
3962#ifdef FEAT_MBYTE
3963 int l;
3964#endif
3965
3966 /* Also use the space for the line number. */
3967 if (prt_use_number())
3968 width += PRINT_NUMBER_WIDTH;
3969
3970 tbuf = alloc(width + IOSIZE);
3971 if (tbuf == NULL)
3972 return;
3973
3974#ifdef FEAT_STL_OPT
3975 if (*p_header != NUL)
3976 {
3977 linenr_T tmp_lnum, tmp_topline, tmp_botline;
3978
3979 /*
3980 * Need to (temporarily) set current line number and first/last line
3981 * number on the 'window'. Since we don't know how long the page is,
3982 * set the first and current line number to the top line, and guess
3983 * that the page length is 64.
3984 */
3985 tmp_lnum = curwin->w_cursor.lnum;
3986 tmp_topline = curwin->w_topline;
3987 tmp_botline = curwin->w_botline;
3988 curwin->w_cursor.lnum = lnum;
3989 curwin->w_topline = lnum;
3990 curwin->w_botline = lnum + 63;
3991 printer_page_num = pagenum;
3992
3993 build_stl_str_hl(curwin, tbuf, (size_t)(width + IOSIZE),
3994 p_header, ' ', width, NULL);
3995
3996 /* Reset line numbers */
3997 curwin->w_cursor.lnum = tmp_lnum;
3998 curwin->w_topline = tmp_topline;
3999 curwin->w_botline = tmp_botline;
4000 }
4001 else
4002#endif
4003 sprintf((char *)tbuf, _("Page %d"), pagenum);
4004
4005 prt_set_fg(PRCOLOR_BLACK);
4006 prt_set_bg(PRCOLOR_WHITE);
4007 prt_set_font(TRUE, FALSE, FALSE);
4008
4009 /* Use a negative line number to indicate printing in the top margin. */
4010 page_line = 0 - prt_header_height();
4011 mch_print_start_line(TRUE, page_line);
4012 for (p = tbuf; *p != NUL; )
4013 {
4014 if (mch_print_text_out(p,
4015#ifdef FEAT_MBYTE
4016 (l = (*mb_ptr2len_check)(p))
4017#else
4018 1
4019#endif
4020 ))
4021 {
4022 ++page_line;
4023 if (page_line >= 0) /* out of room in header */
4024 break;
4025 mch_print_start_line(TRUE, page_line);
4026 }
4027#ifdef FEAT_MBYTE
4028 p += l;
4029#else
4030 p++;
4031#endif
4032 }
4033
4034 vim_free(tbuf);
4035
4036#ifdef FEAT_SYN_HL
4037 if (psettings->do_syntax)
4038 /* Set colors for next character. */
4039 current_syn_id = -1;
4040 else
4041#endif
4042 {
4043 /* Set colors and font back to normal. */
4044 prt_set_fg(PRCOLOR_BLACK);
4045 prt_set_bg(PRCOLOR_WHITE);
4046 prt_set_font(FALSE, FALSE, FALSE);
4047 }
4048}
4049
4050/*
4051 * Display a print status message.
4052 */
4053 static void
4054prt_message(s)
4055 char_u *s;
4056{
4057 screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
4058 screen_puts(s, (int)Rows - 1, 0, hl_attr(HLF_R));
4059 out_flush();
4060}
4061
4062 void
4063ex_hardcopy(eap)
4064 exarg_T *eap;
4065{
4066 linenr_T lnum;
4067 int collated_copies, uncollated_copies;
4068 prt_settings_T settings;
4069 long_u bytes_to_print = 0;
4070 int page_line;
4071 int jobsplit;
4072 int id;
4073
4074 memset(&settings, 0, sizeof(prt_settings_T));
4075 settings.has_color = TRUE;
4076
4077# ifdef FEAT_POSTSCRIPT
4078 if (*eap->arg == '>')
4079 {
4080 char_u *errormsg = NULL;
4081
4082 /* Expand things like "%.ps". */
4083 if (expand_filename(eap, eap->cmdlinep, &errormsg) == FAIL)
4084 {
4085 if (errormsg != NULL)
4086 EMSG(errormsg);
4087 return;
4088 }
4089 settings.outfile = skipwhite(eap->arg + 1);
4090 }
4091 else if (*eap->arg != NUL)
4092 settings.arguments = eap->arg;
4093# endif
4094
4095 /*
4096 * Initialise for printing. Ask the user for settings, unless forceit is
4097 * set.
4098 * The mch_print_init() code should set up margins if applicable. (It may
4099 * not be a real printer - for example the engine might generate HTML or
4100 * PS.)
4101 */
4102 if (mch_print_init(&settings,
4103 curbuf->b_fname == NULL
4104 ? (char_u *)buf_spname(curbuf)
4105 : curbuf->b_sfname == NULL
4106 ? curbuf->b_fname
4107 : curbuf->b_sfname,
4108 eap->forceit) == FAIL)
4109 return;
4110
4111#ifdef FEAT_SYN_HL
4112# ifdef FEAT_GUI
4113 if (gui.in_use)
4114 settings.modec = 'g';
4115 else
4116# endif
4117 if (t_colors > 1)
4118 settings.modec = 'c';
4119 else
4120 settings.modec = 't';
4121
4122 if (!syntax_present(curbuf))
4123 settings.do_syntax = FALSE;
4124 else if (printer_opts[OPT_PRINT_SYNTAX].present
4125 && TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) != 'a')
4126 settings.do_syntax =
4127 (TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) == 'y');
4128 else
4129 settings.do_syntax = settings.has_color;
4130#endif
4131
4132 /* Set up printing attributes for line numbers */
4133 settings.number.fg_color = PRCOLOR_BLACK;
4134 settings.number.bg_color = PRCOLOR_WHITE;
4135 settings.number.bold = FALSE;
4136 settings.number.italic = TRUE;
4137 settings.number.underline = FALSE;
4138#ifdef FEAT_SYN_HL
4139 /*
4140 * Syntax highlighting of line numbers.
4141 */
4142 if (prt_use_number() && settings.do_syntax)
4143 {
4144 id = syn_name2id((char_u *)"LineNr");
4145 if (id > 0)
4146 id = syn_get_final_id(id);
4147
4148 prt_get_attr(id, &settings.number, settings.modec);
4149 }
4150#endif /* FEAT_SYN_HL */
4151
4152 /*
4153 * Estimate the total lines to be printed
4154 */
4155 for (lnum = eap->line1; lnum <= eap->line2; lnum++)
4156 bytes_to_print += (long_u)STRLEN(skipwhite(ml_get(lnum)));
4157 if (bytes_to_print == 0)
4158 {
4159 MSG(_("No text to be printed"));
4160 goto print_fail_no_begin;
4161 }
4162
4163 /* Set colors and font to normal. */
4164 curr_bg = (long_u)0xffffffffL;
4165 curr_fg = (long_u)0xffffffffL;
4166 curr_italic = MAYBE;
4167 curr_bold = MAYBE;
4168 curr_underline = MAYBE;
4169
4170 prt_set_fg(PRCOLOR_BLACK);
4171 prt_set_bg(PRCOLOR_WHITE);
4172 prt_set_font(FALSE, FALSE, FALSE);
4173#ifdef FEAT_SYN_HL
4174 current_syn_id = -1;
4175#endif
4176
4177 jobsplit = (printer_opts[OPT_PRINT_JOBSPLIT].present
4178 && TOLOWER_ASC(printer_opts[OPT_PRINT_JOBSPLIT].string[0]) == 'y');
4179
4180 if (!mch_print_begin(&settings))
4181 goto print_fail_no_begin;
4182
4183 /*
4184 * Loop over collated copies: 1 2 3, 1 2 3, ...
4185 */
4186 page_count = 0;
4187 for (collated_copies = 0;
4188 collated_copies < settings.n_collated_copies;
4189 collated_copies++)
4190 {
4191 prt_pos_T prtpos; /* current print position */
4192 prt_pos_T page_prtpos; /* print position at page start */
4193 int side;
4194
4195 memset(&page_prtpos, 0, sizeof(prt_pos_T));
4196 page_prtpos.file_line = eap->line1;
4197 prtpos = page_prtpos;
4198
4199 if (jobsplit && collated_copies > 0)
4200 {
4201 /* Splitting jobs: Stop a previous job and start a new one. */
4202 mch_print_end(&settings);
4203 if (!mch_print_begin(&settings))
4204 goto print_fail_no_begin;
4205 }
4206
4207 /*
4208 * Loop over all pages in the print job: 1 2 3 ...
4209 */
4210 for (page_count = 0; prtpos.file_line <= eap->line2; ++page_count)
4211 {
4212 /*
4213 * Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ...
4214 * For duplex: 12 12 12 34 34 34, ...
4215 */
4216 for (uncollated_copies = 0;
4217 uncollated_copies < settings.n_uncollated_copies;
4218 uncollated_copies++)
4219 {
4220 /* Set the print position to the start of this page. */
4221 prtpos = page_prtpos;
4222
4223 /*
4224 * Do front and rear side of a page.
4225 */
4226 for (side = 0; side <= settings.duplex; ++side)
4227 {
4228 /*
4229 * Print one page.
4230 */
4231
4232 /* Check for interrupt character every page. */
4233 ui_breakcheck();
4234 if (got_int || settings.user_abort)
4235 goto print_fail;
4236
4237 sprintf((char *)IObuff, _("Printing page %d (%d%%)"),
4238 page_count + 1 + side,
4239 prtpos.bytes_printed > 1000000
4240 ? (int)(prtpos.bytes_printed /
4241 (bytes_to_print / 100))
4242 : (int)((prtpos.bytes_printed * 100)
4243 / bytes_to_print));
4244 if (!mch_print_begin_page(IObuff))
4245 goto print_fail;
4246
4247 if (settings.n_collated_copies > 1)
4248 sprintf((char *)IObuff + STRLEN(IObuff),
4249 _(" Copy %d of %d"),
4250 collated_copies + 1,
4251 settings.n_collated_copies);
4252 prt_message(IObuff);
4253
4254 /*
4255 * Output header if required
4256 */
4257 if (prt_header_height() > 0)
4258 prt_header(&settings, page_count + 1 + side,
4259 prtpos.file_line);
4260
4261 for (page_line = 0; page_line < settings.lines_per_page;
4262 ++page_line)
4263 {
4264 prtpos.column = hardcopy_line(&settings,
4265 page_line, &prtpos);
4266 if (prtpos.column == 0)
4267 {
4268 /* finished a file line */
4269 prtpos.bytes_printed +=
4270 STRLEN(skipwhite(ml_get(prtpos.file_line)));
4271 if (++prtpos.file_line > eap->line2)
4272 break; /* reached the end */
4273 }
4274 else if (prtpos.ff)
4275 {
4276 /* Line had a formfeed in it - start new page but
4277 * stay on the current line */
4278 break;
4279 }
4280 }
4281
4282 if (!mch_print_end_page())
4283 goto print_fail;
4284 if (prtpos.file_line > eap->line2)
4285 break; /* reached the end */
4286 }
4287
4288 /*
4289 * Extra blank page for duplexing with odd number of pages and
4290 * more copies to come.
4291 */
4292 if (prtpos.file_line > eap->line2 && settings.duplex
4293 && side == 0
4294 && uncollated_copies + 1 < settings.n_uncollated_copies)
4295 {
4296 if (!mch_print_blank_page())
4297 goto print_fail;
4298 }
4299 }
4300 if (settings.duplex && prtpos.file_line <= eap->line2)
4301 ++page_count;
4302
4303 /* Remember the position where the next page starts. */
4304 page_prtpos = prtpos;
4305 }
4306
Bram Moolenaar555b2802005-05-19 21:08:39 +00004307 vim_snprintf((char *)IObuff, IOSIZE, _("Printed: %s"),
4308 settings.jobname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 prt_message(IObuff);
4310 }
4311
4312print_fail:
4313 if (got_int || settings.user_abort)
4314 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00004315 sprintf((char *)IObuff, "%s", _("Printing aborted"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 prt_message(IObuff);
4317 }
4318 mch_print_end(&settings);
4319
4320print_fail_no_begin:
4321 mch_print_cleanup();
4322}
4323
4324/*
4325 * Print one page line.
4326 * Return the next column to print, or zero if the line is finished.
4327 */
4328 static colnr_T
4329hardcopy_line(psettings, page_line, ppos)
4330 prt_settings_T *psettings;
4331 int page_line;
4332 prt_pos_T *ppos;
4333{
4334 colnr_T col;
4335 char_u *line;
4336 int need_break = FALSE;
4337 int outputlen;
4338 int tab_spaces;
4339 long_u print_pos;
4340#ifdef FEAT_SYN_HL
4341 prt_text_attr_T attr;
4342 int id;
4343#endif
4344
4345 if (ppos->column == 0 || ppos->ff)
4346 {
4347 print_pos = 0;
4348 tab_spaces = 0;
4349 if (!ppos->ff && prt_use_number())
4350 prt_line_number(psettings, page_line, ppos->file_line);
4351 ppos->ff = FALSE;
4352 }
4353 else
4354 {
4355 /* left over from wrap halfway a tab */
4356 print_pos = ppos->print_pos;
4357 tab_spaces = ppos->lead_spaces;
4358 }
4359
4360 mch_print_start_line(0, page_line);
4361 line = ml_get(ppos->file_line);
4362
4363 /*
4364 * Loop over the columns until the end of the file line or right margin.
4365 */
4366 for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen)
4367 {
4368 outputlen = 1;
4369#ifdef FEAT_MBYTE
4370 if (has_mbyte && (outputlen = (*mb_ptr2len_check)(line + col)) < 1)
4371 outputlen = 1;
4372#endif
4373#ifdef FEAT_SYN_HL
4374 /*
4375 * syntax highlighting stuff.
4376 */
4377 if (psettings->do_syntax)
4378 {
Bram Moolenaar9d0ec2e2005-04-20 19:45:58 +00004379 id = syn_get_id(ppos->file_line, col, 1, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380 if (id > 0)
4381 id = syn_get_final_id(id);
4382 else
4383 id = 0;
4384 /* Get the line again, a multi-line regexp may invalidate it. */
4385 line = ml_get(ppos->file_line);
4386
4387 if (id != current_syn_id)
4388 {
4389 current_syn_id = id;
4390 prt_get_attr(id, &attr, psettings->modec);
4391 prt_set_font(attr.bold, attr.italic, attr.underline);
4392 prt_set_fg(attr.fg_color);
4393 prt_set_bg(attr.bg_color);
4394 }
4395 }
4396#endif /* FEAT_SYN_HL */
4397
4398 /*
4399 * Appropriately expand any tabs to spaces.
4400 */
4401 if (line[col] == TAB || tab_spaces != 0)
4402 {
4403 if (tab_spaces == 0)
4404 tab_spaces = curbuf->b_p_ts - (print_pos % curbuf->b_p_ts);
4405
4406 while (tab_spaces > 0)
4407 {
4408 need_break = mch_print_text_out((char_u *)" ", 1);
4409 print_pos++;
4410 tab_spaces--;
4411 if (need_break)
4412 break;
4413 }
4414 /* Keep the TAB if we didn't finish it. */
4415 if (need_break && tab_spaces > 0)
4416 break;
4417 }
4418 else if (line[col] == FF
4419 && printer_opts[OPT_PRINT_FORMFEED].present
4420 && TOLOWER_ASC(printer_opts[OPT_PRINT_FORMFEED].string[0])
4421 == 'y')
4422 {
4423 ppos->ff = TRUE;
4424 need_break = 1;
4425 }
4426 else
4427 {
4428 need_break = mch_print_text_out(line + col, outputlen);
4429#ifdef FEAT_MBYTE
4430 if (has_mbyte)
4431 print_pos += (*mb_ptr2cells)(line + col);
4432 else
4433#endif
4434 print_pos++;
4435 }
4436 }
4437
4438 ppos->lead_spaces = tab_spaces;
4439 ppos->print_pos = print_pos;
4440
4441 /*
4442 * Start next line of file if we clip lines, or have reached end of the
4443 * line, unless we are doing a formfeed.
4444 */
4445 if (!ppos->ff
4446 && (line[col] == NUL
4447 || (printer_opts[OPT_PRINT_WRAP].present
4448 && TOLOWER_ASC(printer_opts[OPT_PRINT_WRAP].string[0])
4449 == 'n')))
4450 return 0;
4451 return col;
4452}
4453
4454# if defined(FEAT_POSTSCRIPT) || defined(PROTO)
4455
4456/*
4457 * PS printer stuff.
4458 *
4459 * Sources of information to help maintain the PS printing code:
4460 *
4461 * 1. PostScript Language Reference, 3rd Edition,
4462 * Addison-Wesley, 1999, ISBN 0-201-37922-8
4463 * 2. PostScript Language Program Design,
4464 * Addison-Wesley, 1988, ISBN 0-201-14396-8
4465 * 3. PostScript Tutorial and Cookbook,
4466 * Addison Wesley, 1985, ISBN 0-201-10179-3
4467 * 4. PostScript Language Document Structuring Conventions Specification,
4468 * version 3.0,
4469 * Adobe Technote 5001, 25th September 1992
4470 * 5. PostScript Printer Description File Format Specification, Version 4.3,
4471 * Adobe technote 5003, 9th February 1996
4472 * 6. Adobe Font Metrics File Format Specification, Version 4.1,
4473 * Adobe Technote 5007, 7th October 1998
Bram Moolenaar8299df92004-07-10 09:47:34 +00004474 * 7. Adobe CMap and CIDFont Files Specification, Version 1.0,
4475 * Adobe Technote 5014, 8th October 1996
4476 * 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts,
4477 * Adoboe Technote 5094, 8th September, 2001
4478 * 9. CJKV Information Processing, 2nd Edition,
4479 * O'Reilly, 2002, ISBN 1-56592-224-7
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480 *
4481 * Some of these documents can be found in PDF form on Adobe's web site -
4482 * http://www.adobe.com
4483 */
4484
Bram Moolenaar8299df92004-07-10 09:47:34 +00004485#define NUM_ELEMENTS(arr) (sizeof(arr)/sizeof((arr)[0]))
4486
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487#define PRT_PS_DEFAULT_DPI (72) /* Default user space resolution */
4488#define PRT_PS_DEFAULT_FONTSIZE (10)
4489#define PRT_PS_DEFAULT_BUFFER_SIZE (80)
4490
4491struct prt_mediasize_S
4492{
4493 char *name;
4494 float width; /* width and height in points for portrait */
4495 float height;
4496};
4497
4498#define PRT_MEDIASIZE_LEN (sizeof(prt_mediasize) / sizeof(struct prt_mediasize_S))
4499
4500static struct prt_mediasize_S prt_mediasize[] =
4501{
4502 {"A4", 595.0, 842.0},
4503 {"letter", 612.0, 792.0},
4504 {"10x14", 720.0, 1008.0},
4505 {"A3", 842.0, 1191.0},
4506 {"A5", 420.0, 595.0},
4507 {"B4", 729.0, 1032.0},
4508 {"B5", 516.0, 729.0},
4509 {"executive", 522.0, 756.0},
4510 {"folio", 595.0, 935.0},
4511 {"ledger", 1224.0, 792.0}, /* Yes, it is wider than taller! */
4512 {"legal", 612.0, 1008.0},
4513 {"quarto", 610.0, 780.0},
4514 {"statement", 396.0, 612.0},
4515 {"tabloid", 792.0, 1224.0}
4516};
4517
4518/* PS font names, must be in Roman, Bold, Italic, Bold-Italic order */
4519struct prt_ps_font_S
4520{
4521 int wx;
4522 int uline_offset;
4523 int uline_width;
4524 int bbox_min_y;
4525 int bbox_max_y;
4526 char *(ps_fontname[4]);
4527};
4528
4529#define PRT_PS_FONT_ROMAN (0)
4530#define PRT_PS_FONT_BOLD (1)
4531#define PRT_PS_FONT_OBLIQUE (2)
4532#define PRT_PS_FONT_BOLDOBLIQUE (3)
4533
Bram Moolenaar8299df92004-07-10 09:47:34 +00004534/* Standard font metrics for Courier family */
4535static struct prt_ps_font_S prt_ps_courier_font =
Bram Moolenaar071d4272004-06-13 20:20:40 +00004536{
4537 600,
4538 -100, 50,
4539 -250, 805,
4540 {"Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique"}
4541};
4542
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004543#ifdef FEAT_MBYTE
Bram Moolenaar8299df92004-07-10 09:47:34 +00004544/* Generic font metrics for multi-byte fonts */
4545static struct prt_ps_font_S prt_ps_mb_font =
4546{
4547 1000,
4548 -100, 50,
4549 -250, 805,
4550 {NULL, NULL, NULL, NULL}
4551};
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004552#endif
Bram Moolenaar8299df92004-07-10 09:47:34 +00004553
4554/* Pointer to current font set being used */
4555static struct prt_ps_font_S* prt_ps_font;
4556
4557/* Structures to map user named encoding and mapping to PS equivalents for
4558 * building CID font name */
4559struct prt_ps_encoding_S
4560{
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004561 char *encoding;
4562 char *cmap_encoding;
Bram Moolenaar8299df92004-07-10 09:47:34 +00004563 int needs_charset;
4564};
4565
4566struct prt_ps_charset_S
4567{
4568 char *charset;
4569 char *cmap_charset;
4570 int has_charset;
4571};
4572
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004573#ifdef FEAT_MBYTE
4574
Bram Moolenaar8299df92004-07-10 09:47:34 +00004575#define CS_JIS_C_1978 (0x01)
4576#define CS_JIS_X_1983 (0x02)
4577#define CS_JIS_X_1990 (0x04)
4578#define CS_NEC (0x08)
4579#define CS_MSWINDOWS (0x10)
4580#define CS_CP932 (0x20)
4581#define CS_KANJITALK6 (0x40)
4582#define CS_KANJITALK7 (0x80)
4583
4584/* Japanese encodings and charsets */
4585static struct prt_ps_encoding_S j_encodings[] =
4586{
4587 {"iso-2022-jp", NULL, (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990|
4588 CS_NEC)},
4589 {"euc-jp", "EUC", (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990)},
4590 {"sjis", "RKSJ", (CS_JIS_C_1978|CS_JIS_X_1983|CS_MSWINDOWS|
4591 CS_KANJITALK6|CS_KANJITALK7)},
4592 {"cp932", "RKSJ", CS_JIS_X_1983},
4593 {"ucs-2", "UCS2", CS_JIS_X_1990},
4594 {"utf-8", "UTF8" , CS_JIS_X_1990}
4595};
4596static struct prt_ps_charset_S j_charsets[] =
4597{
4598 {"JIS_C_1978", "78", CS_JIS_C_1978},
4599 {"JIS_X_1983", NULL, CS_JIS_X_1983},
4600 {"JIS_X_1990", "Hojo", CS_JIS_X_1990},
4601 {"NEC", "Ext", CS_NEC},
4602 {"MSWINDOWS", "90ms", CS_MSWINDOWS},
4603 {"CP932", "90ms", CS_JIS_X_1983},
4604 {"KANJITALK6", "83pv", CS_KANJITALK6},
4605 {"KANJITALK7", "90pv", CS_KANJITALK7}
4606};
4607
4608#define CS_GB_2312_80 (0x01)
4609#define CS_GBT_12345_90 (0x02)
4610#define CS_GBK2K (0x04)
4611#define CS_SC_MAC (0x08)
4612#define CS_GBT_90_MAC (0x10)
4613#define CS_GBK (0x20)
4614#define CS_SC_ISO10646 (0x40)
4615
4616/* Simplified Chinese encodings and charsets */
4617static struct prt_ps_encoding_S sc_encodings[] =
4618{
4619 {"iso-2022", NULL, (CS_GB_2312_80|CS_GBT_12345_90)},
4620 {"gb18030", NULL, CS_GBK2K},
4621 {"euc-cn", "EUC", (CS_GB_2312_80|CS_GBT_12345_90|CS_SC_MAC|
4622 CS_GBT_90_MAC)},
4623 {"gbk", "EUC", CS_GBK},
4624 {"ucs-2", "UCS2", CS_SC_ISO10646},
4625 {"utf-8", "UTF8", CS_SC_ISO10646}
4626};
4627static struct prt_ps_charset_S sc_charsets[] =
4628{
4629 {"GB_2312-80", "GB", CS_GB_2312_80},
4630 {"GBT_12345-90","GBT", CS_GBT_12345_90},
4631 {"MAC", "GBpc", CS_SC_MAC},
4632 {"GBT-90_MAC", "GBTpc", CS_GBT_90_MAC},
4633 {"GBK", "GBK", CS_GBK},
4634 {"GB18030", "GBK2K", CS_GBK2K},
4635 {"ISO10646", "UniGB", CS_SC_ISO10646}
4636};
4637
4638#define CS_CNS_PLANE_1 (0x01)
4639#define CS_CNS_PLANE_2 (0x02)
4640#define CS_CNS_PLANE_1_2 (0x04)
4641#define CS_B5 (0x08)
4642#define CS_ETEN (0x10)
4643#define CS_HK_GCCS (0x20)
4644#define CS_HK_SCS (0x40)
4645#define CS_HK_SCS_ETEN (0x80)
4646#define CS_MTHKL (0x100)
4647#define CS_MTHKS (0x200)
4648#define CS_DLHKL (0x400)
4649#define CS_DLHKS (0x800)
4650#define CS_TC_ISO10646 (0x1000)
4651
4652/* Traditional Chinese encodings and charsets */
4653static struct prt_ps_encoding_S tc_encodings[] =
4654{
4655 {"iso-2022", NULL, (CS_CNS_PLANE_1|CS_CNS_PLANE_2)},
4656 {"euc-tw", "EUC", CS_CNS_PLANE_1_2},
4657 {"big5", "B5", (CS_B5|CS_ETEN|CS_HK_GCCS|CS_HK_SCS|
4658 CS_HK_SCS_ETEN|CS_MTHKL|CS_MTHKS|CS_DLHKL|
4659 CS_DLHKS)},
4660 {"cp950", "B5", CS_B5},
4661 {"ucs-2", "UCS2", CS_TC_ISO10646},
4662 {"utf-8", "UTF8", CS_TC_ISO10646},
4663 {"utf-16", "UTF16", CS_TC_ISO10646},
4664 {"utf-32", "UTF32", CS_TC_ISO10646}
4665};
4666static struct prt_ps_charset_S tc_charsets[] =
4667{
4668 {"CNS_1992_1", "CNS1", CS_CNS_PLANE_1},
4669 {"CNS_1992_2", "CNS2", CS_CNS_PLANE_2},
4670 {"CNS_1993", "CNS", CS_CNS_PLANE_1_2},
4671 {"BIG5", NULL, CS_B5},
4672 {"CP950", NULL, CS_B5},
4673 {"ETEN", "ETen", CS_ETEN},
4674 {"HK_GCCS", "HKgccs", CS_HK_GCCS},
4675 {"SCS", "HKscs", CS_HK_SCS},
4676 {"SCS_ETEN", "ETHK", CS_HK_SCS_ETEN},
4677 {"MTHKL", "HKm471", CS_MTHKL},
4678 {"MTHKS", "HKm314", CS_MTHKS},
4679 {"DLHKL", "HKdla", CS_DLHKL},
4680 {"DLHKS", "HKdlb", CS_DLHKS},
4681 {"ISO10646", "UniCNS", CS_TC_ISO10646}
4682};
4683
4684#define CS_KR_X_1992 (0x01)
4685#define CS_KR_MAC (0x02)
4686#define CS_KR_X_1992_MS (0x04)
4687#define CS_KR_ISO10646 (0x08)
4688
4689/* Korean encodings and charsets */
4690static struct prt_ps_encoding_S k_encodings[] =
4691{
4692 {"iso-2022-kr", NULL, CS_KR_X_1992},
4693 {"euc-kr", "EUC", (CS_KR_X_1992|CS_KR_MAC)},
4694 {"johab", "Johab", CS_KR_X_1992},
4695 {"cp1361", "Johab", CS_KR_X_1992},
4696 {"uhc", "UHC", CS_KR_X_1992_MS},
4697 {"cp949", "UHC", CS_KR_X_1992_MS},
4698 {"ucs-2", "UCS2", CS_KR_ISO10646},
4699 {"utf-8", "UTF8", CS_KR_ISO10646}
4700};
4701static struct prt_ps_charset_S k_charsets[] =
4702{
4703 {"KS_X_1992", "KSC", CS_KR_X_1992},
4704 {"CP1361", "KSC", CS_KR_X_1992},
4705 {"MAC", "KSCpc", CS_KR_MAC},
4706 {"MSWINDOWS", "KSCms", CS_KR_X_1992_MS},
4707 {"CP949", "KSCms", CS_KR_X_1992_MS},
4708 {"WANSUNG", "KSCms", CS_KR_X_1992_MS},
4709 {"ISO10646", "UniKS", CS_KR_ISO10646}
4710};
4711
4712/* Collections of encodings and charsets for multi-byte printing */
4713struct prt_ps_mbfont_S
4714{
4715 int num_encodings;
4716 struct prt_ps_encoding_S *encodings;
4717 int num_charsets;
4718 struct prt_ps_charset_S *charsets;
4719 char *ascii_enc;
4720 char *defcs;
4721};
4722
4723static struct prt_ps_mbfont_S prt_ps_mbfonts[] =
4724{
4725 {
4726 NUM_ELEMENTS(j_encodings),
4727 j_encodings,
4728 NUM_ELEMENTS(j_charsets),
4729 j_charsets,
4730 "jis_roman",
4731 "JIS_X_1983"
4732 },
4733 {
4734 NUM_ELEMENTS(sc_encodings),
4735 sc_encodings,
4736 NUM_ELEMENTS(sc_charsets),
4737 sc_charsets,
4738 "gb_roman",
4739 "GB_2312-80"
4740 },
4741 {
4742 NUM_ELEMENTS(tc_encodings),
4743 tc_encodings,
4744 NUM_ELEMENTS(tc_charsets),
4745 tc_charsets,
4746 "cns_roman",
4747 "BIG5"
4748 },
4749 {
4750 NUM_ELEMENTS(k_encodings),
4751 k_encodings,
4752 NUM_ELEMENTS(k_charsets),
4753 k_charsets,
4754 "ks_roman",
4755 "KS_X_1992"
4756 }
4757};
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004758#endif /* FEAT_MBYTE */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004759
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760struct prt_ps_resource_S
4761{
4762 char_u name[64];
4763 char_u filename[MAXPATHL + 1];
4764 int type;
4765 char_u title[256];
4766 char_u version[256];
4767};
4768
4769/* Types of PS resource file currently used */
4770#define PRT_RESOURCE_TYPE_PROCSET (0)
4771#define PRT_RESOURCE_TYPE_ENCODING (1)
Bram Moolenaar8299df92004-07-10 09:47:34 +00004772#define PRT_RESOURCE_TYPE_CMAP (2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773
4774/* The PS prolog file version number has to match - if the prolog file is
4775 * updated, increment the number in the file and here. Version checking was
4776 * added as of VIM 6.2.
Bram Moolenaar8299df92004-07-10 09:47:34 +00004777 * The CID prolog file version number behaves as per PS prolog.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 * Table of VIM and prolog versions:
4779 *
Bram Moolenaar8299df92004-07-10 09:47:34 +00004780 * VIM Prolog CIDProlog
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 * 6.2 1.3
Bram Moolenaar8299df92004-07-10 09:47:34 +00004782 * 7.0 1.4 1.0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004784#define PRT_PROLOG_VERSION ((char_u *)"1.4")
Bram Moolenaar8299df92004-07-10 09:47:34 +00004785#define PRT_CID_PROLOG_VERSION ((char_u *)"1.0")
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786
4787/* String versions of PS resource types - indexed by constants above so don't
4788 * re-order!
4789 */
Bram Moolenaar8299df92004-07-10 09:47:34 +00004790static char *prt_resource_types[] =
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791{
4792 "procset",
Bram Moolenaar8299df92004-07-10 09:47:34 +00004793 "encoding",
4794 "cmap"
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795};
4796
4797/* Strings to look for in a PS resource file */
4798#define PRT_RESOURCE_HEADER "%!PS-Adobe-"
4799#define PRT_RESOURCE_RESOURCE "Resource-"
4800#define PRT_RESOURCE_PROCSET "ProcSet"
4801#define PRT_RESOURCE_ENCODING "Encoding"
Bram Moolenaar8299df92004-07-10 09:47:34 +00004802#define PRT_RESOURCE_CMAP "CMap"
4803
4804
4805/* Data for table based DSC comment recognition, easy to extend if VIM needs to
4806 * read more comments. */
4807#define PRT_DSC_MISC_TYPE (-1)
4808#define PRT_DSC_TITLE_TYPE (1)
4809#define PRT_DSC_VERSION_TYPE (2)
4810#define PRT_DSC_ENDCOMMENTS_TYPE (3)
4811
4812#define PRT_DSC_TITLE "%%Title:"
4813#define PRT_DSC_VERSION "%%Version:"
4814#define PRT_DSC_ENDCOMMENTS "%%EndComments:"
4815
4816struct prt_dsc_comment_S
4817{
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004818 char *string;
Bram Moolenaar8299df92004-07-10 09:47:34 +00004819 int len;
4820 int type;
4821};
4822
4823struct prt_dsc_line_S
4824{
4825 int type;
4826 char_u *string;
4827 int len;
4828};
4829
4830
4831#define SIZEOF_CSTR(s) (sizeof(s) - 1)
Bram Moolenaard042c562005-06-30 22:04:15 +00004832static struct prt_dsc_comment_S prt_dsc_table[] =
Bram Moolenaar8299df92004-07-10 09:47:34 +00004833{
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004834 {PRT_DSC_TITLE, SIZEOF_CSTR(PRT_DSC_TITLE), PRT_DSC_TITLE_TYPE},
Bram Moolenaar8299df92004-07-10 09:47:34 +00004835 {PRT_DSC_VERSION, SIZEOF_CSTR(PRT_DSC_VERSION),
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004836 PRT_DSC_VERSION_TYPE},
Bram Moolenaar8299df92004-07-10 09:47:34 +00004837 {PRT_DSC_ENDCOMMENTS, SIZEOF_CSTR(PRT_DSC_ENDCOMMENTS),
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004838 PRT_DSC_ENDCOMMENTS_TYPE}
Bram Moolenaar8299df92004-07-10 09:47:34 +00004839};
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840
4841static void prt_write_file_raw_len __ARGS((char_u *buffer, int bytes));
4842static void prt_write_file __ARGS((char_u *buffer));
4843static void prt_write_file_len __ARGS((char_u *buffer, int bytes));
4844static void prt_write_string __ARGS((char *s));
4845static void prt_write_int __ARGS((int i));
4846static void prt_write_boolean __ARGS((int b));
4847static void prt_def_font __ARGS((char *new_name, char *encoding, int height, char *font));
4848static void prt_real_bits __ARGS((double real, int precision, int *pinteger, int *pfraction));
4849static void prt_write_real __ARGS((double val, int prec));
4850static void prt_def_var __ARGS((char *name, double value, int prec));
4851static void prt_flush_buffer __ARGS((void));
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00004852static void prt_resource_name __ARGS((char_u *filename, void *cookie));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853static int prt_find_resource __ARGS((char *name, struct prt_ps_resource_S *resource));
4854static int prt_open_resource __ARGS((struct prt_ps_resource_S *resource));
4855static int prt_check_resource __ARGS((struct prt_ps_resource_S *resource, char_u *version));
4856static void prt_dsc_start __ARGS((void));
4857static void prt_dsc_noarg __ARGS((char *comment));
4858static void prt_dsc_textline __ARGS((char *comment, char *text));
4859static void prt_dsc_text __ARGS((char *comment, char *text));
4860static void prt_dsc_ints __ARGS((char *comment, int count, int *ints));
4861static void prt_dsc_requirements __ARGS((int duplex, int tumble, int collate, int color, int num_copies));
4862static void prt_dsc_docmedia __ARGS((char *paper_name, double width, double height, double weight, char *colour, char *type));
Bram Moolenaar8299df92004-07-10 09:47:34 +00004863static void prt_dsc_resources __ARGS((char *comment, char *type, char *strings));
4864static void prt_dsc_font_resource __ARGS((char *resource, struct prt_ps_font_S *ps_font));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865static float to_device_units __ARGS((int idx, double physsize, int def_number));
4866static void prt_page_margins __ARGS((double width, double height, double *left, double *right, double *top, double *bottom));
4867static void prt_font_metrics __ARGS((int font_scale));
4868static int prt_get_cpl __ARGS((void));
4869static int prt_get_lpp __ARGS((void));
4870static int prt_add_resource __ARGS((struct prt_ps_resource_S *resource));
Bram Moolenaar8299df92004-07-10 09:47:34 +00004871static int prt_resfile_next_line __ARGS((void));
4872static int prt_resfile_strncmp __ARGS((int offset, char *string, int len));
4873static int prt_resfile_skip_nonws __ARGS((int offset));
4874static int prt_resfile_skip_ws __ARGS((int offset));
4875static int prt_next_dsc __ARGS((struct prt_dsc_line_S *p_dsc_line));
4876#ifdef FEAT_MBYTE
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004877static int prt_build_cid_fontname __ARGS((int font, char_u *name, int name_len));
Bram Moolenaar8299df92004-07-10 09:47:34 +00004878static void prt_def_cidfont __ARGS((char *new_name, int height, char *cidfont));
Bram Moolenaard042c562005-06-30 22:04:15 +00004879static void prt_dup_cidfont __ARGS((char *original_name, char *new_name));
Bram Moolenaar8299df92004-07-10 09:47:34 +00004880static int prt_match_encoding __ARGS((char *p_encoding, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_encoding_S **pp_mbenc));
4881static int prt_match_charset __ARGS((char *p_charset, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_charset_S **pp_mbchar));
4882#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883
4884/*
4885 * Variables for the output PostScript file.
4886 */
4887static FILE *prt_ps_fd;
4888static int prt_file_error;
4889static char_u *prt_ps_file_name = NULL;
4890
4891/*
4892 * Various offsets and dimensions in default PostScript user space (points).
4893 * Used for text positioning calculations
4894 */
4895static float prt_page_width;
4896static float prt_page_height;
4897static float prt_left_margin;
4898static float prt_right_margin;
4899static float prt_top_margin;
4900static float prt_bottom_margin;
4901static float prt_line_height;
4902static float prt_first_line_height;
4903static float prt_char_width;
4904static float prt_number_width;
4905static float prt_bgcol_offset;
4906static float prt_pos_x_moveto = 0.0;
4907static float prt_pos_y_moveto = 0.0;
4908
4909/*
4910 * Various control variables used to decide when and how to change the
4911 * PostScript graphics state.
4912 */
4913static int prt_need_moveto;
4914static int prt_do_moveto;
4915static int prt_need_font;
4916static int prt_font;
4917static int prt_need_underline;
4918static int prt_underline;
4919static int prt_do_underline;
4920static int prt_need_fgcol;
4921static int prt_fgcol;
4922static int prt_need_bgcol;
4923static int prt_do_bgcol;
4924static int prt_bgcol;
4925static int prt_new_bgcol;
4926static int prt_attribute_change;
Bram Moolenaar8299df92004-07-10 09:47:34 +00004927static float prt_text_run;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928static int prt_page_num;
Bram Moolenaar8299df92004-07-10 09:47:34 +00004929static int prt_bufsiz;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930
4931/*
4932 * Variables controlling physical printing.
4933 */
4934static int prt_media;
4935static int prt_portrait;
4936static int prt_num_copies;
4937static int prt_duplex;
4938static int prt_tumble;
4939static int prt_collate;
4940
4941/*
4942 * Buffers used when generating PostScript output
4943 */
4944static char_u prt_line_buffer[257];
4945static garray_T prt_ps_buffer;
4946
4947# ifdef FEAT_MBYTE
4948static int prt_do_conv;
4949static vimconv_T prt_conv;
Bram Moolenaar8299df92004-07-10 09:47:34 +00004950
4951static int prt_out_mbyte;
4952static int prt_custom_cmap;
4953static char prt_cmap[80];
4954static int prt_use_courier;
4955static int prt_in_ascii;
4956static int prt_half_width;
4957static char *prt_ascii_encoding;
4958static char_u prt_hexchar[] = "0123456789abcdef";
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959# endif
4960
4961 static void
4962prt_write_file_raw_len(buffer, bytes)
4963 char_u *buffer;
4964 int bytes;
4965{
4966 if (!prt_file_error
4967 && fwrite(buffer, sizeof(char_u), bytes, prt_ps_fd)
4968 != (size_t)bytes)
4969 {
4970 EMSG(_("E455: Error writing to PostScript output file"));
4971 prt_file_error = TRUE;
4972 }
4973}
4974
4975 static void
4976prt_write_file(buffer)
4977 char_u *buffer;
4978{
4979 prt_write_file_len(buffer, STRLEN(buffer));
4980}
4981
4982 static void
4983prt_write_file_len(buffer, bytes)
4984 char_u *buffer;
4985 int bytes;
4986{
4987#ifdef EBCDIC
4988 ebcdic2ascii(buffer, bytes);
4989#endif
4990 prt_write_file_raw_len(buffer, bytes);
4991}
4992
4993/*
4994 * Write a string.
4995 */
4996 static void
4997prt_write_string(s)
4998 char *s;
4999{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005000 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%s", s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001 prt_write_file(prt_line_buffer);
5002}
5003
5004/*
5005 * Write an int and a space.
5006 */
5007 static void
5008prt_write_int(i)
5009 int i;
5010{
5011 sprintf((char *)prt_line_buffer, "%d ", i);
5012 prt_write_file(prt_line_buffer);
5013}
5014
5015/*
5016 * Write a boolean and a space.
5017 */
5018 static void
5019prt_write_boolean(b)
5020 int b;
5021{
5022 sprintf((char *)prt_line_buffer, "%s ", (b ? "T" : "F"));
5023 prt_write_file(prt_line_buffer);
5024}
5025
5026/*
Bram Moolenaar8299df92004-07-10 09:47:34 +00005027 * Write PostScript to re-encode and define the font.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 */
5029 static void
5030prt_def_font(new_name, encoding, height, font)
5031 char *new_name;
5032 char *encoding;
5033 int height;
5034 char *font;
5035{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005036 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5037 "/_%s /VIM-%s /%s ref\n", new_name, encoding, font);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 prt_write_file(prt_line_buffer);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005039#ifdef FEAT_MBYTE
5040 if (prt_out_mbyte)
5041 sprintf((char *)prt_line_buffer, "/%s %d %f /_%s sffs\n",
5042 new_name, height, 500./prt_ps_courier_font.wx, new_name);
5043 else
5044#endif
Bram Moolenaar555b2802005-05-19 21:08:39 +00005045 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5046 "/%s %d /_%s ffs\n", new_name, height, new_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 prt_write_file(prt_line_buffer);
5048}
5049
Bram Moolenaar8299df92004-07-10 09:47:34 +00005050#ifdef FEAT_MBYTE
5051/*
5052 * Write a line to define the CID font.
5053 */
5054 static void
5055prt_def_cidfont(new_name, height, cidfont)
5056 char *new_name;
5057 int height;
5058 char *cidfont;
5059{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005060 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5061 "/_%s /%s[/%s] vim_composefont\n", new_name, prt_cmap, cidfont);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005062 prt_write_file(prt_line_buffer);
Bram Moolenaar555b2802005-05-19 21:08:39 +00005063 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5064 "/%s %d /_%s ffs\n", new_name, height, new_name);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005065 prt_write_file(prt_line_buffer);
5066}
5067
5068/*
5069 * Write a line to define a duplicate of a CID font
5070 */
5071 static void
5072prt_dup_cidfont(original_name, new_name)
5073 char *original_name;
5074 char *new_name;
5075{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005076 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5077 "/%s %s d\n", new_name, original_name);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005078 prt_write_file(prt_line_buffer);
5079}
5080#endif
5081
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082/*
5083 * Convert a real value into an integer and fractional part as integers, with
5084 * the fractional part being in the range [0,10^precision). The fractional part
5085 * is also rounded based on the precision + 1'th fractional digit.
5086 */
5087 static void
5088prt_real_bits(real, precision, pinteger, pfraction)
5089 double real;
5090 int precision;
5091 int *pinteger;
5092 int *pfraction;
5093{
5094 int i;
5095 int integer;
5096 float fraction;
5097
5098 integer = (int)real;
5099 fraction = (float)(real - integer);
5100 if (real < (double)integer)
5101 fraction = -fraction;
5102 for (i = 0; i < precision; i++)
5103 fraction *= 10.0;
5104
5105 *pinteger = integer;
5106 *pfraction = (int)(fraction + 0.5);
5107}
5108
5109/*
5110 * Write a real and a space. Save bytes if real value has no fractional part!
5111 * We use prt_real_bits() as %f in sprintf uses the locale setting to decide
5112 * what decimal point character to use, but PS always requires a '.'.
5113 */
5114 static void
5115prt_write_real(val, prec)
5116 double val;
5117 int prec;
5118{
5119 int integer;
5120 int fraction;
5121
5122 prt_real_bits(val, prec, &integer, &fraction);
5123 /* Emit integer part */
5124 sprintf((char *)prt_line_buffer, "%d", integer);
5125 prt_write_file(prt_line_buffer);
5126 /* Only emit fraction if necessary */
5127 if (fraction != 0)
5128 {
5129 /* Remove any trailing zeros */
5130 while ((fraction % 10) == 0)
5131 {
5132 prec--;
5133 fraction /= 10;
5134 }
5135 /* Emit fraction left padded with zeros */
5136 sprintf((char *)prt_line_buffer, ".%0*d", prec, fraction);
5137 prt_write_file(prt_line_buffer);
5138 }
5139 sprintf((char *)prt_line_buffer, " ");
5140 prt_write_file(prt_line_buffer);
5141}
5142
5143/*
5144 * Write a line to define a numeric variable.
5145 */
5146 static void
5147prt_def_var(name, value, prec)
5148 char *name;
5149 double value;
5150 int prec;
5151{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005152 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5153 "/%s ", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154 prt_write_file(prt_line_buffer);
5155 prt_write_real(value, prec);
5156 sprintf((char *)prt_line_buffer, "d\n");
5157 prt_write_file(prt_line_buffer);
5158}
5159
5160/* Convert size from font space to user space at current font scale */
5161#define PRT_PS_FONT_TO_USER(scale, size) ((size) * ((scale)/1000.0))
5162
5163 static void
5164prt_flush_buffer()
5165{
5166 if (prt_ps_buffer.ga_len > 0)
5167 {
5168 /* Any background color must be drawn first */
5169 if (prt_do_bgcol && (prt_new_bgcol != PRCOLOR_WHITE))
5170 {
5171 int r, g, b;
5172
5173 if (prt_do_moveto)
5174 {
5175 prt_write_real(prt_pos_x_moveto, 2);
5176 prt_write_real(prt_pos_y_moveto, 2);
5177 prt_write_string("m\n");
5178 prt_do_moveto = FALSE;
5179 }
5180
5181 /* Size of rect of background color on which text is printed */
Bram Moolenaar8299df92004-07-10 09:47:34 +00005182 prt_write_real(prt_text_run, 2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183 prt_write_real(prt_line_height, 2);
5184
5185 /* Lastly add the color of the background */
5186 r = ((unsigned)prt_new_bgcol & 0xff0000) >> 16;
5187 g = ((unsigned)prt_new_bgcol & 0xff00) >> 8;
5188 b = prt_new_bgcol & 0xff;
5189 prt_write_real(r / 255.0, 3);
5190 prt_write_real(g / 255.0, 3);
5191 prt_write_real(b / 255.0, 3);
5192 prt_write_string("bg\n");
5193 }
5194 /* Draw underlines before the text as it makes it slightly easier to
5195 * find the starting point.
5196 */
5197 if (prt_do_underline)
5198 {
5199 if (prt_do_moveto)
5200 {
5201 prt_write_real(prt_pos_x_moveto, 2);
5202 prt_write_real(prt_pos_y_moveto, 2);
5203 prt_write_string("m\n");
5204 prt_do_moveto = FALSE;
5205 }
5206
Bram Moolenaar8299df92004-07-10 09:47:34 +00005207 /* Underline length of text run */
5208 prt_write_real(prt_text_run, 2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 prt_write_string("ul\n");
5210 }
5211 /* Draw the text
5212 * Note: we write text out raw - EBCDIC conversion is handled in the
5213 * PostScript world via the font encoding vector. */
Bram Moolenaar8299df92004-07-10 09:47:34 +00005214#ifdef FEAT_MBYTE
5215 if (prt_out_mbyte)
5216 prt_write_string("<");
5217 else
5218#endif
5219 prt_write_string("(");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220 prt_write_file_raw_len(prt_ps_buffer.ga_data, prt_ps_buffer.ga_len);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005221#ifdef FEAT_MBYTE
5222 if (prt_out_mbyte)
5223 prt_write_string(">");
5224 else
5225#endif
5226 prt_write_string(")");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 /* Add a moveto if need be and use the appropriate show procedure */
5228 if (prt_do_moveto)
5229 {
5230 prt_write_real(prt_pos_x_moveto, 2);
5231 prt_write_real(prt_pos_y_moveto, 2);
5232 /* moveto and a show */
5233 prt_write_string("ms\n");
5234 prt_do_moveto = FALSE;
5235 }
5236 else /* Simple show */
5237 prt_write_string("s\n");
5238
5239 ga_clear(&prt_ps_buffer);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005240 ga_init2(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 }
5242}
5243
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244
5245 static void
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00005246prt_resource_name(filename, cookie)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005247 char_u *filename;
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00005248 void *cookie;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249{
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00005250 char_u *resource_filename = cookie;
5251
Bram Moolenaar071d4272004-06-13 20:20:40 +00005252 if (STRLEN(filename) >= MAXPATHL)
5253 *resource_filename = NUL;
5254 else
5255 STRCPY(resource_filename, filename);
5256}
5257
5258 static int
5259prt_find_resource(name, resource)
5260 char *name;
5261 struct prt_ps_resource_S *resource;
5262{
5263 char_u buffer[MAXPATHL + 1];
5264
5265 STRCPY(resource->name, name);
5266 /* Look for named resource file in runtimepath */
5267 STRCPY(buffer, "print");
5268 add_pathsep(buffer);
5269 STRCAT(buffer, name);
5270 STRCAT(buffer, ".ps");
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00005271 resource->filename[0] = NUL;
5272 return (do_in_runtimepath(buffer, FALSE, prt_resource_name,
5273 resource->filename)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005274 && resource->filename[0] != NUL);
5275}
5276
5277/* PS CR and LF characters have platform independent values */
5278#define PSLF (0x0a)
5279#define PSCR (0x0d)
5280
Bram Moolenaar8299df92004-07-10 09:47:34 +00005281/* Static buffer to read initial comments in a resource file, some can have a
5282 * couple of KB of comments! */
5283#define PRT_FILE_BUFFER_LEN (2048)
5284struct prt_resfile_buffer_S
5285{
5286 char_u buffer[PRT_FILE_BUFFER_LEN];
5287 int len;
5288 int line_start;
5289 int line_end;
5290};
5291
5292static struct prt_resfile_buffer_S prt_resfile;
5293
5294 static int
5295prt_resfile_next_line()
5296{
5297 int index;
5298
5299 /* Move to start of next line and then find end of line */
5300 index = prt_resfile.line_end + 1;
5301 while (index < prt_resfile.len)
5302 {
5303 if (prt_resfile.buffer[index] != PSLF && prt_resfile.buffer[index]
5304 != PSCR)
5305 break;
5306 index++;
5307 }
5308 prt_resfile.line_start = index;
5309
5310 while (index < prt_resfile.len)
5311 {
5312 if (prt_resfile.buffer[index] == PSLF || prt_resfile.buffer[index]
5313 == PSCR)
5314 break;
5315 index++;
5316 }
5317 prt_resfile.line_end = index;
5318
5319 return (index < prt_resfile.len);
5320}
5321
5322 static int
5323prt_resfile_strncmp(offset, string, len)
5324 int offset;
5325 char *string;
5326 int len;
5327{
5328 /* Force not equal if string is longer than remainder of line */
5329 if (len > (prt_resfile.line_end - (prt_resfile.line_start + offset)))
5330 return 1;
5331
5332 return STRNCMP(&prt_resfile.buffer[prt_resfile.line_start + offset],
5333 string, len);
5334}
5335
5336 static int
5337prt_resfile_skip_nonws(offset)
5338 int offset;
5339{
5340 int index;
5341
5342 index = prt_resfile.line_start + offset;
5343 while (index < prt_resfile.line_end)
5344 {
5345 if (isspace(prt_resfile.buffer[index]))
5346 return index - prt_resfile.line_start;
5347 index++;
5348 }
5349 return -1;
5350}
5351
5352 static int
5353prt_resfile_skip_ws(offset)
5354 int offset;
5355{
5356 int index;
5357
5358 index = prt_resfile.line_start + offset;
5359 while (index < prt_resfile.line_end)
5360 {
5361 if (!isspace(prt_resfile.buffer[index]))
5362 return index - prt_resfile.line_start;
5363 index++;
5364 }
5365 return -1;
5366}
5367
5368/* prt_next_dsc() - returns detail on next DSC comment line found. Returns true
5369 * if a DSC comment is found, else false */
5370 static int
5371prt_next_dsc(p_dsc_line)
5372 struct prt_dsc_line_S *p_dsc_line;
5373{
5374 int comment;
5375 int offset;
5376
5377 /* Move to start of next line */
5378 if (!prt_resfile_next_line())
5379 return FALSE;
5380
5381 /* DSC comments always start %% */
5382 if (prt_resfile_strncmp(0, "%%", 2) != 0)
5383 return FALSE;
5384
5385 /* Find type of DSC comment */
5386 for (comment = 0; comment < NUM_ELEMENTS(prt_dsc_table); comment++)
5387 if (prt_resfile_strncmp(0, prt_dsc_table[comment].string,
5388 prt_dsc_table[comment].len) == 0)
5389 break;
5390
5391 if (comment != NUM_ELEMENTS(prt_dsc_table))
5392 {
5393 /* Return type of comment */
5394 p_dsc_line->type = prt_dsc_table[comment].type;
5395 offset = prt_dsc_table[comment].len;
5396 }
5397 else
5398 {
5399 /* Unrecognised DSC comment, skip to ws after comment leader */
5400 p_dsc_line->type = PRT_DSC_MISC_TYPE;
5401 offset = prt_resfile_skip_nonws(0);
5402 if (offset == -1)
5403 return FALSE;
5404 }
5405
5406 /* Skip ws to comment value */
5407 offset = prt_resfile_skip_ws(offset);
5408 if (offset == -1)
5409 return FALSE;
5410
5411 p_dsc_line->string = &prt_resfile.buffer[prt_resfile.line_start + offset];
5412 p_dsc_line->len = prt_resfile.line_end - (prt_resfile.line_start + offset);
5413
5414 return TRUE;
5415}
5416
5417/* Improved hand crafted parser to get the type, title, and version number of a
5418 * PS resource file so the file details can be added to the DSC header comments.
5419 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005420 static int
5421prt_open_resource(resource)
5422 struct prt_ps_resource_S *resource;
5423{
Bram Moolenaar8299df92004-07-10 09:47:34 +00005424 int offset;
5425 int seen_all;
5426 int seen_title;
5427 int seen_version;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005428 FILE *fd_resource;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005429 struct prt_dsc_line_S dsc_line;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430
5431 fd_resource = mch_fopen((char *)resource->filename, READBIN);
5432 if (fd_resource == NULL)
5433 {
5434 EMSG2(_("E624: Can't open file \"%s\""), resource->filename);
5435 return FALSE;
5436 }
Bram Moolenaar8299df92004-07-10 09:47:34 +00005437 vim_memset(prt_resfile.buffer, NUL, PRT_FILE_BUFFER_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438
5439 /* Parse first line to ensure valid resource file */
Bram Moolenaar8299df92004-07-10 09:47:34 +00005440 prt_resfile.len = fread((char *)prt_resfile.buffer, sizeof(char_u),
5441 PRT_FILE_BUFFER_LEN, fd_resource);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442 if (ferror(fd_resource))
5443 {
5444 EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
5445 resource->filename);
5446 fclose(fd_resource);
5447 return FALSE;
5448 }
5449
Bram Moolenaar8299df92004-07-10 09:47:34 +00005450 prt_resfile.line_end = -1;
5451 prt_resfile.line_start = 0;
5452 if (!prt_resfile_next_line())
5453 return FALSE;
5454
5455 offset = 0;
5456
5457 if (prt_resfile_strncmp(offset, PRT_RESOURCE_HEADER,
5458 STRLEN(PRT_RESOURCE_HEADER)) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459 {
5460 EMSG2(_("E618: file \"%s\" is not a PostScript resource file"),
5461 resource->filename);
5462 fclose(fd_resource);
5463 return FALSE;
5464 }
5465
5466 /* Skip over any version numbers and following ws */
Bram Moolenaar8299df92004-07-10 09:47:34 +00005467 offset += STRLEN(PRT_RESOURCE_HEADER);
5468 offset = prt_resfile_skip_nonws(offset);
5469 if (offset == -1)
5470 return FALSE;
5471 offset = prt_resfile_skip_ws(offset);
5472 if (offset == -1)
5473 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474
Bram Moolenaar8299df92004-07-10 09:47:34 +00005475 if (prt_resfile_strncmp(offset, PRT_RESOURCE_RESOURCE,
5476 STRLEN(PRT_RESOURCE_RESOURCE)) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477 {
5478 EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
5479 resource->filename);
5480 fclose(fd_resource);
5481 return FALSE;
5482 }
Bram Moolenaar8299df92004-07-10 09:47:34 +00005483 offset += STRLEN(PRT_RESOURCE_RESOURCE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484
5485 /* Decide type of resource in the file */
Bram Moolenaar8299df92004-07-10 09:47:34 +00005486 if (prt_resfile_strncmp(offset, PRT_RESOURCE_PROCSET,
5487 STRLEN(PRT_RESOURCE_PROCSET)) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 resource->type = PRT_RESOURCE_TYPE_PROCSET;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005489 else if (prt_resfile_strncmp(offset, PRT_RESOURCE_ENCODING,
5490 STRLEN(PRT_RESOURCE_ENCODING)) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491 resource->type = PRT_RESOURCE_TYPE_ENCODING;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005492 else if (prt_resfile_strncmp(offset, PRT_RESOURCE_CMAP,
5493 STRLEN(PRT_RESOURCE_CMAP)) == 0)
5494 resource->type = PRT_RESOURCE_TYPE_CMAP;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495 else
5496 {
5497 EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
5498 resource->filename);
5499 fclose(fd_resource);
5500 return FALSE;
5501 }
5502
Bram Moolenaar8299df92004-07-10 09:47:34 +00005503 /* Look for title and version of resource */
5504 resource->title[0] = '\0';
5505 resource->version[0] = '\0';
5506 seen_title = FALSE;
5507 seen_version = FALSE;
5508 seen_all = FALSE;
5509 while (!seen_all && prt_next_dsc(&dsc_line))
5510 {
5511 switch (dsc_line.type)
5512 {
5513 case PRT_DSC_TITLE_TYPE:
Bram Moolenaarce0842a2005-07-18 21:58:11 +00005514 vim_strncpy(resource->title, dsc_line.string, dsc_line.len);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005515 seen_title = TRUE;
5516 if (seen_version)
5517 seen_all = TRUE;
5518 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519
Bram Moolenaar8299df92004-07-10 09:47:34 +00005520 case PRT_DSC_VERSION_TYPE:
Bram Moolenaarce0842a2005-07-18 21:58:11 +00005521 vim_strncpy(resource->version, dsc_line.string, dsc_line.len);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005522 seen_version = TRUE;
5523 if (seen_title)
5524 seen_all = TRUE;
5525 break;
5526
5527 case PRT_DSC_ENDCOMMENTS_TYPE:
5528 /* Wont find title or resource after this comment, stop searching */
5529 seen_all = TRUE;
5530 break;
5531
5532 case PRT_DSC_MISC_TYPE:
5533 /* Not interested in whatever comment this line had */
5534 break;
5535 }
5536 }
5537
5538 if (!seen_title || !seen_version)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539 {
5540 EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
5541 resource->filename);
5542 fclose(fd_resource);
5543 return FALSE;
5544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545
5546 fclose(fd_resource);
5547
5548 return TRUE;
5549}
5550
5551 static int
5552prt_check_resource(resource, version)
5553 struct prt_ps_resource_S *resource;
5554 char_u *version;
5555{
5556 /* Version number m.n should match, the revision number does not matter */
5557 if (STRNCMP(resource->version, version, STRLEN(version)))
5558 {
5559 EMSG2(_("E621: \"%s\" resource file has wrong version"),
5560 resource->name);
5561 return FALSE;
5562 }
5563
5564 /* Other checks to be added as needed */
5565 return TRUE;
5566}
5567
5568 static void
5569prt_dsc_start()
5570{
5571 prt_write_string("%!PS-Adobe-3.0\n");
5572}
5573
5574 static void
5575prt_dsc_noarg(comment)
5576 char *comment;
5577{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005578 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5579 "%%%%%s\n", comment);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 prt_write_file(prt_line_buffer);
5581}
5582
5583 static void
5584prt_dsc_textline(comment, text)
5585 char *comment;
5586 char *text;
5587{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005588 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5589 "%%%%%s: %s\n", comment, text);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 prt_write_file(prt_line_buffer);
5591}
5592
5593 static void
5594prt_dsc_text(comment, text)
5595 char *comment;
5596 char *text;
5597{
5598 /* TODO - should scan 'text' for any chars needing escaping! */
Bram Moolenaar555b2802005-05-19 21:08:39 +00005599 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5600 "%%%%%s: (%s)\n", comment, text);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 prt_write_file(prt_line_buffer);
5602}
5603
5604#define prt_dsc_atend(c) prt_dsc_text((c), "atend")
5605
5606 static void
5607prt_dsc_ints(comment, count, ints)
5608 char *comment;
5609 int count;
5610 int *ints;
5611{
5612 int i;
5613
Bram Moolenaar555b2802005-05-19 21:08:39 +00005614 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5615 "%%%%%s:", comment);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 prt_write_file(prt_line_buffer);
5617
5618 for (i = 0; i < count; i++)
5619 {
5620 sprintf((char *)prt_line_buffer, " %d", ints[i]);
5621 prt_write_file(prt_line_buffer);
5622 }
5623
5624 prt_write_string("\n");
5625}
5626
5627 static void
Bram Moolenaar8299df92004-07-10 09:47:34 +00005628prt_dsc_resources(comment, type, string)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629 char *comment; /* if NULL add to previous */
5630 char *type;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005631 char *string;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 if (comment != NULL)
Bram Moolenaar555b2802005-05-19 21:08:39 +00005634 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5635 "%%%%%s: %s", comment, type);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00005637 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5638 "%%%%+ %s", type);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 prt_write_file(prt_line_buffer);
5640
Bram Moolenaar555b2802005-05-19 21:08:39 +00005641 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5642 " %s\n", string);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005643 prt_write_file(prt_line_buffer);
5644}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645
Bram Moolenaar8299df92004-07-10 09:47:34 +00005646 static void
5647prt_dsc_font_resource(resource, ps_font)
5648 char *resource;
5649 struct prt_ps_font_S *ps_font;
5650{
5651 int i;
5652
5653 prt_dsc_resources(resource, "font",
5654 ps_font->ps_fontname[PRT_PS_FONT_ROMAN]);
5655 for (i = PRT_PS_FONT_BOLD ; i <= PRT_PS_FONT_BOLDOBLIQUE ; i++)
5656 if (ps_font->ps_fontname[i] != NULL)
5657 prt_dsc_resources(NULL, "font", ps_font->ps_fontname[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658}
5659
5660 static void
5661prt_dsc_requirements(duplex, tumble, collate, color, num_copies)
5662 int duplex;
5663 int tumble;
5664 int collate;
5665 int color;
5666 int num_copies;
5667{
5668 /* Only output the comment if we need to.
5669 * Note: tumble is ignored if we are not duplexing
5670 */
5671 if (!(duplex || collate || color || (num_copies > 1)))
5672 return;
5673
5674 sprintf((char *)prt_line_buffer, "%%%%Requirements:");
5675 prt_write_file(prt_line_buffer);
5676
5677 if (duplex)
5678 {
5679 prt_write_string(" duplex");
5680 if (tumble)
5681 prt_write_string("(tumble)");
5682 }
5683 if (collate)
5684 prt_write_string(" collate");
5685 if (color)
5686 prt_write_string(" color");
5687 if (num_copies > 1)
5688 {
5689 prt_write_string(" numcopies(");
5690 /* Note: no space wanted so dont use prt_write_int() */
5691 sprintf((char *)prt_line_buffer, "%d", num_copies);
5692 prt_write_file(prt_line_buffer);
5693 prt_write_string(")");
5694 }
5695 prt_write_string("\n");
5696}
5697
5698 static void
5699prt_dsc_docmedia(paper_name, width, height, weight, colour, type)
5700 char *paper_name;
5701 double width;
5702 double height;
5703 double weight;
5704 char *colour;
5705 char *type;
5706{
Bram Moolenaar555b2802005-05-19 21:08:39 +00005707 vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer),
5708 "%%%%DocumentMedia: %s ", paper_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709 prt_write_file(prt_line_buffer);
5710 prt_write_real(width, 2);
5711 prt_write_real(height, 2);
5712 prt_write_real(weight, 2);
5713 if (colour == NULL)
5714 prt_write_string("()");
5715 else
5716 prt_write_string(colour);
5717 prt_write_string(" ");
5718 if (type == NULL)
5719 prt_write_string("()");
5720 else
5721 prt_write_string(type);
5722 prt_write_string("\n");
5723}
5724
5725 void
5726mch_print_cleanup()
5727{
5728#ifdef FEAT_MBYTE
Bram Moolenaar8299df92004-07-10 09:47:34 +00005729 if (prt_out_mbyte)
5730 {
5731 int i;
5732
5733 /* Free off all CID font names created, but first clear duplicate
5734 * pointers to the same string (when the same font is used for more than
5735 * one style).
5736 */
5737 for (i = PRT_PS_FONT_ROMAN; i <= PRT_PS_FONT_BOLDOBLIQUE; i++)
5738 {
5739 if (prt_ps_mb_font.ps_fontname[i] != NULL)
5740 vim_free(prt_ps_mb_font.ps_fontname[i]);
5741 prt_ps_mb_font.ps_fontname[i] = NULL;
5742 }
5743 }
5744
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 if (prt_do_conv)
5746 {
5747 convert_setup(&prt_conv, NULL, NULL);
5748 prt_do_conv = FALSE;
5749 }
5750#endif
5751 if (prt_ps_fd != NULL)
5752 {
5753 fclose(prt_ps_fd);
5754 prt_ps_fd = NULL;
5755 prt_file_error = FALSE;
5756 }
5757 if (prt_ps_file_name != NULL)
5758 {
5759 vim_free(prt_ps_file_name);
5760 prt_ps_file_name = NULL;
5761 }
5762}
5763
5764 static float
5765to_device_units(idx, physsize, def_number)
5766 int idx;
5767 double physsize;
5768 int def_number;
5769{
5770 float ret;
5771 int u;
5772 int nr;
5773
5774 u = prt_get_unit(idx);
5775 if (u == PRT_UNIT_NONE)
5776 {
5777 u = PRT_UNIT_PERC;
5778 nr = def_number;
5779 }
5780 else
5781 nr = printer_opts[idx].number;
5782
5783 switch (u)
5784 {
5785 case PRT_UNIT_INCH:
5786 ret = (float)(nr * PRT_PS_DEFAULT_DPI);
5787 break;
5788 case PRT_UNIT_MM:
5789 ret = (float)(nr * PRT_PS_DEFAULT_DPI) / (float)25.4;
5790 break;
5791 case PRT_UNIT_POINT:
5792 ret = (float)nr;
5793 break;
5794 case PRT_UNIT_PERC:
5795 default:
5796 ret = (float)(physsize * nr) / 100;
5797 break;
5798 }
5799
5800 return ret;
5801}
5802
5803/*
5804 * Calculate margins for given width and height from printoptions settings.
5805 */
5806 static void
5807prt_page_margins(width, height, left, right, top, bottom)
5808 double width;
5809 double height;
5810 double *left;
5811 double *right;
5812 double *top;
5813 double *bottom;
5814{
5815 *left = to_device_units(OPT_PRINT_LEFT, width, 10);
5816 *right = width - to_device_units(OPT_PRINT_RIGHT, width, 5);
5817 *top = height - to_device_units(OPT_PRINT_TOP, height, 5);
5818 *bottom = to_device_units(OPT_PRINT_BOT, height, 5);
5819}
5820
5821 static void
5822prt_font_metrics(font_scale)
5823 int font_scale;
5824{
5825 prt_line_height = (float)font_scale;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005826 prt_char_width = (float)PRT_PS_FONT_TO_USER(font_scale, prt_ps_font->wx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005827}
5828
5829
5830 static int
5831prt_get_cpl()
5832{
5833 if (prt_use_number())
5834 {
5835 prt_number_width = PRINT_NUMBER_WIDTH * prt_char_width;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005836#ifdef FEAT_MBYTE
5837 /* If we are outputting multi-byte characters then line numbers will be
5838 * printed with half width characters
5839 */
5840 if (prt_out_mbyte)
5841 prt_number_width /= 2;
5842#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843 prt_left_margin += prt_number_width;
5844 }
5845 else
5846 prt_number_width = 0.0;
5847
5848 return (int)((prt_right_margin - prt_left_margin) / prt_char_width);
5849}
5850
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005851#ifdef FEAT_MBYTE
Bram Moolenaar8299df92004-07-10 09:47:34 +00005852 static int
5853prt_build_cid_fontname(font, name, name_len)
5854 int font;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005855 char_u *name;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005856 int name_len;
5857{
5858 char *fontname;
5859
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005860 fontname = (char *)alloc(name_len + 1);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005861 if (fontname == NULL)
5862 return FALSE;
Bram Moolenaarce0842a2005-07-18 21:58:11 +00005863 vim_strncpy((char_u *)fontname, name, name_len);
Bram Moolenaar8299df92004-07-10 09:47:34 +00005864 prt_ps_mb_font.ps_fontname[font] = fontname;
5865
5866 return TRUE;
5867}
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005868#endif
Bram Moolenaar8299df92004-07-10 09:47:34 +00005869
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870/*
5871 * Get number of lines of text that fit on a page (excluding the header).
5872 */
5873 static int
5874prt_get_lpp()
5875{
5876 int lpp;
5877
5878 /*
5879 * Calculate offset to lower left corner of background rect based on actual
5880 * font height (based on its bounding box) and the line height, handling the
5881 * case where the font height can exceed the line height.
5882 */
5883 prt_bgcol_offset = (float)PRT_PS_FONT_TO_USER(prt_line_height,
Bram Moolenaar8299df92004-07-10 09:47:34 +00005884 prt_ps_font->bbox_min_y);
5885 if ((prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y) < 1000.0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005886 {
5887 prt_bgcol_offset -= (float)PRT_PS_FONT_TO_USER(prt_line_height,
Bram Moolenaar8299df92004-07-10 09:47:34 +00005888 (1000.0 - (prt_ps_font->bbox_max_y -
5889 prt_ps_font->bbox_min_y)) / 2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890 }
5891
5892 /* Get height for topmost line based on background rect offset. */
5893 prt_first_line_height = prt_line_height + prt_bgcol_offset;
5894
5895 /* Calculate lpp */
5896 lpp = (int)((prt_top_margin - prt_bottom_margin) / prt_line_height);
5897
5898 /* Adjust top margin if there is a header */
5899 prt_top_margin -= prt_line_height * prt_header_height();
5900
5901 return lpp - prt_header_height();
5902}
5903
Bram Moolenaar8299df92004-07-10 09:47:34 +00005904#ifdef FEAT_MBYTE
5905 static int
5906prt_match_encoding(p_encoding, p_cmap, pp_mbenc)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005907 char *p_encoding;
5908 struct prt_ps_mbfont_S *p_cmap;
5909 struct prt_ps_encoding_S **pp_mbenc;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005910{
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005911 int mbenc;
5912 int enc_len;
5913 struct prt_ps_encoding_S *p_mbenc;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005914
5915 *pp_mbenc = NULL;
5916 /* Look for recognised encoding */
5917 enc_len = STRLEN(p_encoding);
5918 p_mbenc = p_cmap->encodings;
5919 for (mbenc = 0; mbenc < p_cmap->num_encodings; mbenc++)
5920 {
5921 if (STRNICMP(p_mbenc->encoding, p_encoding, enc_len) == 0)
5922 {
5923 *pp_mbenc = p_mbenc;
5924 return TRUE;
5925 }
5926 p_mbenc++;
5927 }
5928 return FALSE;
5929}
5930
5931 static int
5932prt_match_charset(p_charset, p_cmap, pp_mbchar)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005933 char *p_charset;
5934 struct prt_ps_mbfont_S *p_cmap;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005935 struct prt_ps_charset_S **pp_mbchar;
5936{
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005937 int mbchar;
5938 int char_len;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005939 struct prt_ps_charset_S *p_mbchar;
5940
5941 /* Look for recognised character set, using default if one is not given */
5942 if (*p_charset == NUL)
5943 p_charset = p_cmap->defcs;
5944 char_len = STRLEN(p_charset);
5945 p_mbchar = p_cmap->charsets;
5946 for (mbchar = 0; mbchar < p_cmap->num_charsets; mbchar++)
5947 {
5948 if (STRNICMP(p_mbchar->charset, p_charset, char_len) == 0)
5949 {
5950 *pp_mbchar = p_mbchar;
5951 return TRUE;
5952 }
5953 p_mbchar++;
5954 }
5955 return FALSE;
5956}
5957#endif
5958
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959/*ARGSUSED*/
5960 int
5961mch_print_init(psettings, jobname, forceit)
5962 prt_settings_T *psettings;
5963 char_u *jobname;
5964 int forceit;
5965{
5966 int i;
5967 char *paper_name;
5968 int paper_strlen;
5969 int fontsize;
5970 char_u *p;
5971 double left;
5972 double right;
5973 double top;
5974 double bottom;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005975#ifdef FEAT_MBYTE
5976 int cmap;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005977 char_u *p_encoding;
5978 struct prt_ps_encoding_S *p_mbenc;
5979 struct prt_ps_encoding_S *p_mbenc_first;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005980 struct prt_ps_charset_S *p_mbchar;
Bram Moolenaar8299df92004-07-10 09:47:34 +00005981#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982
5983#if 0
5984 /*
5985 * TODO:
5986 * If "forceit" is false: pop up a dialog to select:
5987 * - printer name
5988 * - copies
5989 * - collated/uncollated
5990 * - duplex off/long side/short side
5991 * - paper size
5992 * - portrait/landscape
5993 * - font size
5994 *
5995 * If "forceit" is true: use the default printer and settings
5996 */
5997 if (forceit)
5998 s_pd.Flags |= PD_RETURNDEFAULT;
5999#endif
6000
6001 /*
Bram Moolenaar8299df92004-07-10 09:47:34 +00006002 * Set up font and encoding.
6003 */
6004#ifdef FEAT_MBYTE
6005 p_encoding = enc_skip(p_penc);
6006 if (*p_encoding == NUL)
6007 p_encoding = enc_skip(p_enc);
6008
6009 /* Look for recognised multi-byte coding, and if the charset is recognised.
6010 * This is to cope with the fact that various unicode encodings are
6011 * supported in more than one of CJK. */
6012 p_mbenc = NULL;
6013 p_mbenc_first = NULL;
6014 p_mbchar = NULL;
6015 for (cmap = 0; cmap < NUM_ELEMENTS(prt_ps_mbfonts); cmap++)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006016 if (prt_match_encoding((char *)p_encoding, &prt_ps_mbfonts[cmap],
6017 &p_mbenc))
Bram Moolenaar8299df92004-07-10 09:47:34 +00006018 {
6019 if (p_mbenc_first == NULL)
6020 p_mbenc_first = p_mbenc;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006021 if (prt_match_charset((char *)p_pmcs, &prt_ps_mbfonts[cmap],
6022 &p_mbchar))
Bram Moolenaar8299df92004-07-10 09:47:34 +00006023 break;
6024 }
6025
6026 /* Use first encoding matched if no charset matched */
6027 if (p_mbchar == NULL && p_mbenc_first != NULL)
6028 p_mbenc = p_mbenc_first;
6029
6030 prt_out_mbyte = (p_mbenc != NULL);
6031 if (prt_out_mbyte)
6032 {
6033 /* Build CMap name - will be same for all multi-byte fonts used */
Bram Moolenaarce0842a2005-07-18 21:58:11 +00006034 prt_cmap[0] = NUL;
Bram Moolenaar8299df92004-07-10 09:47:34 +00006035
6036 prt_custom_cmap = prt_out_mbyte && p_mbchar == NULL;
6037
6038 if (!prt_custom_cmap)
6039 {
6040 /* Check encoding and character set are compatible */
6041 if ((p_mbenc->needs_charset&p_mbchar->has_charset) == 0)
6042 {
6043 EMSG(_("E673: Incompatible multi-byte encoding and character set."));
6044 return FALSE;
6045 }
6046
6047 /* Add charset name if not empty */
6048 if (p_mbchar->cmap_charset != NULL)
6049 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00006050 vim_strncpy((char_u *)prt_cmap,
6051 (char_u *)p_mbchar->cmap_charset, sizeof(prt_cmap) - 3);
Bram Moolenaar8299df92004-07-10 09:47:34 +00006052 STRCAT(prt_cmap, "-");
6053 }
6054 }
6055 else
6056 {
6057 /* Add custom CMap character set name */
Bram Moolenaarce0842a2005-07-18 21:58:11 +00006058 if (*p_pmcs == NUL)
Bram Moolenaar8299df92004-07-10 09:47:34 +00006059 {
6060 EMSG(_("E674: printmbcharset cannot be empty with multi-byte encoding."));
6061 return FALSE;
6062 }
Bram Moolenaarce0842a2005-07-18 21:58:11 +00006063 vim_strncpy((char_u *)prt_cmap, p_pmcs, sizeof(prt_cmap) - 3);
Bram Moolenaar8299df92004-07-10 09:47:34 +00006064 STRCAT(prt_cmap, "-");
6065 }
6066
6067 /* CMap name ends with (optional) encoding name and -H for horizontal */
Bram Moolenaarce0842a2005-07-18 21:58:11 +00006068 if (p_mbenc->cmap_encoding != NULL && STRLEN(prt_cmap)
6069 + STRLEN(p_mbenc->cmap_encoding) + 3 < sizeof(prt_cmap))
Bram Moolenaar8299df92004-07-10 09:47:34 +00006070 {
6071 STRCAT(prt_cmap, p_mbenc->cmap_encoding);
6072 STRCAT(prt_cmap, "-");
6073 }
6074 STRCAT(prt_cmap, "H");
6075
6076 if (!mbfont_opts[OPT_MBFONT_REGULAR].present)
6077 {
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00006078 EMSG(_("E675: No default font specified for multi-byte printing."));
Bram Moolenaar8299df92004-07-10 09:47:34 +00006079 return FALSE;
6080 }
6081
6082 /* Derive CID font names with fallbacks if not defined */
6083 if (!prt_build_cid_fontname(PRT_PS_FONT_ROMAN,
6084 mbfont_opts[OPT_MBFONT_REGULAR].string,
6085 mbfont_opts[OPT_MBFONT_REGULAR].strlen))
6086 return FALSE;
6087 if (mbfont_opts[OPT_MBFONT_BOLD].present)
6088 if (!prt_build_cid_fontname(PRT_PS_FONT_BOLD,
6089 mbfont_opts[OPT_MBFONT_BOLD].string,
6090 mbfont_opts[OPT_MBFONT_BOLD].strlen))
6091 return FALSE;
6092 if (mbfont_opts[OPT_MBFONT_OBLIQUE].present)
6093 if (!prt_build_cid_fontname(PRT_PS_FONT_OBLIQUE,
6094 mbfont_opts[OPT_MBFONT_OBLIQUE].string,
6095 mbfont_opts[OPT_MBFONT_OBLIQUE].strlen))
6096 return FALSE;
6097 if (mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].present)
6098 if (!prt_build_cid_fontname(PRT_PS_FONT_BOLDOBLIQUE,
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006099 mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].string,
6100 mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].strlen))
Bram Moolenaar8299df92004-07-10 09:47:34 +00006101 return FALSE;
6102
6103 /* Check if need to use Courier for ASCII code range, and if so pick up
6104 * the encoding to use */
6105 prt_use_courier = mbfont_opts[OPT_MBFONT_USECOURIER].present &&
6106 (TOLOWER_ASC(mbfont_opts[OPT_MBFONT_USECOURIER].string[0]) == 'y');
6107 if (prt_use_courier)
6108 {
6109 /* Use national ASCII variant unless ASCII wanted */
6110 if (mbfont_opts[OPT_MBFONT_ASCII].present &&
6111 (TOLOWER_ASC(mbfont_opts[OPT_MBFONT_ASCII].string[0]) == 'y'))
6112 prt_ascii_encoding = "ascii";
6113 else
6114 prt_ascii_encoding = prt_ps_mbfonts[cmap].ascii_enc;
6115 }
6116
6117 prt_ps_font = &prt_ps_mb_font;
6118 }
6119 else
6120#endif
6121 {
6122#ifdef FEAT_MBYTE
6123 prt_use_courier = FALSE;
6124#endif
6125 prt_ps_font = &prt_ps_courier_font;
6126 }
6127
6128 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 * Find the size of the paper and set the margins.
6130 */
6131 prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present
6132 || TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) == 'y');
6133 if (printer_opts[OPT_PRINT_PAPER].present)
6134 {
6135 paper_name = (char *)printer_opts[OPT_PRINT_PAPER].string;
6136 paper_strlen = printer_opts[OPT_PRINT_PAPER].strlen;
6137 }
6138 else
6139 {
6140 paper_name = "A4";
6141 paper_strlen = 2;
6142 }
6143 for (i = 0; i < PRT_MEDIASIZE_LEN; ++i)
6144 if (STRLEN(prt_mediasize[i].name) == (unsigned)paper_strlen
6145 && STRNICMP(prt_mediasize[i].name, paper_name,
6146 paper_strlen) == 0)
6147 break;
6148 if (i == PRT_MEDIASIZE_LEN)
6149 i = 0;
6150 prt_media = i;
6151
6152 /*
6153 * Set PS pagesize based on media dimensions and print orientation.
6154 * Note: Media and page sizes have defined meanings in PostScript and should
6155 * be kept distinct. Media is the paper (or transparency, or ...) that is
6156 * printed on, whereas the page size is the area that the PostScript
6157 * interpreter renders into.
6158 */
6159 if (prt_portrait)
6160 {
6161 prt_page_width = prt_mediasize[i].width;
6162 prt_page_height = prt_mediasize[i].height;
6163 }
6164 else
6165 {
6166 prt_page_width = prt_mediasize[i].height;
6167 prt_page_height = prt_mediasize[i].width;
6168 }
6169
6170 /*
6171 * Set PS page margins based on the PS pagesize, not the mediasize - this
6172 * needs to be done before the cpl and lpp are calculated.
6173 */
6174 prt_page_margins(prt_page_width, prt_page_height, &left, &right, &top,
6175 &bottom);
6176 prt_left_margin = (float)left;
6177 prt_right_margin = (float)right;
6178 prt_top_margin = (float)top;
6179 prt_bottom_margin = (float)bottom;
6180
6181 /*
6182 * Set up the font size.
6183 */
6184 fontsize = PRT_PS_DEFAULT_FONTSIZE;
6185 for (p = p_pfn; (p = vim_strchr(p, ':')) != NULL; ++p)
6186 if (p[1] == 'h' && VIM_ISDIGIT(p[2]))
6187 fontsize = atoi((char *)p + 2);
6188 prt_font_metrics(fontsize);
6189
6190 /*
6191 * Return the number of characters per line, and lines per page for the
6192 * generic print code.
6193 */
6194 psettings->chars_per_line = prt_get_cpl();
6195 psettings->lines_per_page = prt_get_lpp();
6196
6197 /* Catch margin settings that leave no space for output! */
6198 if (psettings->chars_per_line <= 0 || psettings->lines_per_page <= 0)
6199 return FAIL;
6200
6201 /*
6202 * Sort out the number of copies to be printed. PS by default will do
6203 * uncollated copies for you, so once we know how many uncollated copies are
6204 * wanted cache it away and lie to the generic code that we only want one
6205 * uncollated copy.
6206 */
6207 psettings->n_collated_copies = 1;
6208 psettings->n_uncollated_copies = 1;
6209 prt_num_copies = 1;
6210 prt_collate = (!printer_opts[OPT_PRINT_COLLATE].present
6211 || TOLOWER_ASC(printer_opts[OPT_PRINT_COLLATE].string[0]) == 'y');
6212 if (prt_collate)
6213 {
6214 /* TODO: Get number of collated copies wanted. */
6215 psettings->n_collated_copies = 1;
6216 }
6217 else
6218 {
6219 /* TODO: Get number of uncollated copies wanted and update the cached
6220 * count.
6221 */
6222 prt_num_copies = 1;
6223 }
6224
6225 psettings->jobname = jobname;
6226
6227 /*
6228 * Set up printer duplex and tumble based on Duplex option setting - default
6229 * is long sided duplex printing (i.e. no tumble).
6230 */
6231 prt_duplex = TRUE;
6232 prt_tumble = FALSE;
6233 psettings->duplex = 1;
6234 if (printer_opts[OPT_PRINT_DUPLEX].present)
6235 {
6236 if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "off", 3) == 0)
6237 {
6238 prt_duplex = FALSE;
6239 psettings->duplex = 0;
6240 }
6241 else if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "short", 5)
6242 == 0)
6243 prt_tumble = TRUE;
6244 }
6245
6246 /* For now user abort not supported */
6247 psettings->user_abort = 0;
6248
6249 /* If the user didn't specify a file name, use a temp file. */
6250 if (psettings->outfile == NULL)
6251 {
6252 prt_ps_file_name = vim_tempname('p');
6253 if (prt_ps_file_name == NULL)
6254 {
6255 EMSG(_(e_notmp));
6256 return FAIL;
6257 }
6258 prt_ps_fd = mch_fopen((char *)prt_ps_file_name, WRITEBIN);
6259 }
6260 else
6261 {
6262 p = expand_env_save(psettings->outfile);
6263 if (p != NULL)
6264 {
6265 prt_ps_fd = mch_fopen((char *)p, WRITEBIN);
6266 vim_free(p);
6267 }
6268 }
6269 if (prt_ps_fd == NULL)
6270 {
6271 EMSG(_("E324: Can't open PostScript output file"));
6272 mch_print_cleanup();
6273 return FAIL;
6274 }
6275
Bram Moolenaar8299df92004-07-10 09:47:34 +00006276 prt_bufsiz = psettings->chars_per_line;
6277#ifdef FEAT_MBYTE
6278 if (prt_out_mbyte)
6279 prt_bufsiz *= 2;
6280#endif
6281 ga_init2(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282
6283 prt_page_num = 0;
6284
6285 prt_attribute_change = FALSE;
6286 prt_need_moveto = FALSE;
6287 prt_need_font = FALSE;
6288 prt_need_fgcol = FALSE;
6289 prt_need_bgcol = FALSE;
6290 prt_need_underline = FALSE;
6291
6292 prt_file_error = FALSE;
6293
6294 return OK;
6295}
6296
6297 static int
6298prt_add_resource(resource)
6299 struct prt_ps_resource_S *resource;
6300{
6301 FILE* fd_resource;
6302 char_u resource_buffer[512];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 size_t bytes_read;
6304
6305 fd_resource = mch_fopen((char *)resource->filename, READBIN);
6306 if (fd_resource == NULL)
6307 {
6308 EMSG2(_("E456: Can't open file \"%s\""), resource->filename);
6309 return FALSE;
6310 }
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006311 prt_dsc_resources("BeginResource", prt_resource_types[resource->type],
6312 (char *)resource->title);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313
6314 prt_dsc_textline("BeginDocument", (char *)resource->filename);
6315
6316 for (;;)
6317 {
6318 bytes_read = fread((char *)resource_buffer, sizeof(char_u),
6319 sizeof(resource_buffer), fd_resource);
6320 if (ferror(fd_resource))
6321 {
6322 EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
6323 resource->filename);
6324 fclose(fd_resource);
6325 return FALSE;
6326 }
6327 if (bytes_read == 0)
6328 break;
6329 prt_write_file_raw_len(resource_buffer, bytes_read);
6330 if (prt_file_error)
6331 {
6332 fclose(fd_resource);
6333 return FALSE;
6334 }
6335 }
6336 fclose(fd_resource);
6337
6338 prt_dsc_noarg("EndDocument");
6339
6340 prt_dsc_noarg("EndResource");
6341
6342 return TRUE;
6343}
6344
6345 int
6346mch_print_begin(psettings)
6347 prt_settings_T *psettings;
6348{
6349 time_t now;
6350 int bbox[4];
6351 char *p_time;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 double left;
6353 double right;
6354 double top;
6355 double bottom;
6356 struct prt_ps_resource_S res_prolog;
6357 struct prt_ps_resource_S res_encoding;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006358 char buffer[256];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 char_u *p_encoding;
6360#ifdef FEAT_MBYTE
Bram Moolenaar8299df92004-07-10 09:47:34 +00006361 struct prt_ps_resource_S res_cidfont;
6362 struct prt_ps_resource_S res_cmap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363#endif
6364
6365 /*
6366 * PS DSC Header comments - no PS code!
6367 */
6368 prt_dsc_start();
6369 prt_dsc_textline("Title", (char *)psettings->jobname);
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006370 if (!get_user_name((char_u *)buffer, 256))
Bram Moolenaar8299df92004-07-10 09:47:34 +00006371 STRCPY(buffer, "Unknown");
6372 prt_dsc_textline("For", buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 prt_dsc_textline("Creator", VIM_VERSION_LONG);
6374 /* Note: to ensure Clean8bit I don't think we can use LC_TIME */
6375 now = time(NULL);
6376 p_time = ctime(&now);
6377 /* Note: ctime() adds a \n so we have to remove it :-( */
6378 *(vim_strchr((char_u *)p_time, '\n')) = '\0';
6379 prt_dsc_textline("CreationDate", p_time);
6380 prt_dsc_textline("DocumentData", "Clean8Bit");
6381 prt_dsc_textline("Orientation", "Portrait");
6382 prt_dsc_atend("Pages");
6383 prt_dsc_textline("PageOrder", "Ascend");
6384 /* The bbox does not change with orientation - it is always in the default
6385 * user coordinate system! We have to recalculate right and bottom
6386 * coordinates based on the font metrics for the bbox to be accurate. */
6387 prt_page_margins(prt_mediasize[prt_media].width,
6388 prt_mediasize[prt_media].height,
6389 &left, &right, &top, &bottom);
6390 bbox[0] = (int)left;
6391 if (prt_portrait)
6392 {
6393 /* In portrait printing the fixed point is the top left corner so we
6394 * derive the bbox from that point. We have the expected cpl chars
6395 * across the media and lpp lines down the media.
6396 */
6397 bbox[1] = (int)(top - (psettings->lines_per_page + prt_header_height())
6398 * prt_line_height);
6399 bbox[2] = (int)(left + psettings->chars_per_line * prt_char_width
6400 + 0.5);
6401 bbox[3] = (int)(top + 0.5);
6402 }
6403 else
6404 {
6405 /* In landscape printing the fixed point is the bottom left corner so we
6406 * derive the bbox from that point. We have lpp chars across the media
6407 * and cpl lines up the media.
6408 */
6409 bbox[1] = (int)bottom;
6410 bbox[2] = (int)(left + ((psettings->lines_per_page
6411 + prt_header_height()) * prt_line_height) + 0.5);
6412 bbox[3] = (int)(bottom + psettings->chars_per_line * prt_char_width
6413 + 0.5);
6414 }
6415 prt_dsc_ints("BoundingBox", 4, bbox);
6416 /* The media width and height does not change with landscape printing! */
6417 prt_dsc_docmedia(prt_mediasize[prt_media].name,
6418 prt_mediasize[prt_media].width,
6419 prt_mediasize[prt_media].height,
6420 (double)0, NULL, NULL);
Bram Moolenaar8299df92004-07-10 09:47:34 +00006421 /* Define fonts needed */
6422#ifdef FEAT_MBYTE
6423 if (!prt_out_mbyte || prt_use_courier)
6424#endif
6425 prt_dsc_font_resource("DocumentNeededResources", &prt_ps_courier_font);
6426#ifdef FEAT_MBYTE
6427 if (prt_out_mbyte)
6428 {
6429 prt_dsc_font_resource((prt_use_courier ? NULL
6430 : "DocumentNeededResources"), &prt_ps_mb_font);
6431 if (!prt_custom_cmap)
6432 prt_dsc_resources(NULL, "cmap", prt_cmap);
6433 }
6434#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435
Bram Moolenaar8299df92004-07-10 09:47:34 +00006436 /* Search for external resources VIM supplies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437 if (!prt_find_resource("prolog", &res_prolog))
6438 {
6439 EMSG(_("E456: Can't find PostScript resource file \"prolog.ps\""));
6440 return FALSE;
6441 }
6442 if (!prt_open_resource(&res_prolog))
6443 return FALSE;
6444 if (!prt_check_resource(&res_prolog, PRT_PROLOG_VERSION))
6445 return FALSE;
Bram Moolenaar8299df92004-07-10 09:47:34 +00006446#ifdef FEAT_MBYTE
6447 if (prt_out_mbyte)
6448 {
6449 /* Look for required version of multi-byte printing procset */
6450 if (!prt_find_resource("cidfont", &res_cidfont))
6451 {
6452 EMSG(_("E456: Can't find PostScript resource file \"cidfont.ps\""));
6453 return FALSE;
6454 }
6455 if (!prt_open_resource(&res_cidfont))
6456 return FALSE;
6457 if (!prt_check_resource(&res_cidfont, PRT_CID_PROLOG_VERSION))
6458 return FALSE;
6459 }
6460#endif
6461
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 /* Find an encoding to use for printing.
6463 * Check 'printencoding'. If not set or not found, then use 'encoding'. If
6464 * that cannot be found then default to "latin1".
6465 * Note: VIM specific encoding header is always skipped.
6466 */
6467#ifdef FEAT_MBYTE
Bram Moolenaar8299df92004-07-10 09:47:34 +00006468 if (!prt_out_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470#endif
Bram Moolenaar8299df92004-07-10 09:47:34 +00006471 p_encoding = enc_skip(p_penc);
6472 if (*p_encoding == NUL
6473 || !prt_find_resource((char *)p_encoding, &res_encoding))
6474 {
6475 /* 'printencoding' not set or not supported - find alternate */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476#ifdef FEAT_MBYTE
Bram Moolenaar8299df92004-07-10 09:47:34 +00006477 int props;
6478
6479 p_encoding = enc_skip(p_enc);
6480 props = enc_canon_props(p_encoding);
6481 if (!(props & ENC_8BIT)
6482 || !prt_find_resource((char *)p_encoding, &res_encoding))
6483 /* 8-bit 'encoding' is not supported */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484#endif
Bram Moolenaar8299df92004-07-10 09:47:34 +00006485 {
6486 /* Use latin1 as default printing encoding */
6487 p_encoding = (char_u *)"latin1";
6488 if (!prt_find_resource((char *)p_encoding, &res_encoding))
6489 {
6490 EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
6491 p_encoding);
6492 return FALSE;
6493 }
6494 }
6495 }
6496 if (!prt_open_resource(&res_encoding))
6497 return FALSE;
6498 /* For the moment there are no checks on encoding resource files to
6499 * perform */
6500#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 }
Bram Moolenaar8299df92004-07-10 09:47:34 +00006502 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00006504 p_encoding = enc_skip(p_penc);
6505 if (*p_encoding == NUL)
6506 p_encoding = enc_skip(p_enc);
6507 if (prt_use_courier)
6508 {
6509 /* Include ASCII range encoding vector */
6510 if (!prt_find_resource(prt_ascii_encoding, &res_encoding))
6511 {
6512 EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006513 prt_ascii_encoding);
Bram Moolenaar8299df92004-07-10 09:47:34 +00006514 return FALSE;
6515 }
6516 if (!prt_open_resource(&res_encoding))
6517 return FALSE;
6518 /* For the moment there are no checks on encoding resource files to
6519 * perform */
6520 }
6521 }
6522
6523 prt_conv.vc_type = CONV_NONE;
6524 if (!(enc_canon_props(p_enc) & enc_canon_props(p_encoding) & ENC_8BIT)) {
6525 /* Set up encoding conversion if required */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 if (FAIL == convert_setup(&prt_conv, p_enc, p_encoding))
6527 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00006528 EMSG2(_("E620: Unable to convert to print encoding \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529 p_encoding);
6530 return FALSE;
6531 }
6532 prt_do_conv = TRUE;
6533 }
Bram Moolenaar8299df92004-07-10 09:47:34 +00006534 prt_do_conv = prt_conv.vc_type != CONV_NONE;
6535
6536 if (prt_out_mbyte && prt_custom_cmap)
6537 {
6538 /* Find user supplied CMap */
6539 if (!prt_find_resource(prt_cmap, &res_cmap))
6540 {
6541 EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006542 prt_cmap);
Bram Moolenaar8299df92004-07-10 09:47:34 +00006543 return FALSE;
6544 }
6545 if (!prt_open_resource(&res_cmap))
6546 return FALSE;
6547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548#endif
6549
6550 /* List resources supplied */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 STRCPY(buffer, res_prolog.title);
6552 STRCAT(buffer, " ");
6553 STRCAT(buffer, res_prolog.version);
Bram Moolenaar8299df92004-07-10 09:47:34 +00006554 prt_dsc_resources("DocumentSuppliedResources", "procset", buffer);
6555#ifdef FEAT_MBYTE
6556 if (prt_out_mbyte)
6557 {
6558 STRCPY(buffer, res_cidfont.title);
6559 STRCAT(buffer, " ");
6560 STRCAT(buffer, res_cidfont.version);
6561 prt_dsc_resources(NULL, "procset", buffer);
6562
6563 if (prt_custom_cmap)
6564 {
6565 STRCPY(buffer, res_cmap.title);
6566 STRCAT(buffer, " ");
6567 STRCAT(buffer, res_cmap.version);
6568 prt_dsc_resources(NULL, "cmap", buffer);
6569 }
6570 }
6571 if (!prt_out_mbyte || prt_use_courier)
6572#endif
6573 {
6574 STRCPY(buffer, res_encoding.title);
6575 STRCAT(buffer, " ");
6576 STRCAT(buffer, res_encoding.version);
6577 prt_dsc_resources(NULL, "encoding", buffer);
6578 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 prt_dsc_requirements(prt_duplex, prt_tumble, prt_collate,
6580#ifdef FEAT_SYN_HL
6581 psettings->do_syntax
6582#else
6583 0
6584#endif
6585 , prt_num_copies);
6586 prt_dsc_noarg("EndComments");
6587
6588 /*
6589 * PS Document page defaults
6590 */
6591 prt_dsc_noarg("BeginDefaults");
6592
6593 /* List font resources most likely common to all pages */
Bram Moolenaar8299df92004-07-10 09:47:34 +00006594#ifdef FEAT_MBYTE
6595 if (!prt_out_mbyte || prt_use_courier)
6596#endif
6597 prt_dsc_font_resource("PageResources", &prt_ps_courier_font);
6598#ifdef FEAT_MBYTE
6599 if (prt_out_mbyte)
6600 {
6601 prt_dsc_font_resource((prt_use_courier ? NULL : "PageResources"),
6602 &prt_ps_mb_font);
6603 if (!prt_custom_cmap)
6604 prt_dsc_resources(NULL, "cmap", prt_cmap);
6605 }
6606#endif
6607
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 /* Paper will be used for all pages */
6609 prt_dsc_textline("PageMedia", prt_mediasize[prt_media].name);
6610
6611 prt_dsc_noarg("EndDefaults");
6612
6613 /*
6614 * PS Document prolog inclusion - all required procsets.
6615 */
6616 prt_dsc_noarg("BeginProlog");
6617
Bram Moolenaar8299df92004-07-10 09:47:34 +00006618 /* Add required procsets - NOTE: order is important! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 if (!prt_add_resource(&res_prolog))
6620 return FALSE;
Bram Moolenaar8299df92004-07-10 09:47:34 +00006621#ifdef FEAT_MBYTE
6622 if (prt_out_mbyte)
6623 {
6624 /* Add CID font procset, and any user supplied CMap */
6625 if (!prt_add_resource(&res_cidfont))
6626 return FALSE;
6627 if (prt_custom_cmap && !prt_add_resource(&res_cmap))
6628 return FALSE;
6629 }
6630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631
Bram Moolenaar8299df92004-07-10 09:47:34 +00006632#ifdef FEAT_MBYTE
6633 if (!prt_out_mbyte || prt_use_courier)
6634#endif
6635 /* There will be only one Roman font encoding to be included in the PS
6636 * file. */
6637 if (!prt_add_resource(&res_encoding))
6638 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639
6640 prt_dsc_noarg("EndProlog");
6641
6642 /*
6643 * PS Document setup - must appear after the prolog
6644 */
6645 prt_dsc_noarg("BeginSetup");
6646
6647 /* Device setup - page size and number of uncollated copies */
6648 prt_write_int((int)prt_mediasize[prt_media].width);
6649 prt_write_int((int)prt_mediasize[prt_media].height);
6650 prt_write_int(0);
6651 prt_write_string("sps\n");
6652 prt_write_int(prt_num_copies);
6653 prt_write_string("nc\n");
6654 prt_write_boolean(prt_duplex);
6655 prt_write_boolean(prt_tumble);
6656 prt_write_string("dt\n");
6657 prt_write_boolean(prt_collate);
6658 prt_write_string("c\n");
6659
6660 /* Font resource inclusion and definition */
Bram Moolenaar8299df92004-07-10 09:47:34 +00006661#ifdef FEAT_MBYTE
6662 if (!prt_out_mbyte || prt_use_courier)
6663 {
6664 /* When using Courier for ASCII range when printing multi-byte, need to
6665 * pick up ASCII encoding to use with it. */
6666 if (prt_use_courier)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006667 p_encoding = (char_u *)prt_ascii_encoding;
Bram Moolenaar8299df92004-07-10 09:47:34 +00006668#endif
6669 prt_dsc_resources("IncludeResource", "font",
6670 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]);
6671 prt_def_font("F0", (char *)p_encoding, (int)prt_line_height,
6672 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]);
6673 prt_dsc_resources("IncludeResource", "font",
6674 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]);
6675 prt_def_font("F1", (char *)p_encoding, (int)prt_line_height,
6676 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]);
6677 prt_dsc_resources("IncludeResource", "font",
6678 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
6679 prt_def_font("F2", (char *)p_encoding, (int)prt_line_height,
6680 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
6681 prt_dsc_resources("IncludeResource", "font",
6682 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
6683 prt_def_font("F3", (char *)p_encoding, (int)prt_line_height,
6684 prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
6685#ifdef FEAT_MBYTE
6686 }
6687 if (prt_out_mbyte)
6688 {
6689 /* Define the CID fonts to be used in the job. Typically CJKV fonts do
6690 * not have an italic form being a western style, so where no font is
6691 * defined for these faces VIM falls back to an existing face.
6692 * Note: if using Courier for the ASCII range then the printout will
6693 * have bold/italic/bolditalic regardless of the setting of printmbfont.
6694 */
6695 prt_dsc_resources("IncludeResource", "font",
6696 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]);
6697 if (!prt_custom_cmap)
6698 prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
6699 prt_def_cidfont("CF0", (int)prt_line_height,
6700 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]);
6701
6702 if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD] != NULL)
6703 {
6704 prt_dsc_resources("IncludeResource", "font",
6705 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]);
6706 if (!prt_custom_cmap)
6707 prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
6708 prt_def_cidfont("CF1", (int)prt_line_height,
6709 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]);
6710 }
6711 else
6712 /* Use ROMAN for BOLD */
6713 prt_dup_cidfont("CF0", "CF1");
6714
6715 if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE] != NULL)
6716 {
6717 prt_dsc_resources("IncludeResource", "font",
6718 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
6719 if (!prt_custom_cmap)
6720 prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
6721 prt_def_cidfont("CF2", (int)prt_line_height,
6722 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
6723 }
6724 else
6725 /* Use ROMAN for OBLIQUE */
6726 prt_dup_cidfont("CF0", "CF2");
6727
6728 if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE] != NULL)
6729 {
6730 prt_dsc_resources("IncludeResource", "font",
6731 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
6732 if (!prt_custom_cmap)
6733 prt_dsc_resources("IncludeResource", "cmap", prt_cmap);
6734 prt_def_cidfont("CF3", (int)prt_line_height,
6735 prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
6736 }
6737 else
6738 /* Use BOLD for BOLDOBLIQUE */
6739 prt_dup_cidfont("CF1", "CF3");
6740 }
6741#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742
6743 /* Misc constant vars used for underlining and background rects */
6744 prt_def_var("UO", PRT_PS_FONT_TO_USER(prt_line_height,
Bram Moolenaar8299df92004-07-10 09:47:34 +00006745 prt_ps_font->uline_offset), 2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 prt_def_var("UW", PRT_PS_FONT_TO_USER(prt_line_height,
Bram Moolenaar8299df92004-07-10 09:47:34 +00006747 prt_ps_font->uline_width), 2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 prt_def_var("BO", prt_bgcol_offset, 2);
6749
6750 prt_dsc_noarg("EndSetup");
6751
6752 /* Fail if any problems writing out to the PS file */
6753 return !prt_file_error;
6754}
6755
6756 void
6757mch_print_end(psettings)
6758 prt_settings_T *psettings;
6759{
6760 prt_dsc_noarg("Trailer");
6761
6762 /*
6763 * Output any info we don't know in toto until we finish
6764 */
6765 prt_dsc_ints("Pages", 1, &prt_page_num);
6766
6767 prt_dsc_noarg("EOF");
6768
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006769 /* Write CTRL-D to close serial communication link if used.
6770 * NOTHING MUST BE WRITTEN AFTER THIS! */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00006771 prt_write_file((char_u *)IF_EB("\004", "\067"));
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006772
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 if (!prt_file_error && psettings->outfile == NULL
6774 && !got_int && !psettings->user_abort)
6775 {
6776 /* Close the file first. */
6777 if (prt_ps_fd != NULL)
6778 {
6779 fclose(prt_ps_fd);
6780 prt_ps_fd = NULL;
6781 }
6782 prt_message((char_u *)_("Sending to printer..."));
6783
6784 /* Not printing to a file: use 'printexpr' to print the file. */
6785 if (eval_printexpr(prt_ps_file_name, psettings->arguments) == FAIL)
6786 EMSG(_("E365: Failed to print PostScript file"));
6787 else
6788 prt_message((char_u *)_("Print job sent."));
6789 }
6790
6791 mch_print_cleanup();
6792}
6793
6794 int
6795mch_print_end_page()
6796{
6797 prt_flush_buffer();
6798
6799 prt_write_string("re sp\n");
6800
6801 prt_dsc_noarg("PageTrailer");
6802
6803 return !prt_file_error;
6804}
6805
6806/*ARGSUSED*/
6807 int
6808mch_print_begin_page(str)
6809 char_u *str;
6810{
6811 int page_num[2];
6812
6813 prt_page_num++;
6814
6815 page_num[0] = page_num[1] = prt_page_num;
6816 prt_dsc_ints("Page", 2, page_num);
6817
6818 prt_dsc_noarg("BeginPageSetup");
6819
Bram Moolenaar8299df92004-07-10 09:47:34 +00006820 prt_write_string("sv\n0 g\n");
6821#ifdef FEAT_MBYTE
6822 prt_in_ascii = !prt_out_mbyte;
6823 if (prt_out_mbyte)
6824 prt_write_string("CF0 sf\n");
6825 else
6826#endif
6827 prt_write_string("F0 sf\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 prt_fgcol = PRCOLOR_BLACK;
6829 prt_bgcol = PRCOLOR_WHITE;
6830 prt_font = PRT_PS_FONT_ROMAN;
6831
6832 /* Set up page transformation for landscape printing. */
6833 if (!prt_portrait)
6834 {
6835 prt_write_int(-((int)prt_mediasize[prt_media].width));
6836 prt_write_string("sl\n");
6837 }
6838
6839 prt_dsc_noarg("EndPageSetup");
6840
6841 /* We have reset the font attributes, force setting them again. */
6842 curr_bg = (long_u)0xffffffff;
6843 curr_fg = (long_u)0xffffffff;
6844 curr_bold = MAYBE;
6845
6846 return !prt_file_error;
6847}
6848
6849 int
6850mch_print_blank_page()
6851{
6852 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
6853}
6854
6855static float prt_pos_x = 0;
6856static float prt_pos_y = 0;
6857
6858 void
6859mch_print_start_line(margin, page_line)
6860 int margin;
6861 int page_line;
6862{
6863 prt_pos_x = prt_left_margin;
6864 if (margin)
6865 prt_pos_x -= prt_number_width;
6866
6867 prt_pos_y = prt_top_margin - prt_first_line_height -
6868 page_line * prt_line_height;
6869
6870 prt_attribute_change = TRUE;
6871 prt_need_moveto = TRUE;
Bram Moolenaar8299df92004-07-10 09:47:34 +00006872#ifdef FEAT_MBYTE
6873 prt_half_width = FALSE;
6874#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875}
6876
6877/*ARGSUSED*/
6878 int
6879mch_print_text_out(p, len)
6880 char_u *p;
6881 int len;
6882{
6883 int need_break;
6884 char_u ch;
6885 char_u ch_buff[8];
Bram Moolenaar8299df92004-07-10 09:47:34 +00006886 float char_width;
6887 float next_pos;
6888#ifdef FEAT_MBYTE
6889 int in_ascii;
6890 int half_width;
6891#endif
6892
6893 char_width = prt_char_width;
6894
6895#ifdef FEAT_MBYTE
6896 /* Ideally VIM would create a rearranged CID font to combine a Roman and
6897 * CJKV font to do what VIM is doing here - use a Roman font for characters
6898 * in the ASCII range, and the origingal CID font for everything else.
6899 * The problem is that GhostScript still (as of 8.13) does not support
6900 * rearranged fonts even though they have been documented by Adobe for 7
6901 * years! If they ever do, a lot of this code will disappear.
6902 */
6903 if (prt_use_courier)
6904 {
6905 in_ascii = (len == 1 && *p < 0x80);
6906 if (prt_in_ascii)
6907 {
6908 if (!in_ascii)
6909 {
6910 /* No longer in ASCII range - need to switch font */
6911 prt_in_ascii = FALSE;
6912 prt_need_font = TRUE;
6913 prt_attribute_change = TRUE;
6914 }
6915 }
6916 else if (in_ascii)
6917 {
6918 /* Now in ASCII range - need to switch font */
6919 prt_in_ascii = TRUE;
6920 prt_need_font = TRUE;
6921 prt_attribute_change = TRUE;
6922 }
6923 }
6924 if (prt_out_mbyte)
6925 {
6926 half_width = ((*mb_ptr2cells)(p) == 1);
6927 if (half_width)
6928 char_width /= 2;
6929 if (prt_half_width)
6930 {
6931 if (!half_width)
6932 {
6933 prt_half_width = FALSE;
6934 prt_pos_x += prt_char_width/4;
6935 prt_need_moveto = TRUE;
6936 prt_attribute_change = TRUE;
6937 }
6938 }
6939 else if (half_width)
6940 {
6941 prt_half_width = TRUE;
6942 prt_pos_x += prt_char_width/4;
6943 prt_need_moveto = TRUE;
6944 prt_attribute_change = TRUE;
6945 }
6946 }
6947#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948
6949 /* Output any required changes to the graphics state, after flushing any
6950 * text buffered so far.
6951 */
6952 if (prt_attribute_change)
6953 {
6954 prt_flush_buffer();
6955 /* Reset count of number of chars that will be printed */
Bram Moolenaar8299df92004-07-10 09:47:34 +00006956 prt_text_run = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957
6958 if (prt_need_moveto)
6959 {
6960 prt_pos_x_moveto = prt_pos_x;
6961 prt_pos_y_moveto = prt_pos_y;
6962 prt_do_moveto = TRUE;
6963
6964 prt_need_moveto = FALSE;
6965 }
6966 if (prt_need_font)
6967 {
Bram Moolenaar8299df92004-07-10 09:47:34 +00006968#ifdef FEAT_MBYTE
6969 if (!prt_in_ascii)
6970 prt_write_string("CF");
6971 else
6972#endif
6973 prt_write_string("F");
6974 prt_write_int(prt_font);
6975 prt_write_string("sf\n");
6976 prt_need_font = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 }
6978 if (prt_need_fgcol)
6979 {
6980 int r, g, b;
6981 r = ((unsigned)prt_fgcol & 0xff0000) >> 16;
6982 g = ((unsigned)prt_fgcol & 0xff00) >> 8;
6983 b = prt_fgcol & 0xff;
6984
6985 prt_write_real(r / 255.0, 3);
6986 if (r == g && g == b)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987 prt_write_string("g\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988 else
6989 {
6990 prt_write_real(g / 255.0, 3);
6991 prt_write_real(b / 255.0, 3);
6992 prt_write_string("r\n");
6993 }
6994 prt_need_fgcol = FALSE;
6995 }
6996
6997 if (prt_bgcol != PRCOLOR_WHITE)
6998 {
6999 prt_new_bgcol = prt_bgcol;
7000 if (prt_need_bgcol)
7001 prt_do_bgcol = TRUE;
7002 }
7003 else
7004 prt_do_bgcol = FALSE;
7005 prt_need_bgcol = FALSE;
7006
7007 if (prt_need_underline)
7008 prt_do_underline = prt_underline;
7009 prt_need_underline = FALSE;
7010
7011 prt_attribute_change = FALSE;
7012 }
7013
7014#ifdef FEAT_MBYTE
7015 if (prt_do_conv)
7016 {
7017 /* Convert from multi-byte to 8-bit encoding */
7018 p = string_convert(&prt_conv, p, &len);
7019 if (p == NULL)
7020 p = (char_u *)"";
7021 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022
Bram Moolenaar8299df92004-07-10 09:47:34 +00007023 if (prt_out_mbyte)
7024 {
7025 /* Multi-byte character strings are represented more efficiently as hex
7026 * strings when outputting clean 8 bit PS.
7027 */
7028 do
7029 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00007030 ch = prt_hexchar[(unsigned)(*p) >> 4];
Bram Moolenaar8299df92004-07-10 09:47:34 +00007031 ga_append(&prt_ps_buffer, ch);
7032 ch = prt_hexchar[(*p) & 0xf];
7033 ga_append(&prt_ps_buffer, ch);
7034 p++;
7035 }
7036 while (--len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 }
7038 else
Bram Moolenaar8299df92004-07-10 09:47:34 +00007039#endif
7040 {
7041 /* Add next character to buffer of characters to output.
7042 * Note: One printed character may require several PS characters to
7043 * represent it, but we only count them as one printed character.
7044 */
7045 ch = *p;
7046 if (ch < 32 || ch == '(' || ch == ')' || ch == '\\')
7047 {
7048 /* Convert non-printing characters to either their escape or octal
7049 * sequence, ensures PS sent over a serial line does not interfere
7050 * with the comms protocol. Note: For EBCDIC we need to write out
7051 * the escape sequences as ASCII codes!
7052 * Note 2: Char codes < 32 are identical in EBCDIC and ASCII AFAIK!
7053 */
7054 ga_append(&prt_ps_buffer, IF_EB('\\', 0134));
7055 switch (ch)
7056 {
7057 case BS: ga_append(&prt_ps_buffer, IF_EB('b', 0142)); break;
7058 case TAB: ga_append(&prt_ps_buffer, IF_EB('t', 0164)); break;
7059 case NL: ga_append(&prt_ps_buffer, IF_EB('n', 0156)); break;
7060 case FF: ga_append(&prt_ps_buffer, IF_EB('f', 0146)); break;
7061 case CAR: ga_append(&prt_ps_buffer, IF_EB('r', 0162)); break;
7062 case '(': ga_append(&prt_ps_buffer, IF_EB('(', 0050)); break;
7063 case ')': ga_append(&prt_ps_buffer, IF_EB(')', 0051)); break;
7064 case '\\': ga_append(&prt_ps_buffer, IF_EB('\\', 0134)); break;
7065
7066 default:
7067 sprintf((char *)ch_buff, "%03o", (unsigned int)ch);
7068#ifdef EBCDIC
7069 ebcdic2ascii(ch_buff, 3);
7070#endif
7071 ga_append(&prt_ps_buffer, ch_buff[0]);
7072 ga_append(&prt_ps_buffer, ch_buff[1]);
7073 ga_append(&prt_ps_buffer, ch_buff[2]);
7074 break;
7075 }
7076 }
7077 else
7078 ga_append(&prt_ps_buffer, ch);
7079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080
7081#ifdef FEAT_MBYTE
7082 /* Need to free any translated characters */
7083 if (prt_do_conv && (*p != NUL))
7084 vim_free(p);
7085#endif
7086
Bram Moolenaar8299df92004-07-10 09:47:34 +00007087 prt_text_run += char_width;
7088 prt_pos_x += char_width;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089
Bram Moolenaar8299df92004-07-10 09:47:34 +00007090 /* The downside of fp - use relative error on right margin check */
7091 next_pos = prt_pos_x + prt_char_width;
7092 need_break = (next_pos > prt_right_margin) &&
7093 ((next_pos - prt_right_margin) > (prt_right_margin*1e-5));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094
7095 if (need_break)
7096 prt_flush_buffer();
7097
7098 return need_break;
7099}
7100
7101 void
7102mch_print_set_font(iBold, iItalic, iUnderline)
7103 int iBold;
7104 int iItalic;
7105 int iUnderline;
7106{
7107 int font = 0;
7108
7109 if (iBold)
7110 font |= 0x01;
7111 if (iItalic)
7112 font |= 0x02;
7113
7114 if (font != prt_font)
7115 {
7116 prt_font = font;
7117 prt_attribute_change = TRUE;
7118 prt_need_font = TRUE;
7119 }
7120 if (prt_underline != iUnderline)
7121 {
7122 prt_underline = iUnderline;
7123 prt_attribute_change = TRUE;
7124 prt_need_underline = TRUE;
7125 }
7126}
7127
7128 void
7129mch_print_set_bg(bgcol)
7130 long_u bgcol;
7131{
7132 prt_bgcol = bgcol;
7133 prt_attribute_change = TRUE;
7134 prt_need_bgcol = TRUE;
7135}
7136
7137 void
7138mch_print_set_fg(fgcol)
7139 long_u fgcol;
7140{
7141 if (fgcol != (long_u)prt_fgcol)
7142 {
7143 prt_fgcol = fgcol;
7144 prt_attribute_change = TRUE;
7145 prt_need_fgcol = TRUE;
7146 }
7147}
7148
7149# endif /*FEAT_POSTSCRIPT*/
7150#endif /*FEAT_PRINTER*/
7151
7152#if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
7153 && (defined(FEAT_EVAL) || defined(FEAT_MULTI_LANG))
7154static char *get_locale_val __ARGS((int what));
7155
7156 static char *
7157get_locale_val(what)
7158 int what;
7159{
7160 char *loc;
7161
7162 /* Obtain the locale value from the libraries. For DJGPP this is
7163 * redefined and it doesn't use the arguments. */
7164 loc = setlocale(what, NULL);
7165
7166# if defined(__BORLANDC__)
7167 if (loc != NULL)
7168 {
7169 char_u *p;
7170
7171 /* Borland returns something like "LC_CTYPE=<name>\n"
7172 * Let's try to fix that bug here... */
7173 p = vim_strchr(loc, '=');
7174 if (p != NULL)
7175 {
7176 loc = ++p;
7177 while (*p != NUL) /* remove trailing newline */
7178 {
7179 if (*p < ' ')
7180 {
7181 *p = NUL;
7182 break;
7183 }
7184 ++p;
7185 }
7186 }
7187 }
7188# endif
7189
7190 return loc;
7191}
7192#endif
7193
7194
7195#ifdef WIN32
7196/*
7197 * On MS-Windows locale names are strings like "German_Germany.1252", but
7198 * gettext expects "de". Try to translate one into another here for a few
7199 * supported languages.
7200 */
7201 static char_u *
7202gettext_lang(char_u *name)
7203{
7204 int i;
7205 static char *(mtable[]) = {
7206 "afrikaans", "af",
7207 "czech", "cs",
7208 "dutch", "nl",
7209 "german", "de",
7210 "english_united kingdom", "en_GB",
7211 "spanish", "es",
7212 "french", "fr",
7213 "italian", "it",
7214 "japanese", "ja",
7215 "korean", "ko",
7216 "norwegian", "no",
7217 "polish", "pl",
7218 "russian", "ru",
7219 "slovak", "sk",
7220 "swedish", "sv",
7221 "ukrainian", "uk",
7222 "chinese_china", "zh_CN",
7223 "chinese_taiwan", "zh_TW",
7224 NULL};
7225
7226 for (i = 0; mtable[i] != NULL; i += 2)
7227 if (STRNICMP(mtable[i], name, STRLEN(mtable[i])) == 0)
7228 return mtable[i + 1];
7229 return name;
7230}
7231#endif
7232
7233#if defined(FEAT_MULTI_LANG) || defined(PROTO)
7234/*
7235 * Obtain the current messages language. Used to set the default for
7236 * 'helplang'. May return NULL or an empty string.
7237 */
7238 char_u *
7239get_mess_lang()
7240{
7241 char_u *p;
7242
7243# if (defined(HAVE_LOCALE_H) || defined(X_LOCALE))
7244# if defined(LC_MESSAGES)
7245 p = (char_u *)get_locale_val(LC_MESSAGES);
7246# else
7247 /* This is necessary for Win32, where LC_MESSAGES is not defined and $LANG
7248 * may be set to the LCID number. */
7249 p = (char_u *)get_locale_val(LC_ALL);
7250# endif
7251# else
7252 p = mch_getenv((char_u *)"LC_ALL");
7253 if (p == NULL || *p == NUL)
7254 {
7255 p = mch_getenv((char_u *)"LC_MESSAGES");
7256 if (p == NULL || *p == NUL)
7257 p = mch_getenv((char_u *)"LANG");
7258 }
7259# endif
7260# ifdef WIN32
7261 p = gettext_lang(p);
7262# endif
7263 return p;
7264}
7265#endif
7266
Bram Moolenaardef9e822004-12-31 20:58:58 +00007267/* Complicated #if; matches with where get_mess_env() is used below. */
7268#if (defined(FEAT_EVAL) && !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
7269 && defined(LC_MESSAGES))) \
7270 || ((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
7271 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)) \
7272 && !defined(LC_MESSAGES))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273static char_u *get_mess_env __ARGS((void));
7274
7275/*
7276 * Get the language used for messages from the environment.
7277 */
7278 static char_u *
7279get_mess_env()
7280{
7281 char_u *p;
7282
7283 p = mch_getenv((char_u *)"LC_ALL");
7284 if (p == NULL || *p == NUL)
7285 {
7286 p = mch_getenv((char_u *)"LC_MESSAGES");
7287 if (p == NULL || *p == NUL)
7288 {
7289 p = mch_getenv((char_u *)"LANG");
7290 if (p != NULL && VIM_ISDIGIT(*p))
7291 p = NULL; /* ignore something like "1043" */
7292# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
7293 if (p == NULL || *p == NUL)
7294 p = (char_u *)get_locale_val(LC_CTYPE);
7295# endif
7296 }
7297 }
7298 return p;
7299}
7300#endif
7301
7302#if defined(FEAT_EVAL) || defined(PROTO)
7303
7304/*
7305 * Set the "v:lang" variable according to the current locale setting.
7306 * Also do "v:lc_time"and "v:ctype".
7307 */
7308 void
7309set_lang_var()
7310{
7311 char_u *loc;
7312
7313# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
7314 loc = (char_u *)get_locale_val(LC_CTYPE);
7315# else
7316 /* setlocale() not supported: use the default value */
7317 loc = (char_u *)"C";
7318# endif
7319 set_vim_var_string(VV_CTYPE, loc, -1);
7320
7321 /* When LC_MESSAGES isn't defined use the value from $LC_MESSAGES, fall
7322 * back to LC_CTYPE if it's empty. */
7323# if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) && defined(LC_MESSAGES)
7324 loc = (char_u *)get_locale_val(LC_MESSAGES);
7325# else
7326 loc = get_mess_env();
7327# endif
7328 set_vim_var_string(VV_LANG, loc, -1);
7329
7330# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
7331 loc = (char_u *)get_locale_val(LC_TIME);
7332# endif
7333 set_vim_var_string(VV_LC_TIME, loc, -1);
7334}
7335#endif
7336
7337#if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
7338 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
7339/*
7340 * ":language": Set the language (locale).
7341 */
7342 void
7343ex_language(eap)
7344 exarg_T *eap;
7345{
7346 char *loc;
7347 char_u *p;
7348 char_u *name;
7349 int what = LC_ALL;
7350 char *whatstr = "";
7351#ifdef LC_MESSAGES
7352# define VIM_LC_MESSAGES LC_MESSAGES
7353#else
7354# define VIM_LC_MESSAGES 6789
7355#endif
7356
7357 name = eap->arg;
7358
7359 /* Check for "messages {name}", "ctype {name}" or "time {name}" argument.
7360 * Allow abbreviation, but require at least 3 characters to avoid
7361 * confusion with a two letter language name "me" or "ct". */
7362 p = skiptowhite(eap->arg);
7363 if ((*p == NUL || vim_iswhite(*p)) && p - eap->arg >= 3)
7364 {
7365 if (STRNICMP(eap->arg, "messages", p - eap->arg) == 0)
7366 {
7367 what = VIM_LC_MESSAGES;
7368 name = skipwhite(p);
7369 whatstr = "messages ";
7370 }
7371 else if (STRNICMP(eap->arg, "ctype", p - eap->arg) == 0)
7372 {
7373 what = LC_CTYPE;
7374 name = skipwhite(p);
7375 whatstr = "ctype ";
7376 }
7377 else if (STRNICMP(eap->arg, "time", p - eap->arg) == 0)
7378 {
7379 what = LC_TIME;
7380 name = skipwhite(p);
7381 whatstr = "time ";
7382 }
7383 }
7384
7385 if (*name == NUL)
7386 {
7387#ifndef LC_MESSAGES
7388 if (what == VIM_LC_MESSAGES)
7389 p = get_mess_env();
7390 else
7391#endif
7392 p = (char_u *)setlocale(what, NULL);
7393 if (p == NULL || *p == NUL)
7394 p = (char_u *)"Unknown";
7395 smsg((char_u *)_("Current %slanguage: \"%s\""), whatstr, p);
7396 }
7397 else
7398 {
7399#ifndef LC_MESSAGES
7400 if (what == VIM_LC_MESSAGES)
7401 loc = "";
7402 else
7403#endif
7404 loc = setlocale(what, (char *)name);
7405 if (loc == NULL)
7406 EMSG2(_("E197: Cannot set language to \"%s\""), name);
7407 else
7408 {
7409#ifdef HAVE_NL_MSG_CAT_CNTR
7410 /* Need to do this for GNU gettext, otherwise cached translations
7411 * will be used again. */
7412 extern int _nl_msg_cat_cntr;
7413
7414 ++_nl_msg_cat_cntr;
7415#endif
7416 /* Reset $LC_ALL, otherwise it would overrule everyting. */
7417 vim_setenv((char_u *)"LC_ALL", (char_u *)"");
7418
7419 if (what != LC_TIME)
7420 {
7421 /* Tell gettext() what to translate to. It apparently doesn't
7422 * use the currently effective locale. Also do this when
7423 * FEAT_GETTEXT isn't defined, so that shell commands use this
7424 * value. */
7425 if (what == LC_ALL)
7426 vim_setenv((char_u *)"LANG", name);
7427 if (what != LC_CTYPE)
7428 {
7429 char_u *mname;
7430#ifdef WIN32
7431 mname = gettext_lang(name);
7432#else
7433 mname = name;
7434#endif
7435 vim_setenv((char_u *)"LC_MESSAGES", mname);
7436#ifdef FEAT_MULTI_LANG
7437 set_helplang_default(mname);
7438#endif
7439 }
7440
7441 /* Set $LC_CTYPE, because it overrules $LANG, and
7442 * gtk_set_locale() calls setlocale() again. gnome_init()
7443 * sets $LC_CTYPE to "en_US" (that's a bug!). */
7444 if (what != VIM_LC_MESSAGES)
7445 vim_setenv((char_u *)"LC_CTYPE", name);
7446# ifdef FEAT_GUI_GTK
7447 /* Let GTK know what locale we're using. Not sure this is
7448 * really needed... */
7449 if (gui.in_use)
7450 (void)gtk_set_locale();
7451# endif
7452 }
7453
7454# ifdef FEAT_EVAL
7455 /* Set v:lang, v:lc_time and v:ctype to the final result. */
7456 set_lang_var();
7457# endif
7458 }
7459 }
7460}
7461
7462# if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7463/*
7464 * Function given to ExpandGeneric() to obtain the possible arguments of the
7465 * ":language" command.
7466 */
7467/*ARGSUSED*/
7468 char_u *
7469get_lang_arg(xp, idx)
7470 expand_T *xp;
7471 int idx;
7472{
7473 if (idx == 0)
7474 return (char_u *)"messages";
7475 if (idx == 1)
7476 return (char_u *)"ctype";
7477 if (idx == 2)
7478 return (char_u *)"time";
7479 return NULL;
7480}
7481# endif
7482
7483#endif