home *** CD-ROM | disk | FTP | other *** search
/ vim.ftp.fu-berlin.de / 2015-02-03.vim.ftp.fu-berlin.de.tar / vim.ftp.fu-berlin.de / unix / vim-6.2.tar.bz2 / vim-6.2.tar / vim62 / src / ex_cmds2.c < prev    next >
Encoding:
C/C++ Source or Header  |  2003-05-29  |  128.6 KB  |  5,459 lines

  1. /* 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. #include "vim.h"
  15. #include "version.h"
  16.  
  17. static void    cmd_source __ARGS((char_u *fname, exarg_T *eap));
  18.  
  19. #if defined(FEAT_EVAL) || defined(PROTO)
  20. static int debug_greedy = FALSE;    /* batch mode debugging: don't save
  21.                        and restore typeahead. */
  22.  
  23. /*
  24.  * do_debug(): Debug mode.
  25.  * Repeatedly get Ex commands, until told to continue normal execution.
  26.  */
  27.     void
  28. do_debug(cmd)
  29.     char_u    *cmd;
  30. {
  31.     int        save_msg_scroll = msg_scroll;
  32.     int        save_State = State;
  33.     int        save_did_emsg = did_emsg;
  34.     int        save_cmd_silent = cmd_silent;
  35.     int        save_msg_silent = msg_silent;
  36.     int        save_emsg_silent = emsg_silent;
  37.     int        save_redir_off = redir_off;
  38.     tasave_T    typeaheadbuf;
  39. # ifdef FEAT_EX_EXTRA
  40.     int        save_ex_normal_busy;
  41. # endif
  42.     int        n;
  43.     char_u    *cmdline = NULL;
  44.     char_u    *p;
  45.     char    *tail = NULL;
  46.     static int    last_cmd = 0;
  47. #define CMD_CONT    1
  48. #define CMD_NEXT    2
  49. #define CMD_STEP    3
  50. #define CMD_FINISH    4
  51. #define CMD_QUIT    5
  52. #define CMD_INTERRUPT    6
  53.  
  54. #ifdef ALWAYS_USE_GUI
  55.     /* Can't do this when there is no terminal for input/output. */
  56.     if (!gui.in_use)
  57.     {
  58.     /* Break as soon as possible. */
  59.     debug_break_level = 9999;
  60.     return;
  61.     }
  62. #endif
  63.  
  64.     /* Make sure we are in raw mode and start termcap mode.  Might have side
  65.      * effects... */
  66.     settmode(TMODE_RAW);
  67.     starttermcap();
  68.  
  69.     ++RedrawingDisabled;    /* don't redisplay the window */
  70.     ++no_wait_return;        /* don't wait for return */
  71.     did_emsg = FALSE;        /* don't use error from debugged stuff */
  72.     cmd_silent = FALSE;        /* display commands */
  73.     msg_silent = FALSE;        /* display messages */
  74.     emsg_silent = FALSE;    /* display error messages */
  75.     redir_off = TRUE;        /* don't redirect debug commands */
  76.  
  77.     State = NORMAL;
  78. #ifdef FEAT_SNIFF
  79.     want_sniff_request = 0;    /* No K_SNIFF wanted */
  80. #endif
  81.  
  82.     if (!debug_did_msg)
  83.     MSG(_("Entering Debug mode.  Type \"cont\" to continue."));
  84.     if (sourcing_name != NULL)
  85.     msg(sourcing_name);
  86.     if (sourcing_lnum != 0)
  87.     smsg((char_u *)_("line %ld: %s"), (long)sourcing_lnum, cmd);
  88.     else
  89.     msg_str((char_u *)_("cmd: %s"), cmd);
  90.  
  91.     /*
  92.      * Repeat getting a command and executing it.
  93.      */
  94.     for (;;)
  95.     {
  96.     msg_scroll = TRUE;
  97.     need_wait_return = FALSE;
  98. #ifdef FEAT_SNIFF
  99.     ProcessSniffRequests();
  100. #endif
  101.     /* Save the current typeahead buffer and replace it with an empty one.
  102.      * This makes sure we get input from the user here and don't interfere
  103.      * with the commands being executed.  Reset "ex_normal_busy" to avoid
  104.      * the side effects of using ":normal". Save the stuff buffer and make
  105.      * it empty. */
  106. # ifdef FEAT_EX_EXTRA
  107.     save_ex_normal_busy = ex_normal_busy;
  108.     ex_normal_busy = 0;
  109. # endif
  110.     if (!debug_greedy)
  111.         save_typeahead(&typeaheadbuf);
  112.  
  113.     cmdline = getcmdline_prompt('>', NULL, 0);
  114.  
  115.     if (!debug_greedy)
  116.         restore_typeahead(&typeaheadbuf);
  117. # ifdef FEAT_EX_EXTRA
  118.     ex_normal_busy = save_ex_normal_busy;
  119. # endif
  120.  
  121.     cmdline_row = msg_row;
  122.     if (cmdline != NULL)
  123.     {
  124.         /* If this is a debug command, set "last_cmd".
  125.          * If not, reset "last_cmd".
  126.          * For a blank line use previous command. */
  127.         p = skipwhite(cmdline);
  128.         if (*p != NUL)
  129.         {
  130.         switch (*p)
  131.         {
  132.             case 'c': last_cmd = CMD_CONT;
  133.                   tail = "ont";
  134.                   break;
  135.             case 'n': last_cmd = CMD_NEXT;
  136.                   tail = "ext";
  137.                   break;
  138.             case 's': last_cmd = CMD_STEP;
  139.                   tail = "tep";
  140.                   break;
  141.             case 'f': last_cmd = CMD_FINISH;
  142.                   tail = "inish";
  143.                   break;
  144.             case 'q': last_cmd = CMD_QUIT;
  145.                   tail = "uit";
  146.                   break;
  147.             case 'i': last_cmd = CMD_INTERRUPT;
  148.                   tail = "nterrupt";
  149.                   break;
  150.             default: last_cmd = 0;
  151.         }
  152.         if (last_cmd != 0)
  153.         {
  154.             /* Check that the tail matches. */
  155.             ++p;
  156.             while (*p != NUL && *p == *tail)
  157.             {
  158.             ++p;
  159.             ++tail;
  160.             }
  161.             if (ASCII_ISALPHA(*p))
  162.             last_cmd = 0;
  163.         }
  164.         }
  165.  
  166.         if (last_cmd != 0)
  167.         {
  168.         /* Execute debug command: decided where to break next and
  169.          * return. */
  170.         switch (last_cmd)
  171.         {
  172.             case CMD_CONT:
  173.             debug_break_level = -1;
  174.             break;
  175.             case CMD_NEXT:
  176.             debug_break_level = ex_nesting_level;
  177.             break;
  178.             case CMD_STEP:
  179.             debug_break_level = 9999;
  180.             break;
  181.             case CMD_FINISH:
  182.             debug_break_level = ex_nesting_level - 1;
  183.             break;
  184.             case CMD_QUIT:
  185.             got_int = TRUE;
  186.             debug_break_level = -1;
  187.             break;
  188.             case CMD_INTERRUPT:
  189.             got_int = TRUE;
  190.             debug_break_level = 9999;
  191.             /* Do not repeat ">interrupt" cmd, continue stepping. */
  192.             last_cmd = CMD_STEP;
  193.             break;
  194.         }
  195.         break;
  196.         }
  197.  
  198.         /* don't debug this command */
  199.         n = debug_break_level;
  200.         debug_break_level = -1;
  201.         (void)do_cmdline(cmdline, getexline, NULL,
  202.                  DOCMD_VERBOSE|DOCMD_EXCRESET);
  203.         debug_break_level = n;
  204.  
  205.         vim_free(cmdline);
  206.     }
  207.     lines_left = Rows - 1;
  208.     }
  209.     vim_free(cmdline);
  210.  
  211.     --RedrawingDisabled;
  212.     --no_wait_return;
  213.     redraw_all_later(NOT_VALID);
  214.     need_wait_return = FALSE;
  215.     msg_scroll = save_msg_scroll;
  216.     lines_left = Rows - 1;
  217.     State = save_State;
  218.     did_emsg = save_did_emsg;
  219.     cmd_silent = save_cmd_silent;
  220.     msg_silent = save_msg_silent;
  221.     emsg_silent = save_emsg_silent;
  222.     redir_off = save_redir_off;
  223.  
  224.     /* Only print the message again when typing a command before coming back
  225.      * here. */
  226.     debug_did_msg = TRUE;
  227. }
  228.  
  229. /*
  230.  * ":debug".
  231.  */
  232.     void
  233. ex_debug(eap)
  234.     exarg_T    *eap;
  235. {
  236.     int        debug_break_level_save = debug_break_level;
  237.  
  238.     debug_break_level = 9999;
  239.     do_cmdline_cmd(eap->arg);
  240.     debug_break_level = debug_break_level_save;
  241. }
  242.  
  243. static char_u    *debug_breakpoint_name = NULL;
  244. static linenr_T    debug_breakpoint_lnum;
  245.  
  246. /*
  247.  * When debugging or a breakpoint is set on a skipped command, no debug prompt
  248.  * is shown by do_one_cmd().  This situation is indicated by debug_skipped, and
  249.  * debug_skipped_name is then set to the source name in the breakpoint case.  If
  250.  * a skipped command decides itself that a debug prompt should be displayed, it
  251.  * can do so by calling dbg_check_skipped().
  252.  */
  253. static int    debug_skipped;
  254. static char_u    *debug_skipped_name;
  255.  
  256. /*
  257.  * Go to debug mode when a breakpoint was encountered or "ex_nesting_level" is
  258.  * at or below the break level.  But only when the line is actually
  259.  * executed.  Return TRUE and set breakpoint_name for skipped commands that
  260.  * decide to execute something themselves.
  261.  * Called from do_one_cmd() before executing a command.
  262.  */
  263.     void
  264. dbg_check_breakpoint(eap)
  265.     exarg_T    *eap;
  266. {
  267.     char_u    *p;
  268.  
  269.     debug_skipped = FALSE;
  270.     if (debug_breakpoint_name != NULL)
  271.     {
  272.     if (!eap->skip)
  273.     {
  274.         /* replace K_SNR with "<SNR>" */
  275.         if (debug_breakpoint_name[0] == K_SPECIAL
  276.             && debug_breakpoint_name[1] == KS_EXTRA
  277.             && debug_breakpoint_name[2] == (int)KE_SNR)
  278.         p = (char_u *)"<SNR>";
  279.         else
  280.         p = (char_u *)"";
  281.         smsg((char_u *)_("Breakpoint in \"%s%s\" line %ld"), p,
  282.             debug_breakpoint_name + (*p == NUL ? 0 : 3),
  283.             (long)debug_breakpoint_lnum);
  284.         debug_breakpoint_name = NULL;
  285.         do_debug(eap->cmd);
  286.     }
  287.     else
  288.     {
  289.         debug_skipped = TRUE;
  290.         debug_skipped_name = debug_breakpoint_name;
  291.         debug_breakpoint_name = NULL;
  292.     }
  293.     }
  294.     else if (ex_nesting_level <= debug_break_level)
  295.     {
  296.     if (!eap->skip)
  297.         do_debug(eap->cmd);
  298.     else
  299.     {
  300.         debug_skipped = TRUE;
  301.         debug_skipped_name = NULL;
  302.     }
  303.     }
  304. }
  305.  
  306. /*
  307.  * Go to debug mode if skipped by dbg_check_breakpoint() because eap->skip was
  308.  * set.  Return TRUE when the debug mode is entered this time.
  309.  */
  310.     int
  311. dbg_check_skipped(eap)
  312.     exarg_T    *eap;
  313. {
  314.     int        prev_got_int;
  315.  
  316.     if (debug_skipped)
  317.     {
  318.     /*
  319.      * Save the value of got_int and reset it.  We don't want a previous
  320.      * interruption cause flushing the input buffer.
  321.      */
  322.     prev_got_int = got_int;
  323.     got_int = FALSE;
  324.     debug_breakpoint_name = debug_skipped_name;
  325.     /* eap->skip is TRUE */
  326.     eap->skip = FALSE;
  327.     (void)dbg_check_breakpoint(eap);
  328.     eap->skip = TRUE;
  329.     got_int |= prev_got_int;
  330.     return TRUE;
  331.     }
  332.     return FALSE;
  333. }
  334.  
  335. /*
  336.  * The list of breakpoints: dbg_breakp.
  337.  * This is a grow-array of structs.
  338.  */
  339. struct debuggy
  340. {
  341.     int        dbg_nr;        /* breakpoint number */
  342.     int        dbg_type;    /* DBG_FUNC or DBG_FILE */
  343.     char_u    *dbg_name;    /* function or file name */
  344.     regprog_T    *dbg_prog;    /* regexp program */
  345.     linenr_T    dbg_lnum;    /* line number in function or file */
  346. };
  347.  
  348. static garray_T dbg_breakp = {0, 0, sizeof(struct debuggy), 4, NULL};
  349. #define BREAKP(idx)    (((struct debuggy *)dbg_breakp.ga_data)[idx])
  350. static int last_breakp = 0;    /* nr of last defined breakpoint */
  351.  
  352. #define DBG_FUNC    1
  353. #define DBG_FILE    2
  354.  
  355. static int dbg_parsearg __ARGS((char_u *arg));
  356.  
  357. /*
  358.  * Parse the arguments of ":breakadd" or ":breakdel" and put them in the entry
  359.  * just after the last one in dbg_breakp.  Note that "dbg_name" is allocated.
  360.  * Returns FAIL for failure.
  361.  */
  362.     static int
  363. dbg_parsearg(arg)
  364.     char_u    *arg;
  365. {
  366.     char_u    *p = arg;
  367.     char_u    *q;
  368.     struct debuggy *bp;
  369.  
  370.     if (ga_grow(&dbg_breakp, 1) == FAIL)
  371.     return FAIL;
  372.     bp = &BREAKP(dbg_breakp.ga_len);
  373.  
  374.     /* Find "func" or "file". */
  375.     if (STRNCMP(p, "func", 4) == 0)
  376.     bp->dbg_type = DBG_FUNC;
  377.     else if (STRNCMP(p, "file", 4) == 0)
  378.     bp->dbg_type = DBG_FILE;
  379.     else
  380.     {
  381.     EMSG2(_(e_invarg2), p);
  382.     return FAIL;
  383.     }
  384.     p = skipwhite(p + 4);
  385.  
  386.     /* Find optional line number. */
  387.     if (isdigit(*p))
  388.     {
  389.     bp->dbg_lnum = getdigits(&p);
  390.     p = skipwhite(p);
  391.     }
  392.     else
  393.     bp->dbg_lnum = 0;
  394.  
  395.     /* Find the function or file name.  Don't accept a function name with (). */
  396.     if (*p == NUL
  397.         || (bp->dbg_type == DBG_FUNC && strstr((char *)p, "()") != NULL))
  398.     {
  399.     EMSG2(_(e_invarg2), arg);
  400.     return FAIL;
  401.     }
  402.  
  403.     if (bp->dbg_type == DBG_FUNC)
  404.     bp->dbg_name = vim_strsave(p);
  405.     else
  406.     {
  407.     /* Expand the file name in the same way as do_source().  This means
  408.      * doing it twice, so that $DIR/file gets expanded when $DIR is
  409.      * "~/dir". */
  410. #ifdef RISCOS
  411.     q = mch_munge_fname(p);
  412. #else
  413.     q = expand_env_save(p);
  414. #endif
  415.     if (q == NULL)
  416.         return FAIL;
  417. #ifdef RISCOS
  418.     p = mch_munge_fname(q);
  419. #else
  420.     p = expand_env_save(q);
  421. #endif
  422.     vim_free(q);
  423.     if (p == NULL)
  424.         return FAIL;
  425.     bp->dbg_name = fix_fname(p);
  426.     vim_free(p);
  427. #ifdef MACOS_CLASSIC
  428.     if (bp->dbg_name != NULL)
  429.         slash_n_colon_adjust(bp->dbg_name);
  430. #endif
  431.     }
  432.  
  433.     if (bp->dbg_name == NULL)
  434.     return FAIL;
  435.     return OK;
  436. }
  437.  
  438. /*
  439.  * ":breakadd".
  440.  */
  441.     void
  442. ex_breakadd(eap)
  443.     exarg_T    *eap;
  444. {
  445.     struct debuggy *bp;
  446.     char_u    *pat;
  447.  
  448.     if (dbg_parsearg(eap->arg) == OK)
  449.     {
  450.     bp = &BREAKP(dbg_breakp.ga_len);
  451.     pat = file_pat_to_reg_pat(bp->dbg_name, NULL, NULL, FALSE);
  452.     if (pat != NULL)
  453.     {
  454.         bp->dbg_prog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
  455.         vim_free(pat);
  456.     }
  457.     if (pat == NULL || bp->dbg_prog == NULL)
  458.         vim_free(bp->dbg_name);
  459.     else
  460.     {
  461.         if (bp->dbg_lnum == 0)    /* default line number is 1 */
  462.         bp->dbg_lnum = 1;
  463.         BREAKP(dbg_breakp.ga_len++).dbg_nr = ++last_breakp;
  464.         --dbg_breakp.ga_room;
  465.         ++debug_tick;
  466.     }
  467.     }
  468. }
  469.  
  470. /*
  471.  * ":debuggreedy".
  472.  */
  473.     void
  474. ex_debuggreedy(eap)
  475.     exarg_T    *eap;
  476. {
  477.     if (eap->addr_count == 0 || eap->line2 != 0)
  478.     debug_greedy = TRUE;
  479.     else
  480.     debug_greedy = FALSE;
  481. }
  482.  
  483. /*
  484.  * ":breakdel".
  485.  */
  486.     void
  487. ex_breakdel(eap)
  488.     exarg_T    *eap;
  489. {
  490.     struct debuggy *bp, *bpi;
  491.     int        nr;
  492.     int        todel = -1;
  493.     int        i;
  494.     linenr_T    best_lnum = 0;
  495.  
  496.     if (isdigit(*eap->arg))
  497.     {
  498.     /* ":breakdel {nr}" */
  499.     nr = atol((char *)eap->arg);
  500.     for (i = 0; i < dbg_breakp.ga_len; ++i)
  501.         if (BREAKP(i).dbg_nr == nr)
  502.         {
  503.         todel = i;
  504.         break;
  505.         }
  506.     }
  507.     else
  508.     {
  509.     /* ":breakdel {func|file} [lnum] {name}" */
  510.     if (dbg_parsearg(eap->arg) == FAIL)
  511.         return;
  512.     bp = &BREAKP(dbg_breakp.ga_len);
  513.     for (i = 0; i < dbg_breakp.ga_len; ++i)
  514.     {
  515.         bpi = &BREAKP(i);
  516.         if (bp->dbg_type == bpi->dbg_type
  517.             && STRCMP(bp->dbg_name, bpi->dbg_name) == 0
  518.             && (bp->dbg_lnum == bpi->dbg_lnum
  519.             || (bp->dbg_lnum == 0
  520.                 && (best_lnum == 0
  521.                 || bpi->dbg_lnum < best_lnum))))
  522.         {
  523.         todel = i;
  524.         best_lnum = bpi->dbg_lnum;
  525.         }
  526.     }
  527.     vim_free(bp->dbg_name);
  528.     }
  529.  
  530.     if (todel < 0)
  531.     EMSG2(_("E161: Breakpoint not found: %s"), eap->arg);
  532.     else
  533.     {
  534.     vim_free(BREAKP(todel).dbg_name);
  535.     vim_free(BREAKP(todel).dbg_prog);
  536.     --dbg_breakp.ga_len;
  537.     ++dbg_breakp.ga_room;
  538.     if (todel < dbg_breakp.ga_len)
  539.         mch_memmove(&BREAKP(todel), &BREAKP(todel + 1),
  540.             (dbg_breakp.ga_len - todel) * sizeof(struct debuggy));
  541.     ++debug_tick;
  542.     }
  543. }
  544.  
  545. /*
  546.  * ":breaklist".
  547.  */
  548. /*ARGSUSED*/
  549.     void
  550. ex_breaklist(eap)
  551.     exarg_T    *eap;
  552. {
  553.     struct debuggy *bp;
  554.     int        i;
  555.  
  556.     if (dbg_breakp.ga_len == 0)
  557.     MSG(_("No breakpoints defined"));
  558.     else
  559.     for (i = 0; i < dbg_breakp.ga_len; ++i)
  560.     {
  561.         bp = &BREAKP(i);
  562.         smsg((char_u *)_("%3d  %s %s  line %ld"),
  563.             bp->dbg_nr,
  564.             bp->dbg_type == DBG_FUNC ? "func" : "file",
  565.             bp->dbg_name,
  566.             (long)bp->dbg_lnum);
  567.     }
  568. }
  569.  
  570. /*
  571.  * Find a breakpoint for a function or sourced file.
  572.  * Returns line number at which to break; zero when no matching breakpoint.
  573.  */
  574.     linenr_T
  575. dbg_find_breakpoint(file, fname, after)
  576.     int        file;        /* TRUE for a file, FALSE for a function */
  577.     char_u    *fname;        /* file or function name */
  578.     linenr_T    after;        /* after this line number */
  579. {
  580.     struct debuggy *bp;
  581.     int        i;
  582.     linenr_T    lnum = 0;
  583.     regmatch_T    regmatch;
  584.     char_u    *name = fname;
  585.     int        prev_got_int;
  586.  
  587.     /* Replace K_SNR in function name with "<SNR>". */
  588.     if (!file && fname[0] == K_SPECIAL)
  589.     {
  590.     name = alloc((unsigned)STRLEN(fname) + 3);
  591.     if (name == NULL)
  592.         name = fname;
  593.     else
  594.     {
  595.         STRCPY(name, "<SNR>");
  596.         STRCPY(name + 5, fname + 3);
  597.     }
  598.     }
  599.  
  600.     for (i = 0; i < dbg_breakp.ga_len; ++i)
  601.     {
  602.     /* skip entries that are not useful or are for a line that is beyond
  603.      * an already found breakpoint */
  604.     bp = &BREAKP(i);
  605.     if ((bp->dbg_type == DBG_FILE) == file
  606.         && bp->dbg_lnum > after
  607.         && (lnum == 0 || bp->dbg_lnum < lnum))
  608.     {
  609.         regmatch.regprog = bp->dbg_prog;
  610.         regmatch.rm_ic = FALSE;
  611.         /*
  612.          * Save the value of got_int and reset it.  We don't want a previous
  613.          * interruption cancel matching, only hitting CTRL-C while matching
  614.          * should abort it.
  615.          */
  616.         prev_got_int = got_int;
  617.         got_int = FALSE;
  618.         if (vim_regexec(®match, name, (colnr_T)0))
  619.         lnum = bp->dbg_lnum;
  620.         got_int |= prev_got_int;
  621.     }
  622.     }
  623.     if (name != fname)
  624.     vim_free(name);
  625.  
  626.     return lnum;
  627. }
  628.  
  629. /*
  630.  * Called when a breakpoint was encountered.
  631.  */
  632.     void
  633. dbg_breakpoint(name, lnum)
  634.     char_u    *name;
  635.     linenr_T    lnum;
  636. {
  637.     /* We need to check if this line is actually executed in do_one_cmd() */
  638.     debug_breakpoint_name = name;
  639.     debug_breakpoint_lnum = lnum;
  640. }
  641. #endif
  642.  
  643. /*
  644.  * If 'autowrite' option set, try to write the file.
  645.  * Careful: autocommands may make "buf" invalid!
  646.  *
  647.  * return FAIL for failure, OK otherwise
  648.  */
  649.     int
  650. autowrite(buf, forceit)
  651.     buf_T    *buf;
  652.     int        forceit;
  653. {
  654.     if (!(p_aw || p_awa) || !p_write
  655. #ifdef FEAT_QUICKFIX
  656.     /* never autowrite a "nofile" or "nowrite" buffer */
  657.     || bt_dontwrite(buf)
  658. #endif
  659.     || (!forceit && buf->b_p_ro) || buf->b_ffname == NULL)
  660.     return FAIL;
  661.     return buf_write_all(buf, forceit);
  662. }
  663.  
  664. /*
  665.  * flush all buffers, except the ones that are readonly
  666.  */
  667.     void
  668. autowrite_all()
  669. {
  670.     buf_T    *buf;
  671.  
  672.     if (!(p_aw || p_awa) || !p_write)
  673.     return;
  674.     for (buf = firstbuf; buf; buf = buf->b_next)
  675.     if (bufIsChanged(buf) && !buf->b_p_ro)
  676.     {
  677.         (void)buf_write_all(buf, FALSE);
  678. #ifdef FEAT_AUTOCMD
  679.         /* an autocommand may have deleted the buffer */
  680.         if (!buf_valid(buf))
  681.         buf = firstbuf;
  682. #endif
  683.     }
  684. }
  685.  
  686. /*
  687.  * return TRUE if buffer was changed and cannot be abandoned.
  688.  */
  689. /*ARGSUSED*/
  690.     int
  691. check_changed(buf, checkaw, mult_win, forceit, allbuf)
  692.     buf_T    *buf;
  693.     int        checkaw;    /* do autowrite if buffer was changed */
  694.     int        mult_win;    /* check also when several wins for the buf */
  695.     int        forceit;
  696.     int        allbuf;        /* may write all buffers */
  697. {
  698.     if (       !forceit
  699.         && bufIsChanged(buf)
  700.         && (mult_win || buf->b_nwindows <= 1)
  701.         && (!checkaw || autowrite(buf, forceit) == FAIL))
  702.     {
  703. #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
  704.     if ((p_confirm || cmdmod.confirm) && p_write)
  705.     {
  706.         buf_T    *buf2;
  707.         int        count = 0;
  708.  
  709.         if (allbuf)
  710.         for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next)
  711.             if (bufIsChanged(buf2)
  712.                      && (buf2->b_ffname != NULL
  713. # ifdef FEAT_BROWSE
  714.                      || cmdmod.browse
  715. # endif
  716.                     ))
  717.             ++count;
  718. #ifdef FEAT_AUTOCMD
  719.         if (!buf_valid(buf))
  720.         /* Autocommand deleted buffer, oops!  It's not changed now. */
  721.         return FALSE;
  722. #endif
  723.         dialog_changed(buf, count > 1);
  724. #ifdef FEAT_AUTOCMD
  725.         if (!buf_valid(buf))
  726.         /* Autocommand deleted buffer, oops!  It's not changed now. */
  727.         return FALSE;
  728. #endif
  729.         return bufIsChanged(buf);
  730.     }
  731. #endif
  732.     EMSG(_(e_nowrtmsg));
  733.     return TRUE;
  734.     }
  735.     return FALSE;
  736. }
  737.  
  738. #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
  739.  
  740. #ifdef FEAT_BROWSE
  741. static void    browse_save_fname __ARGS((buf_T *buf));
  742.  
  743. /*
  744.  * When wanting to write a file without a file name, ask the user for a name.
  745.  */
  746.     static void
  747. browse_save_fname(buf)
  748.     buf_T    *buf;
  749. {
  750.     if (buf->b_fname == NULL)
  751.     {
  752.     char_u *fname;
  753.  
  754.     fname = do_browse(TRUE, (char_u *)_("Save As"), NULL, NULL, NULL,
  755.                                    NULL, buf);
  756.     if (fname != NULL)
  757.     {
  758.         setfname(fname, NULL, TRUE);
  759.         vim_free(fname);
  760.     }
  761.     }
  762. }
  763. #endif
  764.  
  765. /*
  766.  * Ask the user what to do when abondoning a changed buffer.
  767.  */
  768.     void
  769. dialog_changed(buf, checkall)
  770.     buf_T    *buf;
  771.     int        checkall;    /* may abandon all changed buffers */
  772. {
  773.     char_u    buff[IOSIZE];
  774.     int        ret;
  775.     buf_T    *buf2;
  776.  
  777.     dialog_msg(buff, _("Save changes to \"%.*s\"?"),
  778.             (buf->b_fname != NULL) ?
  779.             buf->b_fname : (char_u *)_("Untitled"));
  780.     if (checkall)
  781.     ret = vim_dialog_yesnoallcancel(VIM_QUESTION, NULL, buff, 1);
  782.     else
  783.     ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
  784.  
  785.     if (ret == VIM_YES)
  786.     {
  787. #ifdef FEAT_BROWSE
  788.     /* May get file name, when there is none */
  789.     browse_save_fname(buf);
  790. #endif
  791.     if (buf->b_fname != NULL)   /* didn't hit Cancel */
  792.         (void)buf_write_all(buf, FALSE);
  793.     }
  794.     else if (ret == VIM_NO)
  795.     {
  796.     unchanged(buf, TRUE);
  797.     }
  798.     else if (ret == VIM_ALL)
  799.     {
  800.     /*
  801.      * Write all modified files that can be written.
  802.      * Skip readonly buffers, these need to be confirmed
  803.      * individually.
  804.      */
  805.     for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next)
  806.     {
  807.         if (bufIsChanged(buf2)
  808.             && (buf2->b_ffname != NULL
  809. #ifdef FEAT_BROWSE
  810.             || cmdmod.browse
  811. #endif
  812.             )
  813.             && !buf2->b_p_ro)
  814.         {
  815. #ifdef FEAT_BROWSE
  816.         /* May get file name, when there is none */
  817.         browse_save_fname(buf2);
  818. #endif
  819.         if (buf2->b_fname != NULL)   /* didn't hit Cancel */
  820.             (void)buf_write_all(buf2, FALSE);
  821. #ifdef FEAT_AUTOCMD
  822.         /* an autocommand may have deleted the buffer */
  823.         if (!buf_valid(buf2))
  824.             buf2 = firstbuf;
  825. #endif
  826.         }
  827.     }
  828.     }
  829.     else if (ret == VIM_DISCARDALL)
  830.     {
  831.     /*
  832.      * mark all buffers as unchanged
  833.      */
  834.     for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next)
  835.         unchanged(buf2, TRUE);
  836.     }
  837. }
  838. #endif
  839.  
  840. /*
  841.  * Return TRUE if the buffer "buf" can be abandoned, either by making it
  842.  * hidden, autowriting it or unloading it.
  843.  */
  844.     int
  845. can_abandon(buf, forceit)
  846.     buf_T    *buf;
  847.     int        forceit;
  848. {
  849.     return (       P_HID(buf)
  850.         || !bufIsChanged(buf)
  851.         || buf->b_nwindows > 1
  852.         || autowrite(buf, forceit) == OK
  853.         || forceit);
  854. }
  855.  
  856. /*
  857.  * Return TRUE if any buffer was changed and cannot be abandoned.
  858.  * That changed buffer becomes the current buffer.
  859.  */
  860.     int
  861. check_changed_any(hidden)
  862.     int        hidden;        /* Only check hidden buffers */
  863. {
  864.     buf_T    *buf;
  865.     int        save;
  866. #ifdef FEAT_WINDOWS
  867.     win_T    *wp;
  868. #endif
  869.  
  870. #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
  871.     for (;;)
  872.     {
  873. #endif
  874.     /* check curbuf first: if it was changed we can't abandon it */
  875.     if (!hidden && curbufIsChanged())
  876.         buf = curbuf;
  877.     else
  878.     {
  879.         for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  880.         if ((!hidden || buf->b_nwindows == 0) && bufIsChanged(buf))
  881.             break;
  882.     }
  883.     if (buf == NULL)    /* No buffers changed */
  884.         return FALSE;
  885.  
  886. #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
  887.     if (p_confirm || cmdmod.confirm)
  888.     {
  889.         if (check_changed(buf, p_awa, TRUE, FALSE, TRUE) && buf_valid(buf))
  890.         break;        /* didn't save - still changes */
  891.     }
  892.     else
  893.         break;        /* confirm not active - has changes */
  894.     }
  895. #endif
  896.  
  897.     exiting = FALSE;
  898. #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
  899.     /*
  900.      * When ":confirm" used, don't give an error message.
  901.      */
  902.     if (!(p_confirm || cmdmod.confirm))
  903. #endif
  904.     {
  905.     /* There must be a wait_return for this message, do_buffer()
  906.      * may cause a redraw.  But wait_return() is a no-op when vgetc()
  907.      * is busy (Quit used from window menu), then make sure we don't
  908.      * cause a scroll up. */
  909.     if (vgetc_busy)
  910.     {
  911.         msg_row = cmdline_row;
  912.         msg_col = 0;
  913.         msg_didout = FALSE;
  914.     }
  915.     if (EMSG2(_("E162: No write since last change for buffer \"%s\""),
  916.             buf_spname(buf) != NULL ? (char_u *)buf_spname(buf) :
  917.             buf->b_fname))
  918.     {
  919.         save = no_wait_return;
  920.         no_wait_return = FALSE;
  921.         wait_return(FALSE);
  922.         no_wait_return = save;
  923.     }
  924.     }
  925.  
  926. #ifdef FEAT_WINDOWS
  927.     /* Try to find a window that contains the buffer. */
  928.     if (buf != curbuf)
  929.     for (wp = firstwin; wp != NULL; wp = wp->w_next)
  930.         if (wp->w_buffer == buf)
  931.         {
  932.         win_goto(wp);
  933. # ifdef FEAT_AUTOCMD
  934.         /* Paranoia: did autocms wipe out the buffer with changes? */
  935.         if (!buf_valid(buf))
  936.             return TRUE;
  937. # endif
  938.         break;
  939.         }
  940. #endif
  941.  
  942.     /* Open the changed buffer in the current window. */
  943.     if (buf != curbuf)
  944.     set_curbuf(buf, DOBUF_GOTO);
  945.  
  946.     return TRUE;
  947. }
  948.  
  949. /*
  950.  * return FAIL if there is no file name, OK if there is one
  951.  * give error message for FAIL
  952.  */
  953.     int
  954. check_fname()
  955. {
  956.     if (curbuf->b_ffname == NULL)
  957.     {
  958.     EMSG(_(e_noname));
  959.     return FAIL;
  960.     }
  961.     return OK;
  962. }
  963.  
  964. /*
  965.  * flush the contents of a buffer, unless it has no file name
  966.  *
  967.  * return FAIL for failure, OK otherwise
  968.  */
  969.     int
  970. buf_write_all(buf, forceit)
  971.     buf_T    *buf;
  972.     int        forceit;
  973. {
  974.     int        retval;
  975. #ifdef FEAT_AUTOCMD
  976.     buf_T    *old_curbuf = curbuf;
  977. #endif
  978.  
  979.     retval = (buf_write(buf, buf->b_ffname, buf->b_fname,
  980.                    (linenr_T)1, buf->b_ml.ml_line_count, NULL,
  981.                           FALSE, forceit, TRUE, FALSE));
  982. #ifdef FEAT_AUTOCMD
  983.     if (curbuf != old_curbuf)
  984.     MSG(_("Warning: Entered other buffer unexpectedly (check autocommands)"));
  985. #endif
  986.     return retval;
  987. }
  988.  
  989. /*
  990.  * Code to handle the argument list.
  991.  */
  992.  
  993. /*
  994.  * Isolate one argument, taking quotes and backticks.
  995.  * Changes the argument in-place, puts a NUL after it.
  996.  * Quotes are removed, backticks remain.
  997.  * Return a pointer to the start of the next argument.
  998.  */
  999.     char_u *
  1000. do_one_arg(str)
  1001.     char_u *str;
  1002. {
  1003.     char_u    *p;
  1004.     int        inquote;
  1005.     int        inbacktick;
  1006.  
  1007.     inquote = FALSE;
  1008.     inbacktick = FALSE;
  1009.     for (p = str; *str; ++str)
  1010.     {
  1011.     /*
  1012.      * for MSDOS et.al. a backslash is part of a file name.
  1013.      * Only skip ", space and tab.
  1014.      */
  1015.     if (rem_backslash(str))
  1016.     {
  1017.         *p++ = *str++;
  1018.         *p++ = *str;
  1019.     }
  1020.     else
  1021.     {
  1022.         /* An item ends at a space not in quotes or backticks */
  1023.         if (!inquote && !inbacktick && vim_isspace(*str))
  1024.         break;
  1025.         if (!inquote && *str == '`')
  1026.         inbacktick ^= TRUE;
  1027.         if (!inbacktick && *str == '"')
  1028.         inquote ^= TRUE;
  1029.         else
  1030.         *p++ = *str;
  1031.     }
  1032.     }
  1033.     str = skipwhite(str);
  1034.     *p = NUL;
  1035.  
  1036.     return str;
  1037. }
  1038.  
  1039. static int do_arglist __ARGS((char_u *str, int what, int after));
  1040. static void alist_check_arg_idx __ARGS((void));
  1041. #ifdef FEAT_LISTCMDS
  1042. static int alist_add_list __ARGS((int count, char_u **files, int after));
  1043. #endif
  1044. #define AL_SET    1
  1045. #define AL_ADD    2
  1046. #define AL_DEL    3
  1047.  
  1048. #if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO)
  1049. /*
  1050.  * Redefine the argument list.
  1051.  */
  1052.     void
  1053. set_arglist(str)
  1054.     char_u    *str;
  1055. {
  1056.     do_arglist(str, AL_SET, 0);
  1057. }
  1058. #endif
  1059.  
  1060. /*
  1061.  * "what" == AL_SET: Redefine the argument list to 'str'.
  1062.  * "what" == AL_ADD: add files in 'str' to the argument list after "after".
  1063.  * "what" == AL_DEL: remove files in 'str' from the argument list.
  1064.  *
  1065.  * Return FAIL for failure, OK otherwise.
  1066.  */
  1067. /*ARGSUSED*/
  1068.     static int
  1069. do_arglist(str, what, after)
  1070.     char_u    *str;
  1071.     int        what;
  1072.     int        after;        /* 0 means before first one */
  1073. {
  1074.     garray_T    new_ga;
  1075.     int        exp_count;
  1076.     char_u    **exp_files;
  1077.     int        i;
  1078. #ifdef FEAT_LISTCMDS
  1079.     char_u    *p;
  1080.     int        match;
  1081. #endif
  1082.  
  1083.     /*
  1084.      * Collect all file name arguments in "new_ga".
  1085.      */
  1086.     ga_init2(&new_ga, (int)sizeof(char_u *), 20);
  1087.     while (*str)
  1088.     {
  1089.     if (ga_grow(&new_ga, 1) == FAIL)
  1090.     {
  1091.         ga_clear(&new_ga);
  1092.         return FAIL;
  1093.     }
  1094.     ((char_u **)new_ga.ga_data)[new_ga.ga_len++] = str;
  1095.     --new_ga.ga_room;
  1096.  
  1097.     /* Isolate one argument, change it in-place, put a NUL after it. */
  1098.     str = do_one_arg(str);
  1099.     }
  1100.  
  1101. #ifdef FEAT_LISTCMDS
  1102.     if (what == AL_DEL)
  1103.     {
  1104.     regmatch_T    regmatch;
  1105.     int        didone;
  1106.  
  1107.     /*
  1108.      * Delete the items: use each item as a regexp and find a match in the
  1109.      * argument list.
  1110.      */
  1111. #ifdef CASE_INSENSITIVE_FILENAME
  1112.     regmatch.rm_ic = TRUE;        /* Always ignore case */
  1113. #else
  1114.     regmatch.rm_ic = FALSE;        /* Never ignore case */
  1115. #endif
  1116.     for (i = 0; i < new_ga.ga_len && !got_int; ++i)
  1117.     {
  1118.         p = ((char_u **)new_ga.ga_data)[i];
  1119.         p = file_pat_to_reg_pat(p, NULL, NULL, FALSE);
  1120.         if (p == NULL)
  1121.         break;
  1122.         regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
  1123.         if (regmatch.regprog == NULL)
  1124.         {
  1125.         vim_free(p);
  1126.         break;
  1127.         }
  1128.  
  1129.         didone = FALSE;
  1130.         for (match = 0; match < ARGCOUNT; ++match)
  1131.         if (vim_regexec(®match, alist_name(&ARGLIST[match]),
  1132.                                   (colnr_T)0))
  1133.         {
  1134.             didone = TRUE;
  1135.             vim_free(ARGLIST[match].ae_fname);
  1136.             mch_memmove(ARGLIST + match, ARGLIST + match + 1,
  1137.                 (ARGCOUNT - match - 1) * sizeof(aentry_T));
  1138.             --ALIST(curwin)->al_ga.ga_len;
  1139.             ++ALIST(curwin)->al_ga.ga_room;
  1140.             if (curwin->w_arg_idx > match)
  1141.             --curwin->w_arg_idx;
  1142.             --match;
  1143.         }
  1144.  
  1145.         vim_free(regmatch.regprog);
  1146.         vim_free(p);
  1147.         if (!didone)
  1148.         EMSG2(_(e_nomatch2), ((char_u **)new_ga.ga_data)[i]);
  1149.     }
  1150.     ga_clear(&new_ga);
  1151.     }
  1152.     else
  1153. #endif
  1154.     {
  1155.     i = expand_wildcards(new_ga.ga_len, (char_u **)new_ga.ga_data,
  1156.         &exp_count, &exp_files, EW_DIR|EW_FILE|EW_ADDSLASH|EW_NOTFOUND);
  1157.     ga_clear(&new_ga);
  1158.     if (i == FAIL)
  1159.         return FAIL;
  1160.     if (exp_count == 0)
  1161.     {
  1162.         EMSG(_(e_nomatch));
  1163.         return FAIL;
  1164.     }
  1165.  
  1166. #ifdef FEAT_LISTCMDS
  1167.     if (what == AL_ADD)
  1168.     {
  1169.         (void)alist_add_list(exp_count, exp_files, after);
  1170.         vim_free(exp_files);
  1171.     }
  1172.     else /* what == AL_SET */
  1173. #endif
  1174.         alist_set(ALIST(curwin), exp_count, exp_files, FALSE);
  1175.     }
  1176.  
  1177.     alist_check_arg_idx();
  1178.  
  1179.     return OK;
  1180. }
  1181.  
  1182. /*
  1183.  * Check the validity of the arg_idx for each other window.
  1184.  */
  1185.     static void
  1186. alist_check_arg_idx()
  1187. {
  1188. #ifdef FEAT_WINDOWS
  1189.     win_T    *win;
  1190.  
  1191.     for (win = firstwin; win != NULL; win = win->w_next)
  1192.     if (win->w_alist == curwin->w_alist)
  1193.         check_arg_idx(win);
  1194. #else
  1195.     check_arg_idx(curwin);
  1196. #endif
  1197. }
  1198.  
  1199. /*
  1200.  * Check if window "win" is editing the w_arg_idx file in its argument list.
  1201.  */
  1202.     void
  1203. check_arg_idx(win)
  1204.     win_T    *win;
  1205. {
  1206.     if (WARGCOUNT(win) > 1
  1207.         && (win->w_arg_idx >= WARGCOUNT(win)
  1208.         || (win->w_buffer->b_fnum
  1209.                       != WARGLIST(win)[win->w_arg_idx].ae_fnum
  1210.             && (win->w_buffer->b_ffname == NULL
  1211.              || !(fullpathcmp(
  1212.                  alist_name(&WARGLIST(win)[win->w_arg_idx]),
  1213.                 win->w_buffer->b_ffname, TRUE) & FPC_SAME)))))
  1214.     {
  1215.     /* We are not editing the current entry in the argument list.
  1216.      * Set "arg_had_last" if we are editing the last one. */
  1217.     win->w_arg_idx_invalid = TRUE;
  1218.     if (win->w_arg_idx != WARGCOUNT(win) - 1
  1219.         && arg_had_last == FALSE
  1220. #ifdef FEAT_WINDOWS
  1221.         && ALIST(win) == &global_alist
  1222. #endif
  1223.         && GARGCOUNT > 0
  1224.         && win->w_arg_idx < GARGCOUNT
  1225.         && (win->w_buffer->b_fnum == GARGLIST[GARGCOUNT - 1].ae_fnum
  1226.             || (win->w_buffer->b_ffname != NULL
  1227.             && (fullpathcmp(alist_name(&GARGLIST[GARGCOUNT - 1]),
  1228.                 win->w_buffer->b_ffname, TRUE) & FPC_SAME))))
  1229.         arg_had_last = TRUE;
  1230.     }
  1231.     else
  1232.     {
  1233.     /* We are editing the current entry in the argument list.
  1234.      * Set "arg_had_last" if it's also the last one */
  1235.     win->w_arg_idx_invalid = FALSE;
  1236.     if (win->w_arg_idx == WARGCOUNT(win) - 1
  1237. #ifdef FEAT_WINDOWS
  1238.         && win->w_alist == &global_alist
  1239. #endif
  1240.         )
  1241.         arg_had_last = TRUE;
  1242.     }
  1243. }
  1244.  
  1245. /*
  1246.  * ":args", ":argslocal" and ":argsglobal".
  1247.  */
  1248.     void
  1249. ex_args(eap)
  1250.     exarg_T    *eap;
  1251. {
  1252.     int        i;
  1253.  
  1254.     if (eap->cmdidx != CMD_args)
  1255.     {
  1256. #if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS)
  1257.     alist_unlink(ALIST(curwin));
  1258.     if (eap->cmdidx == CMD_argglobal)
  1259.         ALIST(curwin) = &global_alist;
  1260.     else /* eap->cmdidx == CMD_arglocal */
  1261.         alist_new();
  1262. #else
  1263.     ex_ni(eap);
  1264.     return;
  1265. #endif
  1266.     }
  1267.  
  1268.     if (!ends_excmd(*eap->arg))
  1269.     {
  1270.     /*
  1271.      * ":args file ..": define new argument list, handle like ":next"
  1272.      * Also for ":argslocal file .." and ":argsglobal file ..".
  1273.      */
  1274.     ex_next(eap);
  1275.     }
  1276.     else
  1277. #if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS)
  1278.     if (eap->cmdidx == CMD_args)
  1279. #endif
  1280.     {
  1281.     /*
  1282.      * ":args": list arguments.
  1283.      */
  1284.     if (ARGCOUNT > 0)
  1285.     {
  1286.         /* Overwrite the command, for a short list there is no scrolling
  1287.          * required and no wait_return(). */
  1288.         gotocmdline(TRUE);
  1289.         for (i = 0; i < ARGCOUNT; ++i)
  1290.         {
  1291.         if (i == curwin->w_arg_idx)
  1292.             msg_putchar('[');
  1293.         msg_outtrans(alist_name(&ARGLIST[i]));
  1294.         if (i == curwin->w_arg_idx)
  1295.             msg_putchar(']');
  1296.         msg_putchar(' ');
  1297.         }
  1298.     }
  1299.     }
  1300. #if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS)
  1301.     else if (eap->cmdidx == CMD_arglocal)
  1302.     {
  1303.     garray_T    *gap = &curwin->w_alist->al_ga;
  1304.  
  1305.     /*
  1306.      * ":argslocal": make a local copy of the global argument list.
  1307.      */
  1308.     if (ga_grow(gap, GARGCOUNT) == OK)
  1309.         for (i = 0; i < GARGCOUNT; ++i)
  1310.         if (GARGLIST[i].ae_fname != NULL)
  1311.         {
  1312.             AARGLIST(curwin->w_alist)[gap->ga_len].ae_fname =
  1313.                         vim_strsave(GARGLIST[i].ae_fname);
  1314.             AARGLIST(curwin->w_alist)[gap->ga_len].ae_fnum =
  1315.                               GARGLIST[i].ae_fnum;
  1316.             ++gap->ga_len;
  1317.             --gap->ga_room;
  1318.         }
  1319.     }
  1320. #endif
  1321. }
  1322.  
  1323. /*
  1324.  * ":previous", ":sprevious", ":Next" and ":sNext".
  1325.  */
  1326.     void
  1327. ex_previous(eap)
  1328.     exarg_T    *eap;
  1329. {
  1330.     /* If past the last one already, go to the last one. */
  1331.     if (curwin->w_arg_idx - (int)eap->line2 >= ARGCOUNT)
  1332.     do_argfile(eap, ARGCOUNT - 1);
  1333.     else
  1334.     do_argfile(eap, curwin->w_arg_idx - (int)eap->line2);
  1335. }
  1336.  
  1337. /*
  1338.  * ":rewind", ":first", ":sfirst" and ":srewind".
  1339.  */
  1340.     void
  1341. ex_rewind(eap)
  1342.     exarg_T    *eap;
  1343. {
  1344.     do_argfile(eap, 0);
  1345. }
  1346.  
  1347. /*
  1348.  * ":last" and ":slast".
  1349.  */
  1350.     void
  1351. ex_last(eap)
  1352.     exarg_T    *eap;
  1353. {
  1354.     do_argfile(eap, ARGCOUNT - 1);
  1355. }
  1356.  
  1357. /*
  1358.  * ":argument" and ":sargument".
  1359.  */
  1360.     void
  1361. ex_argument(eap)
  1362.     exarg_T    *eap;
  1363. {
  1364.     int        i;
  1365.  
  1366.     if (eap->addr_count > 0)
  1367.     i = eap->line2 - 1;
  1368.     else
  1369.     i = curwin->w_arg_idx;
  1370.     do_argfile(eap, i);
  1371. }
  1372.  
  1373. /*
  1374.  * Edit file "argn" of the argument lists.
  1375.  */
  1376.     void
  1377. do_argfile(eap, argn)
  1378.     exarg_T    *eap;
  1379.     int        argn;
  1380. {
  1381.     int        other;
  1382.     char_u    *p;
  1383.  
  1384.     if (argn < 0 || argn >= ARGCOUNT)
  1385.     {
  1386.     if (ARGCOUNT <= 1)
  1387.         EMSG(_("E163: There is only one file to edit"));
  1388.     else if (argn < 0)
  1389.         EMSG(_("E164: Cannot go before first file"));
  1390.     else
  1391.         EMSG(_("E165: Cannot go beyond last file"));
  1392.     }
  1393.     else
  1394.     {
  1395.     setpcmark();
  1396. #ifdef FEAT_GUI
  1397.     need_mouse_correct = TRUE;
  1398. #endif
  1399.  
  1400. #ifdef FEAT_WINDOWS
  1401.     if (*eap->cmd == 's')        /* split window first */
  1402.     {
  1403.         if (win_split(0, 0) == FAIL)
  1404.         return;
  1405. # ifdef FEAT_SCROLLBIND
  1406.         curwin->w_p_scb = FALSE;
  1407. # endif
  1408.     }
  1409.     else
  1410. #endif
  1411.     {
  1412.         /*
  1413.          * if 'hidden' set, only check for changed file when re-editing
  1414.          * the same buffer
  1415.          */
  1416.         other = TRUE;
  1417.         if (P_HID(curbuf))
  1418.         {
  1419.         p = fix_fname(alist_name(&ARGLIST[argn]));
  1420.         other = otherfile(p);
  1421.         vim_free(p);
  1422.         }
  1423.         if ((!P_HID(curbuf) || !other)
  1424.           && check_changed(curbuf, TRUE, !other, eap->forceit, FALSE))
  1425.         return;
  1426.     }
  1427.  
  1428.     curwin->w_arg_idx = argn;
  1429.     if (argn == ARGCOUNT - 1
  1430. #ifdef FEAT_WINDOWS
  1431.         && curwin->w_alist == &global_alist
  1432. #endif
  1433.        )
  1434.         arg_had_last = TRUE;
  1435.  
  1436.     /* Edit the file; always use the last known line number. */
  1437.     (void)do_ecmd(0, alist_name(&ARGLIST[curwin->w_arg_idx]), NULL,
  1438.               eap, ECMD_LAST,
  1439.               (P_HID(curwin->w_buffer) ? ECMD_HIDE : 0) +
  1440.                        (eap->forceit ? ECMD_FORCEIT : 0));
  1441.  
  1442.     /* like Vi: set the mark where the cursor is in the file. */
  1443.     if (eap->cmdidx != CMD_argdo)
  1444.         setmark('\'');
  1445.     }
  1446. }
  1447.  
  1448. /*
  1449.  * ":next", and commands that behave like it.
  1450.  */
  1451.     void
  1452. ex_next(eap)
  1453.     exarg_T    *eap;
  1454. {
  1455.     int        i;
  1456.  
  1457.     /*
  1458.      * check for changed buffer now, if this fails the argument list is not
  1459.      * redefined.
  1460.      */
  1461.     if (       P_HID(curbuf)
  1462.         || eap->cmdidx == CMD_snext
  1463.         || !check_changed(curbuf, TRUE, FALSE, eap->forceit, FALSE))
  1464.     {
  1465.     if (*eap->arg != NUL)            /* redefine file list */
  1466.     {
  1467.         if (do_arglist(eap->arg, AL_SET, 0) == FAIL)
  1468.         return;
  1469.         i = 0;
  1470.     }
  1471.     else
  1472.         i = curwin->w_arg_idx + (int)eap->line2;
  1473.     do_argfile(eap, i);
  1474.     }
  1475. }
  1476.  
  1477. #ifdef FEAT_LISTCMDS
  1478. /*
  1479.  * ":argedit"
  1480.  */
  1481.     void
  1482. ex_argedit(eap)
  1483.     exarg_T    *eap;
  1484. {
  1485.     int        fnum;
  1486.     int        i;
  1487.     char_u    *s;
  1488.  
  1489.     /* Add the argument to the buffer list and get the buffer number. */
  1490.     fnum = buflist_add(eap->arg, BLN_LISTED);
  1491.  
  1492.     /* Check if this argument is already in the argument list. */
  1493.     for (i = 0; i < ARGCOUNT; ++i)
  1494.     if (ARGLIST[i].ae_fnum == fnum)
  1495.         break;
  1496.     if (i == ARGCOUNT)
  1497.     {
  1498.     /* Can't find it, add it to the argument list. */
  1499.     s = vim_strsave(eap->arg);
  1500.     if (s == NULL)
  1501.         return;
  1502.     i = alist_add_list(1, &s,
  1503.            eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1);
  1504.     if (i < 0)
  1505.         return;
  1506.     curwin->w_arg_idx = i;
  1507.     }
  1508.  
  1509.     alist_check_arg_idx();
  1510.  
  1511.     /* Edit the argument. */
  1512.     do_argfile(eap, i);
  1513. }
  1514.  
  1515. /*
  1516.  * ":argadd"
  1517.  */
  1518.     void
  1519. ex_argadd(eap)
  1520.     exarg_T    *eap;
  1521. {
  1522.     do_arglist(eap->arg, AL_ADD,
  1523.            eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1);
  1524. #ifdef FEAT_TITLE
  1525.     maketitle();
  1526. #endif
  1527. }
  1528.  
  1529. /*
  1530.  * ":argdelete"
  1531.  */
  1532.     void
  1533. ex_argdelete(eap)
  1534.     exarg_T    *eap;
  1535. {
  1536.     int        i;
  1537.     int        n;
  1538.  
  1539.     if (eap->addr_count > 0)
  1540.     {
  1541.     /* ":1,4argdel": Delete all arguments in the range. */
  1542.     if (eap->line2 > ARGCOUNT)
  1543.         eap->line2 = ARGCOUNT;
  1544.     n = eap->line2 - eap->line1 + 1;
  1545.     if (*eap->arg != NUL || n <= 0)
  1546.         EMSG(_(e_invarg));
  1547.     else
  1548.     {
  1549.         for (i = eap->line1; i <= eap->line2; ++i)
  1550.         vim_free(ARGLIST[i - 1].ae_fname);
  1551.         mch_memmove(ARGLIST + eap->line1 - 1, ARGLIST + eap->line2,
  1552.             (size_t)((ARGCOUNT - eap->line2) * sizeof(aentry_T)));
  1553.         ALIST(curwin)->al_ga.ga_len -= n;
  1554.         ALIST(curwin)->al_ga.ga_room += n;
  1555.         if (curwin->w_arg_idx >= eap->line2)
  1556.         curwin->w_arg_idx -= n;
  1557.         else if (curwin->w_arg_idx > eap->line1)
  1558.         curwin->w_arg_idx = eap->line1;
  1559.     }
  1560.     }
  1561.     else if (*eap->arg == NUL)
  1562.     EMSG(_(e_argreq));
  1563.     else
  1564.     do_arglist(eap->arg, AL_DEL, 0);
  1565. #ifdef FEAT_TITLE
  1566.     maketitle();
  1567. #endif
  1568. }
  1569.  
  1570. /*
  1571.  * ":argdo", ":windo", ":bufdo"
  1572.  */
  1573.     void
  1574. ex_listdo(eap)
  1575.     exarg_T    *eap;
  1576. {
  1577.     int        i;
  1578. #ifdef FEAT_WINDOWS
  1579.     win_T    *win;
  1580. #endif
  1581.     buf_T    *buf;
  1582.     int        next_fnum = 0;
  1583. #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL)
  1584.     char_u    *save_ei = vim_strsave(p_ei);
  1585.     char_u    *new_ei;
  1586. #endif
  1587.  
  1588. #ifndef FEAT_WINDOWS
  1589.     if (eap->cmdidx == CMD_windo)
  1590.     {
  1591.     ex_ni(eap);
  1592.     return;
  1593.     }
  1594. #endif
  1595.  
  1596. #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL)
  1597.     new_ei = vim_strnsave(p_ei, (int)STRLEN(p_ei) + 8);
  1598.     if (new_ei != NULL)
  1599.     {
  1600.     STRCAT(new_ei, ",Syntax");
  1601.     set_string_option_direct((char_u *)"ei", -1, new_ei, OPT_FREE);
  1602.     vim_free(new_ei);
  1603.     }
  1604. #endif
  1605.  
  1606.     if (eap->cmdidx == CMD_windo
  1607.         || P_HID(curbuf)
  1608.         || !check_changed(curbuf, TRUE, FALSE, eap->forceit, FALSE))
  1609.     {
  1610.     /* start at the first argument/window/buffer */
  1611.     i = 0;
  1612. #ifdef FEAT_WINDOWS
  1613.     win = firstwin;
  1614. #endif
  1615.     /* set pcmark now */
  1616.     if (eap->cmdidx == CMD_bufdo)
  1617.         goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
  1618.     else
  1619.         setpcmark();
  1620.     listcmd_busy = TRUE;        /* avoids setting pcmark below */
  1621.  
  1622.     while (!got_int)
  1623.     {
  1624.         if (eap->cmdidx == CMD_argdo)
  1625.         {
  1626.         /* go to argument "i" */
  1627.         if (i == ARGCOUNT)
  1628.             break;
  1629.         /* Don't call do_argfile() when already there, it will try
  1630.          * reloading the file. */
  1631.         if (curwin->w_arg_idx != i)
  1632.             do_argfile(eap, i);
  1633.         if (curwin->w_arg_idx != i)
  1634.             break;
  1635.         ++i;
  1636.         }
  1637. #ifdef FEAT_WINDOWS
  1638.         else if (eap->cmdidx == CMD_windo)
  1639.         {
  1640.         /* go to window "win" */
  1641.         if (!win_valid(win))
  1642.             break;
  1643.         win_goto(win);
  1644.         win = win->w_next;
  1645.         }
  1646. #endif
  1647.         else if (eap->cmdidx == CMD_bufdo)
  1648.         {
  1649.         /* Remember the number of the next listed buffer, in case
  1650.          * ":bwipe" is used or autocommands do something strange. */
  1651.         next_fnum = -1;
  1652.         for (buf = curbuf->b_next; buf != NULL; buf = buf->b_next)
  1653.             if (buf->b_p_bl)
  1654.             {
  1655.             next_fnum = buf->b_fnum;
  1656.             break;
  1657.             }
  1658.         }
  1659.  
  1660.         /* execute the command */
  1661.         do_cmdline(eap->arg, eap->getline, eap->cookie,
  1662.                         DOCMD_VERBOSE + DOCMD_NOWAIT);
  1663.  
  1664.         if (eap->cmdidx == CMD_bufdo)
  1665.         {
  1666.         /* Done? */
  1667.         if (next_fnum < 0)
  1668.             break;
  1669.         /* Check if the buffer still exists. */
  1670.         for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  1671.             if (buf->b_fnum == next_fnum)
  1672.             break;
  1673.         if (buf == NULL)
  1674.             break;
  1675.         goto_buffer(eap, DOBUF_FIRST, FORWARD, next_fnum);
  1676.         /* If autocommands took us elsewhere, quit here */
  1677.         if (curbuf->b_fnum != next_fnum)
  1678.             break;
  1679.         }
  1680.  
  1681. #ifdef FEAT_SCROLLBIND
  1682.         if (eap->cmdidx == CMD_windo && curwin->w_p_scb)
  1683.         {
  1684.         /* required when 'scrollbind' has been set */
  1685.         validate_cursor();    /* may need to update w_leftcol */
  1686.         do_check_scrollbind(TRUE);
  1687.         }
  1688. #endif
  1689.     }
  1690.     listcmd_busy = FALSE;
  1691.     }
  1692.  
  1693. #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL)
  1694.     if (new_ei != NULL)
  1695.     {
  1696.     set_string_option_direct((char_u *)"ei", -1, save_ei, OPT_FREE);
  1697.     apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn,
  1698.                          curbuf->b_fname, TRUE, curbuf);
  1699.     }
  1700.     vim_free(save_ei);
  1701. #endif
  1702. }
  1703.  
  1704. /*
  1705.  * Add files[count] to the arglist of the current window after arg "after".
  1706.  * The file names in files[count] must have been allocated and are taken over.
  1707.  * Files[] itself is not taken over.
  1708.  * Returns index of first added argument.  Returns -1 when failed (out of mem).
  1709.  */
  1710.     static int
  1711. alist_add_list(count, files, after)
  1712.     int        count;
  1713.     char_u    **files;
  1714.     int        after;        /* where to add: 0 = before first one */
  1715. {
  1716.     int        i;
  1717.  
  1718.     if (ga_grow(&ALIST(curwin)->al_ga, count) == OK)
  1719.     {
  1720.     if (after < 0)
  1721.         after = 0;
  1722.     if (after > ARGCOUNT)
  1723.         after = ARGCOUNT;
  1724.     if (after < ARGCOUNT)
  1725.         mch_memmove(&(ARGLIST[after + count]), &(ARGLIST[after]),
  1726.                        (ARGCOUNT - after) * sizeof(aentry_T));
  1727.     for (i = 0; i < count; ++i)
  1728.     {
  1729.         ARGLIST[after + i].ae_fname = files[i];
  1730.         ARGLIST[after + i].ae_fnum = buflist_add(files[i], BLN_LISTED);
  1731.     }
  1732.     ALIST(curwin)->al_ga.ga_len += count;
  1733.     ALIST(curwin)->al_ga.ga_room -= count;
  1734.     if (curwin->w_arg_idx >= after)
  1735.         ++curwin->w_arg_idx;
  1736.     return after;
  1737.     }
  1738.  
  1739.     for (i = 0; i < count; ++i)
  1740.     vim_free(files[i]);
  1741.     return -1;
  1742. }
  1743.  
  1744. #endif /* FEAT_LISTCMDS */
  1745.  
  1746. #ifdef FEAT_EVAL
  1747. /*
  1748.  * ":compiler {name}"
  1749.  */
  1750.     void
  1751. ex_compiler(eap)
  1752.     exarg_T    *eap;
  1753. {
  1754.     char_u    *buf;
  1755.  
  1756.     if (*eap->arg == NUL)
  1757.     {
  1758.     /* List all compiler scripts. */
  1759.     do_cmdline_cmd((char_u *)"echo globpath(&rtp, 'compiler/*.vim')");
  1760.     }
  1761.     else
  1762.     {
  1763.     buf = alloc((unsigned)(STRLEN(eap->arg) + 14));
  1764.     if (buf != NULL)
  1765.     {
  1766.         do_unlet((char_u *)"current_compiler");
  1767.         sprintf((char *)buf, "compiler/%s.vim", eap->arg);
  1768.         (void)cmd_runtime(buf, TRUE);
  1769.         vim_free(buf);
  1770.     }
  1771.     }
  1772. }
  1773. #endif
  1774.  
  1775. /*
  1776.  * ":runtime {name}"
  1777.  */
  1778.     void
  1779. ex_runtime(eap)
  1780.     exarg_T    *eap;
  1781. {
  1782.     cmd_runtime(eap->arg, eap->forceit);
  1783. }
  1784.  
  1785. static void source_callback __ARGS((char_u *fname));
  1786.  
  1787.     static void
  1788. source_callback(fname)
  1789.     char_u    *fname;
  1790. {
  1791.     (void)do_source(fname, FALSE, FALSE);
  1792. }
  1793.  
  1794. /*
  1795.  * Source the file "name" from all directories in 'runtimepath'.
  1796.  * "name" can contain wildcards.
  1797.  * When "all" is TRUE, source all files, otherwise only the first one.
  1798.  * return FAIL when no file could be sourced, OK otherwise.
  1799.  */
  1800.     int
  1801. cmd_runtime(name, all)
  1802.     char_u    *name;
  1803.     int        all;
  1804. {
  1805.     return do_in_runtimepath(name, all, source_callback);
  1806. }
  1807.  
  1808. /*
  1809.  * Find "name" in 'runtimepath'.  When found, call the "callback" function for
  1810.  * it.
  1811.  * When "all" is TRUE repeat for all matches, otherwise only the first one is
  1812.  * used.
  1813.  * Returns OK when at least one match found, FAIL otherwise.
  1814.  */
  1815.     int
  1816. do_in_runtimepath(name, all, callback)
  1817.     char_u    *name;
  1818.     int        all;
  1819.     void    (*callback)__ARGS((char_u *fname));
  1820. {
  1821.     char_u    *rtp;
  1822.     char_u    *np;
  1823.     char_u    *buf;
  1824.     char_u    *tail;
  1825.     int        num_files;
  1826.     char_u    **files;
  1827.     int        i;
  1828.     int        did_one = FALSE;
  1829. #ifdef AMIGA
  1830.     struct Process    *proc = (struct Process *)FindTask(0L);
  1831.     APTR        save_winptr = proc->pr_WindowPtr;
  1832.  
  1833.     /* Avoid a requester here for a volume that doesn't exist. */
  1834.     proc->pr_WindowPtr = (APTR)-1L;
  1835. #endif
  1836.  
  1837.     buf = alloc(MAXPATHL);
  1838.     if (buf != NULL)
  1839.     {
  1840.     if (p_verbose > 1)
  1841.         smsg((char_u *)_("Searching for \"%s\" in \"%s\""),
  1842.                          (char *)name, (char *)p_rtp);
  1843.     /* Loop over all entries in 'runtimepath'. */
  1844.     rtp = p_rtp;
  1845.     while (*rtp != NUL && (all || !did_one))
  1846.     {
  1847.         /* Copy the path from 'runtimepath' to buf[]. */
  1848.         copy_option_part(&rtp, buf, MAXPATHL, ",");
  1849.         if (STRLEN(buf) + STRLEN(name) + 2 < MAXPATHL)
  1850.         {
  1851.         add_pathsep(buf);
  1852.         tail = buf + STRLEN(buf);
  1853.  
  1854.         /* Loop over all patterns in "name" */
  1855.         np = name;
  1856.         while (*np != NUL && (all || !did_one))
  1857.         {
  1858.             /* Append the pattern from "name" to buf[]. */
  1859.             copy_option_part(&np, tail, (int)(MAXPATHL - (tail - buf)),
  1860.                                        "\t ");
  1861.  
  1862.             if (p_verbose > 2)
  1863.             msg_str((char_u *)_("Searching for \"%s\""), buf);
  1864.  
  1865.             /* Expand wildcards and source each match. */
  1866.             if (gen_expand_wildcards(1, &buf, &num_files, &files,
  1867.                                    EW_FILE) == OK)
  1868.             {
  1869.             for (i = 0; i < num_files; ++i)
  1870.             {
  1871.                 (*callback)(files[i]);
  1872.                 did_one = TRUE;
  1873.                 if (!all)
  1874.                 break;
  1875.             }
  1876.             FreeWild(num_files, files);
  1877.             }
  1878.         }
  1879.         }
  1880.     }
  1881.     vim_free(buf);
  1882.     }
  1883.     if (p_verbose > 0 && !did_one)
  1884.     msg_str((char_u *)_("not found in 'runtimepath': \"%s\""), name);
  1885.  
  1886. #ifdef AMIGA
  1887.     proc->pr_WindowPtr = save_winptr;
  1888. #endif
  1889.  
  1890.     return did_one ? OK : FAIL;
  1891. }
  1892.  
  1893. #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD)
  1894. /*
  1895.  * ":options"
  1896.  */
  1897. /*ARGSUSED*/
  1898.     void
  1899. ex_options(eap)
  1900.     exarg_T    *eap;
  1901. {
  1902.     cmd_source((char_u *)SYS_OPTWIN_FILE, NULL);
  1903. }
  1904. #endif
  1905.  
  1906. /*
  1907.  * ":source {fname}"
  1908.  */
  1909.     void
  1910. ex_source(eap)
  1911.     exarg_T    *eap;
  1912. {
  1913. #ifdef FEAT_BROWSE
  1914.     if (cmdmod.browse)
  1915.     {
  1916.     char_u *fname = NULL;
  1917.  
  1918.     fname = do_browse(FALSE, (char_u *)_("Source Vim script"), eap->arg,
  1919.                       NULL, NULL, BROWSE_FILTER_MACROS, NULL);
  1920.     if (fname != NULL)
  1921.     {
  1922.         cmd_source(fname, eap);
  1923.         vim_free(fname);
  1924.     }
  1925.     }
  1926.     else
  1927. #endif
  1928.     cmd_source(eap->arg, eap);
  1929. }
  1930.  
  1931.     static void
  1932. cmd_source(fname, eap)
  1933.     char_u    *fname;
  1934.     exarg_T    *eap;
  1935. {
  1936.     if (*fname == NUL)
  1937.     EMSG(_(e_argreq));
  1938.  
  1939.     /* ":source!" read vi commands */
  1940.     else if (eap != NULL && eap->forceit)
  1941.     /* Need to execute the commands directly when:
  1942.      * - ":g" command busy
  1943.      * - after ":argdo", ":windo" or ":bufdo"
  1944.      * - another command follows
  1945.      * - inside a loop
  1946.      */
  1947.     openscript(fname, global_busy || listcmd_busy || eap->nextcmd != NULL
  1948. #ifdef FEAT_EVAL
  1949.                          || eap->cstack->cs_idx >= 0
  1950. #endif
  1951.                          );
  1952.  
  1953.     /* ":source" read ex commands */
  1954.     else if (do_source(fname, FALSE, FALSE) == FAIL)
  1955.     EMSG2(_(e_notopen), fname);
  1956. }
  1957.  
  1958. /*
  1959.  * ":source" and associated commands.
  1960.  */
  1961. /*
  1962.  * Structure used to store info for each sourced file.
  1963.  * It is shared between do_source() and getsourceline().
  1964.  * This is required, because it needs to be handed to do_cmdline() and
  1965.  * sourcing can be done recursively.
  1966.  */
  1967. struct source_cookie
  1968. {
  1969.     FILE    *fp;        /* opened file for sourcing */
  1970.     char_u      *nextline;      /* if not NULL: line that was read ahead */
  1971.     int        finished;    /* ":finish" used */
  1972. #if defined (USE_CRNL) || defined (USE_CR)
  1973.     int        fileformat;    /* EOL_UNKNOWN, EOL_UNIX or EOL_DOS */
  1974.     int        error;        /* TRUE if LF found after CR-LF */
  1975. #endif
  1976. #ifdef FEAT_EVAL
  1977.     linenr_T    breakpoint;    /* next line with breakpoint or zero */
  1978.     char_u    *fname;        /* name of sourced file */
  1979.     int        dbg_tick;    /* debug_tick when breakpoint was set */
  1980.     int        level;        /* top nesting level of sourced file */
  1981. #endif
  1982. #ifdef FEAT_MBYTE
  1983.     vimconv_T    conv;        /* type of conversion */
  1984. #endif
  1985. };
  1986.  
  1987. #ifdef FEAT_EVAL
  1988. /*
  1989.  * Return the nesting level for a source cookie.
  1990.  */
  1991.     int
  1992. source_level(cookie)
  1993.     void *cookie;
  1994. {
  1995.     return ((struct source_cookie *)cookie)->level;
  1996. }
  1997. #endif
  1998.  
  1999. static char_u *get_one_sourceline __ARGS((struct source_cookie *sp));
  2000.  
  2001. #ifdef FEAT_EVAL
  2002. /* Growarray to store the names of sourced scripts.
  2003.  * For Unix also store the dev/ino, so that we don't have to stat() each
  2004.  * script when going through the list. */
  2005. struct scriptstuff
  2006. {
  2007.     char_u    *name;
  2008. # ifdef UNIX
  2009.     int        dev;
  2010.     ino_t    ino;
  2011. # endif
  2012. };
  2013. static garray_T script_names = {0, 0, sizeof(struct scriptstuff), 4, NULL};
  2014. #define SCRIPT_NAME(id) (((struct scriptstuff *)script_names.ga_data)[(id) - 1].name)
  2015. #define SCRIPT_DEV(id) (((struct scriptstuff *)script_names.ga_data)[(id) - 1].dev)
  2016. #define SCRIPT_INO(id) (((struct scriptstuff *)script_names.ga_data)[(id) - 1].ino)
  2017. #endif
  2018.  
  2019. /*
  2020.  * do_source: Read the file "fname" and execute its lines as EX commands.
  2021.  *
  2022.  * This function may be called recursively!
  2023.  *
  2024.  * return FAIL if file could not be opened, OK otherwise
  2025.  */
  2026.     int
  2027. do_source(fname, check_other, is_vimrc)
  2028.     char_u    *fname;
  2029.     int        check_other;        /* check for .vimrc and _vimrc */
  2030.     int        is_vimrc;        /* call vimrc_found() when file exists */
  2031. {
  2032.     struct source_cookie    cookie;
  2033.     char_u            *save_sourcing_name;
  2034.     linenr_T            save_sourcing_lnum;
  2035.     char_u            *p;
  2036.     char_u            *fname_exp;
  2037.     int                retval = FAIL;
  2038. #ifdef FEAT_EVAL
  2039.     scid_T            save_current_SID;
  2040.     static scid_T        last_current_SID = 0;
  2041.     void            *save_funccalp;
  2042.     int                save_debug_break_level = debug_break_level;
  2043. # ifdef UNIX
  2044.     struct stat            st;
  2045.     int                stat_ok;
  2046. # endif
  2047. #endif
  2048. #ifdef STARTUPTIME
  2049.     struct timeval        tv_rel;
  2050.     struct timeval        tv_start;
  2051. #endif
  2052.  
  2053. #ifdef RISCOS
  2054.     p = mch_munge_fname(fname);
  2055. #else
  2056.     p = expand_env_save(fname);
  2057. #endif
  2058.     if (p == NULL)
  2059.     return retval;
  2060.     fname_exp = fix_fname(p);
  2061.     vim_free(p);
  2062.     if (fname_exp == NULL)
  2063.     return retval;
  2064. #ifdef MACOS_CLASSIC
  2065.     slash_n_colon_adjust(fname_exp);
  2066. #endif
  2067.     if (mch_isdir(fname_exp))
  2068.     {
  2069.     msg_str((char_u *)_("Cannot source a directory: \"%s\""), fname);
  2070.     goto theend;
  2071.     }
  2072.  
  2073.     cookie.fp = mch_fopen((char *)fname_exp, READBIN);
  2074.     if (cookie.fp == NULL && check_other)
  2075.     {
  2076.     /*
  2077.      * Try again, replacing file name ".vimrc" by "_vimrc" or vice versa,
  2078.      * and ".exrc" by "_exrc" or vice versa.
  2079.      */
  2080.     p = gettail(fname_exp);
  2081.     if ((*p == '.' || *p == '_')
  2082.         && (STRICMP(p + 1, "vimrc") == 0
  2083.             || STRICMP(p + 1, "gvimrc") == 0
  2084.             || STRICMP(p + 1, "exrc") == 0))
  2085.     {
  2086.         if (*p == '_')
  2087.         *p = '.';
  2088.         else
  2089.         *p = '_';
  2090.         cookie.fp = mch_fopen((char *)fname_exp, READBIN);
  2091.     }
  2092.     }
  2093.  
  2094.     if (cookie.fp == NULL)
  2095.     {
  2096.     if (p_verbose > 0)
  2097.     {
  2098.         if (sourcing_name == NULL)
  2099.         msg_str((char_u *)_("could not source \"%s\""), fname);
  2100.         else
  2101.         smsg((char_u *)_("line %ld: could not source \"%s\""),
  2102.             sourcing_lnum, fname);
  2103.     }
  2104.     goto theend;
  2105.     }
  2106.  
  2107.     /*
  2108.      * The file exists.
  2109.      * - In verbose mode, give a message.
  2110.      * - For a vimrc file, may want to set 'compatible', call vimrc_found().
  2111.      */
  2112.     if (p_verbose > 1)
  2113.     {
  2114.     if (sourcing_name == NULL)
  2115.         msg_str((char_u *)_("sourcing \"%s\""), fname);
  2116.     else
  2117.         smsg((char_u *)_("line %ld: sourcing \"%s\""),
  2118.             sourcing_lnum, fname);
  2119.     }
  2120.     if (is_vimrc)
  2121.     vimrc_found();
  2122.  
  2123. #ifdef USE_CRNL
  2124.     /* If no automatic file format: Set default to CR-NL. */
  2125.     if (*p_ffs == NUL)
  2126.     cookie.fileformat = EOL_DOS;
  2127.     else
  2128.     cookie.fileformat = EOL_UNKNOWN;
  2129.     cookie.error = FALSE;
  2130. #endif
  2131.  
  2132. #ifdef USE_CR
  2133.     /* If no automatic file format: Set default to CR. */
  2134.     if (*p_ffs == NUL)
  2135.     cookie.fileformat = EOL_MAC;
  2136.     else
  2137.     cookie.fileformat = EOL_UNKNOWN;
  2138.     cookie.error = FALSE;
  2139. #endif
  2140.  
  2141.     cookie.nextline = NULL;
  2142.     cookie.finished = FALSE;
  2143.  
  2144. #ifdef FEAT_EVAL
  2145.     /*
  2146.      * Check if this script has a breakpoint.
  2147.      */
  2148.     cookie.breakpoint = dbg_find_breakpoint(TRUE, fname_exp, (linenr_T)0);
  2149.     cookie.fname = fname_exp;
  2150.     cookie.dbg_tick = debug_tick;
  2151.  
  2152.     cookie.level = ex_nesting_level;
  2153. #endif
  2154. #ifdef FEAT_MBYTE
  2155.     cookie.conv.vc_type = CONV_NONE;        /* no conversion */
  2156. #endif
  2157.  
  2158.     /*
  2159.      * Keep the sourcing name/lnum, for recursive calls.
  2160.      */
  2161.     save_sourcing_name = sourcing_name;
  2162.     sourcing_name = fname_exp;
  2163.     save_sourcing_lnum = sourcing_lnum;
  2164.     sourcing_lnum = 0;
  2165.  
  2166. #ifdef STARTUPTIME
  2167.     time_push(&tv_rel, &tv_start);
  2168. #endif
  2169.  
  2170. #ifdef FEAT_EVAL
  2171.     /*
  2172.      * Check if this script was sourced before to finds its SID.
  2173.      * If it's new, generate a new SID.
  2174.      */
  2175.     save_current_SID = current_SID;
  2176. # ifdef UNIX
  2177.     stat_ok = (mch_stat((char *)fname_exp, &st) >= 0);
  2178. # endif
  2179.     for (current_SID = script_names.ga_len; current_SID > 0; --current_SID)
  2180.     if (SCRIPT_NAME(current_SID) != NULL
  2181.         && (
  2182. # ifdef UNIX
  2183.             /* compare dev/ino when possible, it catches symbolic
  2184.              * links */
  2185.             (stat_ok && SCRIPT_DEV(current_SID) != -1)
  2186.             ? (SCRIPT_DEV(current_SID) == st.st_dev
  2187.                 && SCRIPT_INO(current_SID) == st.st_ino) :
  2188. # endif
  2189.         fnamecmp(SCRIPT_NAME(current_SID), fname_exp) == 0))
  2190.         break;
  2191.     if (current_SID == 0)
  2192.     {
  2193.     current_SID = ++last_current_SID;
  2194.     if (ga_grow(&script_names, (int)(current_SID - script_names.ga_len))
  2195.                                     == OK)
  2196.     {
  2197.         while (script_names.ga_len < current_SID)
  2198.         {
  2199.         SCRIPT_NAME(script_names.ga_len + 1) = NULL;
  2200.         ++script_names.ga_len;
  2201.         --script_names.ga_room;
  2202.         }
  2203.         SCRIPT_NAME(current_SID) = fname_exp;
  2204. # ifdef UNIX
  2205.         if (stat_ok)
  2206.         {
  2207.         SCRIPT_DEV(current_SID) = st.st_dev;
  2208.         SCRIPT_INO(current_SID) = st.st_ino;
  2209.         }
  2210.         else
  2211.         SCRIPT_DEV(current_SID) = -1;
  2212. # endif
  2213.         fname_exp = NULL;
  2214.     }
  2215.     /* Allocate the local script variables to use for this script. */
  2216.     new_script_vars(current_SID);
  2217.     }
  2218.  
  2219.     /* Don't use local function variables, if called from a function */
  2220.     save_funccalp = save_funccal();
  2221. #endif
  2222.  
  2223.     /*
  2224.      * Call do_cmdline, which will call getsourceline() to get the lines.
  2225.      */
  2226.     do_cmdline(NULL, getsourceline, (void *)&cookie,
  2227.                      DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_REPEAT);
  2228.  
  2229.     retval = OK;
  2230.     fclose(cookie.fp);
  2231.     vim_free(cookie.nextline);
  2232.     if (got_int)
  2233.     EMSG(_(e_interr));
  2234.     sourcing_name = save_sourcing_name;
  2235.     sourcing_lnum = save_sourcing_lnum;
  2236. #ifdef FEAT_EVAL
  2237.     current_SID = save_current_SID;
  2238.     restore_funccal(save_funccalp);
  2239. #endif
  2240.     if (p_verbose > 1)
  2241.     {
  2242.     msg_str((char_u *)_("finished sourcing %s"), fname);
  2243.     if (sourcing_name != NULL)
  2244.         msg_str((char_u *)_("continuing in %s"), sourcing_name);
  2245.     }
  2246. #ifdef STARTUPTIME
  2247. # ifdef HAVE_SNPRINTF
  2248.     snprintf(IObuff, IOSIZE, "sourcing %s", fname);
  2249. # else
  2250.     sprintf(IObuff, "sourcing %s", fname);
  2251. # endif
  2252.     time_msg(IObuff, &tv_start);
  2253.     time_pop(&tv_rel);
  2254. #endif
  2255.  
  2256. #ifdef FEAT_EVAL
  2257.     /*
  2258.      * After a "finish" in debug mode, need to break at first command of next
  2259.      * sourced file.
  2260.      */
  2261.     if (save_debug_break_level > ex_nesting_level
  2262.         && debug_break_level == ex_nesting_level)
  2263.     ++debug_break_level;
  2264. #endif
  2265.  
  2266. theend:
  2267.     vim_free(fname_exp);
  2268.     return retval;
  2269. }
  2270.  
  2271. #if defined(FEAT_EVAL) || defined(PROTO)
  2272. /*
  2273.  * ":scriptnames"
  2274.  */
  2275. /*ARGSUSED*/
  2276.     void
  2277. ex_scriptnames(eap)
  2278.     exarg_T    *eap;
  2279. {
  2280.     int i;
  2281.  
  2282.     for (i = 1; i <= script_names.ga_len && !got_int; ++i)
  2283.     if (SCRIPT_NAME(i) != NULL)
  2284.         smsg((char_u *)"%3d: %s", i, SCRIPT_NAME(i));
  2285. }
  2286.  
  2287. # if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
  2288. /*
  2289.  * Fix slashes in the list of script names for 'shellslash'.
  2290.  */
  2291.     void
  2292. scriptnames_slash_adjust()
  2293. {
  2294.     int i;
  2295.  
  2296.     for (i = 1; i <= script_names.ga_len; ++i)
  2297.     if (SCRIPT_NAME(i) != NULL)
  2298.         slash_adjust(SCRIPT_NAME(i));
  2299. }
  2300. # endif
  2301.  
  2302. /*
  2303.  * Get a pointer to a script name.  Used for ":verbose set".
  2304.  */
  2305.     char_u *
  2306. get_scriptname(id)
  2307.     scid_T    id;
  2308. {
  2309.     if (id == SID_MODELINE)
  2310.     return (char_u *)"modeline";
  2311.     return SCRIPT_NAME(id);
  2312. }
  2313. #endif
  2314.  
  2315. #if defined(USE_CR) || defined(PROTO)
  2316.  
  2317. # if defined(__MSL__) && (__MSL__ >= 22)
  2318. /*
  2319.  * Newer version of the Metrowerks library handle DOS and UNIX files
  2320.  * without help.
  2321.  * Test with earlier versions, MSL 2.2 is the library supplied with
  2322.  * Codewarrior Pro 2.
  2323.  */
  2324.     char *
  2325. fgets_cr(s, n, stream)
  2326.     char    *s;
  2327.     int        n;
  2328.     FILE    *stream;
  2329. {
  2330.     return fgets(s, n, stream);
  2331. }
  2332. # else
  2333. /*
  2334.  * Version of fgets() which also works for lines ending in a <CR> only
  2335.  * (Macintosh format).
  2336.  * For older versions of the Metrowerks library.
  2337.  * At least CodeWarrior 9 needed this code.
  2338.  */
  2339.     char *
  2340. fgets_cr(s, n, stream)
  2341.     char    *s;
  2342.     int        n;
  2343.     FILE    *stream;
  2344. {
  2345.     int    c = 0;
  2346.     int char_read = 0;
  2347.  
  2348.     while (!feof(stream) && c != '\r' && c != '\n' && char_read < n - 1)
  2349.     {
  2350.     c = fgetc(stream);
  2351.     s[char_read++] = c;
  2352.     /* If the file is in DOS format, we need to skip a NL after a CR.  I
  2353.      * thought it was the other way around, but this appears to work... */
  2354.     if (c == '\n')
  2355.     {
  2356.         c = fgetc(stream);
  2357.         if (c != '\r')
  2358.         ungetc(c, stream);
  2359.     }
  2360.     }
  2361.  
  2362.     s[char_read] = 0;
  2363.     if (char_read == 0)
  2364.     return NULL;
  2365.  
  2366.     if (feof(stream) && char_read == 1)
  2367.     return NULL;
  2368.  
  2369.     return s;
  2370. }
  2371. # endif
  2372. #endif
  2373.  
  2374. /*
  2375.  * Get one full line from a sourced file.
  2376.  * Called by do_cmdline() when it's called from do_source().
  2377.  *
  2378.  * Return a pointer to the line in allocated memory.
  2379.  * Return NULL for end-of-file or some error.
  2380.  */
  2381. /* ARGSUSED */
  2382.     char_u *
  2383. getsourceline(c, cookie, indent)
  2384.     int        c;        /* not used */
  2385.     void    *cookie;
  2386.     int        indent;        /* not used */
  2387. {
  2388.     struct source_cookie *sp = (struct source_cookie *)cookie;
  2389.     char_u        *line;
  2390.     char_u        *p, *s;
  2391.  
  2392. #ifdef FEAT_EVAL
  2393.     /* If breakpoints have been added/deleted need to check for it. */
  2394.     if (sp->dbg_tick < debug_tick)
  2395.     {
  2396.     sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, sourcing_lnum);
  2397.     sp->dbg_tick = debug_tick;
  2398.     }
  2399. #endif
  2400.     /*
  2401.      * Get current line.  If there is a read-ahead line, use it, otherwise get
  2402.      * one now.
  2403.      */
  2404.     if (sp->finished)
  2405.     line = NULL;
  2406.     else if (sp->nextline == NULL)
  2407.     line = get_one_sourceline(sp);
  2408.     else
  2409.     {
  2410.     line = sp->nextline;
  2411.     sp->nextline = NULL;
  2412.     ++sourcing_lnum;
  2413.     }
  2414.  
  2415.     /* Only concatenate lines starting with a \ when 'cpoptions' doesn't
  2416.      * contain the 'C' flag. */
  2417.     if (line != NULL && (vim_strchr(p_cpo, CPO_CONCAT) == NULL))
  2418.     {
  2419.     /* compensate for the one line read-ahead */
  2420.     --sourcing_lnum;
  2421.     for (;;)
  2422.     {
  2423.         sp->nextline = get_one_sourceline(sp);
  2424.         if (sp->nextline == NULL)
  2425.         break;
  2426.         p = skipwhite(sp->nextline);
  2427.         if (*p != '\\')
  2428.         break;
  2429.         s = alloc((int)(STRLEN(line) + STRLEN(p)));
  2430.         if (s == NULL)    /* out of memory */
  2431.         break;
  2432.         STRCPY(s, line);
  2433.         STRCAT(s, p + 1);
  2434.         vim_free(line);
  2435.         line = s;
  2436.         vim_free(sp->nextline);
  2437.     }
  2438.     }
  2439.  
  2440. #ifdef FEAT_MBYTE
  2441.     if (line != NULL && sp->conv.vc_type != CONV_NONE)
  2442.     {
  2443.     /* Convert the encoding of the script line. */
  2444.     s = string_convert(&sp->conv, line, NULL);
  2445.     if (s != NULL)
  2446.     {
  2447.         vim_free(line);
  2448.         line = s;
  2449.     }
  2450.     }
  2451. #endif
  2452.  
  2453. #ifdef FEAT_EVAL
  2454.     /* Did we encounter a breakpoint? */
  2455.     if (sp->breakpoint != 0 && sp->breakpoint <= sourcing_lnum)
  2456.     {
  2457.     dbg_breakpoint(sp->fname, sourcing_lnum);
  2458.     /* Find next breakpoint. */
  2459.     sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, sourcing_lnum);
  2460.     sp->dbg_tick = debug_tick;
  2461.     }
  2462. #endif
  2463.  
  2464.     return line;
  2465. }
  2466.  
  2467.     static char_u *
  2468. get_one_sourceline(sp)
  2469.     struct source_cookie    *sp;
  2470. {
  2471.     garray_T        ga;
  2472.     int            len;
  2473.     int            c;
  2474.     char_u        *buf;
  2475. #ifdef USE_CRNL
  2476.     int            has_cr;        /* CR-LF found */
  2477. #endif
  2478. #ifdef USE_CR
  2479.     char_u        *scan;
  2480. #endif
  2481.     int            have_read = FALSE;
  2482.  
  2483.     /* use a growarray to store the sourced line */
  2484.     ga_init2(&ga, 1, 200);
  2485.  
  2486.     /*
  2487.      * Loop until there is a finished line (or end-of-file).
  2488.      */
  2489.     sourcing_lnum++;
  2490.     for (;;)
  2491.     {
  2492.     /* make room to read at least 80 (more) characters */
  2493.     if (ga_grow(&ga, 80) == FAIL)
  2494.         break;
  2495.     buf = (char_u *)ga.ga_data;
  2496.  
  2497. #ifdef USE_CR
  2498.     if (sp->fileformat == EOL_MAC)
  2499.     {
  2500.         if (fgets_cr((char *)buf + ga.ga_len, ga.ga_room, sp->fp) == NULL)
  2501.         break;
  2502.     }
  2503.     else
  2504. #endif
  2505.         if (fgets((char *)buf + ga.ga_len, ga.ga_room, sp->fp) == NULL)
  2506.         break;
  2507.     len = (int)STRLEN(buf);
  2508. #ifdef USE_CRNL
  2509.     /* Ignore a trailing CTRL-Z, when in Dos mode.    Only recognize the
  2510.      * CTRL-Z by its own, or after a NL. */
  2511.     if (       (len == 1 || (len >= 2 && buf[len - 2] == '\n'))
  2512.         && sp->fileformat == EOL_DOS
  2513.         && buf[len - 1] == Ctrl_Z)
  2514.     {
  2515.         buf[len - 1] = NUL;
  2516.         break;
  2517.     }
  2518. #endif
  2519.  
  2520. #ifdef USE_CR
  2521.     /* If the read doesn't stop on a new line, and there's
  2522.      * some CR then we assume a Mac format */
  2523.     if (sp->fileformat == EOL_UNKNOWN)
  2524.     {
  2525.         if (buf[len - 1] != '\n' && vim_strchr(buf, '\r') != NULL)
  2526.         sp->fileformat = EOL_MAC;
  2527.         else
  2528.         sp->fileformat = EOL_UNIX;
  2529.     }
  2530.  
  2531.     if (sp->fileformat == EOL_MAC)
  2532.     {
  2533.         scan = vim_strchr(buf, '\r');
  2534.  
  2535.         if (scan != NULL)
  2536.         {
  2537.         *scan = '\n';
  2538.         if (*(scan + 1) != 0)
  2539.         {
  2540.             *(scan + 1) = 0;
  2541.             fseek(sp->fp, (long)(scan - buf - len + 1), SEEK_CUR);
  2542.         }
  2543.         }
  2544.         len = STRLEN(buf);
  2545.     }
  2546. #endif
  2547.  
  2548.     have_read = TRUE;
  2549.     ga.ga_room -= len - ga.ga_len;
  2550.     ga.ga_len = len;
  2551.  
  2552.     /* If the line was longer than the buffer, read more. */
  2553.     if (ga.ga_room == 1 && buf[len - 1] != '\n')
  2554.         continue;
  2555.  
  2556.     if (len >= 1 && buf[len - 1] == '\n')    /* remove trailing NL */
  2557.     {
  2558. #ifdef USE_CRNL
  2559.         has_cr = (len >= 2 && buf[len - 2] == '\r');
  2560.         if (sp->fileformat == EOL_UNKNOWN)
  2561.         {
  2562.         if (has_cr)
  2563.             sp->fileformat = EOL_DOS;
  2564.         else
  2565.             sp->fileformat = EOL_UNIX;
  2566.         }
  2567.  
  2568.         if (sp->fileformat == EOL_DOS)
  2569.         {
  2570.         if (has_cr)        /* replace trailing CR */
  2571.         {
  2572.             buf[len - 2] = '\n';
  2573.             --len;
  2574.             --ga.ga_len;
  2575.             ++ga.ga_room;
  2576.         }
  2577.         else        /* lines like ":map xx yy^M" will have failed */
  2578.         {
  2579.             if (!sp->error)
  2580.             EMSG(_("W15: Warning: Wrong line separator, ^M may be missing"));
  2581.             sp->error = TRUE;
  2582.             sp->fileformat = EOL_UNIX;
  2583.         }
  2584.         }
  2585. #endif
  2586.         /* The '\n' is escaped if there is an odd number of ^V's just
  2587.          * before it, first set "c" just before the 'V's and then check
  2588.          * len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo */
  2589.         for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)
  2590.         ;
  2591.         if ((len & 1) != (c & 1))    /* escaped NL, read more */
  2592.         {
  2593.         sourcing_lnum++;
  2594.         continue;
  2595.         }
  2596.  
  2597.         buf[len - 1] = NUL;        /* remove the NL */
  2598.     }
  2599.  
  2600.     /*
  2601.      * Check for ^C here now and then, so recursive :so can be broken.
  2602.      */
  2603.     line_breakcheck();
  2604.     break;
  2605.     }
  2606.  
  2607.     if (have_read)
  2608.     return (char_u *)ga.ga_data;
  2609.  
  2610.     vim_free(ga.ga_data);
  2611.     return NULL;
  2612. }
  2613.  
  2614. /*
  2615.  * ":scriptencoding": Set encoding conversion for a sourced script.
  2616.  * Without the multi-byte feature it's simply ignored.
  2617.  */
  2618. /*ARGSUSED*/
  2619.     void
  2620. ex_scriptencoding(eap)
  2621.     exarg_T    *eap;
  2622. {
  2623. #ifdef FEAT_MBYTE
  2624.     struct source_cookie    *sp;
  2625.     char_u            *name;
  2626.  
  2627.     if (eap->getline != getsourceline)
  2628.     {
  2629.     EMSG(_("E167: :scriptencoding used outside of a sourced file"));
  2630.     return;
  2631.     }
  2632.  
  2633.     if (*eap->arg != NUL)
  2634.     {
  2635.     name = enc_canonize(eap->arg);
  2636.     if (name == NULL)    /* out of memory */
  2637.         return;
  2638.     }
  2639.     else
  2640.     name = eap->arg;
  2641.  
  2642.     /* Setup for conversion from the specified encoding to 'encoding'. */
  2643.     sp = (struct source_cookie *)eap->cookie;
  2644.     convert_setup(&sp->conv, name, p_enc);
  2645.  
  2646.     if (name != eap->arg)
  2647.     vim_free(name);
  2648. #endif
  2649. }
  2650.  
  2651. #if defined(FEAT_EVAL) || defined(PROTO)
  2652. /*
  2653.  * ":finish": Mark a sourced file as finished.
  2654.  */
  2655.     void
  2656. ex_finish(eap)
  2657.     exarg_T    *eap;
  2658. {
  2659.     if (eap->getline == getsourceline)
  2660.     do_finish(eap, FALSE);
  2661.     else
  2662.     EMSG(_("E168: :finish used outside of a sourced file"));
  2663. }
  2664.  
  2665. /*
  2666.  * Mark a sourced file as finished.  Possibly makes the ":finish" pending.
  2667.  * Also called for a pending finish at the ":endtry" or after returning from
  2668.  * an extra do_cmdline().  "reanimate" is used in the latter case.
  2669.  */
  2670.     void
  2671. do_finish(eap, reanimate)
  2672.     exarg_T    *eap;
  2673.     int        reanimate;
  2674. {
  2675.     int        idx;
  2676.  
  2677.     if (reanimate)
  2678.     ((struct source_cookie *)eap->cookie)->finished = FALSE;
  2679.  
  2680.     /*
  2681.      * Cleanup (and inactivate) conditionals, but stop when a try conditional
  2682.      * not in its finally clause (which then is to be executed next) is found.
  2683.      * In this case, make the ":finish" pending for execution at the ":endtry".
  2684.      * Otherwise, finish normally.
  2685.      */
  2686.     idx = cleanup_conditionals(eap->cstack, 0, TRUE);
  2687.     if (idx >= 0)
  2688.     {
  2689.     eap->cstack->cs_pending[idx] = CSTP_FINISH;
  2690.     report_make_pending(CSTP_FINISH, NULL);
  2691.     }
  2692.     else
  2693.     ((struct source_cookie *)eap->cookie)->finished = TRUE;
  2694. }
  2695.  
  2696.  
  2697. /*
  2698.  * Return TRUE when a sourced file had the ":finish" command: Don't give error
  2699.  * message for missing ":endif".
  2700.  */
  2701.     int
  2702. source_finished(cookie)
  2703.     void    *cookie;
  2704. {
  2705.     return ((struct source_cookie *)cookie)->finished == TRUE;
  2706. }
  2707. #endif
  2708.  
  2709. #if defined(FEAT_LISTCMDS) || defined(PROTO)
  2710. /*
  2711.  * ":checktime [buffer]"
  2712.  */
  2713.     void
  2714. ex_checktime(eap)
  2715.     exarg_T    *eap;
  2716. {
  2717.     buf_T    *buf;
  2718.     int        save_no_check_timestamps = no_check_timestamps;
  2719.  
  2720.     no_check_timestamps = 0;
  2721.     if (eap->addr_count == 0)    /* default is all buffers */
  2722.     check_timestamps(FALSE);
  2723.     else
  2724.     {
  2725.     buf = buflist_findnr((int)eap->line2);
  2726.     if (buf != NULL)    /* cannot happen? */
  2727.         (void)buf_check_timestamp(buf, FALSE);
  2728.     }
  2729.     no_check_timestamps = save_no_check_timestamps;
  2730. }
  2731. #endif
  2732.  
  2733. #if defined(FEAT_PRINTER) || defined(PROTO)
  2734. /*
  2735.  * Printing code (Machine-independent.)
  2736.  * To implement printing on a platform, the following functions must be
  2737.  * defined:
  2738.  *
  2739.  * int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
  2740.  * Called once.  Code should display printer dialogue (if appropriate) and
  2741.  * determine printer font and margin settings.  Reset has_color if the printer
  2742.  * doesn't support colors at all.
  2743.  * Returns FAIL to abort.
  2744.  *
  2745.  * int mch_print_begin(prt_settings_T *settings)
  2746.  * Called to start the print job.
  2747.  * Return FALSE to abort.
  2748.  *
  2749.  * int mch_print_begin_page(char_u *msg)
  2750.  * Called at the start of each page.
  2751.  * "msg" indicates the progress of the print job, can be NULL.
  2752.  * Return FALSE to abort.
  2753.  *
  2754.  * int mch_print_end_page()
  2755.  * Called at the end of each page.
  2756.  * Return FALSE to abort.
  2757.  *
  2758.  * int mch_print_blank_page()
  2759.  * Called to generate a blank page for collated, duplex, multiple copy
  2760.  * document.  Return FALSE to abort.
  2761.  *
  2762.  * void mch_print_end(prt_settings_T *psettings)
  2763.  * Called at normal end of print job.
  2764.  *
  2765.  * void mch_print_cleanup()
  2766.  * Called if print job ends normally or is abandoned. Free any memory, close
  2767.  * devices and handles.  Also called when mch_print_begin() fails, but not
  2768.  * when mch_print_init() fails.
  2769.  *
  2770.  * void mch_print_set_font(int Bold, int Italic, int Underline);
  2771.  * Called whenever the font style changes.
  2772.  *
  2773.  * void mch_print_set_bg(long bgcol);
  2774.  * Called to set the background color for the following text. Parameter is an
  2775.  * RGB value.
  2776.  *
  2777.  * void mch_print_set_fg(long fgcol);
  2778.  * Called to set the foreground color for the following text. Parameter is an
  2779.  * RGB value.
  2780.  *
  2781.  * mch_print_start_line(int margin, int page_line)
  2782.  * Sets the current position at the start of line "page_line".
  2783.  * If margin is TRUE start in the left margin (for header and line number).
  2784.  *
  2785.  * int mch_print_text_out(char_u *p, int len);
  2786.  * Output one character of text p[len] at the current position.
  2787.  * Return TRUE if there is no room for another character in the same line.
  2788.  *
  2789.  * Note that the generic code has no idea of margins. The machine code should
  2790.  * simply make the page look smaller!  The header and the line numbers are
  2791.  * printed in the margin.
  2792.  */
  2793.  
  2794. #ifdef FEAT_SYN_HL
  2795. static const long_u  cterm_color_8[8] =
  2796. {
  2797.     (long_u)0x000000L, (long_u)0xff0000L, (long_u)0x00ff00L, (long_u)0xffff00L,
  2798.     (long_u)0x0000ffL, (long_u)0xff00ffL, (long_u)0x00ffffL, (long_u)0xffffffL
  2799. };
  2800.  
  2801. static const long_u  cterm_color_16[16] =
  2802. {
  2803.     (long_u)0x000000L, (long_u)0x0000c0L, (long_u)0x008000L, (long_u)0x004080L,
  2804.     (long_u)0xc00000L, (long_u)0xc000c0L, (long_u)0x808000L, (long_u)0xc0c0c0L,
  2805.     (long_u)0x808080L, (long_u)0x6060ffL, (long_u)0x00ff00L, (long_u)0x00ffffL,
  2806.     (long_u)0xff8080L, (long_u)0xff40ffL, (long_u)0xffff00L, (long_u)0xffffffL
  2807. };
  2808.  
  2809. static int        current_syn_id;
  2810. #endif
  2811.  
  2812. #define PRCOLOR_BLACK    (long_u)0
  2813. #define PRCOLOR_WHITE    (long_u)0xFFFFFFL
  2814.  
  2815. static int    curr_italic;
  2816. static int    curr_bold;
  2817. static int    curr_underline;
  2818. static long_u    curr_bg;
  2819. static long_u    curr_fg;
  2820. static int    page_count;
  2821.  
  2822. /*
  2823.  * These values determine the print position on a page.
  2824.  */
  2825. typedef struct
  2826. {
  2827.     int        lead_spaces;        /* remaining spaces for a TAB */
  2828.     int        print_pos;        /* virtual column for computing TABs */
  2829.     colnr_T    column;            /* byte column */
  2830.     linenr_T    file_line;        /* line nr in the buffer */
  2831.     long_u    bytes_printed;        /* bytes printed so far */
  2832.     int        ff;            /* seen form feed character */
  2833. } prt_pos_T;
  2834.  
  2835. #ifdef FEAT_SYN_HL
  2836. static long_u darken_rgb __ARGS((long_u rgb));
  2837. static long_u prt_get_term_color __ARGS((int colorindex));
  2838. #endif
  2839. static void prt_set_fg __ARGS((long_u fg));
  2840. static void prt_set_bg __ARGS((long_u bg));
  2841. static void prt_set_font __ARGS((int bold, int italic, int underline));
  2842. static void prt_line_number __ARGS((prt_settings_T *psettings, int page_line, linenr_T lnum));
  2843. static void prt_header __ARGS((prt_settings_T *psettings, int pagenum, linenr_T lnum));
  2844. static void prt_message __ARGS((char_u *s));
  2845. static colnr_T hardcopy_line __ARGS((prt_settings_T *psettings, int page_line, prt_pos_T *ppos));
  2846. static void prt_get_attr __ARGS((int hl_id, prt_text_attr_T* pattr, int modec));
  2847.  
  2848. #ifdef FEAT_SYN_HL
  2849. /*
  2850.  * If using a dark background, the colors will probably be too bright to show
  2851.  * up well on white paper, so reduce their brightness.
  2852.  */
  2853.     static long_u
  2854. darken_rgb(rgb)
  2855.     long_u    rgb;
  2856. {
  2857.     return    ((rgb >> 17) << 16)
  2858.         +    (((rgb & 0xff00) >> 9) << 8)
  2859.         +    ((rgb & 0xff) >> 1);
  2860. }
  2861.  
  2862.     static long_u
  2863. prt_get_term_color(colorindex)
  2864.     int        colorindex;
  2865. {
  2866.     /* TODO: Should check for xterm with 88 or 256 colors. */
  2867.     if (t_colors > 8)
  2868.     return cterm_color_16[colorindex % 16];
  2869.     return cterm_color_8[colorindex % 8];
  2870. }
  2871.  
  2872.     static void
  2873. prt_get_attr(hl_id, pattr, modec)
  2874.     int            hl_id;
  2875.     prt_text_attr_T*    pattr;
  2876.     int            modec;
  2877. {
  2878.     int     colorindex;
  2879.     long_u  fg_color;
  2880.     long_u  bg_color;
  2881.     char    *color;
  2882.  
  2883.     pattr->bold = (highlight_has_attr(hl_id, HL_BOLD, modec) != NULL);
  2884.     pattr->italic = (highlight_has_attr(hl_id, HL_ITALIC, modec) != NULL);
  2885.     pattr->underline = (highlight_has_attr(hl_id, HL_UNDERLINE, modec) != NULL);
  2886.  
  2887. # ifdef FEAT_GUI
  2888.     if (gui.in_use)
  2889.     {
  2890.     bg_color = highlight_gui_color_rgb(hl_id, FALSE);
  2891.     if (bg_color == PRCOLOR_BLACK)
  2892.         bg_color = PRCOLOR_WHITE;
  2893.  
  2894.     fg_color = highlight_gui_color_rgb(hl_id, TRUE);
  2895.     }
  2896.     else
  2897. # endif
  2898.     {
  2899.     bg_color = PRCOLOR_WHITE;
  2900.  
  2901.     color = (char *)highlight_color(hl_id, (char_u *)"fg", modec);
  2902.     if (color == NULL)
  2903.         colorindex = 0;
  2904.     else
  2905.         colorindex = atoi(color);
  2906.  
  2907.     if (colorindex >= 0 && colorindex < t_colors)
  2908.         fg_color = prt_get_term_color(colorindex);
  2909.     else
  2910.         fg_color = PRCOLOR_BLACK;
  2911.     }
  2912.  
  2913.     if (fg_color == PRCOLOR_WHITE)
  2914.     fg_color = PRCOLOR_BLACK;
  2915.     else if (*p_bg == 'd')
  2916.     fg_color = darken_rgb(fg_color);
  2917.  
  2918.     pattr->fg_color = fg_color;
  2919.     pattr->bg_color = bg_color;
  2920. }
  2921. #endif /* FEAT_SYN_HL */
  2922.  
  2923.     static void
  2924. prt_set_fg(fg)
  2925.     long_u fg;
  2926. {
  2927.     if (fg != curr_fg)
  2928.     {
  2929.     curr_fg = fg;
  2930.     mch_print_set_fg(fg);
  2931.     }
  2932. }
  2933.  
  2934.     static void
  2935. prt_set_bg(bg)
  2936.     long_u bg;
  2937. {
  2938.     if (bg != curr_bg)
  2939.     {
  2940.     curr_bg = bg;
  2941.     mch_print_set_bg(bg);
  2942.     }
  2943. }
  2944.  
  2945.     static void
  2946. prt_set_font(bold, italic, underline)
  2947.     int        bold;
  2948.     int        italic;
  2949.     int        underline;
  2950. {
  2951.     if (curr_bold != bold
  2952.         || curr_italic != italic
  2953.         || curr_underline != underline)
  2954.     {
  2955.     curr_underline = underline;
  2956.     curr_italic = italic;
  2957.     curr_bold = bold;
  2958.     mch_print_set_font(bold, italic, underline);
  2959.     }
  2960. }
  2961.  
  2962. /*
  2963.  * Print the line number in the left margin.
  2964.  */
  2965.     static void
  2966. prt_line_number(psettings, page_line, lnum)
  2967.     prt_settings_T *psettings;
  2968.     int        page_line;
  2969.     linenr_T    lnum;
  2970. {
  2971.     int        i;
  2972.     char_u    tbuf[20];
  2973.  
  2974.     prt_set_fg(psettings->number.fg_color);
  2975.     prt_set_bg(psettings->number.bg_color);
  2976.     prt_set_font(psettings->number.bold, psettings->number.italic, psettings->number.underline);
  2977.     mch_print_start_line(TRUE, page_line);
  2978.  
  2979.     /* Leave two spaces between the number and the text; depends on
  2980.      * PRINT_NUMBER_WIDTH. */
  2981.     sprintf((char *)tbuf, "%6ld", (long)lnum);
  2982.     for (i = 0; i < 6; i++)
  2983.     (void)mch_print_text_out(&tbuf[i], 1);
  2984.  
  2985. #ifdef FEAT_SYN_HL
  2986.     if (psettings->do_syntax)
  2987.     /* Set colors for next character. */
  2988.     current_syn_id = -1;
  2989.     else
  2990. #endif
  2991.     {
  2992.     /* Set colors and font back to normal. */
  2993.     prt_set_fg(PRCOLOR_BLACK);
  2994.     prt_set_bg(PRCOLOR_WHITE);
  2995.     prt_set_font(FALSE, FALSE, FALSE);
  2996.     }
  2997. }
  2998.  
  2999. static linenr_T printer_page_num;
  3000.  
  3001.     int
  3002. get_printer_page_num()
  3003. {
  3004.     return printer_page_num;
  3005. }
  3006.  
  3007. /*
  3008.  * Get the currently effective header height.
  3009.  */
  3010.     int
  3011. prt_header_height()
  3012. {
  3013.     if (printer_opts[OPT_PRINT_HEADERHEIGHT].present)
  3014.     return printer_opts[OPT_PRINT_HEADERHEIGHT].number;
  3015.     return 2;
  3016. }
  3017.  
  3018. /*
  3019.  * Return TRUE if using a line number for printing.
  3020.  */
  3021.     int
  3022. prt_use_number()
  3023. {
  3024.     return (printer_opts[OPT_PRINT_NUMBER].present
  3025.         && TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y');
  3026. }
  3027.  
  3028. /*
  3029.  * Return the unit used in a margin item in 'printoptions'.
  3030.  * Returns PRT_UNIT_NONE if not recognized.
  3031.  */
  3032.     int
  3033. prt_get_unit(idx)
  3034.     int        idx;
  3035. {
  3036.     int        u = PRT_UNIT_NONE;
  3037.     int        i;
  3038.     static char *(units[4]) = PRT_UNIT_NAMES;
  3039.  
  3040.     if (printer_opts[idx].present)
  3041.     for (i = 0; i < 4; ++i)
  3042.         if (STRNICMP(printer_opts[idx].string, units[i], 2) == 0)
  3043.         {
  3044.         u = i;
  3045.         break;
  3046.         }
  3047.     return u;
  3048. }
  3049.  
  3050. /*
  3051.  * Print the page header.
  3052.  */
  3053. /*ARGSUSED*/
  3054.     static void
  3055. prt_header(psettings, pagenum, lnum)
  3056.     prt_settings_T  *psettings;
  3057.     int        pagenum;
  3058.     linenr_T    lnum;
  3059. {
  3060.     int        width = psettings->chars_per_line;
  3061.     int        page_line;
  3062.     char_u    *tbuf;
  3063.     char_u    *p;
  3064. #ifdef FEAT_MBYTE
  3065.     int        l;
  3066. #endif
  3067.  
  3068.     /* Also use the space for the line number. */
  3069.     if (prt_use_number())
  3070.     width += PRINT_NUMBER_WIDTH;
  3071.  
  3072.     tbuf = alloc(width + IOSIZE);
  3073.     if (tbuf == NULL)
  3074.     return;
  3075.  
  3076. #ifdef FEAT_STL_OPT
  3077.     if (*p_header != NUL)
  3078.     {
  3079.     linenr_T    tmp_lnum, tmp_topline, tmp_botline;
  3080.  
  3081.     /*
  3082.      * Need to (temporarily) set current line number and first/last line
  3083.      * number on the 'window'.  Since we don't know how long the page is,
  3084.      * set the first and current line number to the top line, and guess
  3085.      * that the page length is 64.
  3086.      */
  3087.     tmp_lnum = curwin->w_cursor.lnum;
  3088.     tmp_topline = curwin->w_topline;
  3089.     tmp_botline = curwin->w_botline;
  3090.     curwin->w_cursor.lnum = lnum;
  3091.     curwin->w_topline = lnum;
  3092.     curwin->w_botline = lnum + 63;
  3093.     printer_page_num = pagenum;
  3094.  
  3095.     build_stl_str_hl(curwin, tbuf, (size_t)(width + IOSIZE),
  3096.                           p_header, ' ', width, NULL);
  3097.  
  3098.     /* Reset line numbers */
  3099.     curwin->w_cursor.lnum = tmp_lnum;
  3100.     curwin->w_topline = tmp_topline;
  3101.     curwin->w_botline = tmp_botline;
  3102.     }
  3103.     else
  3104. #endif
  3105.     sprintf((char *)tbuf, _("Page %d"), pagenum);
  3106.  
  3107.     prt_set_fg(PRCOLOR_BLACK);
  3108.     prt_set_bg(PRCOLOR_WHITE);
  3109.     prt_set_font(TRUE, FALSE, FALSE);
  3110.  
  3111.     /* Use a negative line number to indicate printing in the top margin. */
  3112.     page_line = 0 - prt_header_height();
  3113.     mch_print_start_line(TRUE, page_line);
  3114.     for (p = tbuf; *p != NUL; )
  3115.     {
  3116.     if (mch_print_text_out(p,
  3117. #ifdef FEAT_MBYTE
  3118.         (l = (*mb_ptr2len_check)(p))
  3119. #else
  3120.         1
  3121. #endif
  3122.             ))
  3123.     {
  3124.         ++page_line;
  3125.         if (page_line >= 0) /* out of room in header */
  3126.         break;
  3127.         mch_print_start_line(TRUE, page_line);
  3128.     }
  3129. #ifdef FEAT_MBYTE
  3130.     p += l;
  3131. #else
  3132.     p++;
  3133. #endif
  3134.     }
  3135.  
  3136.     vim_free(tbuf);
  3137.  
  3138. #ifdef FEAT_SYN_HL
  3139.     if (psettings->do_syntax)
  3140.     /* Set colors for next character. */
  3141.     current_syn_id = -1;
  3142.     else
  3143. #endif
  3144.     {
  3145.     /* Set colors and font back to normal. */
  3146.     prt_set_fg(PRCOLOR_BLACK);
  3147.     prt_set_bg(PRCOLOR_WHITE);
  3148.     prt_set_font(FALSE, FALSE, FALSE);
  3149.     }
  3150. }
  3151.  
  3152. /*
  3153.  * Display a print status message.
  3154.  */
  3155.     static void
  3156. prt_message(s)
  3157.     char_u    *s;
  3158. {
  3159.     screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
  3160.     screen_puts(s, (int)Rows - 1, 0, hl_attr(HLF_R));
  3161.     out_flush();
  3162. }
  3163.  
  3164.     void
  3165. ex_hardcopy(eap)
  3166.     exarg_T    *eap;
  3167. {
  3168.     linenr_T        lnum;
  3169.     int            collated_copies, uncollated_copies;
  3170.     prt_settings_T    settings;
  3171.     long_u        bytes_to_print = 0;
  3172.     int            page_line;
  3173.     int            jobsplit;
  3174.     int            id;
  3175.  
  3176.     memset(&settings, 0, sizeof(prt_settings_T));
  3177.     settings.has_color = TRUE;
  3178.  
  3179. # ifdef FEAT_POSTSCRIPT
  3180.     if (*eap->arg == '>')
  3181.     {
  3182.     char_u    *errormsg = NULL;
  3183.  
  3184.     /* Expand things like "%.ps". */
  3185.     if (expand_filename(eap, eap->cmdlinep, &errormsg) == FAIL)
  3186.     {
  3187.         if (errormsg != NULL)
  3188.         EMSG(errormsg);
  3189.         return;
  3190.     }
  3191.     settings.outfile = skipwhite(eap->arg + 1);
  3192.     }
  3193.     else if (*eap->arg != NUL)
  3194.     settings.arguments = eap->arg;
  3195. # endif
  3196.  
  3197.     /*
  3198.      * Initialise for printing.  Ask the user for settings, unless forceit is
  3199.      * set.
  3200.      * The mch_print_init() code should set up margins if applicable. (It may
  3201.      * not be a real printer - for example the engine might generate HTML or
  3202.      * PS.)
  3203.      */
  3204.     if (mch_print_init(&settings,
  3205.             curbuf->b_fname == NULL
  3206.                 ? (char_u *)buf_spname(curbuf)
  3207.                 : curbuf->b_sfname == NULL
  3208.                 ? curbuf->b_fname
  3209.                 : curbuf->b_sfname,
  3210.             eap->forceit) == FAIL)
  3211.     return;
  3212.  
  3213. #ifdef FEAT_SYN_HL
  3214. # ifdef  FEAT_GUI
  3215.     if (gui.in_use)
  3216.     settings.modec = 'g';
  3217.     else
  3218. # endif
  3219.     if (t_colors > 1)
  3220.         settings.modec = 'c';
  3221.     else
  3222.         settings.modec = 't';
  3223.  
  3224.     if (!syntax_present(curbuf))
  3225.     settings.do_syntax = FALSE;
  3226.     else if (printer_opts[OPT_PRINT_SYNTAX].present
  3227.         && TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) != 'a')
  3228.     settings.do_syntax =
  3229.            (TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) == 'y');
  3230.     else
  3231.     settings.do_syntax = settings.has_color;
  3232. #endif
  3233.  
  3234.     /* Set up printing attributes for line numbers */
  3235.     settings.number.fg_color = PRCOLOR_BLACK;
  3236.     settings.number.bg_color = PRCOLOR_WHITE;
  3237.     settings.number.bold = FALSE;
  3238.     settings.number.italic = TRUE;
  3239.     settings.number.underline = FALSE;
  3240. #ifdef FEAT_SYN_HL
  3241.     /*
  3242.      * Syntax highlighting of line numbers.
  3243.      */
  3244.     if (prt_use_number() && settings.do_syntax)
  3245.     {
  3246.     id = syn_name2id((char_u *)"LineNr");
  3247.     if (id > 0)
  3248.         id = syn_get_final_id(id);
  3249.  
  3250.     prt_get_attr(id, &settings.number, settings.modec);
  3251.     }
  3252. #endif /* FEAT_SYN_HL */
  3253.  
  3254.     /*
  3255.      * Estimate the total lines to be printed
  3256.      */
  3257.     for (lnum = eap->line1; lnum <= eap->line2; lnum++)
  3258.     bytes_to_print += (long_u)STRLEN(skipwhite(ml_get(lnum)));
  3259.     if (bytes_to_print == 0)
  3260.     {
  3261.     MSG(_("No text to be printed"));
  3262.     goto print_fail_no_begin;
  3263.     }
  3264.  
  3265.     /* Set colors and font to normal. */
  3266.     curr_bg = (long_u)0xffffffffL;
  3267.     curr_fg = (long_u)0xffffffffL;
  3268.     curr_italic = MAYBE;
  3269.     curr_bold = MAYBE;
  3270.     curr_underline = MAYBE;
  3271.  
  3272.     prt_set_fg(PRCOLOR_BLACK);
  3273.     prt_set_bg(PRCOLOR_WHITE);
  3274.     prt_set_font(FALSE, FALSE, FALSE);
  3275. #ifdef FEAT_SYN_HL
  3276.     current_syn_id = -1;
  3277. #endif
  3278.  
  3279.     jobsplit = (printer_opts[OPT_PRINT_JOBSPLIT].present
  3280.        && TOLOWER_ASC(printer_opts[OPT_PRINT_JOBSPLIT].string[0]) == 'y');
  3281.  
  3282.     if (!mch_print_begin(&settings))
  3283.     goto print_fail_no_begin;
  3284.  
  3285.     /*
  3286.      * Loop over collated copies: 1 2 3, 1 2 3, ...
  3287.      */
  3288.     page_count = 0;
  3289.     for (collated_copies = 0;
  3290.         collated_copies < settings.n_collated_copies;
  3291.         collated_copies++)
  3292.     {
  3293.     prt_pos_T    prtpos;        /* current print position */
  3294.     prt_pos_T    page_prtpos;    /* print position at page start */
  3295.     int        side;
  3296.  
  3297.     memset(&page_prtpos, 0, sizeof(prt_pos_T));
  3298.     page_prtpos.file_line = eap->line1;
  3299.     prtpos = page_prtpos;
  3300.  
  3301.     if (jobsplit && collated_copies > 0)
  3302.     {
  3303.         /* Splitting jobs: Stop a previous job and start a new one. */
  3304.         mch_print_end(&settings);
  3305.         if (!mch_print_begin(&settings))
  3306.         goto print_fail_no_begin;
  3307.     }
  3308.  
  3309.     /*
  3310.      * Loop over all pages in the print job: 1 2 3 ...
  3311.      */
  3312.     for (page_count = 0; prtpos.file_line <= eap->line2; ++page_count)
  3313.     {
  3314.         /*
  3315.          * Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ...
  3316.          * For duplex: 12 12 12 34 34 34, ...
  3317.          */
  3318.         for (uncollated_copies = 0;
  3319.             uncollated_copies < settings.n_uncollated_copies;
  3320.             uncollated_copies++)
  3321.         {
  3322.         /* Set the print position to the start of this page. */
  3323.         prtpos = page_prtpos;
  3324.  
  3325.         /*
  3326.          * Do front and rear side of a page.
  3327.          */
  3328.         for (side = 0; side <= settings.duplex; ++side)
  3329.         {
  3330.             /*
  3331.              * Print one page.
  3332.              */
  3333.  
  3334.             /* Check for interrupt character every page. */
  3335.             ui_breakcheck();
  3336.             if (got_int || settings.user_abort)
  3337.             goto print_fail;
  3338.  
  3339.             sprintf((char *)IObuff, _("Printing page %d (%d%%)"),
  3340.                 page_count + 1 + side,
  3341.                 (int)((prtpos.bytes_printed * 100)
  3342.                                / bytes_to_print));
  3343.             if (!mch_print_begin_page(IObuff))
  3344.             goto print_fail;
  3345.  
  3346.             if (settings.n_collated_copies > 1)
  3347.             sprintf((char *)IObuff + STRLEN(IObuff),
  3348.                 _(" Copy %d of %d"),
  3349.                 collated_copies + 1,
  3350.                 settings.n_collated_copies);
  3351.             prt_message(IObuff);
  3352.  
  3353.             /*
  3354.              * Output header if required
  3355.              */
  3356.             if (prt_header_height() > 0)
  3357.             prt_header(&settings, page_count + 1 + side,
  3358.                             prtpos.file_line);
  3359.  
  3360.             for (page_line = 0; page_line < settings.lines_per_page;
  3361.                                   ++page_line)
  3362.             {
  3363.             prtpos.column = hardcopy_line(&settings,
  3364.                                page_line, &prtpos);
  3365.             if (prtpos.column == 0)
  3366.             {
  3367.                 /* finished a file line */
  3368.                 prtpos.bytes_printed +=
  3369.                   STRLEN(skipwhite(ml_get(prtpos.file_line)));
  3370.                 if (++prtpos.file_line > eap->line2)
  3371.                 break; /* reached the end */
  3372.             }
  3373.             else if (prtpos.ff)
  3374.             {
  3375.                 /* Line had a formfeed in it - start new page but
  3376.                  * stay on the current line */
  3377.                 break;
  3378.             }
  3379.             }
  3380.  
  3381.             if (!mch_print_end_page())
  3382.             goto print_fail;
  3383.             if (prtpos.file_line > eap->line2)
  3384.             break; /* reached the end */
  3385.         }
  3386.  
  3387.         /*
  3388.          * Extra blank page for duplexing with odd number of pages and
  3389.          * more copies to come.
  3390.          */
  3391.         if (prtpos.file_line > eap->line2 && settings.duplex
  3392.                                  && side == 0
  3393.             && uncollated_copies + 1 < settings.n_uncollated_copies)
  3394.         {
  3395.             if (!mch_print_blank_page())
  3396.             goto print_fail;
  3397.         }
  3398.         }
  3399.         if (settings.duplex && prtpos.file_line <= eap->line2)
  3400.         ++page_count;
  3401.  
  3402.         /* Remember the position where the next page starts. */
  3403.         page_prtpos = prtpos;
  3404.     }
  3405.  
  3406.     sprintf((char *)IObuff, _("Printed: %s"), settings.jobname);
  3407.     prt_message(IObuff);
  3408.     }
  3409.  
  3410. print_fail:
  3411.     if (got_int || settings.user_abort)
  3412.     {
  3413.     sprintf((char *)IObuff, _("Printing aborted"));
  3414.     prt_message(IObuff);
  3415.     }
  3416.     mch_print_end(&settings);
  3417.  
  3418. print_fail_no_begin:
  3419.     mch_print_cleanup();
  3420. }
  3421.  
  3422. /*
  3423.  * Print one page line.
  3424.  * Return the next column to print, or zero if the line is finished.
  3425.  */
  3426.     static colnr_T
  3427. hardcopy_line(psettings, page_line, ppos)
  3428.     prt_settings_T    *psettings;
  3429.     int            page_line;
  3430.     prt_pos_T        *ppos;
  3431. {
  3432.     colnr_T    col;
  3433.     char_u    *line;
  3434.     int        need_break = FALSE;
  3435.     int        outputlen;
  3436.     int        tab_spaces;
  3437.     long_u    print_pos;
  3438. #ifdef FEAT_SYN_HL
  3439.     prt_text_attr_T attr;
  3440.     int        id;
  3441. #endif
  3442.  
  3443.     if (ppos->column == 0 || ppos->ff)
  3444.     {
  3445.     print_pos = 0;
  3446.     tab_spaces = 0;
  3447.     if (!ppos->ff && prt_use_number())
  3448.         prt_line_number(psettings, page_line, ppos->file_line);
  3449.     ppos->ff = FALSE;
  3450.     }
  3451.     else
  3452.     {
  3453.     /* left over from wrap halfway a tab */
  3454.     print_pos = ppos->print_pos;
  3455.     tab_spaces = ppos->lead_spaces;
  3456.     }
  3457.  
  3458.     mch_print_start_line(0, page_line);
  3459.     line = ml_get(ppos->file_line);
  3460.  
  3461.     /*
  3462.      * Loop over the columns until the end of the file line or right margin.
  3463.      */
  3464.     for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen)
  3465.     {
  3466.     outputlen = 1;
  3467. #ifdef FEAT_MBYTE
  3468.     if (has_mbyte && (outputlen = (*mb_ptr2len_check)(line + col)) < 1)
  3469.         outputlen = 1;
  3470. #endif
  3471. #ifdef FEAT_SYN_HL
  3472.     /*
  3473.      * syntax highlighting stuff.
  3474.      */
  3475.     if (psettings->do_syntax)
  3476.     {
  3477.         id = syn_get_id(ppos->file_line, (long)col, 1);
  3478.         if (id > 0)
  3479.         id = syn_get_final_id(id);
  3480.         else
  3481.         id = 0;
  3482.         /* Get the line again, a multi-line regexp may invalidate it. */
  3483.         line = ml_get(ppos->file_line);
  3484.  
  3485.         if (id != current_syn_id)
  3486.         {
  3487.         current_syn_id = id;
  3488.         prt_get_attr(id, &attr, psettings->modec);
  3489.         prt_set_font(attr.bold, attr.italic, attr.underline);
  3490.         prt_set_fg(attr.fg_color);
  3491.         prt_set_bg(attr.bg_color);
  3492.         }
  3493.     }
  3494. #endif /* FEAT_SYN_HL */
  3495.  
  3496.     /*
  3497.      * Appropriately expand any tabs to spaces.
  3498.      */
  3499.     if (line[col] == TAB || tab_spaces != 0)
  3500.     {
  3501.         if (tab_spaces == 0)
  3502.         tab_spaces = curbuf->b_p_ts - (print_pos % curbuf->b_p_ts);
  3503.  
  3504.         while (tab_spaces > 0)
  3505.         {
  3506.         need_break = mch_print_text_out((char_u *)" ", 1);
  3507.         print_pos++;
  3508.         tab_spaces--;
  3509.         if (need_break)
  3510.             break;
  3511.         }
  3512.         /* Keep the TAB if we didn't finish it. */
  3513.         if (need_break && tab_spaces > 0)
  3514.         break;
  3515.     }
  3516.     else if (line[col] == FF
  3517.         && printer_opts[OPT_PRINT_FORMFEED].present
  3518.         && TOLOWER_ASC(printer_opts[OPT_PRINT_FORMFEED].string[0])
  3519.                                        == 'y')
  3520.     {
  3521.         ppos->ff = TRUE;
  3522.         need_break = 1;
  3523.     }
  3524.     else
  3525.     {
  3526.         need_break = mch_print_text_out(line + col, outputlen);
  3527. #ifdef FEAT_MBYTE
  3528.         if (has_mbyte)
  3529.         print_pos += (*mb_ptr2cells)(line + col);
  3530.         else
  3531. #endif
  3532.         print_pos++;
  3533.     }
  3534.     }
  3535.  
  3536.     ppos->lead_spaces = tab_spaces;
  3537.     ppos->print_pos = print_pos;
  3538.  
  3539.     /*
  3540.      * Start next line of file if we clip lines, or have reached end of the
  3541.      * line, unless we are doing a formfeed.
  3542.      */
  3543.     if (!ppos->ff
  3544.         && (line[col] == NUL
  3545.         || (printer_opts[OPT_PRINT_WRAP].present
  3546.             && TOLOWER_ASC(printer_opts[OPT_PRINT_WRAP].string[0])
  3547.                                      == 'n')))
  3548.     return 0;
  3549.     return col;
  3550. }
  3551.  
  3552. # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
  3553.  
  3554. /*
  3555.  * PS printer stuff.
  3556.  *
  3557.  * Sources of information to help maintain the PS printing code:
  3558.  *
  3559.  * 1. PostScript Language Reference, 3rd Edition,
  3560.  *      Addison-Wesley, 1999, ISBN 0-201-37922-8
  3561.  * 2. PostScript Language Program Design,
  3562.  *      Addison-Wesley, 1988, ISBN 0-201-14396-8
  3563.  * 3. PostScript Tutorial and Cookbook,
  3564.  *      Addison Wesley, 1985, ISBN 0-201-10179-3
  3565.  * 4. PostScript Language Document Structuring Conventions Specification,
  3566.  *    version 3.0,
  3567.  *      Adobe Technote 5001, 25th September 1992
  3568.  * 5. PostScript Printer Description File Format Specification, Version 4.3,
  3569.  *      Adobe technote 5003, 9th February 1996
  3570.  * 6. Adobe Font Metrics File Format Specification, Version 4.1,
  3571.  *      Adobe Technote 5007, 7th October 1998
  3572.  *
  3573.  * Some of these documents can be found in PDF form on Adobe's web site -
  3574.  * http://www.adobe.com
  3575.  */
  3576.  
  3577. #define PRT_PS_DEFAULT_DPI        (72)    /* Default user space resolution */
  3578. #define PRT_PS_DEFAULT_FONTSIZE     (10)
  3579. #define PRT_PS_DEFAULT_BUFFER_SIZE  (80)
  3580.  
  3581. struct prt_mediasize_S
  3582. {
  3583.     char    *name;
  3584.     float    width;        /* width and height in points for portrait */
  3585.     float    height;
  3586. };
  3587.  
  3588. #define PRT_MEDIASIZE_LEN  (sizeof(prt_mediasize) / sizeof(struct prt_mediasize_S))
  3589.  
  3590. static struct prt_mediasize_S prt_mediasize[] =
  3591. {
  3592.     {"A4",        595.0,  842.0},
  3593.     {"letter",        612.0,  792.0},
  3594.     {"10x14",        720.0, 1008.0},
  3595.     {"A3",        842.0, 1191.0},
  3596.     {"A5",        420.0,  595.0},
  3597.     {"B4",        729.0, 1032.0},
  3598.     {"B5",        516.0,  729.0},
  3599.     {"executive",    522.0,  756.0},
  3600.     {"folio",        595.0,  935.0},
  3601.     {"ledger",           1224.0,  792.0},   /* Yes, it is wider than taller! */
  3602.     {"legal",        612.0, 1008.0},
  3603.     {"quarto",        610.0,  780.0},
  3604.     {"statement",    396.0,  612.0},
  3605.     {"tabloid",        792.0, 1224.0}
  3606. };
  3607.  
  3608. /* PS font names, must be in Roman, Bold, Italic, Bold-Italic order */
  3609. struct prt_ps_font_S
  3610. {
  3611.     int        wx;
  3612.     int        uline_offset;
  3613.     int        uline_width;
  3614.     int        bbox_min_y;
  3615.     int        bbox_max_y;
  3616.     char    *(ps_fontname[4]);
  3617. };
  3618.  
  3619. #define PRT_PS_FONT_ROMAN    (0)
  3620. #define PRT_PS_FONT_BOLD    (1)
  3621. #define PRT_PS_FONT_OBLIQUE    (2)
  3622. #define PRT_PS_FONT_BOLDOBLIQUE (3)
  3623.  
  3624. static struct prt_ps_font_S prt_ps_font =
  3625. {
  3626.     600,
  3627.     -100, 50,
  3628.     -250, 805,
  3629.     {"Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique"}
  3630. };
  3631.  
  3632. struct prt_ps_resource_S
  3633. {
  3634.     char_u  name[64];
  3635.     char_u  filename[MAXPATHL + 1];
  3636.     int     type;
  3637.     char_u  title[256];
  3638.     char_u  version[256];
  3639. };
  3640.  
  3641. /* Types of PS resource file currently used */
  3642. #define PRT_RESOURCE_TYPE_PROCSET   (0)
  3643. #define PRT_RESOURCE_TYPE_ENCODING  (1)
  3644.  
  3645. /* The PS prolog file version number has to match - if the prolog file is
  3646.  * updated, increment the number in the file and here.  Version checking was
  3647.  * added as of VIM 6.2.
  3648.  * Table of VIM and prolog versions:
  3649.  *
  3650.  * VIM      Prolog
  3651.  * 6.2      1.3
  3652.  */
  3653. #define PRT_PROLOG_VERSION  ((char_u *)"1.3")
  3654.  
  3655. /* String versions of PS resource types - indexed by constants above so don't
  3656.  * re-order!
  3657.  */
  3658. static char *resource_types[] =
  3659. {
  3660.     "procset",
  3661.     "encoding"
  3662. };
  3663.  
  3664. /* Strings to look for in a PS resource file */
  3665. #define PRT_RESOURCE_HEADER        "%!PS-Adobe-"
  3666. #define PRT_RESOURCE_RESOURCE        "Resource-"
  3667. #define PRT_RESOURCE_PROCSET        "ProcSet"
  3668. #define PRT_RESOURCE_ENCODING        "Encoding"
  3669. #define PRT_RESOURCE_TITLE        "%%Title:"
  3670. #define PRT_RESOURCE_VERSION        "%%Version:"
  3671.  
  3672. static void prt_write_file_raw_len __ARGS((char_u *buffer, int bytes));
  3673. static void prt_write_file __ARGS((char_u *buffer));
  3674. static void prt_write_file_len __ARGS((char_u *buffer, int bytes));
  3675. static void prt_write_string __ARGS((char *s));
  3676. static void prt_write_int __ARGS((int i));
  3677. static void prt_write_boolean __ARGS((int b));
  3678. static void prt_def_font __ARGS((char *new_name, char *encoding, int height, char *font));
  3679. static void prt_real_bits __ARGS((double real, int precision, int *pinteger, int *pfraction));
  3680. static void prt_write_real __ARGS((double val, int prec));
  3681. static void prt_def_var __ARGS((char *name, double value, int prec));
  3682. static void prt_flush_buffer __ARGS((void));
  3683. static void prt_resource_name __ARGS((char_u *filename));
  3684. static int prt_find_resource __ARGS((char *name, struct prt_ps_resource_S *resource));
  3685. static int prt_open_resource __ARGS((struct prt_ps_resource_S *resource));
  3686. static int prt_check_resource __ARGS((struct prt_ps_resource_S *resource, char_u *version));
  3687. static void prt_dsc_start __ARGS((void));
  3688. static void prt_dsc_noarg __ARGS((char *comment));
  3689. static void prt_dsc_textline __ARGS((char *comment, char *text));
  3690. static void prt_dsc_text __ARGS((char *comment, char *text));
  3691. static void prt_dsc_ints __ARGS((char *comment, int count, int *ints));
  3692. static void prt_dsc_requirements __ARGS((int duplex, int tumble, int collate, int color, int num_copies));
  3693. static void prt_dsc_docmedia __ARGS((char *paper_name, double width, double height, double weight, char *colour, char *type));
  3694. static void prt_dsc_resources __ARGS((char *comment, char *type, int count, char **strings));
  3695. static float to_device_units __ARGS((int idx, double physsize, int def_number));
  3696. static void prt_page_margins __ARGS((double width, double height, double *left, double *right, double *top, double *bottom));
  3697. static void prt_font_metrics __ARGS((int font_scale));
  3698. static int prt_get_cpl __ARGS((void));
  3699. static int prt_get_lpp __ARGS((void));
  3700. static int prt_add_resource __ARGS((struct prt_ps_resource_S *resource));
  3701.  
  3702. /*
  3703.  * Variables for the output PostScript file.
  3704.  */
  3705. static FILE *prt_ps_fd;
  3706. static int prt_file_error;
  3707. static char_u *prt_ps_file_name = NULL;
  3708.  
  3709. /*
  3710.  * Various offsets and dimensions in default PostScript user space (points).
  3711.  * Used for text positioning calculations
  3712.  */
  3713. static float prt_page_width;
  3714. static float prt_page_height;
  3715. static float prt_left_margin;
  3716. static float prt_right_margin;
  3717. static float prt_top_margin;
  3718. static float prt_bottom_margin;
  3719. static float prt_line_height;
  3720. static float prt_first_line_height;
  3721. static float prt_char_width;
  3722. static float prt_number_width;
  3723. static float prt_bgcol_offset;
  3724. static float prt_pos_x_moveto = 0.0;
  3725. static float prt_pos_y_moveto = 0.0;
  3726.  
  3727. /*
  3728.  * Various control variables used to decide when and how to change the
  3729.  * PostScript graphics state.
  3730.  */
  3731. static int prt_need_moveto;
  3732. static int prt_do_moveto;
  3733. static int prt_need_font;
  3734. static int prt_font;
  3735. static int prt_need_underline;
  3736. static int prt_underline;
  3737. static int prt_do_underline;
  3738. static int prt_need_fgcol;
  3739. static int prt_fgcol;
  3740. static int prt_need_bgcol;
  3741. static int prt_do_bgcol;
  3742. static int prt_bgcol;
  3743. static int prt_new_bgcol;
  3744. static int prt_attribute_change;
  3745. static int prt_text_count;
  3746. static int prt_page_num;
  3747.  
  3748. /*
  3749.  * Variables controlling physical printing.
  3750.  */
  3751. static int prt_media;
  3752. static int prt_portrait;
  3753. static int prt_num_copies;
  3754. static int prt_duplex;
  3755. static int prt_tumble;
  3756. static int prt_collate;
  3757.  
  3758. /*
  3759.  * Buffers used when generating PostScript output
  3760.  */
  3761. static char_u prt_line_buffer[257];
  3762. static garray_T prt_ps_buffer;
  3763.  
  3764. # ifdef FEAT_MBYTE
  3765. static int prt_do_conv;
  3766. static vimconv_T prt_conv;
  3767. # endif
  3768.  
  3769.     static void
  3770. prt_write_file_raw_len(buffer, bytes)
  3771.     char_u    *buffer;
  3772.     int        bytes;
  3773. {
  3774.     if (!prt_file_error
  3775.         && fwrite(buffer, sizeof(char_u), bytes, prt_ps_fd)
  3776.                                  != (size_t)bytes)
  3777.     {
  3778.     EMSG(_("E455: Error writing to PostScript output file"));
  3779.     prt_file_error = TRUE;
  3780.     }
  3781. }
  3782.  
  3783.     static void
  3784. prt_write_file(buffer)
  3785.     char_u    *buffer;
  3786. {
  3787.     prt_write_file_len(buffer, STRLEN(buffer));
  3788. }
  3789.  
  3790.     static void
  3791. prt_write_file_len(buffer, bytes)
  3792.     char_u    *buffer;
  3793.     int        bytes;
  3794. {
  3795. #ifdef EBCDIC
  3796.     ebcdic2ascii(buffer, bytes);
  3797. #endif
  3798.     prt_write_file_raw_len(buffer, bytes);
  3799. }
  3800.  
  3801. /*
  3802.  * Write a string.
  3803.  */
  3804.     static void
  3805. prt_write_string(s)
  3806.     char    *s;
  3807. {
  3808.     sprintf((char *)prt_line_buffer, "%s", s);
  3809.     prt_write_file(prt_line_buffer);
  3810. }
  3811.  
  3812. /*
  3813.  * Write an int and a space.
  3814.  */
  3815.     static void
  3816. prt_write_int(i)
  3817.     int        i;
  3818. {
  3819.     sprintf((char *)prt_line_buffer, "%d ", i);
  3820.     prt_write_file(prt_line_buffer);
  3821. }
  3822.  
  3823. /*
  3824.  * Write a boolean and a space.
  3825.  */
  3826.     static void
  3827. prt_write_boolean(b)
  3828.     int        b;
  3829. {
  3830.     sprintf((char *)prt_line_buffer, "%s ", (b ? "T" : "F"));
  3831.     prt_write_file(prt_line_buffer);
  3832. }
  3833.  
  3834. /*
  3835.  * Write a line to define the font.
  3836.  */
  3837.     static void
  3838. prt_def_font(new_name, encoding, height, font)
  3839.     char    *new_name;
  3840.     char    *encoding;
  3841.     int        height;
  3842.     char    *font;
  3843. {
  3844.     sprintf((char *)prt_line_buffer, "/_%s /VIM-%s /%s ref\n", new_name, encoding, font);
  3845.     prt_write_file(prt_line_buffer);
  3846.     sprintf((char *)prt_line_buffer, "/%s %d /_%s ffs\n",
  3847.                             new_name, height, new_name);
  3848.     prt_write_file(prt_line_buffer);
  3849. }
  3850.  
  3851. /*
  3852.  * Convert a real value into an integer and fractional part as integers, with
  3853.  * the fractional part being in the range [0,10^precision).  The fractional part
  3854.  * is also rounded based on the precision + 1'th fractional digit.
  3855.  */
  3856.     static void
  3857. prt_real_bits(real, precision, pinteger, pfraction)
  3858.     double      real;
  3859.     int        precision;
  3860.     int        *pinteger;
  3861.     int        *pfraction;
  3862. {
  3863.     int     i;
  3864.     int     integer;
  3865.     float   fraction;
  3866.  
  3867.     integer = (int)real;
  3868.     fraction = (float)(real - integer);
  3869.     if (real < (double)integer)
  3870.     fraction = -fraction;
  3871.     for (i = 0; i < precision; i++)
  3872.     fraction *= 10.0;
  3873.  
  3874.     *pinteger = integer;
  3875.     *pfraction = (int)(fraction + 0.5);
  3876. }
  3877.  
  3878. /*
  3879.  * Write a real and a space.  Save bytes if real value has no fractional part!
  3880.  * We use prt_real_bits() as %f in sprintf uses the locale setting to decide
  3881.  * what decimal point character to use, but PS always requires a '.'.
  3882.  */
  3883.     static void
  3884. prt_write_real(val, prec)
  3885.     double    val;
  3886.     int        prec;
  3887. {
  3888.     int     integer;
  3889.     int     fraction;
  3890.  
  3891.     prt_real_bits(val, prec, &integer, &fraction);
  3892.     /* Emit integer part */
  3893.     sprintf((char *)prt_line_buffer, "%d", integer);
  3894.     prt_write_file(prt_line_buffer);
  3895.     /* Only emit fraction if necessary */
  3896.     if (fraction != 0)
  3897.     {
  3898.     /* Remove any trailing zeros */
  3899.     while ((fraction % 10) == 0)
  3900.     {
  3901.         prec--;
  3902.         fraction /= 10;
  3903.     }
  3904.     /* Emit fraction left padded with zeros */
  3905.     sprintf((char *)prt_line_buffer, ".%0*d", prec, fraction);
  3906.     prt_write_file(prt_line_buffer);
  3907.     }
  3908.     sprintf((char *)prt_line_buffer, " ");
  3909.     prt_write_file(prt_line_buffer);
  3910. }
  3911.  
  3912. /*
  3913.  * Write a line to define a numeric variable.
  3914.  */
  3915.     static void
  3916. prt_def_var(name, value, prec)
  3917.     char    *name;
  3918.     double    value;
  3919.     int        prec;
  3920. {
  3921.     sprintf((char *)prt_line_buffer, "/%s ", name);
  3922.     prt_write_file(prt_line_buffer);
  3923.     prt_write_real(value, prec);
  3924.     sprintf((char *)prt_line_buffer, "d\n");
  3925.     prt_write_file(prt_line_buffer);
  3926. }
  3927.  
  3928. /* Convert size from font space to user space at current font scale */
  3929. #define PRT_PS_FONT_TO_USER(scale, size)    ((size) * ((scale)/1000.0))
  3930.  
  3931.     static void
  3932. prt_flush_buffer()
  3933. {
  3934.     if (prt_ps_buffer.ga_len > 0)
  3935.     {
  3936.     /* Any background color must be drawn first */
  3937.     if (prt_do_bgcol && (prt_new_bgcol != PRCOLOR_WHITE))
  3938.     {
  3939.         int     r, g, b;
  3940.  
  3941.         if (prt_do_moveto)
  3942.         {
  3943.         prt_write_real(prt_pos_x_moveto, 2);
  3944.         prt_write_real(prt_pos_y_moveto, 2);
  3945.         prt_write_string("m\n");
  3946.         prt_do_moveto = FALSE;
  3947.         }
  3948.  
  3949.         /* Size of rect of background color on which text is printed */
  3950.         prt_write_real(prt_text_count * prt_char_width, 2);
  3951.         prt_write_real(prt_line_height, 2);
  3952.  
  3953.         /* Lastly add the color of the background */
  3954.         r = ((unsigned)prt_new_bgcol & 0xff0000) >> 16;
  3955.         g = ((unsigned)prt_new_bgcol & 0xff00) >> 8;
  3956.         b = prt_new_bgcol & 0xff;
  3957.         prt_write_real(r / 255.0, 3);
  3958.         prt_write_real(g / 255.0, 3);
  3959.         prt_write_real(b / 255.0, 3);
  3960.         prt_write_string("bg\n");
  3961.     }
  3962.     /* Draw underlines before the text as it makes it slightly easier to
  3963.      * find the starting point.
  3964.      */
  3965.     if (prt_do_underline)
  3966.     {
  3967.         if (prt_do_moveto)
  3968.         {
  3969.         prt_write_real(prt_pos_x_moveto, 2);
  3970.         prt_write_real(prt_pos_y_moveto, 2);
  3971.         prt_write_string("m\n");
  3972.         prt_do_moveto = FALSE;
  3973.         }
  3974.  
  3975.         /* Underlining is easy - just need the number of characters to
  3976.          * print. */
  3977.         prt_write_real(prt_text_count * prt_char_width, 2);
  3978.         prt_write_string("ul\n");
  3979.     }
  3980.     /* Draw the text
  3981.      * Note: we write text out raw - EBCDIC conversion is handled in the
  3982.      * PostScript world via the font encoding vector. */
  3983.     prt_write_string("(");
  3984.     prt_write_file_raw_len(prt_ps_buffer.ga_data, prt_ps_buffer.ga_len);
  3985.     prt_write_string(")");
  3986.     /* Add a moveto if need be and use the appropriate show procedure */
  3987.     if (prt_do_moveto)
  3988.     {
  3989.         prt_write_real(prt_pos_x_moveto, 2);
  3990.         prt_write_real(prt_pos_y_moveto, 2);
  3991.         /* moveto and a show */
  3992.         prt_write_string("ms\n");
  3993.         prt_do_moveto = FALSE;
  3994.     }
  3995.     else /* Simple show */
  3996.         prt_write_string("s\n");
  3997.  
  3998.     ga_clear(&prt_ps_buffer);
  3999.     ga_init2(&prt_ps_buffer, (int)sizeof(char), PRT_PS_DEFAULT_BUFFER_SIZE);
  4000.     }
  4001. }
  4002.  
  4003. static char_u *resource_filename;
  4004.  
  4005.     static void
  4006. prt_resource_name(filename)
  4007.     char_u  *filename;
  4008. {
  4009.     if (STRLEN(filename) >= MAXPATHL)
  4010.     *resource_filename = NUL;
  4011.     else
  4012.     STRCPY(resource_filename, filename);
  4013. }
  4014.  
  4015.     static int
  4016. prt_find_resource(name, resource)
  4017.     char    *name;
  4018.     struct prt_ps_resource_S *resource;
  4019. {
  4020.     char_u    buffer[MAXPATHL + 1];
  4021.  
  4022.     STRCPY(resource->name, name);
  4023.     /* Look for named resource file in runtimepath */
  4024.     STRCPY(buffer, "print");
  4025.     add_pathsep(buffer);
  4026.     STRCAT(buffer, name);
  4027.     STRCAT(buffer, ".ps");
  4028.     resource_filename = resource->filename;
  4029.     *resource_filename = NUL;
  4030.     return (do_in_runtimepath(buffer, FALSE, prt_resource_name)
  4031.         && resource->filename[0] != NUL);
  4032. }
  4033.  
  4034. /* PS CR and LF characters have platform independent values */
  4035. #define PSLF  (0x0a)
  4036. #define PSCR  (0x0d)
  4037.  
  4038. /* Very simple hand crafted parser to get the type, title, and version number of
  4039.  * a PS resource file so the file details can be added to the DSC header
  4040.  * comments. */
  4041.     static int
  4042. prt_open_resource(resource)
  4043.     struct prt_ps_resource_S *resource;
  4044. {
  4045.     FILE    *fd_resource;
  4046.     char_u    buffer[128];
  4047.     char_u    *ch = buffer;
  4048.     char_u    *ch2;
  4049.  
  4050.     fd_resource = mch_fopen((char *)resource->filename, READBIN);
  4051.     if (fd_resource == NULL)
  4052.     {
  4053.     EMSG2(_("E624: Can't open file \"%s\""), resource->filename);
  4054.     return FALSE;
  4055.     }
  4056.     vim_memset(buffer, NUL, sizeof(buffer));
  4057.  
  4058.     /* Parse first line to ensure valid resource file */
  4059.     (void)fread((char *)buffer, sizeof(char_u), sizeof(buffer),
  4060.                                  fd_resource);
  4061.     if (ferror(fd_resource))
  4062.     {
  4063.     EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
  4064.         resource->filename);
  4065.     fclose(fd_resource);
  4066.     return FALSE;
  4067.     }
  4068.  
  4069.     if (STRNCMP(ch, PRT_RESOURCE_HEADER, STRLEN(PRT_RESOURCE_HEADER)) != 0)
  4070.     {
  4071.     EMSG2(_("E618: file \"%s\" is not a PostScript resource file"),
  4072.         resource->filename);
  4073.     fclose(fd_resource);
  4074.     return FALSE;
  4075.     }
  4076.  
  4077.     /* Skip over any version numbers and following ws */
  4078.     ch += STRLEN(PRT_RESOURCE_HEADER);
  4079.     while (!isspace(*ch))
  4080.     ch++;
  4081.     while (isspace(*ch))
  4082.     ch++;
  4083.  
  4084.     if (STRNCMP(ch, PRT_RESOURCE_RESOURCE, STRLEN(PRT_RESOURCE_RESOURCE)) != 0)
  4085.     {
  4086.     EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
  4087.         resource->filename);
  4088.     fclose(fd_resource);
  4089.     return FALSE;
  4090.     }
  4091.     ch += STRLEN(PRT_RESOURCE_RESOURCE);
  4092.  
  4093.     /* Decide type of resource in the file */
  4094.     if (STRNCMP(ch, PRT_RESOURCE_PROCSET, STRLEN(PRT_RESOURCE_PROCSET)) == 0)
  4095.     {
  4096.     resource->type = PRT_RESOURCE_TYPE_PROCSET;
  4097.     ch += STRLEN(PRT_RESOURCE_PROCSET);
  4098.     }
  4099.     else if (STRNCMP(ch, PRT_RESOURCE_ENCODING, STRLEN(PRT_RESOURCE_ENCODING)) == 0)
  4100.     {
  4101.     resource->type = PRT_RESOURCE_TYPE_ENCODING;
  4102.     ch += STRLEN(PRT_RESOURCE_ENCODING);
  4103.     }
  4104.     else
  4105.     {
  4106.     EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
  4107.         resource->filename);
  4108.     fclose(fd_resource);
  4109.     return FALSE;
  4110.     }
  4111.  
  4112.     /* Consume up to and including the CR/LF/CR_LF */
  4113.     while (*ch != PSCR && *ch != PSLF)
  4114.     ch++;
  4115.     while (*ch == PSCR || *ch == PSLF)
  4116.     ch++;
  4117.  
  4118.     /* Match %%Title: */
  4119.     if (STRNCMP(ch, PRT_RESOURCE_TITLE, STRLEN(PRT_RESOURCE_TITLE)) != 0)
  4120.     {
  4121.     EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
  4122.         resource->filename);
  4123.     fclose(fd_resource);
  4124.     return FALSE;
  4125.     }
  4126.     ch += STRLEN(PRT_RESOURCE_TITLE);
  4127.  
  4128.     /* Skip ws after %%Title: */
  4129.     while (isspace(*ch))
  4130.     ch++;
  4131.  
  4132.     /* Copy up to the CR/LF/CR_LF */
  4133.     ch2 = resource->title;
  4134.     while (*ch != PSCR && *ch != PSLF)
  4135.     *ch2++ = *ch++;
  4136.     *ch2 = '\0';
  4137.     while (*ch == PSCR || *ch == PSLF)
  4138.     ch++;
  4139.  
  4140.     /* Match %%Version: */
  4141.     if (STRNCMP(ch, PRT_RESOURCE_VERSION, STRLEN(PRT_RESOURCE_VERSION)) != 0)
  4142.     {
  4143.     EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"),
  4144.         resource->filename);
  4145.     fclose(fd_resource);
  4146.     return FALSE;
  4147.     }
  4148.     ch += STRLEN(PRT_RESOURCE_VERSION);
  4149.  
  4150.     /* Skip ws after %%Version: */
  4151.     while (isspace(*ch))
  4152.     ch++;
  4153.  
  4154.     /* Copy up to the CR/LF/CR_LF */
  4155.     ch2 = resource->version;
  4156.     while (*ch != PSCR && *ch != PSLF)
  4157.     *ch2++ = *ch++;
  4158.     *ch2 = '\0';
  4159.  
  4160.     fclose(fd_resource);
  4161.  
  4162.     return TRUE;
  4163. }
  4164.  
  4165.     static int
  4166. prt_check_resource(resource, version)
  4167.     struct prt_ps_resource_S *resource;
  4168.     char_u  *version;
  4169. {
  4170.     /* Version number m.n should match, the revision number does not matter */
  4171.     if (STRNCMP(resource->version, version, STRLEN(version)))
  4172.     {
  4173.     EMSG2(_("E621: \"%s\" resource file has wrong version"),
  4174.         resource->name);
  4175.     return FALSE;
  4176.     }
  4177.  
  4178.     /* Other checks to be added as needed */
  4179.     return TRUE;
  4180. }
  4181.  
  4182.     static void
  4183. prt_dsc_start()
  4184. {
  4185.     prt_write_string("%!PS-Adobe-3.0\n");
  4186. }
  4187.  
  4188.     static void
  4189. prt_dsc_noarg(comment)
  4190.     char    *comment;
  4191. {
  4192.     sprintf((char *)prt_line_buffer, "%%%%%s\n", comment);
  4193.     prt_write_file(prt_line_buffer);
  4194. }
  4195.  
  4196.     static void
  4197. prt_dsc_textline(comment, text)
  4198.     char    *comment;
  4199.     char    *text;
  4200. {
  4201.     sprintf((char *)prt_line_buffer, "%%%%%s: %s\n", comment, text);
  4202.     prt_write_file(prt_line_buffer);
  4203. }
  4204.  
  4205.     static void
  4206. prt_dsc_text(comment, text)
  4207.     char    *comment;
  4208.     char    *text;
  4209. {
  4210.     /* TODO - should scan 'text' for any chars needing escaping! */
  4211.     sprintf((char *)prt_line_buffer, "%%%%%s: (%s)\n", comment, text);
  4212.     prt_write_file(prt_line_buffer);
  4213. }
  4214.  
  4215. #define prt_dsc_atend(c)    prt_dsc_text((c), "atend")
  4216.  
  4217.     static void
  4218. prt_dsc_ints(comment, count, ints)
  4219.     char    *comment;
  4220.     int        count;
  4221.     int        *ints;
  4222. {
  4223.     int        i;
  4224.  
  4225.     sprintf((char *)prt_line_buffer, "%%%%%s:", comment);
  4226.     prt_write_file(prt_line_buffer);
  4227.  
  4228.     for (i = 0; i < count; i++)
  4229.     {
  4230.     sprintf((char *)prt_line_buffer, " %d", ints[i]);
  4231.     prt_write_file(prt_line_buffer);
  4232.     }
  4233.  
  4234.     prt_write_string("\n");
  4235. }
  4236.  
  4237.     static void
  4238. prt_dsc_resources(comment, type, count, strings)
  4239.     char    *comment;    /* if NULL add to previous */
  4240.     char    *type;
  4241.     int        count;
  4242.     char    **strings;
  4243. {
  4244.     int        i;
  4245.  
  4246.     if (comment != NULL)
  4247.     sprintf((char *)prt_line_buffer, "%%%%%s: %s", comment, type);
  4248.     else
  4249.     sprintf((char *)prt_line_buffer, "%%%%+ %s", type);
  4250.     prt_write_file(prt_line_buffer);
  4251.  
  4252.     for (i = 0; i < count; i++)
  4253.     {
  4254.     sprintf((char *)prt_line_buffer, " %s", strings[i]);
  4255.     prt_write_file(prt_line_buffer);
  4256.     }
  4257.  
  4258.     prt_write_string("\n");
  4259. }
  4260.  
  4261.     static void
  4262. prt_dsc_requirements(duplex, tumble, collate, color, num_copies)
  4263.     int        duplex;
  4264.     int        tumble;
  4265.     int        collate;
  4266.     int        color;
  4267.     int        num_copies;
  4268. {
  4269.     /* Only output the comment if we need to.
  4270.      * Note: tumble is ignored if we are not duplexing
  4271.      */
  4272.     if (!(duplex || collate || color || (num_copies > 1)))
  4273.     return;
  4274.  
  4275.     sprintf((char *)prt_line_buffer, "%%%%Requirements:");
  4276.     prt_write_file(prt_line_buffer);
  4277.  
  4278.     if (duplex)
  4279.     {
  4280.     prt_write_string(" duplex");
  4281.     if (tumble)
  4282.         prt_write_string("(tumble)");
  4283.     }
  4284.     if (collate)
  4285.     prt_write_string(" collate");
  4286.     if (color)
  4287.     prt_write_string(" color");
  4288.     if (num_copies > 1)
  4289.     {
  4290.     prt_write_string(" numcopies(");
  4291.     /* Note: no space wanted so dont use prt_write_int() */
  4292.     sprintf((char *)prt_line_buffer, "%d", num_copies);
  4293.     prt_write_file(prt_line_buffer);
  4294.     prt_write_string(")");
  4295.     }
  4296.     prt_write_string("\n");
  4297. }
  4298.  
  4299.     static void
  4300. prt_dsc_docmedia(paper_name, width, height, weight, colour, type)
  4301.     char    *paper_name;
  4302.     double    width;
  4303.     double    height;
  4304.     double    weight;
  4305.     char    *colour;
  4306.     char    *type;
  4307. {
  4308.     sprintf((char *)prt_line_buffer, "%%%%DocumentMedia: %s ", paper_name);
  4309.     prt_write_file(prt_line_buffer);
  4310.     prt_write_real(width, 2);
  4311.     prt_write_real(height, 2);
  4312.     prt_write_real(weight, 2);
  4313.     if (colour == NULL)
  4314.     prt_write_string("()");
  4315.     else
  4316.     prt_write_string(colour);
  4317.     prt_write_string(" ");
  4318.     if (type == NULL)
  4319.     prt_write_string("()");
  4320.     else
  4321.     prt_write_string(type);
  4322.     prt_write_string("\n");
  4323. }
  4324.  
  4325.     void
  4326. mch_print_cleanup()
  4327. {
  4328. #ifdef FEAT_MBYTE
  4329.     if (prt_do_conv)
  4330.     {
  4331.     convert_setup(&prt_conv, NULL, NULL);
  4332.     prt_do_conv = FALSE;
  4333.     }
  4334. #endif
  4335.     if (prt_ps_fd != NULL)
  4336.     {
  4337.     fclose(prt_ps_fd);
  4338.     prt_ps_fd = NULL;
  4339.     prt_file_error = FALSE;
  4340.     }
  4341.     if (prt_ps_file_name != NULL)
  4342.     {
  4343.     vim_free(prt_ps_file_name);
  4344.     prt_ps_file_name = NULL;
  4345.     }
  4346. }
  4347.  
  4348.     static float
  4349. to_device_units(idx, physsize, def_number)
  4350.     int        idx;
  4351.     double    physsize;
  4352.     int        def_number;
  4353. {
  4354.     float    ret;
  4355.     int        u;
  4356.     int        nr;
  4357.  
  4358.     u = prt_get_unit(idx);
  4359.     if (u == PRT_UNIT_NONE)
  4360.     {
  4361.     u = PRT_UNIT_PERC;
  4362.     nr = def_number;
  4363.     }
  4364.     else
  4365.     nr = printer_opts[idx].number;
  4366.  
  4367.     switch (u)
  4368.     {
  4369.     case PRT_UNIT_INCH:
  4370.         ret = (float)(nr * PRT_PS_DEFAULT_DPI);
  4371.         break;
  4372.     case PRT_UNIT_MM:
  4373.         ret = (float)(nr * PRT_PS_DEFAULT_DPI) / (float)25.4;
  4374.         break;
  4375.     case PRT_UNIT_POINT:
  4376.         ret = (float)nr;
  4377.         break;
  4378.     case PRT_UNIT_PERC:
  4379.     default:
  4380.         ret = (float)(physsize * nr) / 100;
  4381.         break;
  4382.     }
  4383.  
  4384.     return ret;
  4385. }
  4386.  
  4387. /*
  4388.  * Calculate margins for given width and height from printoptions settings.
  4389.  */
  4390.     static void
  4391. prt_page_margins(width, height, left, right, top, bottom)
  4392.     double    width;
  4393.     double    height;
  4394.     double    *left;
  4395.     double    *right;
  4396.     double    *top;
  4397.     double    *bottom;
  4398. {
  4399.     *left   = to_device_units(OPT_PRINT_LEFT, width, 10);
  4400.     *right  = width - to_device_units(OPT_PRINT_RIGHT, width, 5);
  4401.     *top    = height - to_device_units(OPT_PRINT_TOP, height, 5);
  4402.     *bottom = to_device_units(OPT_PRINT_BOT, height, 5);
  4403. }
  4404.  
  4405.     static void
  4406. prt_font_metrics(font_scale)
  4407.     int        font_scale;
  4408. {
  4409.     prt_line_height = (float)font_scale;
  4410.     prt_char_width = (float)PRT_PS_FONT_TO_USER(font_scale, prt_ps_font.wx);
  4411. }
  4412.  
  4413.  
  4414.     static int
  4415. prt_get_cpl()
  4416. {
  4417.     if (prt_use_number())
  4418.     {
  4419.     prt_number_width = PRINT_NUMBER_WIDTH * prt_char_width;
  4420.     prt_left_margin += prt_number_width;
  4421.     }
  4422.     else
  4423.     prt_number_width = 0.0;
  4424.  
  4425.     return (int)((prt_right_margin - prt_left_margin) / prt_char_width);
  4426. }
  4427.  
  4428. /*
  4429.  * Get number of lines of text that fit on a page (excluding the header).
  4430.  */
  4431.     static int
  4432. prt_get_lpp()
  4433. {
  4434.     int lpp;
  4435.  
  4436.     /*
  4437.      * Calculate offset to lower left corner of background rect based on actual
  4438.      * font height (based on its bounding box) and the line height, handling the
  4439.      * case where the font height can exceed the line height.
  4440.      */
  4441.     prt_bgcol_offset = (float)PRT_PS_FONT_TO_USER(prt_line_height,
  4442.                        prt_ps_font.bbox_min_y);
  4443.     if ((prt_ps_font.bbox_max_y - prt_ps_font.bbox_min_y) < 1000.0)
  4444.     {
  4445.     prt_bgcol_offset -= (float)PRT_PS_FONT_TO_USER(prt_line_height,
  4446.                 (1000.0 - (prt_ps_font.bbox_max_y -
  4447.                         prt_ps_font.bbox_min_y)) / 2);
  4448.     }
  4449.  
  4450.     /* Get height for topmost line based on background rect offset. */
  4451.     prt_first_line_height = prt_line_height + prt_bgcol_offset;
  4452.  
  4453.     /* Calculate lpp */
  4454.     lpp = (int)((prt_top_margin - prt_bottom_margin) / prt_line_height);
  4455.  
  4456.     /* Adjust top margin if there is a header */
  4457.     prt_top_margin -= prt_line_height * prt_header_height();
  4458.  
  4459.     return lpp - prt_header_height();
  4460. }
  4461.  
  4462. /*ARGSUSED*/
  4463.     int
  4464. mch_print_init(psettings, jobname, forceit)
  4465.     prt_settings_T *psettings;
  4466.     char_u    *jobname;
  4467.     int        forceit;
  4468. {
  4469.     int        i;
  4470.     char    *paper_name;
  4471.     int        paper_strlen;
  4472.     int        fontsize;
  4473.     char_u    *p;
  4474.     double      left;
  4475.     double      right;
  4476.     double      top;
  4477.     double      bottom;
  4478.  
  4479. #if 0
  4480.     /*
  4481.      * TODO:
  4482.      * If "forceit" is false: pop up a dialog to select:
  4483.      *    - printer name
  4484.      *    - copies
  4485.      *    - collated/uncollated
  4486.      *    - duplex off/long side/short side
  4487.      *    - paper size
  4488.      *    - portrait/landscape
  4489.      *    - font size
  4490.      *
  4491.      * If "forceit" is true: use the default printer and settings
  4492.      */
  4493.     if (forceit)
  4494.     s_pd.Flags |= PD_RETURNDEFAULT;
  4495. #endif
  4496.  
  4497.     /*
  4498.      * Find the size of the paper and set the margins.
  4499.      */
  4500.     prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present
  4501.        || TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) == 'y');
  4502.     if (printer_opts[OPT_PRINT_PAPER].present)
  4503.     {
  4504.     paper_name = (char *)printer_opts[OPT_PRINT_PAPER].string;
  4505.     paper_strlen = printer_opts[OPT_PRINT_PAPER].strlen;
  4506.     }
  4507.     else
  4508.     {
  4509.     paper_name = "A4";
  4510.     paper_strlen = 2;
  4511.     }
  4512.     for (i = 0; i < PRT_MEDIASIZE_LEN; ++i)
  4513.     if (STRLEN(prt_mediasize[i].name) == (unsigned)paper_strlen
  4514.         && STRNICMP(prt_mediasize[i].name, paper_name,
  4515.                                paper_strlen) == 0)
  4516.         break;
  4517.     if (i == PRT_MEDIASIZE_LEN)
  4518.     i = 0;
  4519.     prt_media = i;
  4520.  
  4521.     /*
  4522.      * Set PS pagesize based on media dimensions and print orientation.
  4523.      * Note: Media and page sizes have defined meanings in PostScript and should
  4524.      * be kept distinct.  Media is the paper (or transparency, or ...) that is
  4525.      * printed on, whereas the page size is the area that the PostScript
  4526.      * interpreter renders into.
  4527.      */
  4528.     if (prt_portrait)
  4529.     {
  4530.     prt_page_width = prt_mediasize[i].width;
  4531.     prt_page_height = prt_mediasize[i].height;
  4532.     }
  4533.     else
  4534.     {
  4535.     prt_page_width = prt_mediasize[i].height;
  4536.     prt_page_height = prt_mediasize[i].width;
  4537.     }
  4538.  
  4539.     /*
  4540.      * Set PS page margins based on the PS pagesize, not the mediasize - this
  4541.      * needs to be done before the cpl and lpp are calculated.
  4542.      */
  4543.     prt_page_margins(prt_page_width, prt_page_height, &left, &right, &top,
  4544.                                     &bottom);
  4545.     prt_left_margin = (float)left;
  4546.     prt_right_margin = (float)right;
  4547.     prt_top_margin = (float)top;
  4548.     prt_bottom_margin = (float)bottom;
  4549.  
  4550.     /*
  4551.      * Set up the font size.
  4552.      */
  4553.     fontsize = PRT_PS_DEFAULT_FONTSIZE;
  4554.     for (p = p_pfn; (p = vim_strchr(p, ':')) != NULL; ++p)
  4555.     if (p[1] == 'h' && isdigit(p[2]))
  4556.         fontsize = atoi((char *)p + 2);
  4557.     prt_font_metrics(fontsize);
  4558.  
  4559.     /*
  4560.      * Return the number of characters per line, and lines per page for the
  4561.      * generic print code.
  4562.      */
  4563.     psettings->chars_per_line = prt_get_cpl();
  4564.     psettings->lines_per_page = prt_get_lpp();
  4565.  
  4566.     /* Catch margin settings that leave no space for output! */
  4567.     if (psettings->chars_per_line <= 0 || psettings->lines_per_page <= 0)
  4568.     return FAIL;
  4569.  
  4570.     /*
  4571.      * Sort out the number of copies to be printed.  PS by default will do
  4572.      * uncollated copies for you, so once we know how many uncollated copies are
  4573.      * wanted cache it away and lie to the generic code that we only want one
  4574.      * uncollated copy.
  4575.      */
  4576.     psettings->n_collated_copies = 1;
  4577.     psettings->n_uncollated_copies = 1;
  4578.     prt_num_copies = 1;
  4579.     prt_collate = (!printer_opts[OPT_PRINT_COLLATE].present
  4580.         || TOLOWER_ASC(printer_opts[OPT_PRINT_COLLATE].string[0]) == 'y');
  4581.     if (prt_collate)
  4582.     {
  4583.     /* TODO: Get number of collated copies wanted. */
  4584.     psettings->n_collated_copies = 1;
  4585.     }
  4586.     else
  4587.     {
  4588.     /* TODO: Get number of uncollated copies wanted and update the cached
  4589.      * count.
  4590.      */
  4591.     prt_num_copies = 1;
  4592.     }
  4593.  
  4594.     psettings->jobname = jobname;
  4595.  
  4596.     /*
  4597.      * Set up printer duplex and tumble based on Duplex option setting - default
  4598.      * is long sided duplex printing (i.e. no tumble).
  4599.      */
  4600.     prt_duplex = TRUE;
  4601.     prt_tumble = FALSE;
  4602.     psettings->duplex = 1;
  4603.     if (printer_opts[OPT_PRINT_DUPLEX].present)
  4604.     {
  4605.     if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "off", 3) == 0)
  4606.     {
  4607.         prt_duplex = FALSE;
  4608.         psettings->duplex = 0;
  4609.     }
  4610.     else if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "short", 5)
  4611.                                      == 0)
  4612.         prt_tumble = TRUE;
  4613.     }
  4614.  
  4615.     /* For now user abort not supported */
  4616.     psettings->user_abort = 0;
  4617.  
  4618.     /* If the user didn't specify a file name, use a temp file. */
  4619.     if (psettings->outfile == NULL)
  4620.     {
  4621.     prt_ps_file_name = vim_tempname('p');
  4622.     if (prt_ps_file_name == NULL)
  4623.     {
  4624.         EMSG(_(e_notmp));
  4625.         return FAIL;
  4626.     }
  4627.     prt_ps_fd = mch_fopen((char *)prt_ps_file_name, WRITEBIN);
  4628.     }
  4629.     else
  4630.     {
  4631.     p = expand_env_save(psettings->outfile);
  4632.     if (p != NULL)
  4633.     {
  4634.         prt_ps_fd = mch_fopen((char *)p, WRITEBIN);
  4635.         vim_free(p);
  4636.     }
  4637.     }
  4638.     if (prt_ps_fd == NULL)
  4639.     {
  4640.     EMSG(_("E324: Can't open PostScript output file"));
  4641.     mch_print_cleanup();
  4642.     return FAIL;
  4643.     }
  4644.  
  4645.     ga_init2(&prt_ps_buffer, (int)sizeof(char), PRT_PS_DEFAULT_BUFFER_SIZE);
  4646.  
  4647.     prt_page_num = 0;
  4648.  
  4649.     prt_attribute_change = FALSE;
  4650.     prt_need_moveto = FALSE;
  4651.     prt_need_font = FALSE;
  4652.     prt_need_fgcol = FALSE;
  4653.     prt_need_bgcol = FALSE;
  4654.     prt_need_underline = FALSE;
  4655.  
  4656.     prt_file_error = FALSE;
  4657.  
  4658.     return OK;
  4659. }
  4660.  
  4661.     static int
  4662. prt_add_resource(resource)
  4663.     struct prt_ps_resource_S *resource;
  4664. {
  4665.     FILE*    fd_resource;
  4666.     char_u    resource_buffer[512];
  4667.     char    *resource_name[1];
  4668.     size_t    bytes_read;
  4669.  
  4670.     fd_resource = mch_fopen((char *)resource->filename, READBIN);
  4671.     if (fd_resource == NULL)
  4672.     {
  4673.     EMSG2(_("E456: Can't open file \"%s\""), resource->filename);
  4674.     return FALSE;
  4675.     }
  4676.     resource_name[0] = (char *)resource->title;
  4677.     prt_dsc_resources("BeginResource",
  4678.                 resource_types[resource->type], 1, resource_name);
  4679.  
  4680.     prt_dsc_textline("BeginDocument", (char *)resource->filename);
  4681.  
  4682.     for (;;)
  4683.     {
  4684.     bytes_read = fread((char *)resource_buffer, sizeof(char_u),
  4685.                sizeof(resource_buffer), fd_resource);
  4686.     if (ferror(fd_resource))
  4687.     {
  4688.         EMSG2(_("E457: Can't read PostScript resource file \"%s\""),
  4689.                                 resource->filename);
  4690.         fclose(fd_resource);
  4691.         return FALSE;
  4692.     }
  4693.     if (bytes_read == 0)
  4694.         break;
  4695.     prt_write_file_raw_len(resource_buffer, bytes_read);
  4696.     if (prt_file_error)
  4697.     {
  4698.         fclose(fd_resource);
  4699.         return FALSE;
  4700.     }
  4701.     }
  4702.     fclose(fd_resource);
  4703.  
  4704.     prt_dsc_noarg("EndDocument");
  4705.  
  4706.     prt_dsc_noarg("EndResource");
  4707.  
  4708.     return TRUE;
  4709. }
  4710.  
  4711.     int
  4712. mch_print_begin(psettings)
  4713.     prt_settings_T *psettings;
  4714. {
  4715.     time_t    now;
  4716.     int        bbox[4];
  4717.     char    *p_time;
  4718.     char    *resource[1];
  4719.     double      left;
  4720.     double      right;
  4721.     double      top;
  4722.     double      bottom;
  4723.     struct prt_ps_resource_S res_prolog;
  4724.     struct prt_ps_resource_S res_encoding;
  4725.     char_u      buffer[256];
  4726.     char_u      *p_encoding;
  4727. #ifdef FEAT_MBYTE
  4728.     int        props;
  4729. #endif
  4730.  
  4731.     /*
  4732.      * PS DSC Header comments - no PS code!
  4733.      */
  4734.     prt_dsc_start();
  4735.     prt_dsc_textline("Title", (char *)psettings->jobname);
  4736.     /* TODO - platform dependent user name retrieval */
  4737.     prt_dsc_textline("For", "Unknown");
  4738.     prt_dsc_textline("Creator", VIM_VERSION_LONG);
  4739.     /* Note: to ensure Clean8bit I don't think we can use LC_TIME */
  4740.     now = time(NULL);
  4741.     p_time = ctime(&now);
  4742.     /* Note: ctime() adds a \n so we have to remove it :-( */
  4743.     *(vim_strchr((char_u *)p_time, '\n')) = '\0';
  4744.     prt_dsc_textline("CreationDate", p_time);
  4745.     prt_dsc_textline("DocumentData", "Clean8Bit");
  4746.     prt_dsc_textline("Orientation", "Portrait");
  4747.     prt_dsc_atend("Pages");
  4748.     prt_dsc_textline("PageOrder", "Ascend");
  4749.     /* The bbox does not change with orientation - it is always in the default
  4750.      * user coordinate system!  We have to recalculate right and bottom
  4751.      * coordinates based on the font metrics for the bbox to be accurate. */
  4752.     prt_page_margins(prt_mediasize[prt_media].width,
  4753.                         prt_mediasize[prt_media].height,
  4754.                         &left, &right, &top, &bottom);
  4755.     bbox[0] = (int)left;
  4756.     if (prt_portrait)
  4757.     {
  4758.     /* In portrait printing the fixed point is the top left corner so we
  4759.      * derive the bbox from that point.  We have the expected cpl chars
  4760.      * across the media and lpp lines down the media.
  4761.      */
  4762.     bbox[1] = (int)(top - (psettings->lines_per_page + prt_header_height())
  4763.                                 * prt_line_height);
  4764.     bbox[2] = (int)(left + psettings->chars_per_line * prt_char_width
  4765.                                     + 0.5);
  4766.     bbox[3] = (int)(top + 0.5);
  4767.     }
  4768.     else
  4769.     {
  4770.     /* In landscape printing the fixed point is the bottom left corner so we
  4771.      * derive the bbox from that point.  We have lpp chars across the media
  4772.      * and cpl lines up the media.
  4773.      */
  4774.     bbox[1] = (int)bottom;
  4775.     bbox[2] = (int)(left + ((psettings->lines_per_page
  4776.                   + prt_header_height()) * prt_line_height) + 0.5);
  4777.     bbox[3] = (int)(bottom + psettings->chars_per_line * prt_char_width
  4778.                                     + 0.5);
  4779.     }
  4780.     prt_dsc_ints("BoundingBox", 4, bbox);
  4781.     /* The media width and height does not change with landscape printing! */
  4782.     prt_dsc_docmedia(prt_mediasize[prt_media].name,
  4783.                 prt_mediasize[prt_media].width,
  4784.                 prt_mediasize[prt_media].height,
  4785.                 (double)0, NULL, NULL);
  4786.     prt_dsc_resources("DocumentNeededResources", "font", 4,
  4787.                              prt_ps_font.ps_fontname);
  4788.  
  4789.     /* Search for external resources we supply */
  4790.     if (!prt_find_resource("prolog", &res_prolog))
  4791.     {
  4792.     EMSG(_("E456: Can't find PostScript resource file \"prolog.ps\""));
  4793.     return FALSE;
  4794.     }
  4795.     if (!prt_open_resource(&res_prolog))
  4796.     return FALSE;
  4797.     if (!prt_check_resource(&res_prolog, PRT_PROLOG_VERSION))
  4798.     return FALSE;
  4799.     /* Find an encoding to use for printing.
  4800.      * Check 'printencoding'. If not set or not found, then use 'encoding'. If
  4801.      * that cannot be found then default to "latin1".
  4802.      * Note: VIM specific encoding header is always skipped.
  4803.      */
  4804. #ifdef FEAT_MBYTE
  4805.     props = enc_canon_props(p_enc);
  4806. #endif
  4807.     p_encoding = enc_skip(p_penc);
  4808.     if (*p_encoding == NUL
  4809.         || !prt_find_resource((char *)p_encoding, &res_encoding))
  4810.     {
  4811.     /* 'printencoding' not set or not supported - find alternate */
  4812. #ifdef FEAT_MBYTE
  4813.     p_encoding = enc_skip(p_enc);
  4814.     if (!(props & ENC_8BIT)
  4815.         || !prt_find_resource((char *)p_encoding, &res_encoding))
  4816.     {
  4817.         /* 8-bit 'encoding' is not supported */
  4818. #endif
  4819.         /* Use latin1 as default printing encoding */
  4820.         p_encoding = (char_u *)"latin1";
  4821.         if (!prt_find_resource((char *)p_encoding, &res_encoding))
  4822.         {
  4823.         EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""),
  4824.             p_encoding);
  4825.         return FALSE;
  4826.         }
  4827. #ifdef FEAT_MBYTE
  4828.     }
  4829. #endif
  4830.     }
  4831.     if (!prt_open_resource(&res_encoding))
  4832.     return FALSE;
  4833.     /* For the moment there are no checks on encoding resource files to perform */
  4834. #ifdef FEAT_MBYTE
  4835.     /* Set up encoding conversion if starting from multi-byte */
  4836.     props = enc_canon_props(p_enc);
  4837.     if (!(props & ENC_8BIT))
  4838.     {
  4839.     if (FAIL == convert_setup(&prt_conv, p_enc, p_encoding))
  4840.     {
  4841.         EMSG2(_("E620: Unable to convert from multi-byte to \"%s\" encoding"),
  4842.             p_encoding);
  4843.         return FALSE;
  4844.     }
  4845.     prt_do_conv = TRUE;
  4846.     }
  4847. #endif
  4848.  
  4849.     /* List resources supplied */
  4850.     resource[0] = (char *)buffer;
  4851.     STRCPY(buffer, res_prolog.title);
  4852.     STRCAT(buffer, " ");
  4853.     STRCAT(buffer, res_prolog.version);
  4854.     prt_dsc_resources("DocumentSuppliedResources", "procset", 1, resource);
  4855.     STRCPY(buffer, res_encoding.title);
  4856.     STRCAT(buffer, " ");
  4857.     STRCAT(buffer, res_encoding.version);
  4858.     prt_dsc_resources(NULL, "encoding", 1, resource);
  4859.     prt_dsc_requirements(prt_duplex, prt_tumble, prt_collate,
  4860. #ifdef FEAT_SYN_HL
  4861.                     psettings->do_syntax
  4862. #else
  4863.                     0
  4864. #endif
  4865.                     , prt_num_copies);
  4866.     prt_dsc_noarg("EndComments");
  4867.  
  4868.     /*
  4869.      * PS Document page defaults
  4870.      */
  4871.     prt_dsc_noarg("BeginDefaults");
  4872.  
  4873.     /* List font resources most likely common to all pages */
  4874.     prt_dsc_resources("PageResources", "font", 4, prt_ps_font.ps_fontname);
  4875.     /* Paper will be used for all pages */
  4876.     prt_dsc_textline("PageMedia", prt_mediasize[prt_media].name);
  4877.  
  4878.     prt_dsc_noarg("EndDefaults");
  4879.  
  4880.     /*
  4881.      * PS Document prolog inclusion - all required procsets.
  4882.      */
  4883.     prt_dsc_noarg("BeginProlog");
  4884.  
  4885.     /* For now there is just the one procset to be included in the PS file. */
  4886.     if (!prt_add_resource(&res_prolog))
  4887.     return FALSE;
  4888.  
  4889.     /* There will be only one font encoding to be included in the PS file. */
  4890.     if (!prt_add_resource(&res_encoding))
  4891.     return FALSE;
  4892.  
  4893.     prt_dsc_noarg("EndProlog");
  4894.  
  4895.     /*
  4896.      * PS Document setup - must appear after the prolog
  4897.      */
  4898.     prt_dsc_noarg("BeginSetup");
  4899.  
  4900.     /* Device setup - page size and number of uncollated copies */
  4901.     prt_write_int((int)prt_mediasize[prt_media].width);
  4902.     prt_write_int((int)prt_mediasize[prt_media].height);
  4903.     prt_write_int(0);
  4904.     prt_write_string("sps\n");
  4905.     prt_write_int(prt_num_copies);
  4906.     prt_write_string("nc\n");
  4907.     prt_write_boolean(prt_duplex);
  4908.     prt_write_boolean(prt_tumble);
  4909.     prt_write_string("dt\n");
  4910.     prt_write_boolean(prt_collate);
  4911.     prt_write_string("c\n");
  4912.  
  4913.     /* Font resource inclusion and definition */
  4914.     prt_dsc_resources("IncludeResource", "font", 1,
  4915.                  &prt_ps_font.ps_fontname[PRT_PS_FONT_ROMAN]);
  4916.     prt_def_font("F0", (char *)p_encoding, (int)prt_line_height,
  4917.                   prt_ps_font.ps_fontname[PRT_PS_FONT_ROMAN]);
  4918.     prt_dsc_resources("IncludeResource", "font", 1,
  4919.                   &prt_ps_font.ps_fontname[PRT_PS_FONT_BOLD]);
  4920.     prt_def_font("F1", (char *)p_encoding, (int)prt_line_height,
  4921.                    prt_ps_font.ps_fontname[PRT_PS_FONT_BOLD]);
  4922.     prt_dsc_resources("IncludeResource", "font", 1,
  4923.                    &prt_ps_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
  4924.     prt_def_font("F2", (char *)p_encoding, (int)prt_line_height,
  4925.                 prt_ps_font.ps_fontname[PRT_PS_FONT_OBLIQUE]);
  4926.     prt_dsc_resources("IncludeResource", "font", 1,
  4927.                &prt_ps_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
  4928.     prt_def_font("F3", (char *)p_encoding, (int)prt_line_height,
  4929.                 prt_ps_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]);
  4930.  
  4931.     /* Misc constant vars used for underlining and background rects */
  4932.     prt_def_var("UO", PRT_PS_FONT_TO_USER(prt_line_height,
  4933.                         prt_ps_font.uline_offset), 2);
  4934.     prt_def_var("UW", PRT_PS_FONT_TO_USER(prt_line_height,
  4935.                          prt_ps_font.uline_width), 2);
  4936.     prt_def_var("BO", prt_bgcol_offset, 2);
  4937.  
  4938.     prt_dsc_noarg("EndSetup");
  4939.  
  4940.     /* Fail if any problems writing out to the PS file */
  4941.     return !prt_file_error;
  4942. }
  4943.  
  4944.     void
  4945. mch_print_end(psettings)
  4946.     prt_settings_T *psettings;
  4947. {
  4948.     prt_dsc_noarg("Trailer");
  4949.  
  4950.     /*
  4951.      * Output any info we don't know in toto until we finish
  4952.      */
  4953.     prt_dsc_ints("Pages", 1, &prt_page_num);
  4954.  
  4955.     prt_dsc_noarg("EOF");
  4956.  
  4957.     if (!prt_file_error && psettings->outfile == NULL
  4958.                     && !got_int && !psettings->user_abort)
  4959.     {
  4960.     /* Close the file first. */
  4961.     if (prt_ps_fd != NULL)
  4962.     {
  4963.         fclose(prt_ps_fd);
  4964.         prt_ps_fd = NULL;
  4965.     }
  4966.     prt_message((char_u *)_("Sending to printer..."));
  4967.  
  4968.     /* Not printing to a file: use 'printexpr' to print the file. */
  4969.     if (eval_printexpr(prt_ps_file_name, psettings->arguments) == FAIL)
  4970.         EMSG(_("E365: Failed to print PostScript file"));
  4971.     else
  4972.         prt_message((char_u *)_("Print job sent."));
  4973.     }
  4974.  
  4975.     mch_print_cleanup();
  4976. }
  4977.  
  4978.     int
  4979. mch_print_end_page()
  4980. {
  4981.     prt_flush_buffer();
  4982.  
  4983.     prt_write_string("re sp\n");
  4984.  
  4985.     prt_dsc_noarg("PageTrailer");
  4986.  
  4987.     return !prt_file_error;
  4988. }
  4989.  
  4990. /*ARGSUSED*/
  4991.     int
  4992. mch_print_begin_page(str)
  4993.     char_u    *str;
  4994. {
  4995.     int        page_num[2];
  4996.  
  4997.     prt_page_num++;
  4998.  
  4999.     page_num[0] = page_num[1] = prt_page_num;
  5000.     prt_dsc_ints("Page", 2, page_num);
  5001.  
  5002.     prt_dsc_noarg("BeginPageSetup");
  5003.  
  5004.     prt_write_string("sv\n0 g\nF0 sf\n");
  5005.     prt_fgcol = PRCOLOR_BLACK;
  5006.     prt_bgcol = PRCOLOR_WHITE;
  5007.     prt_font = PRT_PS_FONT_ROMAN;
  5008.  
  5009.     /* Set up page transformation for landscape printing. */
  5010.     if (!prt_portrait)
  5011.     {
  5012.     prt_write_int(-((int)prt_mediasize[prt_media].width));
  5013.     prt_write_string("sl\n");
  5014.     }
  5015.  
  5016.     prt_dsc_noarg("EndPageSetup");
  5017.  
  5018.     /* We have reset the font attributes, force setting them again. */
  5019.     curr_bg = (long_u)0xffffffff;
  5020.     curr_fg = (long_u)0xffffffff;
  5021.     curr_bold = MAYBE;
  5022.  
  5023.     return !prt_file_error;
  5024. }
  5025.  
  5026.     int
  5027. mch_print_blank_page()
  5028. {
  5029.     return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
  5030. }
  5031.  
  5032. static float prt_pos_x = 0;
  5033. static float prt_pos_y = 0;
  5034.  
  5035.     void
  5036. mch_print_start_line(margin, page_line)
  5037.     int        margin;
  5038.     int        page_line;
  5039. {
  5040.     prt_pos_x = prt_left_margin;
  5041.     if (margin)
  5042.     prt_pos_x -= prt_number_width;
  5043.  
  5044.     prt_pos_y = prt_top_margin - prt_first_line_height -
  5045.                     page_line * prt_line_height;
  5046.  
  5047.     prt_attribute_change = TRUE;
  5048.     prt_need_moveto = TRUE;
  5049. }
  5050.  
  5051. /*ARGSUSED*/
  5052.     int
  5053. mch_print_text_out(p, len)
  5054.     char_u    *p;
  5055.     int        len;
  5056. {
  5057.     int        need_break;
  5058.     char_u    ch;
  5059.     char_u      ch_buff[8];
  5060.  
  5061.     /* Output any required changes to the graphics state, after flushing any
  5062.      * text buffered so far.
  5063.      */
  5064.     if (prt_attribute_change)
  5065.     {
  5066.     prt_flush_buffer();
  5067.     /* Reset count of number of chars that will be printed */
  5068.     prt_text_count = 0;
  5069.  
  5070.     if (prt_need_moveto)
  5071.     {
  5072.         prt_pos_x_moveto = prt_pos_x;
  5073.         prt_pos_y_moveto = prt_pos_y;
  5074.         prt_do_moveto = TRUE;
  5075.  
  5076.         prt_need_moveto = FALSE;
  5077.     }
  5078.     if (prt_need_font)
  5079.     {
  5080.         prt_write_string("F");
  5081.         prt_write_int(prt_font);
  5082.         prt_write_string("sf\n");
  5083.         prt_need_font = FALSE;
  5084.     }
  5085.     if (prt_need_fgcol)
  5086.     {
  5087.         int     r, g, b;
  5088.         r = ((unsigned)prt_fgcol & 0xff0000) >> 16;
  5089.         g = ((unsigned)prt_fgcol & 0xff00) >> 8;
  5090.         b = prt_fgcol & 0xff;
  5091.  
  5092.         prt_write_real(r / 255.0, 3);
  5093.         if (r == g && g == b)
  5094.         {
  5095.         prt_write_string("g\n");
  5096.         }
  5097.         else
  5098.         {
  5099.         prt_write_real(g / 255.0, 3);
  5100.         prt_write_real(b / 255.0, 3);
  5101.         prt_write_string("r\n");
  5102.         }
  5103.         prt_need_fgcol = FALSE;
  5104.     }
  5105.  
  5106.     if (prt_bgcol != PRCOLOR_WHITE)
  5107.     {
  5108.         prt_new_bgcol = prt_bgcol;
  5109.         if (prt_need_bgcol)
  5110.         prt_do_bgcol = TRUE;
  5111.     }
  5112.     else
  5113.         prt_do_bgcol = FALSE;
  5114.     prt_need_bgcol = FALSE;
  5115.  
  5116.     if (prt_need_underline)
  5117.         prt_do_underline = prt_underline;
  5118.     prt_need_underline = FALSE;
  5119.  
  5120.     prt_attribute_change = FALSE;
  5121.     }
  5122.  
  5123. #ifdef FEAT_MBYTE
  5124.     if (prt_do_conv)
  5125.     {
  5126.     /* Convert from multi-byte to 8-bit encoding */
  5127.     p = string_convert(&prt_conv, p, &len);
  5128.     if (p == NULL)
  5129.         p = (char_u *)"";
  5130.     }
  5131. #endif
  5132.     /* Add next character to buffer of characters to output.
  5133.      * Note: One printed character may require several PS characters to
  5134.      * represent it, but we only count them as one printed character.
  5135.      */
  5136.     ch = *p;
  5137.     if (ch < 32 || ch == '(' || ch == ')' || ch == '\\')
  5138.     {
  5139.     /* Convert non-printing characters to either their escape or octal
  5140.      * sequence, ensures PS sent over a serial line does not interfere with
  5141.      * the comms protocol.
  5142.      * Note: For EBCDIC we need to write out the escape sequences as ASCII
  5143.      * codes!
  5144.      * Note 2: Char codes < 32 are identical in EBCDIC and ASCII AFAIK!
  5145.      */
  5146.     ga_append(&prt_ps_buffer, IF_EB('\\', 0134));
  5147.     switch (ch)
  5148.     {
  5149.         case BS:   ga_append(&prt_ps_buffer, IF_EB('b', 0142)); break;
  5150.         case TAB:  ga_append(&prt_ps_buffer, IF_EB('t', 0164)); break;
  5151.         case NL:   ga_append(&prt_ps_buffer, IF_EB('n', 0156)); break;
  5152.         case FF:   ga_append(&prt_ps_buffer, IF_EB('f', 0146)); break;
  5153.         case CR:   ga_append(&prt_ps_buffer, IF_EB('r', 0162)); break;
  5154.         case '(':  ga_append(&prt_ps_buffer, IF_EB('(', 0050)); break;
  5155.         case ')':  ga_append(&prt_ps_buffer, IF_EB(')', 0051)); break;
  5156.         case '\\': ga_append(&prt_ps_buffer, IF_EB('\\', 0134)); break;
  5157.  
  5158.         default:
  5159.                sprintf((char *)ch_buff, "%03o", (unsigned int)ch);
  5160. #ifdef EBCDIC
  5161.                ebcdic2ascii(ch_buff, 3);
  5162. #endif
  5163.                ga_append(&prt_ps_buffer, ch_buff[0]);
  5164.                ga_append(&prt_ps_buffer, ch_buff[1]);
  5165.                ga_append(&prt_ps_buffer, ch_buff[2]);
  5166.                break;
  5167.     }
  5168.     }
  5169.     else
  5170.     ga_append(&prt_ps_buffer, ch);
  5171.  
  5172. #ifdef FEAT_MBYTE
  5173.     /* Need to free any translated characters */
  5174.     if (prt_do_conv && (*p != NUL))
  5175.     vim_free(p);
  5176. #endif
  5177.  
  5178.     prt_text_count++;
  5179.     prt_pos_x += prt_char_width;
  5180.  
  5181.     /* The downside of fp - need a little tolerance in the right margin check */
  5182.     need_break = (prt_pos_x + prt_char_width > (prt_right_margin + 0.01));
  5183.  
  5184.     if (need_break)
  5185.     prt_flush_buffer();
  5186.  
  5187.     return need_break;
  5188. }
  5189.  
  5190.     void
  5191. mch_print_set_font(iBold, iItalic, iUnderline)
  5192.     int        iBold;
  5193.     int        iItalic;
  5194.     int        iUnderline;
  5195. {
  5196.     int        font = 0;
  5197.  
  5198.     if (iBold)
  5199.     font |= 0x01;
  5200.     if (iItalic)
  5201.     font |= 0x02;
  5202.  
  5203.     if (font != prt_font)
  5204.     {
  5205.     prt_font = font;
  5206.     prt_attribute_change = TRUE;
  5207.     prt_need_font = TRUE;
  5208.     }
  5209.     if (prt_underline != iUnderline)
  5210.     {
  5211.     prt_underline = iUnderline;
  5212.     prt_attribute_change = TRUE;
  5213.     prt_need_underline = TRUE;
  5214.     }
  5215. }
  5216.  
  5217.     void
  5218. mch_print_set_bg(bgcol)
  5219.     long_u    bgcol;
  5220. {
  5221.     prt_bgcol = bgcol;
  5222.     prt_attribute_change = TRUE;
  5223.     prt_need_bgcol = TRUE;
  5224. }
  5225.  
  5226.     void
  5227. mch_print_set_fg(fgcol)
  5228.     long_u    fgcol;
  5229. {
  5230.     if (fgcol != (long_u)prt_fgcol)
  5231.     {
  5232.     prt_fgcol = fgcol;
  5233.     prt_attribute_change = TRUE;
  5234.     prt_need_fgcol = TRUE;
  5235.     }
  5236. }
  5237.  
  5238. # endif /*FEAT_POSTSCRIPT*/
  5239. #endif /*FEAT_PRINTER*/
  5240.  
  5241.  
  5242. #ifdef FEAT_EVAL
  5243.  
  5244. # if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
  5245. static char *get_locale_val __ARGS((int what));
  5246.  
  5247.     static char *
  5248. get_locale_val(what)
  5249.     int        what;
  5250. {
  5251.     char    *loc;
  5252.  
  5253.     /* Obtain the locale value from the libraries.  For DJGPP this is
  5254.      * redefined and it doesn't use the arguments. */
  5255.     loc = setlocale(what, NULL);
  5256.  
  5257. #  if defined(__BORLANDC__)
  5258.     if (loc != NULL)
  5259.     {
  5260.     char_u    *p;
  5261.  
  5262.     /* Borland returns something like "LC_CTYPE=<name>\n"
  5263.      * Let's try to fix that bug here... */
  5264.     p = vim_strchr(loc, '=');
  5265.     if (p != NULL)
  5266.     {
  5267.         loc = ++p;
  5268.         while (*p != NUL)    /* remove trailing newline */
  5269.         {
  5270.         if (*p < ' ')
  5271.         {
  5272.             *p = NUL;
  5273.             break;
  5274.         }
  5275.         ++p;
  5276.         }
  5277.     }
  5278.     }
  5279. #  endif
  5280.  
  5281.     return loc;
  5282. }
  5283. # endif
  5284.  
  5285. /*
  5286.  * Set the "v:lang" variable according to the current locale setting.
  5287.  * Also do "v:lc_time"and "v:ctype".
  5288.  */
  5289.     void
  5290. set_lang_var()
  5291. {
  5292.     char_u    *loc;
  5293.  
  5294. # if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
  5295.     loc = (char_u *)get_locale_val(LC_CTYPE);
  5296. # else
  5297.     /* setlocale() not supported: use the default value */
  5298.     loc = (char_u *)"C";
  5299. # endif
  5300.     set_vim_var_string(VV_CTYPE, loc, -1);
  5301.  
  5302.     /* When LC_MESSAGES isn't defined use the value from LC_CTYPE. */
  5303. # if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) && defined(LC_MESSAGES)
  5304.     loc = (char_u *)get_locale_val(LC_MESSAGES);
  5305. # endif
  5306.     set_vim_var_string(VV_LANG, loc, -1);
  5307.  
  5308. # if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
  5309.     loc = (char_u *)get_locale_val(LC_TIME);
  5310. # endif
  5311.     set_vim_var_string(VV_LC_TIME, loc, -1);
  5312. }
  5313. #endif
  5314.  
  5315. #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
  5316.     && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
  5317. /*
  5318.  * ":language":  Set the language (locale).
  5319.  */
  5320.     void
  5321. ex_language(eap)
  5322.     exarg_T    *eap;
  5323. {
  5324.     char    *loc;
  5325.     char_u    *p;
  5326.     char_u    *name;
  5327.     int        what = LC_ALL;
  5328.     char    *whatstr = "";
  5329. #ifdef LC_MESSAGES
  5330. # define VIM_LC_MESSAGES LC_MESSAGES
  5331. #else
  5332. # define VIM_LC_MESSAGES 6789
  5333. #endif
  5334.  
  5335.     name = eap->arg;
  5336.  
  5337.     /* Check for "messages {name}", "ctype {name}" or "time {name}" argument.
  5338.      * Allow abbreviation, but require at least 3 characters to avoid
  5339.      * confusion with a two letter language name "me" or "ct". */
  5340.     p = skiptowhite(eap->arg);
  5341.     if ((*p == NUL || vim_iswhite(*p)) && p - eap->arg >= 3)
  5342.     {
  5343.     if (STRNICMP(eap->arg, "messages", p - eap->arg) == 0)
  5344.     {
  5345.         what = VIM_LC_MESSAGES;
  5346.         name = skipwhite(p);
  5347.         whatstr = "messages ";
  5348.     }
  5349.     else if (STRNICMP(eap->arg, "ctype", p - eap->arg) == 0)
  5350.     {
  5351.         what = LC_CTYPE;
  5352.         name = skipwhite(p);
  5353.         whatstr = "ctype ";
  5354.     }
  5355.     else if (STRNICMP(eap->arg, "time", p - eap->arg) == 0)
  5356.     {
  5357.         what = LC_TIME;
  5358.         name = skipwhite(p);
  5359.         whatstr = "time ";
  5360.     }
  5361.     }
  5362.  
  5363.     if (*name == NUL)
  5364.     {
  5365. #ifndef LC_MESSAGES
  5366.     if (what == VIM_LC_MESSAGES)
  5367.     {
  5368.         p = mch_getenv((char_u *)"LC_ALL");
  5369.         if (p == NULL || *p == NUL)
  5370.         {
  5371.         p = mch_getenv((char_u *)"LC_MESSAGES");
  5372.         if (p == NULL || *p == NUL)
  5373.             p = mch_getenv((char_u *)"LANG");
  5374.         }
  5375.     }
  5376.     else
  5377. #endif
  5378.         p = (char_u *)setlocale(what, NULL);
  5379.     if (p == NULL || *p == NUL)
  5380.         p = (char_u *)"Unknown";
  5381.     smsg((char_u *)_("Current %slanguage: \"%s\""), whatstr, p);
  5382.     }
  5383.     else
  5384.     {
  5385. #ifndef LC_MESSAGES
  5386.     if (what == VIM_LC_MESSAGES)
  5387.         loc = "";
  5388.     else
  5389. #endif
  5390.         loc = setlocale(what, (char *)name);
  5391.     if (loc == NULL)
  5392.         EMSG2(_("E197: Cannot set language to \"%s\""), name);
  5393.     else
  5394.     {
  5395. #ifdef HAVE_NL_MSG_CAT_CNTR
  5396.         /* Need to do this for GNU gettext, otherwise cached translations
  5397.          * will be used again. */
  5398.         extern int _nl_msg_cat_cntr;
  5399.  
  5400.         ++_nl_msg_cat_cntr;
  5401. #endif
  5402.         /* Reset $LC_ALL, otherwise it would overrule everyting. */
  5403.         vim_setenv((char_u *)"LC_ALL", (char_u *)"");
  5404.  
  5405.         if (what != LC_TIME)
  5406.         {
  5407.         /* Tell gettext() what to translate to.  It apparently doesn't
  5408.          * use the currently effective locale.  Also do this when
  5409.          * FEAT_GETTEXT isn't defined, so that shell commands use this
  5410.          * value. */
  5411.         if (what == LC_ALL)
  5412.             vim_setenv((char_u *)"LANG", name);
  5413.         if (what != LC_CTYPE)
  5414.             vim_setenv((char_u *)"LC_MESSAGES", name);
  5415.  
  5416.         /* Set $LC_CTYPE, because it overrules $LANG, and
  5417.          * gtk_set_locale() calls setlocale() again.  gnome_init()
  5418.          * sets $LC_CTYPE to "en_US" (that's a bug!). */
  5419.         if (what != VIM_LC_MESSAGES)
  5420.             vim_setenv((char_u *)"LC_CTYPE", name);
  5421. # ifdef FEAT_GUI_GTK
  5422.         /* Let GTK know what locale we're using.  Not sure this is
  5423.          * really needed... */
  5424.         if (gui.in_use)
  5425.             (void)gtk_set_locale();
  5426. # endif
  5427.         }
  5428.  
  5429. # ifdef FEAT_EVAL
  5430.         /* Set v:lang, v:lc_time and v:ctype to the final result. */
  5431.         set_lang_var();
  5432. # endif
  5433.     }
  5434.     }
  5435. }
  5436.  
  5437. # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
  5438. /*
  5439.  * Function given to ExpandGeneric() to obtain the possible arguments of the
  5440.  * ":language" command.
  5441.  */
  5442. /*ARGSUSED*/
  5443.     char_u *
  5444. get_lang_arg(xp, idx)
  5445.     expand_T    *xp;
  5446.     int        idx;
  5447. {
  5448.     if (idx == 0)
  5449.     return (char_u *)"messages";
  5450.     if (idx == 1)
  5451.     return (char_u *)"ctype";
  5452.     if (idx == 2)
  5453.     return (char_u *)"time";
  5454.     return NULL;
  5455. }
  5456. # endif
  5457.  
  5458. #endif
  5459.