Merge branch 'vim-with-runtime' into fix/fast-join
[vim_extended.git] / src / os_msdos.c
blob0df20c72b4404d4e09833691648b06ff0e8779c0
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * os_msdos.c
13 * MSDOS system-dependent routines.
14 * A cheap plastic imitation of the amiga dependent code.
15 * A lot in this file was made by Juergen Weigert (jw).
17 * DJGPP changes by Gert van Antwerpen
18 * Faster text screens by John Lange (jlange@zilker.net)
19 * Windows clipboard functionality added by David Kotchan (dk)
21 * Some functions are also used for Win16 (MS-Windows 3.1).
24 #include "vimio.h"
25 #include "vim.h"
27 #include <conio.h>
30 * MS-DOS only code, not used for Win16.
32 #ifndef WIN16
35 #include <bios.h>
36 #ifdef DJGPP
37 # include <dpmi.h>
38 # include <signal.h>
39 # include <sys/movedata.h>
40 # include <crt0.h>
41 # ifdef FEAT_CLIPBOARD
42 # include <sys/segments.h>
43 # endif
44 #else
45 # include <alloc.h>
46 #endif
48 #if defined(DJGPP) || defined(PROTO)
49 # define _cdecl /* DJGPP doesn't have this */
50 #endif
52 static int cbrk_pressed = FALSE; /* set by ctrl-break interrupt */
53 static int ctrlc_pressed = FALSE; /* set when ctrl-C or ctrl-break detected */
54 static int delayed_redraw = FALSE; /* set when ctrl-C detected */
56 static int bioskey_read = _NKEYBRD_READ; /* bioskey() argument: read key */
57 static int bioskey_ready = _NKEYBRD_READY; /* bioskey() argument: key ready? */
59 #ifdef FEAT_MOUSE
60 static int mouse_avail = FALSE; /* mouse present */
61 static int mouse_active; /* mouse enabled */
62 static int mouse_hidden; /* mouse not shown */
63 static int mouse_click = -1; /* mouse status */
64 static int mouse_last_click = -1; /* previous status at click */
65 static int mouse_x = -1; /* mouse x coordinate */
66 static int mouse_y = -1; /* mouse y coordinate */
67 static long mouse_click_time = 0; /* biostime() of last click */
68 static int mouse_click_count = 0; /* count for multi-clicks */
69 static int mouse_click_x = 0; /* x of previous mouse click */
70 static int mouse_click_y = 0; /* y of previous mouse click */
71 static linenr_T mouse_topline = 0; /* w_topline at previous mouse click */
72 #ifdef FEAT_DIFF
73 static int mouse_topfill = 0; /* w_topfill at previous mouse click */
74 #endif
75 static int mouse_x_div = 8; /* column = x coord / mouse_x_div */
76 static int mouse_y_div = 8; /* line = y coord / mouse_y_div */
77 #endif
79 #define BIOSTICK 55 /* biostime() increases one tick about
80 every 55 msec */
82 static int orig_attr = 0x0700; /* video attributes when starting */
84 static int S_iLeft = 0; /* Scroll window; these are 1 offset */
85 static int S_iTop = 0;
86 static int S_iRight = 0;
87 static int S_iBottom = 0;
90 * Need to remember the values, because we set horizontal and vertical
91 * edges separately.
93 static void
94 mywindow(int iLeft, int iTop, int iRight, int iBottom)
96 S_iLeft = iLeft;
97 S_iTop = iTop;
98 S_iRight = iRight;
99 S_iBottom = iBottom;
100 window(iLeft, iTop, iRight, iBottom);
103 #ifdef DJGPP
105 * For DJGPP, use our own functions for fast text screens. JML 1/18/98
108 unsigned long S_ulScreenBase = 0xb8000;
109 unsigned short S_uiAttribute = 0;
110 int S_iCurrentRow = 0; /* These are 0 offset */
111 int S_iCurrentColumn = 0;
112 short S_selVideo; /* Selector for DJGPP direct video transfers */
115 * Use burst writes to improve mch_write speed - VJN 01/10/99
117 unsigned short S_linebuffer[8000]; /* <VN> enough for 160x50 */
118 unsigned short S_blankbuffer[256]; /* <VN> max length of console line */
119 unsigned short *S_linebufferpos = S_linebuffer;
120 int S_iBufferRow;
121 int S_iBufferColumn;
123 static void
124 myflush(void)
126 if (S_linebufferpos != S_linebuffer)
128 _dosmemputw(S_linebuffer, (S_linebufferpos - S_linebuffer),
129 S_ulScreenBase
130 + S_iBufferRow * (Columns << 1) + (S_iBufferColumn << 1));
131 S_linebufferpos = S_linebuffer;
135 static void
136 mygotoxy(int x, int y)
138 S_iCurrentRow = y - 1;
139 S_iCurrentColumn = x - 1;
143 * Set the system cursor to our cursor position.
145 static void
146 set_sys_cursor(void)
148 if (term_console && full_screen)
150 myflush();
151 gotoxy(S_iCurrentColumn + 1, S_iCurrentRow + 1);
155 static void
156 setblankbuffer(unsigned short uiValue)
158 int i;
159 static unsigned short olduiValue = 0;
161 if (olduiValue != uiValue)
163 /* Load blank line buffer with spaces */
164 for (i = 0; i < Columns; ++i)
165 S_blankbuffer[i] = uiValue;
166 olduiValue = uiValue;
170 static void
171 myclreol(void)
173 /* Clear to end of line */
174 setblankbuffer(S_uiAttribute | ' ');
175 _dosmemputw(S_blankbuffer, S_iRight - S_iCurrentColumn, S_ulScreenBase
176 + (S_iCurrentRow) * (Columns << 1)
177 + (S_iCurrentColumn << 1));
180 static void
181 myclrscr(void)
183 /* Clear whole screen */
184 short iColumn;
185 int endpoint = (Rows * Columns) << 1;
187 setblankbuffer(S_uiAttribute | ' ');
189 for (iColumn = 0; iColumn < endpoint; iColumn += (Columns << 1))
190 _dosmemputw(S_blankbuffer, Columns, S_ulScreenBase + iColumn);
193 static void
194 mydelline(void)
196 short iRow, iColumn;
198 iColumn = (S_iLeft - 1) << 1;
200 /* Copy the lines underneath */
201 for (iRow = S_iCurrentRow; iRow < S_iBottom - 1; iRow++)
202 movedata(S_selVideo, (((iRow + 1) * Columns) << 1) + iColumn,
203 S_selVideo, ((iRow * Columns) << 1) + iColumn,
204 (S_iRight - S_iLeft + 1) << 1);
206 /* Clear the new row */
207 setblankbuffer(S_uiAttribute | ' ');
209 _dosmemputw(S_blankbuffer, (S_iRight - S_iLeft) + 1, S_ulScreenBase
210 + (S_iBottom - 1) * (Columns << 1) + iColumn);
213 static void
214 myinsline(void)
216 short iRow, iColumn;
218 iColumn = (S_iLeft - 1) << 1;
220 /* Copy the lines underneath */
221 for (iRow = S_iBottom - 1; iRow >= S_iTop; iRow--)
222 movedata(S_selVideo, (((iRow - 1) * Columns) << 1) + iColumn,
223 S_selVideo, ((iRow * Columns) << 1) + iColumn,
224 (S_iRight - S_iLeft + 1) << 1);
226 /* Clear the new row */
227 setblankbuffer(S_uiAttribute | ' ');
229 _dosmemputw(S_blankbuffer, (S_iRight - S_iLeft) + 1, S_ulScreenBase
230 + (S_iTop - 1) * (Columns << 1) + iColumn);
234 * Scroll the screen one line up, clear the last line.
236 static void
237 myscroll(void)
239 short iRow, iColumn;
241 iColumn = (S_iLeft - 1) << 1;
243 /* Copy the screen */
244 for (iRow = S_iTop; iRow < S_iBottom; iRow++)
245 movedata(S_selVideo, ((iRow * Columns) << 1) + iColumn,
246 S_selVideo, (((iRow - 1) * Columns) << 1) + iColumn,
247 (S_iRight - S_iLeft + 1) << 1);
249 /* Clear the bottom row */
250 setblankbuffer(S_uiAttribute | ' ');
252 _dosmemputw(S_blankbuffer, (S_iRight - S_iLeft) + 1, S_ulScreenBase
253 + (S_iBottom - 1) * (Columns << 1) + iColumn);
256 static int
257 myputch(int iChar)
259 unsigned short uiValue;
261 if (iChar == '\n')
263 myflush();
264 if (S_iCurrentRow >= S_iBottom - S_iTop)
265 myscroll();
266 else
268 S_iCurrentColumn = S_iLeft - 1;
269 S_iCurrentRow++;
272 else if (iChar == '\r')
274 myflush();
275 S_iCurrentColumn = S_iLeft - 1;
277 else if (iChar == '\b')
279 myflush();
280 if (S_iCurrentColumn >= S_iLeft)
281 S_iCurrentColumn--;
283 else if (iChar == 7)
285 sound(440); /* short beep */
286 delay(200);
287 nosound();
289 else
291 uiValue = S_uiAttribute | (unsigned char)iChar;
294 * Normal char - are we starting to buffer?
296 if (S_linebufferpos == S_linebuffer)
298 S_iBufferColumn = S_iCurrentColumn;
299 S_iBufferRow = S_iCurrentRow;
302 *S_linebufferpos++ = uiValue;
304 S_iCurrentColumn++;
305 if (S_iCurrentColumn >= S_iRight && S_iCurrentRow >= S_iBottom - S_iTop)
307 myflush();
308 myscroll();
309 S_iCurrentColumn = S_iLeft - 1;
310 S_iCurrentRow++;
314 return 0;
317 static void
318 mytextinit(struct text_info *pTextinfo)
320 S_selVideo = __dpmi_segment_to_descriptor(S_ulScreenBase >> 4);
321 S_uiAttribute = pTextinfo->normattr << 8;
324 static void
325 get_screenbase(void)
327 static union REGS regs;
329 /* old Hercules grafic card has different base address (Macewicz) */
330 regs.h.ah = 0x0f;
331 (void)int86(0x10, &regs, &regs); /* int 10 0f */
332 if (regs.h.al == 0x07) /* video mode 7 -- hercules mono */
333 S_ulScreenBase = 0xb0000;
334 else
335 S_ulScreenBase = 0xb8000;
338 static void
339 mytextattr(int iAttribute)
341 S_uiAttribute = (unsigned short)iAttribute << 8;
344 static void
345 mynormvideo(void)
347 mytextattr(orig_attr);
350 static void
351 mytextcolor(int iTextColor)
353 S_uiAttribute = (unsigned short)((S_uiAttribute & 0xf000)
354 | (unsigned short)iTextColor << 8);
357 static void
358 mytextbackground(int iBkgColor)
360 S_uiAttribute = (unsigned short)((S_uiAttribute & 0x0f00)
361 | (unsigned short)(iBkgColor << 12));
364 * Getdigits: Get a number from a string and skip over it.
365 * Note: the argument is a pointer to a char_u pointer!
368 static long
369 mygetdigits(pp)
370 char_u **pp;
372 char_u *p;
373 long retval = 0;
375 p = *pp;
376 if (*p == '-') /* skip negative sign */
377 ++p;
378 while (VIM_ISDIGIT(*p))
380 retval = (retval * 10) + (*p - '0');
381 ++p;
383 if (**pp == '-') /* process negative sign */
384 retval = -retval;
386 *pp = p;
387 return retval;
389 #else
390 # define mygotoxy gotoxy
391 # define myputch putch
392 # define myscroll scroll
393 # define mynormvideo normvideo
394 # define mytextattr textattr
395 # define mytextcolor textcolor
396 # define mytextbackground textbackground
397 # define mygetdigits getdigits
398 # define myclreol clreol
399 # define myclrscr clrscr
400 # define myinsline insline
401 # define mydelline delline
402 #endif
404 static const struct
406 char_u scancode;
407 char_u metakey;
408 } altkey_table[] =
410 {0x1e, 0xe1}, /* a */
411 {0x30, 0xe2}, /* b */
412 {0x2e, 0xe3}, /* c */
413 {0x20, 0xe4}, /* d */
414 {0x12, 0xe5}, /* e */
415 {0x21, 0xe6}, /* f */
416 {0x22, 0xe7}, /* g */
417 {0x23, 0xe8}, /* h */
418 {0x17, 0xe9}, /* i */
419 {0x24, 0xea}, /* j */
420 {0x25, 0xeb}, /* k */
421 {0x26, 0xec}, /* l */
422 {0x32, 0xed}, /* m */
423 {0x31, 0xee}, /* n */
424 {0x18, 0xef}, /* o */
425 {0x19, 0xf0}, /* p */
426 {0x10, 0xf1}, /* q */
427 {0x13, 0xf2}, /* r */
428 {0x1f, 0xf3}, /* s */
429 {0x14, 0xf4}, /* t */
430 {0x16, 0xf5}, /* u */
431 {0x2f, 0xf6}, /* v */
432 {0x11, 0xf7}, /* w */
433 {0x2d, 0xf8}, /* x */
434 {0x15, 0xf9}, /* y */
435 {0x2c, 0xfa}, /* z */
436 {0x78, 0xb1}, /* 1 */
437 {0x79, 0xb2}, /* 2 */
438 {0x7a, 0xb3}, /* 3 */
439 {0x7b, 0xb4}, /* 4 */
440 {0x7c, 0xb5}, /* 5 */
441 {0x7d, 0xb6}, /* 6 */
442 {0x7e, 0xb7}, /* 7 */
443 {0x7f, 0xb8}, /* 8 */
444 {0x80, 0xb9}, /* 9 */
445 {0x81, 0xb0}, /* 0 */
449 * Translate extended keycodes into meta-chars where applicable
451 static int
452 translate_altkeys(int rawkey)
454 int i, c;
456 if ((rawkey & 0xff) == 0)
458 c = (rawkey >> 8);
459 for (i = sizeof(altkey_table) / sizeof(altkey_table[0]); --i >= 0; )
461 if (c == altkey_table[i].scancode)
462 return (int)altkey_table[i].metakey;
465 return rawkey;
469 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
471 void
472 mch_set_normal_colors()
474 char_u *p;
475 int n;
477 cterm_normal_fg_color = (orig_attr & 0xf) + 1;
478 cterm_normal_bg_color = ((orig_attr >> 4) & 0xf) + 1;
479 if (T_ME[0] == ESC && T_ME[1] == '|')
481 p = T_ME + 2;
482 n = getdigits(&p);
483 if (*p == 'm' && n > 0)
485 cterm_normal_fg_color = (n & 0xf) + 1;
486 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
491 #if defined(MCH_CURSOR_SHAPE) || defined(PROTO)
493 * Save/restore the shape of the cursor.
494 * call with FALSE to save, TRUE to restore
496 static void
497 mch_restore_cursor_shape(int restore)
499 static union REGS regs;
500 static int saved = FALSE;
502 if (restore)
504 if (saved)
505 regs.h.ah = 0x01; /* Set Cursor */
506 else
507 return;
509 else
511 regs.h.ah = 0x03; /* Get Cursor */
512 regs.h.bh = 0x00; /* Page */
513 saved = TRUE;
516 (void)int86(0x10, &regs, &regs);
520 * Set the shape of the cursor.
521 * 'thickness' can be from 0 (thin) to 7 (block)
523 static void
524 mch_set_cursor_shape(int thickness)
526 union REGS regs;
528 regs.h.ch = 7 - thickness; /* Starting Line */
529 regs.h.cl = 7; /* Ending Line */
530 regs.h.ah = 0x01; /* Set Cursor */
531 (void)int86(0x10, &regs, &regs);
534 void
535 mch_update_cursor(void)
537 int idx;
538 int thickness;
541 * How the cursor is drawn depends on the current mode.
543 idx = get_shape_idx(FALSE);
545 if (shape_table[idx].shape == SHAPE_BLOCK)
546 thickness = 7;
547 else
548 thickness = (7 * shape_table[idx].percentage + 90) / 100;
549 mch_set_cursor_shape(thickness);
551 #endif
554 * Return amount of memory currently available.
556 long_u
557 mch_avail_mem(int special)
559 #ifdef DJGPP
560 return _go32_dpmi_remaining_virtual_memory();
561 #else
562 return coreleft();
563 #endif
566 #ifdef FEAT_MOUSE
569 * Set area where mouse can be moved to: The whole screen.
570 * Rows and Columns must be valid when calling!
572 static void
573 mouse_area(void)
575 union REGS regs;
577 if (mouse_avail)
579 regs.x.cx = 0; /* mouse visible between cx and dx */
580 regs.x.dx = Columns * mouse_x_div - 1;
581 regs.x.ax = 7;
582 (void)int86(0x33, &regs, &regs);
584 regs.x.cx = 0; /* mouse visible between cx and dx */
585 regs.x.dx = Rows * mouse_y_div - 1;
586 regs.x.ax = 8;
587 (void)int86(0x33, &regs, &regs);
591 static void
592 show_mouse(int on)
594 static int was_on = FALSE;
595 union REGS regs;
597 if (mouse_avail)
599 if (!mouse_active || mouse_hidden)
600 on = FALSE;
602 * Careful: Each switch on must be compensated by exactly one switch
603 * off
605 if ((on && !was_on) || (!on && was_on))
607 was_on = on;
608 regs.x.ax = on ? 1 : 2;
609 int86(0x33, &regs, &regs); /* show mouse */
610 if (on)
611 mouse_area();
616 #endif
619 * Version of kbhit() and getch() that use direct console I/O.
620 * This avoids trouble with CTRL-P and the like, and should work over a telnet
621 * connection (it works for Xvi).
624 static int cons_key = -1;
627 * Try to get one character directly from the console.
628 * If there is a key, it is stored in cons_key.
629 * Only call when cons_key is -1!
631 static void
632 cons_getkey(void)
634 union REGS regs;
636 /* call DOS function 6: Direct console I/O */
637 regs.h.ah = 0x06;
638 regs.h.dl = 0xff;
639 (void)intdos(&regs, &regs);
640 if ((regs.x.flags & 0x40) == 0) /* zero flag not set? */
641 cons_key = (regs.h.al & 0xff);
645 * Return TRUE if a character is available.
647 static int
648 cons_kbhit(void)
650 if (cons_key < 0)
651 cons_getkey();
652 return (cons_key >= 0);
656 * Return a character from the console.
657 * Should only be called when vim_kbhit() returns TRUE.
659 static int
660 cons_getch(void)
662 int c = -1;
664 if (cons_key < 0)
665 cons_getkey();
666 c = cons_key;
667 cons_key = -1;
668 return c;
672 #ifdef DJGPP
674 * DJGPP provides a kbhit() function that goes to the BIOS instead of DOS.
675 * This doesn't work for terminals connected to a serial port.
676 * Redefine kbhit() here to make it work.
678 static int
679 vim_kbhit(void)
681 union REGS regs;
683 regs.h.ah = 0x0b;
684 (void)intdos(&regs, &regs);
685 return regs.h.al;
688 #ifdef kbhit
689 # undef kbhit /* might have been defined in conio.h */
690 #endif
691 #define kbhit() vim_kbhit()
693 #endif
696 * Simulate WaitForChar() by slowly polling with bioskey(1) or kbhit().
698 * If Vim should work over the serial line after a 'ctty com1' we must use
699 * kbhit() and getch(). (jw)
700 * Usually kbhit() is not used, because then CTRL-C and CTRL-P
701 * will be catched by DOS (mool).
703 * return TRUE if a character is available, FALSE otherwise
706 #define FOREVER 1999999999L
708 static int
709 WaitForChar(long msec)
711 long starttime = 0;
713 if (msec != 0)
714 starttime = biostime(0, 0L);
716 for (;;)
718 #ifdef FEAT_MOUSE
719 long clicktime;
720 static int old_status = 0;
721 union REGS regs;
722 int x, y;
724 if (mouse_avail && mouse_active && mouse_click < 0)
726 regs.x.ax = 3;
727 int86(0x33, &regs, &regs); /* check mouse status */
728 /* only recognize button-down and button-up event */
729 x = regs.x.cx / mouse_x_div;
730 y = regs.x.dx / mouse_y_div;
731 if ((old_status == 0) != (regs.x.bx == 0))
733 if (old_status) /* button up */
734 mouse_click = MOUSE_RELEASE;
735 else /* button down */
738 * Translate MSDOS mouse events to Vim mouse events.
739 * TODO: should handle middle mouse button, by pressing
740 * left and right at the same time.
742 if (regs.x.bx & MSDOS_MOUSE_LEFT)
743 mouse_click = MOUSE_LEFT;
744 else if (regs.x.bx & MSDOS_MOUSE_RIGHT)
745 mouse_click = MOUSE_RIGHT;
746 else if (regs.x.bx & MSDOS_MOUSE_MIDDLE)
747 mouse_click = MOUSE_MIDDLE;
750 * Find out if this is a multi-click
752 clicktime = biostime(0, 0L);
753 if (mouse_click_x == x && mouse_click_y == y
754 && mouse_topline == curwin->w_topline
755 #ifdef FEAT_DIFF
756 && mouse_topfill == curwin->w_topfill
757 #endif
758 && mouse_click_count != 4
759 && mouse_click == mouse_last_click
760 && clicktime < mouse_click_time
761 + p_mouset / BIOSTICK)
762 ++mouse_click_count;
763 else
764 mouse_click_count = 1;
765 mouse_click_time = clicktime;
766 mouse_last_click = mouse_click;
767 mouse_click_x = x;
768 mouse_click_y = y;
769 mouse_topline = curwin->w_topline;
770 #ifdef FEAT_DIFF
771 mouse_topfill = curwin->w_topfill;
772 #endif
773 SET_NUM_MOUSE_CLICKS(mouse_click, mouse_click_count);
776 else if (old_status && (x != mouse_x || y != mouse_y))
777 mouse_click = MOUSE_DRAG;
778 old_status = regs.x.bx;
779 if (mouse_hidden && mouse_x >= 0 && (mouse_x != x || mouse_y != y))
781 mouse_hidden = FALSE;
782 show_mouse(TRUE);
784 mouse_x = x;
785 mouse_y = y;
787 #endif
789 if ((p_consk ? cons_kbhit()
790 : p_biosk ? bioskey(bioskey_ready) : kbhit())
791 || cbrk_pressed
792 #ifdef FEAT_MOUSE
793 || mouse_click >= 0
794 #endif
796 return TRUE;
798 * Use biostime() to wait until our time is done.
799 * We busy-wait here. Unfortunately, delay() and usleep() have been
800 * reported to give problems with the original Windows 95. This is
801 * fixed in service pack 1, but not everybody installed that.
802 * The DJGPP implementation of usleep() uses a busy-wait loop too.
804 if (msec == 0 || (msec != FOREVER
805 && biostime(0, 0L) > starttime + msec / BIOSTICK))
806 break;
808 #ifdef DJGPP
809 /* Yield the CPU to the next process. */
810 __dpmi_yield();
811 #endif
813 return FALSE;
817 * don't do anything for about "msec" msec
819 void
820 mch_delay(
821 long msec,
822 int ignoreinput)
824 long starttime;
826 if (ignoreinput)
829 * We busy-wait here. Unfortunately, delay() and usleep() have been
830 * reported to give problems with the original Windows 95. This is
831 * fixed in service pack 1, but not everybody installed that.
833 starttime = biostime(0, 0L);
834 while (biostime(0, 0L) < starttime + msec / BIOSTICK)
837 else
838 WaitForChar(msec);
842 * mch_write(): write the output buffer to the screen
844 void
845 mch_write(
846 char_u *s,
847 int len)
849 char_u *p;
850 int row, col;
852 if (term_console && full_screen)
853 while (len--)
855 /* translate ESC | sequences into bios calls */
856 if (p_wd) /* testing: wait a bit for each char */
857 WaitForChar(p_wd);
859 if (s[0] == '\n')
860 #ifdef DJGPP
862 myflush();
863 S_iCurrentColumn = S_iLeft - 1;
865 #else
866 myputch('\r');
867 #endif
868 else if (s[0] == ESC && len > 1 && s[1] == '|')
870 switch (s[2])
872 #ifdef DJGPP
873 case 'B': ScreenVisualBell();
874 goto got3;
875 #endif
876 case 'J':
877 #ifdef DJGPP
878 myflush();
879 #endif
880 myclrscr();
881 goto got3;
883 case 'K':
884 #ifdef DJGPP
885 myflush();
886 #endif
887 myclreol();
888 goto got3;
890 case 'L':
891 #ifdef DJGPP
892 myflush();
893 #endif
894 myinsline();
895 goto got3;
897 case 'M':
898 #ifdef DJGPP
899 myflush();
900 #endif
901 mydelline();
902 got3: s += 3;
903 len -= 2;
904 continue;
906 case '0':
907 case '1':
908 case '2':
909 case '3':
910 case '4':
911 case '5':
912 case '6':
913 case '7':
914 case '8':
915 case '9': p = s + 2;
916 row = mygetdigits(&p); /* no check for length! */
917 if (p > s + len)
918 break;
919 if (*p == ';')
921 ++p;
922 col = mygetdigits(&p); /* no check for length! */
923 if (p > s + len)
924 break;
925 if (*p == 'H' || *p == 'r' || *p == 'V')
927 #ifdef DJGPP
928 myflush();
929 #endif
930 if (*p == 'H') /* set cursor position */
931 mygotoxy(col, row);
932 else if (*p == 'V')
933 mywindow(row, S_iTop, col, S_iBottom);
934 else /* set scroll region */
935 mywindow(S_iLeft, row, S_iRight, col);
936 len -= p - s;
937 s = p + 1;
938 continue;
941 else if (*p == 'm' || *p == 'f' || *p == 'b')
943 if (*p == 'm') /* set color */
945 if (row == 0)
946 mynormvideo();/* reset color */
947 else
948 mytextattr(row);
950 else if (*p == 'f') /* set foreground color */
951 mytextcolor(row);
952 else /* set background color */
953 mytextbackground(row);
955 len -= p - s;
956 s = p + 1;
957 continue;
961 myputch(*s++);
963 else
965 write(1, s, (unsigned)len);
970 * mch_inchar(): low level input funcion.
971 * Get a characters from the keyboard.
972 * If time == 0 do not wait for characters.
973 * If time == n wait a short time for characters.
974 * If time == -1 wait forever for characters.
976 * return the number of characters obtained
979 mch_inchar(
980 char_u *buf,
981 int maxlen,
982 long time,
983 int tb_change_cnt)
985 int len = 0;
986 int c;
987 int tmp_c;
988 static int nextchar = 0; /* may keep character when maxlen == 1 */
991 * if we got a ctrl-C when we were busy, there will be a "^C" somewhere
992 * on the sceen, so we need to redisplay it.
994 if (delayed_redraw)
996 delayed_redraw = FALSE;
997 update_screen(CLEAR);
998 setcursor();
999 out_flush();
1002 /* return remaining character from last call */
1003 if (nextchar)
1005 *buf = nextchar;
1006 nextchar = 0;
1007 return 1;
1010 #ifdef FEAT_MOUSE
1011 if (time != 0)
1012 show_mouse(TRUE);
1013 #endif
1014 #ifdef DJGPP
1015 set_sys_cursor();
1016 #endif
1017 if (time >= 0)
1019 if (WaitForChar(time) == 0) /* no character available */
1021 #ifdef FEAT_MOUSE
1022 show_mouse(FALSE);
1023 #endif
1024 return 0;
1027 else /* time == -1 */
1030 * If there is no character available within 2 seconds (default)
1031 * write the autoscript file to disk. Or cause the CursorHold event
1032 * to be triggered.
1034 if (WaitForChar(p_ut) == 0)
1036 #ifdef FEAT_AUTOCMD
1037 if (trigger_cursorhold() && maxlen >= 3)
1039 buf[0] = K_SPECIAL;
1040 buf[1] = KS_EXTRA;
1041 buf[2] = (int)KE_CURSORHOLD;
1042 return 3;
1044 #endif
1045 before_blocking();
1048 WaitForChar(FOREVER); /* wait for key or mouse click */
1051 * Try to read as many characters as there are, until the buffer is full.
1054 * we will get at least one key. Get more if they are available
1055 * After a ctrl-break we have to read a 0 (!) from the buffer.
1056 * bioskey(1) will return 0 if no key is available and when a
1057 * ctrl-break was typed. When ctrl-break is hit, this does not always
1058 * implies a key hit.
1060 cbrk_pressed = FALSE;
1061 #ifdef FEAT_MOUSE
1062 if (mouse_click >= 0 && maxlen >= 5)
1064 len = 5;
1065 *buf++ = ESC + 128;
1066 *buf++ = 'M';
1067 *buf++ = mouse_click;
1068 *buf++ = mouse_x + '!';
1069 *buf++ = mouse_y + '!';
1070 mouse_click = -1;
1072 else
1073 #endif
1075 #ifdef FEAT_MOUSE
1076 mouse_hidden = TRUE;
1077 #endif
1078 if (p_biosk && !p_consk)
1080 while ((len == 0 || bioskey(bioskey_ready)) && len < maxlen)
1082 c = translate_altkeys(bioskey(bioskey_read)); /* get the key */
1084 * translate a few things for inchar():
1085 * 0x0000 == CTRL-break -> 3 (CTRL-C)
1086 * 0x0300 == CTRL-@ -> NUL
1087 * 0xnn00 == extended key code -> K_NUL, nn
1088 * 0xnne0 == enhanced keyboard -> K_NUL, nn
1089 * K_NUL -> K_NUL, 3
1091 if (c == 0)
1092 c = 3;
1093 else if (c == 0x0300)
1094 c = NUL;
1095 else if ((c & 0xff) == 0
1096 || c == K_NUL
1097 || c == 0x4e2b
1098 || c == 0x4a2d
1099 || c == 0x372a
1100 || ((c & 0xff) == 0xe0 && c != 0xe0))
1102 if (c == K_NUL)
1103 c = 3;
1104 else
1105 c >>= 8;
1106 *buf++ = K_NUL;
1107 ++len;
1110 if (len < maxlen)
1112 *buf++ = c;
1113 len++;
1114 #ifdef FEAT_MBYTE
1115 /* Convert from 'termencoding' to 'encoding'. Only
1116 * translate normal characters, not key codes. */
1117 if (input_conv.vc_type != CONV_NONE
1118 && (len == 1 || buf[-2] != K_NUL))
1119 len += convert_input(buf - 1, 1, maxlen - len + 1) - 1;
1120 #endif
1122 else
1123 nextchar = c;
1126 else
1128 while ((len == 0 || (p_consk ? cons_kbhit() : kbhit()))
1129 && len < maxlen)
1131 switch (c = (p_consk ? cons_getch() : getch()))
1133 case 0:
1134 /* NUL means that there is another character.
1135 * Get it immediately, because kbhit() doesn't always
1136 * return TRUE for the second character.
1138 if (p_consk)
1139 c = cons_getch();
1140 else
1141 c = getch();
1142 tmp_c = translate_altkeys(c << 8);
1143 if (tmp_c == (c << 8))
1145 *buf++ = K_NUL;
1146 ++len;
1148 else
1149 c = tmp_c;
1150 break;
1151 case K_NUL:
1152 *buf++ = K_NUL;
1153 ++len;
1154 c = 3;
1155 break;
1156 case 3:
1157 cbrk_pressed = TRUE;
1158 /*FALLTHROUGH*/
1159 default:
1160 break;
1162 if (len < maxlen)
1164 *buf++ = c;
1165 ++len;
1167 else
1168 nextchar = c;
1172 #ifdef FEAT_MOUSE
1173 show_mouse(FALSE);
1174 #endif
1176 beep_count = 0; /* may beep again now that we got some chars */
1177 return len;
1181 * return non-zero if a character is available
1184 mch_char_avail(void)
1186 return WaitForChar(0L);
1189 #ifdef DJGPP
1190 # define INT_ARG int
1191 #else
1192 # define INT_ARG
1193 #endif
1196 * function for ctrl-break interrupt
1198 static void interrupt
1199 #ifdef DJGPP
1200 catch_cbrk(int a)
1201 #else
1202 catch_cbrk(void)
1203 #endif
1205 cbrk_pressed = TRUE;
1206 ctrlc_pressed = TRUE;
1209 #ifndef DJGPP
1211 * ctrl-break handler for DOS. Never called when a ctrl-break is typed, because
1212 * we catch interrupt 1b. If you type ctrl-C while Vim is waiting for a
1213 * character this function is not called. When a ctrl-C is typed while Vim is
1214 * busy this function may be called. By that time a ^C has been displayed on
1215 * the screen, so we have to redisplay the screen. We can't do that here,
1216 * because we may be called by DOS. The redraw is in mch_inchar().
1218 static int _cdecl
1219 cbrk_handler(void)
1221 delayed_redraw = TRUE;
1222 return 1; /* resume operation after ctrl-break */
1226 * function for critical error interrupt
1227 * For DOS 1 and 2 return 0 (Ignore).
1228 * For DOS 3 and later return 3 (Fail)
1230 static void interrupt
1231 catch_cint(bp, di, si, ds, es, dx, cx, bx, ax)
1232 unsigned bp, di, si, ds, es, dx, cx, bx, ax;
1234 ax = (ax & 0xff00); /* set AL to 0 */
1235 if (_osmajor >= 3)
1236 ax |= 3; /* set AL to 3 */
1238 #endif
1241 * Set the interrupt vectors for use with Vim on or off.
1242 * on == TRUE means as used within Vim
1244 static void
1245 set_interrupts(int on)
1247 static int saved_cbrk;
1248 #ifndef DJGPP
1249 static void interrupt (*old_cint)();
1250 #endif
1251 static void interrupt (*old_cbrk)(INT_ARG);
1253 if (on)
1255 saved_cbrk = getcbrk(); /* save old ctrl-break setting */
1256 setcbrk(0); /* do not check for ctrl-break */
1257 #ifdef DJGPP
1258 old_cbrk = signal(SIGINT, catch_cbrk); /* critical error interrupt */
1259 #else
1260 old_cint = getvect(0x24); /* save old critical error interrupt */
1261 setvect(0x24, catch_cint); /* install our critical error interrupt */
1262 old_cbrk = getvect(0x1B); /* save old ctrl-break interrupt */
1263 setvect(0x1B, catch_cbrk); /* install our ctrl-break interrupt */
1264 ctrlbrk(cbrk_handler); /* vim's ctrl-break handler */
1265 #endif
1266 if (term_console)
1267 out_str(T_ME); /* set colors */
1269 else
1271 setcbrk(saved_cbrk); /* restore ctrl-break setting */
1272 #ifdef DJGPP
1273 signal(SIGINT,old_cbrk); /* critical error interrupt */
1274 #else
1275 setvect(0x24, old_cint); /* restore critical error interrupt */
1276 setvect(0x1B, old_cbrk); /* restore ctrl-break interrupt */
1277 #endif
1278 /* restore ctrl-break handler, how ??? */
1279 if (term_console)
1280 mynormvideo(); /* restore screen colors */
1285 * We have no job control, fake it by starting a new shell.
1287 void
1288 mch_suspend(void)
1290 suspend_shell();
1293 extern int _fmode;
1296 * Prepare window for use by Vim.
1298 void
1299 mch_init(void)
1301 union REGS regs;
1303 #if defined(DJGPP) && defined(FEAT_CLIPBOARD)
1304 __dpmi_regs dpmi_regs;
1305 #endif
1308 * Get the video attributes at the cursor. These will be used as the
1309 * default attributes.
1311 regs.h.ah = 0x08;
1312 regs.h.bh = 0x00; /* video page 0 */
1313 int86(0x10, &regs, &regs);
1314 orig_attr = regs.h.ah;
1315 mynormvideo();
1316 if (cterm_normal_fg_color == 0)
1317 cterm_normal_fg_color = (orig_attr & 0xf) + 1;
1318 if (cterm_normal_bg_color == 0)
1319 cterm_normal_bg_color = ((orig_attr >> 4) & 0xf) + 1;
1321 term_console = TRUE; /* assume using the console for the things here */
1322 _fmode = O_BINARY; /* we do our own CR-LF translation */
1323 out_flush();
1324 set_interrupts(TRUE); /* catch interrupts */
1326 #ifdef DJGPP
1328 * Use Long File Names by default, if $LFN not set.
1330 if (getenv("LFN") == NULL)
1331 putenv("LFN=y");
1333 get_screenbase();
1334 #endif
1336 #ifdef FEAT_MOUSE
1337 /* find out if a MS compatible mouse is available */
1338 regs.x.ax = 0;
1339 (void)int86(0x33, &regs, &regs);
1340 mouse_avail = regs.x.ax;
1341 /* best guess for mouse coordinate computations */
1342 mch_get_shellsize();
1343 if (Columns <= 40)
1344 mouse_x_div = 16;
1345 if (Rows == 30)
1346 mouse_y_div = 16;
1347 #endif
1350 * Try switching to 16 colors for background, instead of 8 colors and
1351 * blinking. Does this always work? Can the old value be restored?
1353 regs.x.ax = 0x1003;
1354 regs.h.bl = 0x00;
1355 regs.h.bh = 0x00;
1356 int86(0x10, &regs, &regs);
1359 * Test if we have an enhanced AT keyboard. Write 0xFFFF to the keyboard
1360 * buffer and try to read it back. If we can't in 16 tries, it's an old
1361 * type XT keyboard.
1363 regs.h.ah = 0x05;
1364 regs.x.cx = 0xffff;
1365 int86(0x16, &regs, &regs);
1366 if (regs.h.al != 1) /* skip this when keyboard buffer is full */
1368 int i;
1370 for (i = 0; i < 16; ++i)
1372 regs.h.ah = 0x10;
1373 int86(0x16, &regs, &regs);
1374 if (regs.x.ax == 0xffff)
1375 break;
1377 if (i == 16) /* 0xffff not read, must be old keyboard */
1379 bioskey_read = 0;
1380 bioskey_ready = 1;
1384 #ifdef MCH_CURSOR_SHAPE
1385 /* Save the old cursor shape */
1386 mch_restore_cursor_shape(FALSE);
1387 /* Initialise the cursor shape */
1388 mch_update_cursor();
1389 #endif
1391 #if defined(DJGPP) && defined(FEAT_CLIPBOARD)
1393 * Check to see if the Windows clipboard is available, ie. are we
1394 * running from a DOS session within Windows. Obviously, the Windows
1395 * clipboard will not be available if we're running under pure DOS.
1397 * int 0x2f, AX = 0x1700 identifies the Windows version we're running
1398 * under. Upon return from the interrupt, if AX is unchanged, we're
1399 * running under pure DOS and no Windows clipboard is available.
1401 * Remark: could use int86() here but __dpmi_int() is recommended in
1402 * the DJGPP docs, since int86() doesn't cover all available interrupts.
1404 dpmi_regs.x.ax = 0x1700;
1405 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
1406 /* real-mode interrupt failed? */
1407 dpmi_regs.x.ax = 0x1700; /* force failure */
1409 if (dpmi_regs.x.ax == 0x1700) /* no change in AX? */
1410 clip_init(FALSE); /* no clipboard available, too bad */
1411 else /* else, running under Windows, OK */
1412 clip_init(TRUE); /* clipboard is available */
1413 #endif
1417 mch_check_win(
1418 int argc,
1419 char **argv)
1421 /* store argv[0], may be used for $VIM */
1422 if (*argv[0] != NUL)
1423 exe_name = FullName_save((char_u *)argv[0], FALSE);
1426 * Try the DOS search path. The executable may in
1427 * fact be called differently, so try this last.
1429 if (exe_name == NULL || *exe_name == NUL)
1430 exe_name = searchpath("vim.exe");
1432 if (isatty(1))
1433 return OK;
1434 return FAIL;
1438 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1441 mch_input_isatty(void)
1443 if (isatty(read_cmd_fd))
1444 return TRUE;
1445 return FALSE;
1448 #if defined(USE_FNAME_CASE) || defined(PROTO)
1450 * fname_case(): Set the case of the file name, if it already exists.
1451 * TODO: should expand short to long file names. Need to use DOS interrupts,
1452 * see DJGPP sources libc/dos/dir/findfirs.c.
1454 void
1455 fname_case(char_u *name, int len)
1457 char_u *tail;
1458 struct ffblk fb;
1460 slash_adjust(name);
1461 if (findfirst(name, &fb, 0) == 0)
1463 tail = gettail(name);
1464 if (len == 0 ? STRLEN(tail) == STRLEN(fb.ff_name)
1465 : (tail - name) + STRLEN(fb.ff_name) < len)
1466 STRCPY(tail, fb.ff_name);
1469 #endif
1472 * return process ID
1474 long
1475 mch_get_pid(void)
1477 return (long)0;
1481 * Change default drive (just like _chdrive of Borland C 3.1)
1483 static int
1484 change_drive(int drive)
1486 union REGS regs;
1488 regs.h.ah = 0x0e;
1489 regs.h.dl = drive - 1;
1490 intdos(&regs, &regs); /* set default drive */
1491 regs.h.ah = 0x19;
1492 intdos(&regs, &regs); /* get default drive */
1493 if (regs.h.al == drive - 1)
1494 return 0;
1495 return -1;
1499 * Get absolute file name into buffer 'buf' of length 'len' bytes.
1500 * All slashes are replaced with backslashes, to avoid trouble when comparing
1501 * file names. When 'shellslash' set do it the other way around.
1503 * return FAIL for failure, OK otherwise
1506 mch_FullName(
1507 char_u *fname,
1508 char_u *buf,
1509 int len,
1510 int force)
1512 if (!force && mch_isFullName(fname)) /* already expanded */
1514 vim_strncpy(buf, fname, len - 1);
1515 slash_adjust(buf);
1516 return OK;
1519 #ifdef __BORLANDC__ /* Only Borland C++ has this */
1520 if (_fullpath((char *)buf, (char *)fname, len - 1) == NULL)
1521 return FAIL;
1522 return OK;
1523 #else /* almost the same as mch_FullName() in os_unix.c */
1525 # if 1
1526 char_u fullpath[MAXPATHL];
1528 if (!_truename(fname, fullpath))
1529 return FAIL;
1530 slash_adjust(fullpath); /* Only needed when 'shellslash' set */
1531 vim_strncpy(buf, fullpath, len - 1);
1532 return OK;
1534 # else /* Old code, to be deleted... */
1535 int l;
1536 char_u olddir[MAXPATHL];
1537 char_u *p, *q;
1538 int c;
1539 int retval = OK;
1541 *buf = 0;
1543 * change to the directory for a moment,
1544 * and then do the getwd() (and get back to where we were).
1545 * This will get the correct path name with "../" things.
1547 p = vim_strrchr(fname, '/');
1548 q = vim_strrchr(fname, '\\');
1549 if (q != NULL && (p == NULL || q > p))
1550 p = q;
1551 q = vim_strrchr(fname, ':');
1552 if (q != NULL && (p == NULL || q > p))
1553 p = q;
1554 if (p != NULL)
1556 if (getcwd(olddir, MAXPATHL) == NULL)
1558 p = NULL; /* can't get current dir: don't chdir */
1559 retval = FAIL;
1561 else
1563 if (p == fname) /* /fname */
1564 q = p + 1; /* -> / */
1565 else if (q + 1 == p) /* ... c:\foo */
1566 q = p + 1; /* -> c:\ */
1567 else /* but c:\foo\bar */
1568 q = p; /* -> c:\foo */
1570 c = *q; /* truncate at start of fname */
1571 *q = NUL;
1572 # ifdef DJGPP
1573 STRCPY(buf, fname);
1574 slash_adjust(buf); /* needed when fname starts with \ */
1575 if (mch_chdir(buf)) /* change to the directory */
1576 # else
1577 if (mch_chdir(fname)) /* change to the directory */
1578 # endif
1579 retval = FAIL;
1580 else
1582 fname = q;
1583 if (c == psepc) /* if we cut the name at a */
1584 fname++; /* '\', don't add it again */
1586 *q = c;
1589 if (getcwd(buf, len) == NULL)
1591 retval = FAIL;
1592 *buf = NUL;
1594 # ifdef USE_FNAME_CASE
1595 else
1597 char_u *head;
1598 char_u *tail;
1599 struct ffblk fb;
1600 int c;
1601 int added;
1603 /* Apparently "longna~1" isn't expanded by getcwd(), at least not
1604 * for DJGPP. Expand it here. Have to do each dirname
1605 * separately. */
1606 slash_adjust(buf);
1607 head = buf;
1608 if (isalpha(*head) && head[1] == ':')
1609 head += 2; /* skip "c:" */
1610 while (*head != NUL)
1612 /* Advance "head" to the start of a dirname and "tail" to just
1613 * after it. */
1614 while (*head == '/' || *head == '\\')
1615 ++head;
1616 for (tail = head; *tail != NUL; ++tail)
1617 if (*tail == '/' || *tail == '\\')
1618 break;
1619 c = *tail;
1620 *tail = NUL;
1622 if (findfirst(buf, &fb, FA_DIREC) == 0)
1624 added = STRLEN(fb.ff_name);
1625 if ((head - buf) + added + STRLEN(tail + 1) + 2 < len)
1627 added -= (tail - head);
1628 if (added != 0)
1629 STRMOVE(tail + 1 + added, tail + 1);
1630 STRCPY(head, fb.ff_name);
1631 tail += added;
1634 *tail = c;
1635 head = tail;
1638 # endif
1639 if (p != NULL)
1640 mch_chdir(olddir);
1642 * Concatenate the file name to the path.
1644 if (*fname != NUL)
1646 l = STRLEN(buf);
1647 if (l > 0 && buf[l - 1] != '/' && buf[l - 1] != '\\')
1648 strcat(buf, pseps);
1649 strcat(buf, fname);
1651 return retval;
1652 # endif
1654 #endif
1658 * Replace all slashes by backslashes.
1659 * This used to be the other way around, but MS-DOS sometimes has problems
1660 * with slashes (e.g. in a command name). We can't have mixed slashes and
1661 * backslashes, because comparing file names will not work correctly. The
1662 * commands that use a file name should try to avoid the need to type a
1663 * backslash twice.
1664 * When 'shellslash' set do it the other way around.
1666 void
1667 slash_adjust(char_u *p)
1669 #ifdef OLD_DJGPP /* this seems to have been fixed in DJGPP 2.01 */
1670 /* DJGPP can't handle a file name that starts with a backslash, and when it
1671 * starts with a slash there should be no backslashes */
1672 if (*p == '\\' || *p == '/')
1673 while (*p)
1675 if (*p == '\\')
1676 *p = '/';
1677 mb_ptr_adv(p);
1679 else
1680 #endif
1681 while (*p)
1683 if (*p == psepcN)
1684 *p = psepc;
1685 mb_ptr_adv(p);
1690 * Return TRUE if "fname" does not depend on the current directory.
1693 mch_isFullName(char_u *fname)
1695 /* A name like "d:/foo" and "//server/share" is absolute */
1696 return (fname[0] != NUL && fname[1] == ':'
1697 && (fname[2] == '/' || fname[2] == '\\'))
1698 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\'));
1702 void
1703 mch_early_init(void)
1708 * Careful: mch_exit() may be called before mch_init()!
1710 void
1711 mch_exit(int r)
1713 settmode(TMODE_COOK);
1714 stoptermcap();
1715 set_interrupts(FALSE); /* restore interrupts */
1716 #ifdef DJGPP
1717 set_sys_cursor();
1718 #endif
1719 /* Somehow outputting CR-NL causes the original colors to be restored */
1720 out_char('\r');
1721 out_char('\n');
1722 out_flush();
1723 ml_close_all(TRUE); /* remove all memfiles */
1724 #ifdef MCH_CURSOR_SHAPE
1725 mch_restore_cursor_shape(TRUE);
1726 #endif
1727 exit(r);
1731 * set the tty in (raw) ? "raw" : "cooked" mode
1732 * Does not change the tty, as bioskey() and kbhit() work raw all the time.
1734 void
1735 mch_settmode(int tmode)
1739 #ifdef FEAT_MOUSE
1740 void
1741 mch_setmouse(int on)
1743 mouse_active = on;
1744 mouse_hidden = TRUE; /* dont show it until moved */
1746 #endif
1749 * set screen mode
1750 * return FAIL for failure, OK otherwise
1753 mch_screenmode(char_u *arg)
1755 int mode;
1756 int i;
1757 static char *(names[]) = {"BW40", "C40", "BW80", "C80", "MONO", "C4350"};
1758 static int modes[] = { BW40, C40, BW80, C80, MONO, C4350};
1760 mode = -1;
1761 if (VIM_ISDIGIT(*arg)) /* mode number given */
1762 mode = atoi((char *)arg);
1763 else
1765 for (i = 0; i < sizeof(names) / sizeof(char_u *); ++i)
1766 if (stricmp(names[i], (char *)arg) == 0)
1768 mode = modes[i];
1769 break;
1772 if (mode == -1)
1774 EMSG("E362: Unsupported screen mode");
1775 return FAIL;
1777 textmode(mode); /* use Borland function */
1778 #ifdef DJGPP
1779 /* base address may have changed */
1780 get_screenbase();
1781 #endif
1783 /* Screen colors may have changed. */
1784 out_str(T_ME);
1786 #ifdef FEAT_MOUSE
1787 if (mode <= 1 || mode == 4 || mode == 5 || mode == 13 || mode == 0x13)
1788 mouse_x_div = 16;
1789 else
1790 mouse_x_div = 8;
1791 if (mode == 0x11 || mode == 0x12)
1792 mouse_y_div = 16;
1793 else if (mode == 0x10)
1794 mouse_y_div = 14;
1795 else
1796 mouse_y_div = 8;
1797 shell_resized();
1798 #endif
1799 return OK;
1803 * Structure used by Turbo-C/Borland-C to store video parameters.
1805 #ifndef DJGPP
1806 extern struct text_info _video;
1807 #endif
1810 * try to get the real window size
1811 * return FAIL for failure, OK otherwise
1814 mch_get_shellsize(void)
1816 struct text_info textinfo;
1819 * The screenwidth is returned by the BIOS OK.
1820 * The screenheight is in a location in the bios RAM, if the display is
1821 * EGA or VGA.
1823 if (!term_console)
1824 return FAIL;
1825 gettextinfo(&textinfo);
1826 Columns = textinfo.screenwidth;
1827 Rows = textinfo.screenheight;
1828 #ifndef DJGPP
1829 if (textinfo.currmode > 10)
1830 Rows = *(char far *)MK_FP(0x40, 0x84) + 1;
1831 #endif
1833 if (Columns < MIN_COLUMNS || Rows < MIN_LINES)
1835 /* these values are overwritten by termcap size or default */
1836 Columns = 80;
1837 Rows = 25;
1838 return FAIL;
1840 #ifdef DJGPP
1841 mytextinit(&textinfo); /* Added by JML, 1/15/98 */
1842 #endif
1844 return OK;
1848 * Set the active window for delline/insline.
1850 static void
1851 set_window(void)
1853 if (term_console)
1855 #ifndef DJGPP
1856 _video.screenheight = Rows;
1857 #endif
1858 mywindow(1, 1, Columns, Rows);
1860 screen_start();
1863 void
1864 mch_set_shellsize(void)
1866 /* Should try to set the window size to Rows and Columns.
1867 * May involve switching display mode....
1868 * We assume the user knows the size and just use it. */
1872 * Rows and/or Columns has changed.
1874 void
1875 mch_new_shellsize()
1877 #ifdef FEAT_MOUSE
1878 /* best guess for mouse coordinate computations */
1879 if (Columns <= 40)
1880 mouse_x_div = 16;
1881 if (Rows == 30)
1882 mouse_y_div = 16;
1883 #endif
1884 set_window();
1885 #ifdef FEAT_MOUSE
1886 mouse_area(); /* set area where mouse can go */
1887 #endif
1890 #if defined(DJGPP) || defined(PROTO)
1892 * Check the number of Columns with a BIOS call. This avoids a crash of the
1893 * DOS console when 'columns' is set to a too large value.
1895 void
1896 mch_check_columns()
1898 static union REGS regs;
1900 regs.h.ah = 0x0f;
1901 (void)int86(0x10, &regs, &regs);
1902 if ((unsigned)Columns > (unsigned)regs.h.ah)
1903 Columns = (unsigned)regs.h.ah;
1905 #endif
1908 * call shell, return FAIL for failure, OK otherwise
1909 * options: SHELL_*, see vim.h.
1912 mch_call_shell(
1913 char_u *cmd,
1914 int options)
1916 int x;
1917 int tmode = cur_tmode;
1918 #ifndef DJGPP
1919 char_u *newcmd;
1920 #endif
1922 out_flush();
1923 #ifdef DJGPP
1924 set_sys_cursor();
1925 #endif
1927 if (options & SHELL_COOKED)
1928 settmode(TMODE_COOK); /* set to normal mode */
1929 set_interrupts(FALSE); /* restore interrupts */
1931 #ifdef DJGPP
1932 /* ignore signals while external command is running */
1933 signal(SIGINT, SIG_IGN);
1934 signal(SIGHUP, SIG_IGN);
1935 signal(SIGQUIT, SIG_IGN);
1936 signal(SIGTERM, SIG_IGN);
1937 #endif
1938 if (cmd == NULL)
1939 x = system((char *)p_sh);
1940 else
1942 #ifdef DJGPP
1944 * Use 'shell' for system().
1946 setenv("SHELL", (char *)p_sh, 1);
1947 x = system(cmd);
1948 #else
1949 /* we use "command" to start the shell, slow but easy */
1950 newcmd = alloc(STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 3);
1951 if (newcmd == NULL)
1952 x = -1;
1953 else
1955 sprintf((char *)newcmd, "%s %s %s", p_sh, p_shcf, cmd);
1956 x = system((char *)newcmd);
1957 vim_free(newcmd);
1959 #endif
1961 #ifdef DJGPP
1962 signal(SIGINT, SIG_DFL);
1963 signal(SIGHUP, SIG_DFL);
1964 signal(SIGQUIT, SIG_DFL);
1965 signal(SIGTERM, SIG_DFL);
1966 #endif
1967 if (tmode == TMODE_RAW)
1968 settmode(TMODE_RAW); /* set to raw mode */
1969 set_interrupts(TRUE); /* catch interrupts */
1971 if (x && !(options & SHELL_SILENT) && !emsg_silent)
1973 MSG_PUTS("\nshell returned ");
1974 msg_outnum((long)x);
1975 msg_putchar('\n');
1978 return x;
1982 * check for an "interrupt signal": CTRL-break or CTRL-C
1984 void
1985 mch_breakcheck(void)
1987 if (ctrlc_pressed)
1989 ctrlc_pressed = FALSE;
1990 got_int = TRUE;
1995 * Return TRUE if "p" contain a wildcard that can be expanded by
1996 * dos_expandpath().
1999 mch_has_exp_wildcard(char_u *p)
2001 for ( ; *p; mb_ptr_adv(p))
2003 if (vim_strchr((char_u *)"?*[", *p) != NULL
2004 || (*p == '~' && p[1] != NUL))
2005 return TRUE;
2007 return FALSE;
2011 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
2012 * shortened file name).
2015 mch_has_wildcard(char_u *p)
2017 for ( ; *p; mb_ptr_adv(p))
2019 if (vim_strchr((char_u *)
2020 # ifdef VIM_BACKTICK
2021 "?*$[`"
2022 # else
2023 "?*$["
2024 # endif
2025 , *p) != NULL
2026 || (*p == '~' && p[1] != NUL))
2027 return TRUE;
2029 return FALSE;
2033 * Change directory to "path".
2034 * The normal chdir() does not change the default drive. This one does.
2035 * Return 0 for success, -1 for failure.
2038 mch_chdir(char *path)
2040 if (path[0] == NUL) /* just checking... */
2041 return 0;
2042 if (p_verbose >= 5)
2044 verbose_enter();
2045 smsg((char_u *)"chdir(%s)", path);
2046 verbose_leave();
2048 if (path[1] == ':') /* has a drive name */
2050 if (change_drive(TOLOWER_ASC(path[0]) - 'a' + 1))
2051 return -1; /* invalid drive name */
2052 path += 2;
2054 if (*path == NUL) /* drive name only */
2055 return 0;
2056 return chdir(path); /* let the normal chdir() do the rest */
2059 #ifdef DJGPP
2061 * mch_rename() works around a bug in rename (aka MoveFile) in
2062 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
2063 * file whose short file name is "FOO.BAR" (its long file name will
2064 * be correct: "foo.bar~"). Because a file can be accessed by
2065 * either its SFN or its LFN, "foo.bar" has effectively been
2066 * renamed to "foo.bar", which is not at all what was wanted. This
2067 * seems to happen only when renaming files with three-character
2068 * extensions by appending a suffix that does not include ".".
2069 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
2070 * This works like mch_rename in os_win32.c, but is a bit simpler.
2072 * Like rename(), returns 0 upon success, non-zero upon failure.
2073 * Should probably set errno appropriately when errors occur.
2077 mch_rename(const char *OldFile, const char *NewFile)
2079 char_u *TempFile;
2080 int retval;
2081 int fd;
2083 /* rename() works correctly without long file names, so use that */
2084 if (!_USE_LFN)
2085 return rename(OldFile, NewFile);
2087 if ((TempFile = alloc((unsigned)(STRLEN(OldFile) + 13))) == NULL)
2088 return -1;
2090 STRCPY(TempFile, OldFile);
2091 STRCPY(gettail(TempFile), "axlqwqhy.ba~");
2092 if (rename(OldFile, TempFile))
2093 retval = -1;
2094 else
2096 /* now create an empty file called OldFile; this prevents
2097 * the operating system using OldFile as an alias (SFN)
2098 * if we're renaming within the same directory. For example,
2099 * we're editing a file called filename.asc.txt by its SFN,
2100 * filena~1.txt. If we rename filena~1.txt to filena~1.txt~
2101 * (i.e., we're making a backup while writing it), the SFN
2102 * for filena~1.txt~ will be filena~1.txt, by default, which
2103 * will cause all sorts of problems later in buf_write(). So, we
2104 * create an empty file called filena~1.txt and the system will have
2105 * to find some other SFN for filena~1.txt~, such as filena~2.txt
2107 if ((fd = open(OldFile, O_RDWR|O_CREAT|O_EXCL, 0444)) < 0)
2108 return -1;
2109 retval = rename(TempFile, NewFile);
2110 close(fd);
2111 mch_remove((char_u *)OldFile);
2113 /* If renaming to NewFile failed, rename TempFile back to OldFile, so
2114 * that it looks like nothing happened. */
2115 if (retval)
2116 rename(TempFile, OldFile);
2118 vim_free(TempFile);
2120 return retval; /* success */
2122 #endif
2124 #if defined(DJGPP) || defined(PROTO)
2126 * setlocale() for DJGPP with MS-DOS codepage support
2127 * Author: Cyril Slobin <slobin@fe.msk.ru>
2129 * Scaled down a lot for use by Vim: Only support setlocale(LC_ALL, "").
2132 #undef setlocale
2134 #include <go32.h>
2135 #include <inlines/ctype.ha>
2136 #include <locale.h>
2138 #define UPCASE (__dj_ISALNUM | __dj_ISALPHA | __dj_ISGRAPH | __dj_ISPRINT | __dj_ISUPPER)
2139 #define LOCASE (__dj_ISALNUM | __dj_ISALPHA | __dj_ISGRAPH | __dj_ISPRINT | __dj_ISLOWER)
2141 char *
2142 djgpp_setlocale(void)
2144 __dpmi_regs regs;
2145 struct { char id; unsigned short off, seg; } __attribute__ ((packed)) info;
2146 unsigned char buffer[0x82], lower, upper;
2147 int i;
2149 regs.x.ax = 0x6502;
2150 regs.x.bx = 0xffff;
2151 regs.x.dx = 0xffff;
2152 regs.x.cx = 5;
2153 regs.x.es = __tb >> 4;
2154 regs.x.di = __tb & 0xf;
2156 __dpmi_int(0x21, &regs);
2158 if (regs.x.flags & 1)
2159 return NULL;
2161 dosmemget(__tb, 5, &info);
2162 dosmemget((info.seg << 4) + info.off, 0x82, buffer);
2164 if (*(short *)buffer != 0x80)
2165 return NULL;
2167 /* Fix problem of underscores being replaced with y-umlaut. (Levin) */
2168 if (buffer[26] == 0x5f)
2169 buffer[26] = 0x98;
2171 for (i = 0; i < 0x80; i++)
2173 lower = i + 0x80;
2174 upper = (buffer+2)[i];
2175 if (lower != upper)
2177 __dj_ctype_flags[lower+1] = LOCASE;
2178 __dj_ctype_toupper[lower+1] = upper;
2179 if (__dj_ctype_flags[upper+1] == 0)
2180 __dj_ctype_flags[upper+1] = UPCASE;
2181 if (__dj_ctype_tolower[upper+1] == upper)
2182 __dj_ctype_tolower[upper+1] = lower;
2186 return "C";
2189 #if defined(FEAT_CLIPBOARD) || defined(PROTO)
2192 * Clipboard stuff, for cutting and pasting text to other windows.
2194 * Implementation of DOS/Windows clipboard data transfer
2195 * by David Kotchan (dkotchan@sympatico.ca)
2198 #define CF_TEXT 0x01 /* Windows clipboard format: Windows (ANSI) text */
2199 #define CF_OEMTEXT 0x07 /* Windows clipboard format: OEM (DOS) text */
2200 #define CF_VIMCLIP 0x04 /* trick: SYLK clipboard format for VimClipboard */
2202 static int Win16OpenClipboard(void);
2203 static int Win16CloseClipboard(void);
2204 static int Win16EmptyClipboard(void);
2205 static char_u *Win16GetClipboardData(int clip_data_format);
2206 static int Win16SetClipboardData(int clip_data_format, char_u *clip_data, int clip_data_size, int clip_data_type);
2209 * Make vim the owner of the current selection. Return OK upon success.
2212 clip_mch_own_selection(VimClipboard *cbd)
2215 * Never actually own the clipboard. If another application sets the
2216 * clipboard, we don't want to think that we still own it.
2218 return FAIL;
2222 * Make vim NOT the owner of the current selection.
2224 void
2225 clip_mch_lose_selection(VimClipboard *cbd)
2227 /* Nothing needs to be done here */
2231 * Read the Windows clipboard text and put it in Vim's clipboard register.
2233 void
2234 clip_mch_request_selection(VimClipboard *cbd)
2236 int type = MCHAR;
2237 char_u *pAllocated = NULL;
2238 char_u *pClipText = NULL;
2239 int clip_data_format = 0;
2241 if (Win16OpenClipboard())
2243 /* Check for Vim's own clipboard format first. The CF_VIMCLIP format
2244 * is just ordinary text (like CF_TEXT) except prepended by the
2245 * selection type (as a single character). Note that under DOS we
2246 * actually cannot define a custom CF_VIMCLIP clipboard format; we
2247 * use instead one of the existing Windows-defined formats, usually
2248 * "DIF" or "SYLK". See Win16GetClipboardData() for details.
2250 * Note that Win16GetClipboardData() returns the address of the memory
2251 * block it allocated. This is not necessary the start of the
2252 * clipboard text data: there may be other bytes ahead of the
2253 * text (particularly for CF_VIMCLIP) which are used for data
2254 * management. So pClipText is not necessarily == pAllocated.
2257 if ((pAllocated = Win16GetClipboardData(CF_VIMCLIP)) != NULL)
2259 clip_data_format = CF_VIMCLIP;
2260 pClipText = pAllocated;
2262 switch (*pClipText++) /* after ++, pClipText points to text */
2264 default:
2265 case 'L': type = MLINE; break;
2266 case 'C': type = MCHAR; break;
2267 #ifdef FEAT_VISUAL
2268 case 'B': type = MBLOCK; break;
2269 #endif
2273 /* Otherwise, check for the normal Windows text formats. There are
2274 * two of these: CF_TEXT (common) and CF_OEMTEXT (used for DOS
2275 * compatibility). Experiments show that, under the DOS/Windows
2276 * clipboard interface, writing CF_TEXT data to the clipboard
2277 * automatically creates a CF_OEMTEXT format as well.
2280 else if ((pAllocated = Win16GetClipboardData(CF_TEXT)) != NULL)
2282 clip_data_format = CF_TEXT;
2283 pClipText = pAllocated;
2284 type = (vim_strchr((char*)pClipText, '\r') != NULL) ? MLINE : MCHAR;
2287 else if ((pAllocated = Win16GetClipboardData(CF_OEMTEXT)) != NULL)
2289 clip_data_format = CF_OEMTEXT;
2290 pClipText = pAllocated;
2291 type = (vim_strchr((char*)pClipText, '\r') != NULL) ? MLINE : MCHAR;
2294 /* Did we get anything? */
2296 if (pClipText != NULL)
2298 char_u *pDest;
2299 char_u *pStart;
2300 char_u *pEnd;
2302 long_u clip_data_size = 0;
2304 /* The Windows clipboard normally stores its text lines terminated
2305 * by <CR><NL>. But Vim uses only <NL>, so translate the <CR><NL>
2306 * into <NL>. Also, watch for possible null bytes at the end of
2307 * pClipText. These are padding added by "get_clipboard_data"
2308 * (int 0x2f, AX= 0x1705) in order to round the data size up to the
2309 * next multiple of 32 bytes. See Win16GetClipboardData() for
2310 * details.
2313 pDest = strstr( pClipText, "\r\n" ); /* find first <CR><NL> */
2315 if (pDest != NULL) /* found one? */
2317 pStart = pDest + 1; /* points to <NL> after <CR> */
2318 pEnd = strstr( pStart, "\r\n" );/* find next <CR><NL> */
2320 while (pEnd != NULL) /* found one? */
2322 memmove(pDest, pStart, (long)(pEnd - pStart));
2323 /* exclude <CR> */
2324 pDest += (long)(pEnd - pStart); /* new destination */
2325 pStart = pEnd + 1; /* new starting point */
2326 pEnd = strstr(pStart, "\r\n"); /* find next <CR><NL> */
2329 /* Fell out of while() loop: no more <CR><NL> pairs. Just copy
2330 * the rest of the data, up to the first null byte. */
2331 pEnd = strchr(pStart, '\0'); /* find first null */
2333 memmove(pDest, pStart, (long)(pEnd - pStart)); /* exclude nul */
2334 pDest += (long)(pEnd - pStart);
2335 *pDest = '\0'; /* terminate */
2337 /* Now that all <CR><NL> pairs have been "compressed" into just
2338 * <NL>'s, determine the true text length. */
2339 clip_data_size = (long_u)(pDest - pClipText);
2341 else
2343 /* no <CR><NL> pairs at all */
2344 /* Since the data may have been padded with trailing nulls,
2345 * determine the true string length. */
2346 clip_data_size = STRLEN(pClipText); /* true data length */
2349 /* Copy the cleaned-up data over to Vim's clipboard "*" register. */
2350 clip_yank_selection(type, pClipText, clip_data_size, cbd);
2352 /* Free the memory that Win16GetClipboardData() allocated. */
2353 vim_free(pAllocated);
2356 Win16CloseClipboard();
2358 } // end if (Win16OpenClipboard())
2362 * Send the currently selected Vim text to the Windows clipboard.
2364 void
2365 clip_mch_set_selection( VimClipboard *cbd )
2367 char_u *pClipData = NULL;
2368 long_u clip_data_size;
2369 int clip_data_type;
2371 /* If the '*' register isn't already filled in, fill it in now. */
2372 cbd->owned = TRUE;
2373 clip_get_selection(cbd);
2374 cbd->owned = FALSE;
2377 * clip_convert_selection() returns a pointer to a buffer containing
2378 * the text to send to the Windows clipboard, together with a count
2379 * of the number of characters (bytes) in the buffer. The function's
2380 * return value is the 'type' of selection: MLINE, MCHAR, or MBLOCK;
2381 * or -1 for failure.
2383 clip_data_type = clip_convert_selection(&pClipData, &clip_data_size, cbd);
2385 if (clip_data_type < 0) /* could not convert? */
2386 return; /* early exit */
2388 if (Win16OpenClipboard())
2390 if (Win16EmptyClipboard())
2392 int sentOK;
2394 sentOK = Win16SetClipboardData(CF_TEXT, pClipData,
2395 clip_data_size, clip_data_type);
2396 sentOK = Win16SetClipboardData(CF_VIMCLIP,
2397 pClipData, clip_data_size, clip_data_type) && sentOK;
2399 if (!sentOK)
2401 /* one or both of Win16SetClipboardData() failed. */
2402 /* Technically we don't know why Win16SetClipboardData()
2403 * failed, but almost always it will be because there wasn't
2404 * enough DOS memory to buffer the data, so report that as the
2405 * problem.
2407 * We report the error here (instead of in
2408 * Win16SetClipboardData()) because we don't want the error
2409 * reported twice.
2411 EMSG("E450: Selection too large, cannot allocate DOS buffer");
2415 Win16CloseClipboard();
2418 /* release memory allocated by clip_convert_selection() */
2419 vim_free(pClipData);
2421 return;
2425 * Win16OpenClipboard: open the Windows clipboard. The clipboard must be open
2426 * before it can be communicated with at all. Return TRUE on success,
2427 * FALSE on failure.
2429 static int
2430 Win16OpenClipboard(void)
2432 __dpmi_regs dpmi_regs;
2434 long start_time;
2435 int tick_count;
2437 /* int 02xf, AX = 0x1701 attempts to open the Windows clipboard. Upon
2438 * return from the interrupt, if AX is non-zero, the clipboard was
2439 * successfully opened. If AX is zero, the clipboard could not be opened
2440 * because it is currently in use by another process.
2442 * Remark: other DOS programs I (dk) have written that use the Windows
2443 * clipboard sometimes encounter the problem that the clipboard cannot
2444 * be opened even though it is demonstrably not in use by any other
2445 * process. In all cases, repeated attempts to open the clipboard
2446 * eventually succeed, but the initial attempt occasionally fails.
2448 * The problem is intermittent and appears to be related to DOS being
2449 * "busy" at certain unpredictable times. DOS maintains two internal
2450 * flags that indicate whether it's busy: InDOS and CritErr. The
2451 * location of InDOS can be found by calling int 0x21, AH = 0x34. The
2452 * location of CritErr can be found by calling int 0x21, AX = 0x5d06.
2453 * If either of these flags is set, DOS is "busy" and cannot be
2454 * interrupted. See "Undocumented DOS" by Schulman et al for details.
2456 * However here I take the easier approach that if the first call to open
2457 * the clipboard does not succeed, just try again. In fact, try once per
2458 * biostime() clock tick, up to 18 times (about one second).
2461 tick_count = 0;
2463 dpmi_regs.x.ax = 0x1701; /* open Windows clipboard */
2464 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
2466 /* real-mode interrupt failed? */
2467 return FALSE; /* FALSE --> clipboard not open */
2470 /* wait up to one second */
2471 while (dpmi_regs.x.ax == 0 && tick_count++ < 18)
2473 /* Wait one clock tick (18.2 ticks/sec = 55 msec per tick).
2475 * We busy-wait here. Unfortunately, delay() and usleep() have been
2476 * reported to give problems with the original Windows 95. This is
2477 * fixed in service pack 1, but not everybody installed that.
2479 start_time = biostime(0, 0L);
2480 while (biostime(0, 0L) == start_time)
2483 dpmi_regs.x.ax = 0x1701; /* open Windows clipboard */
2484 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
2486 /* real-mode interrupt failed? */
2487 return FALSE; /* FALSE --> clipboard not open */
2491 /* Couldn't open the clipboard, even after 18 attempts? */
2493 if (tick_count >= 18 && dpmi_regs.x.ax == 0)
2494 return FALSE; /* FALSE --> clipboard not open */
2496 return TRUE; /* TRUE --> clipboard opened successfully, OK */
2500 * Win16CloseClipboard: close the Windows clipboard. Return TRUE on
2501 * success, FALSE on failure. This function can always be called,
2502 * whether the clipboard is open or not.
2504 static int
2505 Win16CloseClipboard(void)
2507 __dpmi_regs dpmi_regs;
2509 /* Close the clipboard. This interrupt can always be called, even
2510 * if the clipboard is already closed.
2513 dpmi_regs.x.ax = 0x1708; /* close the clipboard */
2514 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
2516 /* real-mode interrupt failed? */
2517 return FALSE; /* FALSE --> clipboard could not be closed */
2520 return TRUE; /* TRUE --> clipboard closed successfully, OK */
2524 * Win16EmptyClipboard: empty the (previously opened) Windows clipboard.
2525 * Return TRUE on success, FALSE on failure.
2527 static int
2528 Win16EmptyClipboard(void)
2530 __dpmi_regs dpmi_regs;
2532 /* int 02xf, AX = 0x1702 attempts to empty the Windows clipboard. Upon
2533 * return from the interrupt, if AX == 0, the clipboard could not be
2534 * emptied (for some reason).
2536 dpmi_regs.x.ax = 0x1702; /* empty the Windows clipboard */
2537 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
2539 /* real-mode interrupt failed? */
2540 return FALSE; /* FALSE --> clipboard could not be emptied */
2543 /* Did we succeed in clearing the clipboard? */
2544 if (dpmi_regs.x.ax == 0)
2545 return FALSE; /* FALSE --> clipboard could not be emptied */
2547 return TRUE; /* TRUE --> clipboard was emptied, OK */
2551 * FreeDOSMemory: a helper function to free memory previously
2552 * allocated by a call to __dpmi_allocate_dos_memory().
2554 static void
2555 FreeDOSMemory(int protected_mode_selector)
2557 /* Free the DOS buffer and release the DPMI prot-mode selector.
2559 * It's important that DOS memory be properly released because
2560 * there's only a limited amount of it. Therefore, if the call
2561 * to __dpmi_free_dos_memory() fails, emit an error message
2562 * unconditionally.
2564 if (__dpmi_free_dos_memory(protected_mode_selector) == -1)
2565 EMSG("E451: could not free DOS memory buffer (DJGPP)");
2569 * Win16GetClipboardData: query the Windows clipboard as to whether data
2570 * is available in a particular clipboard format. If data is
2571 * available, allocate a buffer for it and read the data from the
2572 * clipboard into the buffer. Return a pointer to the buffer. If
2573 * no data is available in the requested format, return NULL.
2575 * This routine allocates memory to hold the retrieved clipboard
2576 * data. It's the caller's responsibility to free this memory
2577 * once it's finished using it. The memory should be freed by
2578 * calling vim_free().
2580 static char_u *
2581 Win16GetClipboardData(int clip_data_format)
2583 __dpmi_regs dpmi_regs;
2585 int real_mode_segment_address;
2586 int protected_mode_selector;
2588 char_u *clip_data_buffer;
2589 long_u clip_data_size;
2591 /* We only handle clipboard formats we recognize, others are ignored.
2593 * It's not possible to create a custom clipboard format for VimClipboard
2594 * data under DOS, so one of the predefined Windows formats had to be
2595 * used for CF_VIMCLIP. Two obscure formats, popular when Windows 3.0
2596 * came out but no longer in much use today, are the DIF and SYLK formats.
2597 * DIF is the Data Interchange Format, SYLK is the Symbolic Link format.
2598 * They are both text formats and either one can be hijacked for use as
2599 * "the VimClipboard format". Of course, this conflicts with anyone who
2600 * still *is* using DIF or SYLK data formats, but that will be very few
2601 * people.
2603 * I (dk) chose SYLK as the more obscure format because it was used
2604 * mostly for Microsoft Multiplan (the pre-cursor to Excel) and it's not
2605 * likely Multiplan is used anywhere much anymore. Mind you, Excel can
2606 * still export to both DIF and SYLK formats.
2609 switch (clip_data_format)
2611 case CF_VIMCLIP: /* Vim's own special clipboard format */
2612 case CF_TEXT: /* Windows text */
2613 case CF_OEMTEXT: /* DOS (OEM) text */
2615 /* int 02xf, AX = 0x1704 returns the number of bytes of data currently
2616 * on the Windows clipboard, for the specified format. Upon return
2617 * from the interrupt, DX:AX = the number of bytes, rounded up to the
2618 * nearest multiple of 32.
2621 dpmi_regs.x.ax = 0x1704; /* get size of clipbd data */
2622 dpmi_regs.x.dx = clip_data_format;
2623 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
2625 /* real-mode interrupt failed? */
2626 return NULL; /* early exit */
2629 /* Did we get anything? If not, this is not an error. */
2630 if (dpmi_regs.x.dx == 0 && dpmi_regs.x.ax == 0)
2632 /* no CF_VIMCLIP data? */
2633 return NULL; /* early exit */
2636 /* There is data available in the requested clipboard format.
2638 * Calculate data size. Remember this is rounded up to the nearest
2639 * multiple of 32, so clip_data_size is actually an upper limit.
2640 * The extra bytes, if any, are set to null (0x00) when the data is
2641 * read from the clipboard. (Later:) actually I'm no longer sure
2642 * this is strictly true: the end-of-data is marked by a null, but
2643 * the extra bytes appear to sometimes be null, sometimes not.
2644 * They may just be garbage.
2646 clip_data_size = dpmi_regs.x.ax + (dpmi_regs.x.dx << 16);
2648 /* Allocate memory to retrieve the data. The buffer has to lie in the
2649 * DOS memory region (in the first 1 MByte of address space) because
2650 * the Windows clipboard interface expects a 16-bit segment:offset
2651 * pointer to a buffer address within the DOS region. Must therefore
2652 * use __dpmi_allocate_dos_memory() instead of lalloc() or alloc().
2654 real_mode_segment_address = __dpmi_allocate_dos_memory(
2655 (clip_data_size + 15) >> 4, /* buffer size, in 16-byte paragraphs */
2656 &protected_mode_selector); /* prot-mode selector for the address */
2658 if (real_mode_segment_address == -1)
2660 /* memory allocation failed. */
2662 /* Technically we don't know why the allocation failed, but
2663 * almost always it will be because there wasn't enough DOS
2664 * memory to satisfy the request, so report that as the problem.
2665 * On my system, DJGPP is able to satisfy a DOS allocation request
2666 * up to about 600K in size. This depends on your HIMEM.SYS and
2667 * EMM386.EXE settings however.
2669 EMSG("E452: Clipboard data too large, cannot allocate DOS buffer");
2670 return NULL; /* early exit */
2673 /* Copy data from the clipboard into the buffer. Experiments show that
2674 * the Windows clipboard is smart enough to handle data transfers
2675 * larger than 64K properly, even though the buffer address is a 16-bit
2676 * segment:offset (which would normally limit the block size to 64K
2677 * unless ES gets incremented).
2679 dpmi_regs.x.ax = 0x1705; /* get clipboard data */
2680 dpmi_regs.x.dx = clip_data_format; /* CF_VIMCLIP */
2681 dpmi_regs.x.es = real_mode_segment_address; /* buffer ad: segment */
2682 dpmi_regs.x.bx = 0; /* buffer ad: offset */
2683 if (__dpmi_int( 0x2f, &dpmi_regs) == -1)
2685 /* real-mode interrupt failed? */
2686 EMSG("E453: could not copy clipboard data to DOS buffer");
2687 FreeDOSMemory(protected_mode_selector); /* clean up DOS mem */
2688 return NULL; /* early exit */
2691 /* Clipboard data is now in DOS memory in the buffer pointed to by
2692 * ES:BX. Copy this into ordinary memory that Vim can access (ie.
2693 * prot-mode memory). Allocate one extra byte to ensure the text
2694 * is terminated properly (in case it was somehow corrupted).
2696 clip_data_buffer = (char_u *)lalloc(clip_data_size + 1, TRUE);
2698 if (clip_data_buffer == NULL)
2700 /* allocation failed? */
2701 EMSG("E454: could not allocate clipboard memory buffer");
2702 FreeDOSMemory(protected_mode_selector); /* clean up DOS mem */
2703 return NULL; /* early exit */
2706 *(clip_data_buffer + clip_data_size) = '\0'; /* ensure terminated */
2708 /* Copy the data from DOS memory to Vim-accessible memory. */
2709 movedata( /* DJGPP version of memcpy() */
2710 protected_mode_selector, 0, /* source: DOS ad (via selector) */
2711 _my_ds(), (unsigned)clip_data_buffer,
2712 /* target: normal mem address */
2713 clip_data_size); /* how many bytes */
2715 /* Free the DOS buffer and release the DPMI prot-mode selector. */
2716 FreeDOSMemory(protected_mode_selector); /* clean up DOS memory */
2718 return clip_data_buffer; /* return pointer to allocated buffer */
2720 default: /* unknown clipboard format */
2721 return NULL;
2726 * Win16SetClipboardData: send 'clip_data_size' bytes of data from the buffer
2727 * pointed to by 'clip_data', to the Windows clipboard. The data is
2728 * registered with the clipboard as being in the 'clip_data_format'
2729 * format.
2731 static int
2732 Win16SetClipboardData(
2733 int clip_data_format,
2734 char_u *clip_data,
2735 int clip_data_size,
2736 int clip_data_type)
2738 __dpmi_regs dpmi_regs;
2740 int real_mode_segment_address;
2741 int protected_mode_selector;
2742 long_u protected_mode_offset = 0L;
2743 int total_size = clip_data_size;
2745 char_u *clip_sel_type;
2747 /* If we're using the CF_VIMCLIP custom format, allocate an extra
2748 * byte for clip_sel_type, which is a character indicating the type
2749 * of text selection: MLINE, MCHAR, or MBLOCK.
2751 if (clip_data_format == CF_VIMCLIP)
2752 total_size++; /* extra byte for marker */
2754 /* Data cannot be sent directly from a Vim string (pClipData) to
2755 * the Windows clipboard, because the Windows clipboard interface
2756 * expects a 16-bit (DOS) segment:offset address for the source
2757 * buffer. Therefore we must create a "transfer buffer" in the DOS
2758 * memory region (in the first 1 MByte of address space) and copy
2759 * the Vim string into that. From there, the data can then be sent
2760 * to the Windows clipboard.
2762 * To allocate DOS memory, we must use __dpmi_allocate_dos_memory()
2763 * instead of lalloc() or alloc(). If the allocation fails, it will
2764 * almost invariably be because there is not enough DOS memory
2765 * available to accommodate the size of clip_data. There is nothing
2766 * we can do about this, we simply have to fail.
2768 real_mode_segment_address = __dpmi_allocate_dos_memory(
2769 (total_size + 15) >> 4, /* buffer size, in 16-byte paragraphs */
2770 &protected_mode_selector); /* prot-mode selector for the address */
2772 if (real_mode_segment_address == -1)
2774 /* memory allocation failed. */
2775 /* Technically we don't know why the allocation failed, but
2776 * almost always it will be because there wasn't enough DOS
2777 * memory to satisfy the request. On my system, DJGPP is able
2778 * to satisfy a DOS allocation request up to about 600K in size.
2779 * This depends however on HIMEM.SYS and EMM386.EXE settings.
2781 return FALSE; /* early exit */
2784 /* Copy data from Vim's buffer (clip_data) into the DOS transfer buffer.
2785 * This can be larger than 64K; movedata() takes care of crossing any
2786 * 16-bit segment boundaries.
2788 * If we're using Vim's custom clipboard format, we must copy one extra
2789 * byte to indicate the type of selection: line, character, or block.
2791 if (clip_data_format == CF_VIMCLIP)
2793 switch (clip_data_type)
2795 default:
2796 case MLINE: clip_sel_type = "L"; break;
2797 case MCHAR: clip_sel_type = "C"; break;
2798 #ifdef FEAT_VISUAL
2799 case MBLOCK: clip_sel_type = "B"; break;
2800 #endif
2803 movedata(
2804 _my_ds(), (unsigned)clip_sel_type,
2805 /* source: normal memory address */
2806 protected_mode_selector, 0, /* target: DOS ad (via selector) */
2807 1); /* how many bytes to copy */
2809 protected_mode_offset += STRLEN(clip_sel_type); /* allow for marker */
2812 movedata(
2813 _my_ds(), (unsigned)clip_data, /* source: normal memory address */
2814 protected_mode_selector, /* target: DOS address (via selector) */
2815 protected_mode_offset, /* non-zero, if using clip_sel_type */
2816 clip_data_size); /* how many bytes to copy */
2818 /* Send data from the DOS transfer buffer to the Windows clipboard.
2819 * int 02xf, AX = 0x1703 sends SI:CX bytes of data from the buffer
2820 * at ES:BX, to the clipboard.
2822 dpmi_regs.x.ax = 0x1703; /* send clipboard data */
2823 dpmi_regs.x.dx = clip_data_format; /* flag: format of the data */
2824 dpmi_regs.x.si = ((total_size >> 16)
2825 & 0x0000ffffL); /* hi word of data size */
2826 dpmi_regs.x.cx = (total_size & 0x0000ffffL);
2827 /* lo word of data size */
2828 dpmi_regs.x.es = real_mode_segment_address; /* buffer address: segment */
2829 dpmi_regs.x.bx = 0; /* buffer address: offset */
2830 if (__dpmi_int(0x2f, &dpmi_regs) == -1)
2832 /* real-mode interrupt failed. */
2833 FreeDOSMemory(protected_mode_selector); /* clean up DOS memory */
2834 return FALSE; /* early exit */
2837 /* Free the DOS buffer and release the DPMI prot-mode selector. */
2838 FreeDOSMemory(protected_mode_selector); /* clean up DOS memory */
2840 return TRUE; /* TRUE --> data successfully sent to clipboard */
2843 #endif /* FEAT_CLIPBOARD */
2844 #endif /* DJGPP */
2847 * End of MS-DOS only code
2849 #endif /* WIN16 */
2851 /* common MS-DOS and Win16 code follows */
2853 static int
2854 vim_chmod(char_u *name)
2856 char_u *p;
2857 int f;
2858 int c = 0;
2860 /* chmod() can't handle a file name with a trailing slash, remove it.
2861 * But don't remove it for "/" or "c:/". */
2862 p = name + STRLEN(name);
2863 if (p > name)
2864 --p;
2865 if (p > name && (*p == '\\' || *p == '/') && p[-1] != ':')
2867 c = *p; /* remove trailing (back)slash */
2868 *p = NUL;
2870 else
2871 p = NULL;
2872 #if defined(__BORLANDC__) && (__BORLANDC__ > 0x410)
2873 /* this also sets the archive bit, supported by Borland C 4.0 and later,
2874 * where __BORLANDC__ is 0x450 (3.1 is 0x410) */
2875 f = _rtl_chmod((char *)name, 0, 0);
2876 #else
2877 f = _chmod((char *)name, 0, 0);
2878 #endif
2879 if (p != NULL)
2880 *p = c; /* put back (back)slash */
2881 return f;
2885 * get file permissions for 'name'
2886 * Returns -1 for error.
2887 * Returns FA_attributes defined in dos.h
2889 long
2890 mch_getperm(char_u *name)
2892 return (long)vim_chmod(name); /* get file mode */
2896 * set file permission for 'name' to 'perm'
2898 * return FAIL for failure, OK otherwise
2901 mch_setperm(
2902 char_u *name,
2903 long perm)
2905 perm |= FA_ARCH; /* file has changed, set archive bit */
2906 #if defined(__BORLANDC__) && (__BORLANDC__ > 0x410)
2907 return (_rtl_chmod((char *)name, 1, (int)perm) == -1 ? FAIL : OK);
2908 #else
2909 return (_chmod((char *)name, 1, (int)perm) == -1 ? FAIL : OK);
2910 #endif
2914 * Set hidden flag for "name".
2916 void
2917 mch_hide(char_u *name)
2919 /* DOS 6.2 share.exe causes "seek error on file write" errors when making
2920 * the swap file hidden. Thus don't do it. */
2924 * return TRUE if "name" is a directory
2925 * return FALSE if "name" is not a directory
2926 * return FALSE for error
2928 * beware of a trailing (back)slash
2931 mch_isdir(char_u *name)
2933 int f;
2935 f = vim_chmod(name);
2936 if (f == -1)
2937 return FALSE; /* file does not exist at all */
2938 if ((f & FA_DIREC) == 0)
2939 return FALSE; /* not a directory */
2940 return TRUE;
2944 * Return 1 if "name" can be executed, 0 if not.
2945 * Return -1 if unknown.
2948 mch_can_exe(name)
2949 char_u *name;
2951 char *p;
2953 p = searchpath(name);
2954 if (p == NULL || mch_isdir(p))
2955 return FALSE;
2956 return TRUE;
2960 * Check what "name" is:
2961 * NODE_NORMAL: file or directory (or doesn't exist)
2962 * NODE_WRITABLE: writable device, socket, fifo, etc.
2963 * NODE_OTHER: non-writable things
2966 mch_nodetype(char_u *name)
2968 if (STRICMP(name, "AUX") == 0
2969 || STRICMP(name, "CON") == 0
2970 || STRICMP(name, "CLOCK$") == 0
2971 || STRICMP(name, "NUL") == 0
2972 || STRICMP(name, "PRN") == 0
2973 || ((STRNICMP(name, "COM", 3) == 0
2974 || STRNICMP(name, "LPT", 3) == 0)
2975 && VIM_ISDIGIT(name[3])
2976 && name[4] == NUL))
2977 return NODE_WRITABLE;
2978 /* TODO: NODE_OTHER? */
2979 return NODE_NORMAL;
2983 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2984 * Return OK for success, FAIL for failure.
2987 mch_dirname(
2988 char_u *buf,
2989 int len)
2991 #ifdef DJGPP
2992 if (getcwd((char *)buf, len) == NULL)
2993 return FAIL;
2994 /* turn the '/'s returned by DJGPP into '\'s */
2995 slash_adjust(buf);
2996 return OK;
2997 #else
2998 return (getcwd((char *)buf, len) != NULL ? OK : FAIL);
2999 #endif
3003 * this version of remove is not scared by a readonly (backup) file
3005 * returns -1 on error, 0 otherwise (just like remove())
3008 mch_remove(char_u *name)
3010 (void)mch_setperm(name, 0); /* default permissions */
3011 return unlink((char *)name);
3015 * Special version of getenv(): Use uppercase name.
3017 char_u *
3018 mch_getenv(char_u *name)
3020 int i;
3021 #define MAXENVLEN 50
3022 char_u var_copy[MAXENVLEN + 1];
3023 char_u *p;
3024 char_u *res;
3027 * Take a copy of the argument, and force it to upper case before passing
3028 * to getenv(). On DOS systems, getenv() doesn't like lower-case argument
3029 * (unlike Win32 et al.) If the name is too long to fit in var_copy[]
3030 * allocate memory.
3032 if ((i = STRLEN(name)) > MAXENVLEN)
3033 p = alloc(i + 1);
3034 else
3035 p = var_copy;
3036 if (p == NULL)
3037 p = name; /* out of memory, fall back to unmodified name */
3038 else
3040 for (i = 0; name[i] != NUL; ++i)
3041 p[i] = toupper(name[i]);
3042 p[i] = NUL;
3045 res = (char_u *)getenv((char *)p);
3047 if (p != var_copy && p != name)
3048 vim_free(p);
3050 return res;
3054 * Insert user name in s[len].
3057 mch_get_user_name(
3058 char_u *s,
3059 int len)
3061 *s = NUL;
3062 return FAIL;
3066 * Insert host name is s[len].
3068 void
3069 mch_get_host_name(
3070 char_u *s,
3071 int len)
3073 #ifdef DJGPP
3074 vim_strncpy(s, "PC (32 bits Vim)", len - 1);
3075 #else
3076 vim_strncpy(s, "PC (16 bits Vim)", len - 1);
3077 #endif