blob: b24101f3f6cfce46e8d378a1e9e6717f6f21f921 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * X command server by Flemming Madsen
5 *
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
9 *
10 * if_xcmdsrv.c: Functions for passing commands through an X11 display.
11 *
12 */
13
14#include "vim.h"
15#include "version.h"
16
17#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
18
19# ifdef FEAT_X11
20# include <X11/Intrinsic.h>
21# include <X11/Xatom.h>
22# endif
23
24# if defined(HAVE_SYS_SELECT_H) && \
25 (!defined(HAVE_SYS_TIME_H) || defined(SYS_SELECT_WITH_SYS_TIME))
26# include <sys/select.h>
27# endif
28
29# ifndef HAVE_SELECT
30# ifdef HAVE_SYS_POLL_H
31# include <sys/poll.h>
32# else
33# ifdef HAVE_POLL_H
34# include <poll.h>
35# endif
36# endif
37# endif
38
39/*
40 * This file provides procedures that implement the command server functionality
41 * of Vim when in contact with an X11 server.
42 *
43 * Adapted from TCL/TK's send command in tkSend.c of the tk 3.6 distribution.
44 * Adapted for use in Vim by Flemming Madsen. Protocol changed to that of tk 4
45 */
46
47/*
48 * Copyright (c) 1989-1993 The Regents of the University of California.
49 * All rights reserved.
50 *
51 * Permission is hereby granted, without written agreement and without
52 * license or royalty fees, to use, copy, modify, and distribute this
53 * software and its documentation for any purpose, provided that the
54 * above copyright notice and the following two paragraphs appear in
55 * all copies of this software.
56 *
57 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
58 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
59 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
60 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61 *
62 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
63 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
64 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
65 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
66 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
67 */
68
69
70/*
71 * When a result is being awaited from a sent command, one of
72 * the following structures is present on a list of all outstanding
73 * sent commands. The information in the structure is used to
74 * process the result when it arrives. You're probably wondering
75 * how there could ever be multiple outstanding sent commands.
76 * This could happen if Vim instances invoke each other recursively.
77 * It's unlikely, but possible.
78 */
79
80typedef struct PendingCommand
81{
82 int serial; /* Serial number expected in result. */
83 int code; /* Result Code. 0 is OK */
84 char_u *result; /* String result for command (malloc'ed).
85 * NULL means command still pending. */
86 struct PendingCommand *nextPtr;
87 /* Next in list of all outstanding commands.
88 * NULL means end of list. */
89} PendingCommand;
90
91static PendingCommand *pendingCommands = NULL;
92 /* List of all commands currently
93 * being waited for. */
94
95/*
96 * The information below is used for communication between processes
97 * during "send" commands. Each process keeps a private window, never
98 * even mapped, with one property, "Comm". When a command is sent to
99 * an interpreter, the command is appended to the comm property of the
100 * communication window associated with the interp's process. Similarly,
101 * when a result is returned from a sent command, it is also appended
102 * to the comm property.
103 *
104 * Each command and each result takes the form of ASCII text. For a
105 * command, the text consists of a nul character followed by several
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000106 * nul-terminated ASCII strings. The first string consists of a
107 * single letter:
108 * "c" for an expression
109 * "k" for keystrokes
110 * "r" for reply
111 * "n" for notification.
112 * Subsequent strings have the form "option value" where the following options
113 * are supported:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114 *
115 * -r commWindow serial
116 *
117 * This option means that a response should be sent to the window
118 * whose X identifier is "commWindow" (in hex), and the response should
119 * be identified with the serial number given by "serial" (in decimal).
120 * If this option isn't specified then the send is asynchronous and
121 * no response is sent.
122 *
123 * -n name
124 * "Name" gives the name of the application for which the command is
125 * intended. This option must be present.
126 *
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000127 * -E encoding
128 * Encoding name used for the text. This is the 'encoding' of the
129 * sender. The receiver may want to do conversion to his 'encoding'.
130 *
Bram Moolenaar071d4272004-06-13 20:20:40 +0000131 * -s script
132 * "Script" is the script to be executed. This option must be
133 * present. Taken as a series of keystrokes in a "k" command where
134 * <Key>'s are expanded
135 *
136 * The options may appear in any order. The -n and -s options must be
137 * present, but -r may be omitted for asynchronous RPCs. For compatibility
138 * with future releases that may add new features, there may be additional
139 * options present; as long as they start with a "-" character, they will
140 * be ignored.
141 *
142 * A result also consists of a zero character followed by several null-
143 * terminated ASCII strings. The first string consists of the single
144 * letter "r". Subsequent strings have the form "option value" where
145 * the following options are supported:
146 *
147 * -s serial
148 * Identifies the command for which this is the result. It is the
149 * same as the "serial" field from the -s option in the command. This
150 * option must be present.
151 *
152 * -r result
153 * "Result" is the result string for the script, which may be either
154 * a result or an error message. If this field is omitted then it
155 * defaults to an empty string.
156 *
157 * -c code
158 * 0: for OK. This is the default.
159 * 1: for error: Result is the last error
160 *
161 * -i errorInfo
162 * -e errorCode
163 * Not applicable for Vim
164 *
165 * Options may appear in any order, and only the -s option must be
166 * present. As with commands, there may be additional options besides
167 * these; unknown options are ignored.
168 */
169
170/*
171 * Maximum size property that can be read at one time by
172 * this module:
173 */
174
175#define MAX_PROP_WORDS 100000
176
177struct ServerReply
178{
179 Window id;
180 garray_T strings;
181};
182static garray_T serverReply = { 0, 0, 0, 0, 0 };
183enum ServerReplyOp { SROP_Find, SROP_Add, SROP_Delete };
184
185typedef int (*EndCond) __ARGS((void *));
186
187/*
188 * Forward declarations for procedures defined later in this file:
189 */
190
191static Window LookupName __ARGS((Display *dpy, char_u *name, int delete, char_u **loose));
192static int SendInit __ARGS((Display *dpy));
193static int DoRegisterName __ARGS((Display *dpy, char_u *name));
194static void DeleteAnyLingerer __ARGS((Display *dpy, Window w));
195static int GetRegProp __ARGS((Display *dpy, char_u **regPropp, long_u *numItemsp, int domsg));
196static int WaitForPend __ARGS((void *p));
197static int WaitForReply __ARGS((void *p));
198static int WindowValid __ARGS((Display *dpy, Window w));
199static void ServerWait __ARGS((Display *dpy, Window w, EndCond endCond, void *endData, int localLoop, int seconds));
200static struct ServerReply *ServerReplyFind __ARGS((Window w, enum ServerReplyOp op));
201static int AppendPropCarefully __ARGS((Display *display, Window window, Atom property, char_u *value, int length));
202static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
203static int IsSerialName __ARGS((char_u *name));
204
205/* Private variables for the "server" functionality */
206static Atom registryProperty = None;
207static Atom vimProperty = None;
208static int got_x_error = FALSE;
209
210static char_u *empty_prop = (char_u *)""; /* empty GetRegProp() result */
211
212/*
213 * Associate an ASCII name with Vim. Try real hard to get a unique one.
214 * Returns FAIL or OK.
215 */
216 int
217serverRegisterName(dpy, name)
218 Display *dpy; /* display to register with */
219 char_u *name; /* the name that will be used as a base */
220{
221 int i;
222 int res;
223 char_u *p = NULL;
224
225 res = DoRegisterName(dpy, name);
226 if (res < 0)
227 {
228 i = 1;
229 do
230 {
231 if (res < -1 || i >= 1000)
232 {
233 MSG_ATTR(_("Unable to register a command server name"),
234 hl_attr(HLF_W));
235 return FAIL;
236 }
237 if (p == NULL)
238 p = alloc(STRLEN(name) + 10);
239 if (p == NULL)
240 {
241 res = -10;
242 continue;
243 }
244 sprintf((char *)p, "%s%d", name, i++);
245 res = DoRegisterName(dpy, p);
246 }
247 while (res < 0)
248 ;
249 vim_free(p);
250 }
251 return OK;
252}
253
254 static int
255DoRegisterName(dpy, name)
256 Display *dpy;
257 char_u *name;
258{
259 Window w;
260 XErrorHandler old_handler;
261#define MAX_NAME_LENGTH 100
262 char_u propInfo[MAX_NAME_LENGTH + 20];
263
264 if (commProperty == None)
265 {
266 if (SendInit(dpy) < 0)
267 return -2;
268 }
269
270 /*
271 * Make sure the name is unique, and append info about it to
272 * the registry property. It's important to lock the server
273 * here to prevent conflicting changes to the registry property.
274 * WARNING: Do not step through this while debugging, it will hangup the X
275 * server!
276 */
277 XGrabServer(dpy);
278 w = LookupName(dpy, name, FALSE, NULL);
279 if (w != (Window)0)
280 {
281 Status status;
282 int dummyInt;
283 unsigned int dummyUns;
284 Window dummyWin;
285
286 /*
287 * The name is currently registered. See if the commWindow
288 * associated with the name exists. If not, or if the commWindow
289 * is *our* commWindow, then just unregister the old name (this
290 * could happen if an application dies without cleaning up the
291 * registry).
292 */
293 old_handler = XSetErrorHandler(x_error_check);
294 status = XGetGeometry(dpy, w, &dummyWin, &dummyInt, &dummyInt,
295 &dummyUns, &dummyUns, &dummyUns, &dummyUns);
296 (void)XSetErrorHandler(old_handler);
297 if (status != Success && w != commWindow)
298 {
299 XUngrabServer(dpy);
300 XFlush(dpy);
301 return -1;
302 }
303 (void)LookupName(dpy, name, /*delete=*/TRUE, NULL);
304 }
305 sprintf((char *)propInfo, "%x %.*s", (int_u)commWindow,
306 MAX_NAME_LENGTH, name);
307 old_handler = XSetErrorHandler(x_error_check);
308 got_x_error = FALSE;
309 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
310 PropModeAppend, propInfo, STRLEN(propInfo) + 1);
311 XUngrabServer(dpy);
312 XSync(dpy, False);
313 (void)XSetErrorHandler(old_handler);
314
315 if (!got_x_error)
316 {
317#ifdef FEAT_EVAL
318 set_vim_var_string(VV_SEND_SERVER, name, -1);
319#endif
320 serverName = vim_strsave(name);
321#ifdef FEAT_TITLE
322 need_maketitle = TRUE;
323#endif
324 return 0;
325 }
326 return -2;
327}
328
329#if defined(FEAT_GUI) || defined(PROTO)
330/*
331 * Clean out new ID from registry and set it as comm win.
332 * Change any registered window ID.
333 */
334 void
335serverChangeRegisteredWindow(dpy, newwin)
336 Display *dpy; /* Display to register with */
337 Window newwin; /* Re-register to this ID */
338{
339 char_u propInfo[MAX_NAME_LENGTH + 20];
340
341 commWindow = newwin;
342
343 /* Always call SendInit() here, to make sure commWindow is marked as a Vim
344 * window. */
345 if (SendInit(dpy) < 0)
346 return;
347
348 /* WARNING: Do not step through this while debugging, it will hangup the X
349 * server! */
350 XGrabServer(dpy);
351 DeleteAnyLingerer(dpy, newwin);
352 if (serverName != NULL)
353 {
354 /* Reinsert name if we was already registered */
355 (void)LookupName(dpy, serverName, /*delete=*/TRUE, NULL);
356 sprintf((char *)propInfo, "%x %.*s",
357 (int_u)newwin, MAX_NAME_LENGTH, serverName);
358 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
359 PropModeAppend, (char_u *)propInfo,
360 STRLEN(propInfo) + 1);
361 }
362 XUngrabServer(dpy);
363}
364#endif
365
366/*
367 * Send to an instance of Vim via the X display.
368 * Returns 0 for OK, negative for an error.
369 */
370 int
371serverSendToVim(dpy, name, cmd, result, server, asExpr, localLoop, silent)
372 Display *dpy; /* Where to send. */
373 char_u *name; /* Where to send. */
374 char_u *cmd; /* What to send. */
375 char_u **result; /* Result of eval'ed expression */
376 Window *server; /* Actual ID of receiving app */
377 Bool asExpr; /* Interpret as keystrokes or expr ? */
378 Bool localLoop; /* Throw away everything but result */
379 int silent; /* don't complain about no server */
380{
381 Window w;
382 char_u *property;
383 int length;
384 int res;
385 static int serial = 0; /* Running count of sent commands.
386 * Used to give each command a
387 * different serial number. */
388 PendingCommand pending;
389 char_u *loosename = NULL;
390
391 if (result != NULL)
392 *result = NULL;
393 if (name == NULL || *name == NUL)
394 name = (char_u *)"GVIM"; /* use a default name */
395
396 if (commProperty == None && dpy != NULL)
397 {
398 if (SendInit(dpy) < 0)
399 return -1;
400 }
401
402 /* Execute locally if no display or target is ourselves */
403 if (dpy == NULL || (serverName != NULL && STRICMP(name, serverName) == 0))
404 {
405 if (asExpr)
406 {
407 char_u *ret;
408
409 ret = eval_client_expr_to_string(cmd);
410 if (result != NULL)
411 {
412 if (ret == NULL)
413 *result = vim_strsave((char_u *)_(e_invexprmsg));
414 else
415 *result = ret;
416 }
417 else
418 vim_free(ret);
419 return ret == NULL ? -1 : 0;
420 }
421 else
422 server_to_input_buf(cmd);
423 return 0;
424 }
425
426 /*
427 * Bind the server name to a communication window.
428 *
429 * Find any survivor with a serialno attached to the name if the
430 * original registrant of the wanted name is no longer present.
431 *
432 * Delete any lingering names from dead editors.
433 */
434 while (TRUE)
435 {
436 w = LookupName(dpy, name, FALSE, &loosename);
437 /* Check that the window is hot */
438 if (w != None)
439 {
440 if (!WindowValid(dpy, w))
441 {
442 LookupName(dpy, loosename ? loosename : name,
443 /*DELETE=*/TRUE, NULL);
444 continue;
445 }
446 }
447 break;
448 }
449 if (w == None)
450 {
451 if (!silent)
452 EMSG2(_(e_noserver), name);
453 return -1;
454 }
455 else if (loosename != NULL)
456 name = loosename;
457 if (server != NULL)
458 *server = w;
459
460 /*
461 * Send the command to target interpreter by appending it to the
462 * comm window in the communication window.
463 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000464 length = STRLEN(name) + STRLEN(cmd) + 14;
465#ifdef FEAT_MBYTE
466 length += STRLEN(p_enc);
467#endif
468 property = (char_u *)alloc((unsigned)length + 30);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000470#ifdef FEAT_MBYTE
471 sprintf((char *)property, "%c%c%c-n %s%c-E %s%c-s %s",
472 0, asExpr ? 'c' : 'k', 0, name, 0, p_enc, 0, cmd);
473#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 sprintf((char *)property, "%c%c%c-n %s%c-s %s",
475 0, asExpr ? 'c' : 'k', 0, name, 0, cmd);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 if (name == loosename)
478 vim_free(loosename);
479 /* Add a back reference to our comm window */
480 serial++;
481 sprintf((char *)property + length, "%c-r %x %d",
482 0, (int_u)commWindow, serial);
483 length += STRLEN(property + length + 1) + 1;
484
485 res = AppendPropCarefully(dpy, w, commProperty, property, length + 1);
486 vim_free(property);
487 if (res < 0)
488 {
489 EMSG(_("E248: Failed to send command to the destination program"));
490 return -1;
491 }
492
493 if (!asExpr) /* There is no answer for this - Keys are sent async */
494 return 0;
495
496 /*
497 * Register the fact that we're waiting for a command to
498 * complete (this is needed by SendEventProc and by
499 * AppendErrorProc to pass back the command's results).
500 */
501 pending.serial = serial;
502 pending.code = 0;
503 pending.result = NULL;
504 pending.nextPtr = pendingCommands;
505 pendingCommands = &pending;
506
507 ServerWait(dpy, w, WaitForPend, &pending, localLoop, 600);
508
509 /*
510 * Unregister the information about the pending command
511 * and return the result.
512 */
513 if (pendingCommands == &pending)
514 pendingCommands = pending.nextPtr;
515 else
516 {
517 PendingCommand *pcPtr;
518
519 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
520 if (pcPtr->nextPtr == &pending)
521 {
522 pcPtr->nextPtr = pending.nextPtr;
523 break;
524 }
525 }
526 if (result != NULL)
527 *result = pending.result;
528 else
529 vim_free(pending.result);
530
531 return pending.code == 0 ? 0 : -1;
532}
533
534 static int
535WaitForPend(p)
536 void *p;
537{
538 PendingCommand *pending = (PendingCommand *) p;
539 return pending->result != NULL;
540}
541
542/*
543 * Return TRUE if window "w" exists and has a "Vim" property on it.
544 */
545 static int
546WindowValid(dpy, w)
547 Display *dpy;
548 Window w;
549{
550 XErrorHandler old_handler;
551 Atom *plist;
552 int numProp;
553 int i;
554
555 old_handler = XSetErrorHandler(x_error_check);
556 got_x_error = 0;
557 plist = XListProperties(dpy, w, &numProp);
558 XSync(dpy, False);
559 XSetErrorHandler(old_handler);
560 if (plist == NULL || got_x_error)
561 return FALSE;
562
563 for (i = 0; i < numProp; i++)
564 if (plist[i] == vimProperty)
565 {
566 XFree(plist);
567 return TRUE;
568 }
569 XFree(plist);
570 return FALSE;
571}
572
573/*
574 * Enter a loop processing X events & polling chars until we see a result
575 */
576 static void
577ServerWait(dpy, w, endCond, endData, localLoop, seconds)
578 Display *dpy;
579 Window w;
580 EndCond endCond;
581 void *endData;
582 int localLoop;
583 int seconds;
584{
585 time_t start;
586 time_t now;
587 time_t lastChk = 0;
588 XEvent event;
589 XPropertyEvent *e = (XPropertyEvent *)&event;
590# define SEND_MSEC_POLL 50
591
592 time(&start);
593 while (endCond(endData) == 0)
594 {
595 time(&now);
596 if (seconds >= 0 && (now - start) >= seconds)
597 break;
598 if (now != lastChk)
599 {
600 lastChk = now;
601 if (!WindowValid(dpy, w))
602 break;
603 /*
604 * Sometimes the PropertyChange event doesn't come.
605 * This can be seen in eg: vim -c 'echo remote_expr("gvim", "3+2")'
606 */
607 serverEventProc(dpy, NULL);
608 }
609 if (localLoop)
610 {
611 /* Just look out for the answer without calling back into Vim */
612#ifndef HAVE_SELECT
613 struct pollfd fds;
614
615 fds.fd = ConnectionNumber(dpy);
616 fds.events = POLLIN;
617 if (poll(&fds, 1, SEND_MSEC_POLL) < 0)
618 break;
619#else
620 fd_set fds;
621 struct timeval tv;
622
623 tv.tv_sec = 0;
624 tv.tv_usec = SEND_MSEC_POLL * 1000;
625 FD_ZERO(&fds);
626 FD_SET(ConnectionNumber(dpy), &fds);
627 if (select(ConnectionNumber(dpy) + 1, &fds, NULL, NULL, &tv) < 0)
628 break;
629#endif
630 while (XEventsQueued(dpy, QueuedAfterReading) > 0)
631 {
632 XNextEvent(dpy, &event);
633 if (event.type == PropertyNotify && e->window == commWindow)
634 serverEventProc(dpy, &event);
635 }
636 }
637 else
638 {
639 if (got_int)
640 break;
641 ui_delay((long)SEND_MSEC_POLL, TRUE);
642 ui_breakcheck();
643 }
644 }
645}
646
647
648/*
649 * Fetch a list of all the Vim instance names currently registered for the
650 * display.
651 *
652 * Returns a newline separated list in allocated memory or NULL.
653 */
654 char_u *
655serverGetVimNames(dpy)
656 Display *dpy;
657{
658 char_u *regProp;
659 char_u *entry;
660 char_u *p;
661 long_u numItems;
662 int_u w;
663 garray_T ga;
664
665 if (registryProperty == None)
666 {
667 if (SendInit(dpy) < 0)
668 return NULL;
669 }
670 ga_init2(&ga, 1, 100);
671
672 /*
673 * Read the registry property.
674 */
675 if (GetRegProp(dpy, &regProp, &numItems, TRUE) == FAIL)
676 return NULL;
677
678 /*
679 * Scan all of the names out of the property.
680 */
681 ga_init2(&ga, 1, 100);
682 for (p = regProp; (p - regProp) < numItems; p++)
683 {
684 entry = p;
685 while (*p != 0 && !isspace(*p))
686 p++;
687 if (*p != 0)
688 {
689 w = None;
690 sscanf((char *)entry, "%x", &w);
691 if (WindowValid(dpy, (Window)w))
692 {
693 ga_concat(&ga, p + 1);
694 ga_concat(&ga, (char_u *)"\n");
695 }
696 while (*p != 0)
697 p++;
698 }
699 }
700 if (regProp != empty_prop)
701 XFree(regProp);
Bram Moolenaar269ec652004-07-29 08:43:53 +0000702 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703 return ga.ga_data;
704}
705
706/* ----------------------------------------------------------
707 * Reply stuff
708 */
709
710 static struct ServerReply *
711ServerReplyFind(w, op)
712 Window w;
713 enum ServerReplyOp op;
714{
715 struct ServerReply *p;
716 struct ServerReply e;
717 int i;
718
719 p = (struct ServerReply *) serverReply.ga_data;
720 for (i = 0; i < serverReply.ga_len; i++, p++)
721 if (p->id == w)
722 break;
723 if (i >= serverReply.ga_len)
724 p = NULL;
725
726 if (p == NULL && op == SROP_Add)
727 {
728 if (serverReply.ga_growsize == 0)
729 ga_init2(&serverReply, sizeof(struct ServerReply), 1);
730 if (ga_grow(&serverReply, 1) == OK)
731 {
732 p = ((struct ServerReply *) serverReply.ga_data)
733 + serverReply.ga_len;
734 e.id = w;
735 ga_init2(&e.strings, 1, 100);
736 memcpy(p, &e, sizeof(e));
737 serverReply.ga_len++;
738 serverReply.ga_room--;
739 }
740 }
741 else if (p != NULL && op == SROP_Delete)
742 {
743 ga_clear(&p->strings);
744 mch_memmove(p, p + 1, (serverReply.ga_len - i - 1) * sizeof(*p));
745 serverReply.ga_len--;
746 serverReply.ga_room++;
747 }
748
749 return p;
750}
751
752/*
753 * Convert string to windowid.
754 * Issue an error if the id is invalid.
755 */
756 Window
757serverStrToWin(str)
758 char_u *str;
759{
760 unsigned id = None;
761
762 sscanf((char *)str, "0x%x", &id);
763 if (id == None)
764 EMSG2(_("E573: Invalid server id used: %s"), str);
765
766 return (Window)id;
767}
768
769/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000770 * Send a reply string (notification) to client with id "name".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 * Return -1 if the window is invalid.
772 */
773 int
774serverSendReply(name, str)
775 char_u *name;
776 char_u *str;
777{
778 char_u *property;
779 int length;
780 int res;
781 Display *dpy = X_DISPLAY;
782 Window win = serverStrToWin(name);
783
784 if (commProperty == None)
785 {
786 if (SendInit(dpy) < 0)
787 return -2;
788 }
789 if (!WindowValid(dpy, win))
790 return -1;
791
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000792 length = STRLEN(str) + 11;
793#ifdef FEAT_MBYTE
794 length += STRLEN(p_enc);
795#endif
796 if ((property = (char_u *)alloc((unsigned)length + 30)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000797 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000798#ifdef FEAT_MBYTE
799 sprintf((char *)property, "%cn%c-E %s%c-n %s%c-w %x",
800 0, 0, p_enc, 0, str, 0, (unsigned int)commWindow);
801#else
802 sprintf((char *)property, "%cn%c-n %s%c-w %x",
803 0, 0, str, 0, (unsigned int)commWindow);
804#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805 length += STRLEN(property + length);
806 res = AppendPropCarefully(dpy, win, commProperty, property, length + 1);
807 vim_free(property);
808 return res;
809 }
810 return -1;
811}
812
813 static int
814WaitForReply(p)
815 void *p;
816{
817 Window *w = (Window *) p;
818 return ServerReplyFind(*w, SROP_Find) != NULL;
819}
820
821/*
822 * Wait for replies from id (win)
823 * Return 0 and the malloc'ed string when a reply is available.
824 * Return -1 if the window becomes invalid while waiting.
825 */
826 int
827serverReadReply(dpy, win, str, localLoop)
828 Display *dpy;
829 Window win;
830 char_u **str;
831 int localLoop;
832{
833 int len;
834 char_u *s;
835 struct ServerReply *p;
836
837 ServerWait(dpy, win, WaitForReply, &win, localLoop, -1);
838
839 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
840 {
841 *str = vim_strsave(p->strings.ga_data);
842 len = STRLEN(*str) + 1;
843 if (len < p->strings.ga_len)
844 {
845 s = (char_u *) p->strings.ga_data;
846 mch_memmove(s, s + len, p->strings.ga_len - len);
847 p->strings.ga_room += len;
848 p->strings.ga_len -= len;
849 }
850 else
851 {
852 /* Last string read. Remove from list */
853 ga_clear(&p->strings);
854 ServerReplyFind(win, SROP_Delete);
855 }
856 return 0;
857 }
858 return -1;
859}
860
861/*
862 * Check for replies from id (win).
863 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
864 */
865 int
866serverPeekReply(dpy, win, str)
867 Display *dpy;
868 Window win;
869 char_u **str;
870{
871 struct ServerReply *p;
872
873 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
874 {
875 if (str != NULL)
876 *str = p->strings.ga_data;
877 return 1;
878 }
879 if (!WindowValid(dpy, win))
880 return -1;
881 return 0;
882}
883
884
885/*
886 * Initialize the communication channels for sending commands and receiving
887 * results.
888 */
889 static int
890SendInit(dpy)
891 Display *dpy;
892{
893 XErrorHandler old_handler;
894
895 /*
896 * Create the window used for communication, and set up an
897 * event handler for it.
898 */
899 old_handler = XSetErrorHandler(x_error_check);
900 got_x_error = FALSE;
901
902 if (commProperty == None)
903 commProperty = XInternAtom(dpy, "Comm", False);
904 if (vimProperty == None)
905 vimProperty = XInternAtom(dpy, "Vim", False);
906 if (registryProperty == None)
907 registryProperty = XInternAtom(dpy, "VimRegistry", False);
908
909 if (commWindow == None)
910 {
911 commWindow = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy),
912 getpid(), 0, 10, 10, 0,
913 WhitePixel(dpy, DefaultScreen(dpy)),
914 WhitePixel(dpy, DefaultScreen(dpy)));
915 XSelectInput(dpy, commWindow, PropertyChangeMask);
916 /* WARNING: Do not step through this while debugging, it will hangup
917 * the X server! */
918 XGrabServer(dpy);
919 DeleteAnyLingerer(dpy, commWindow);
920 XUngrabServer(dpy);
921 }
922
923 /* Make window recognizable as a vim window */
924 XChangeProperty(dpy, commWindow, vimProperty, XA_STRING,
925 8, PropModeReplace, (char_u *)VIM_VERSION_SHORT,
926 (int)STRLEN(VIM_VERSION_SHORT) + 1);
927
928 XSync(dpy, False);
929 (void)XSetErrorHandler(old_handler);
930
931 return got_x_error ? -1 : 0;
932}
933
934/*
935 * Given a server name, see if the name exists in the registry for a
936 * particular display.
937 *
938 * If the given name is registered, return the ID of the window associated
939 * with the name. If the name isn't registered, then return 0.
940 *
941 * Side effects:
942 * If the registry property is improperly formed, then it is deleted.
943 * If "delete" is non-zero, then if the named server is found it is
944 * removed from the registry property.
945 */
946 static Window
947LookupName(dpy, name, delete, loose)
948 Display *dpy; /* Display whose registry to check. */
949 char_u *name; /* Name of a server. */
950 int delete; /* If non-zero, delete info about name. */
951 char_u **loose; /* Do another search matching -999 if not found
952 Return result here if a match is found */
953{
954 char_u *regProp, *entry;
955 char_u *p;
956 long_u numItems;
957 int_u returnValue;
958
959 /*
960 * Read the registry property.
961 */
962 if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL)
963 return 0;
964
965 /*
966 * Scan the property for the desired name.
967 */
968 returnValue = (int_u)None;
969 entry = NULL; /* Not needed, but eliminates compiler warning. */
970 for (p = regProp; (p - regProp) < numItems; )
971 {
972 entry = p;
973 while (*p != 0 && !isspace(*p))
974 p++;
975 if (*p != 0 && STRICMP(name, p + 1) == 0)
976 {
977 sscanf((char *)entry, "%x", &returnValue);
978 break;
979 }
980 while (*p != 0)
981 p++;
982 p++;
983 }
984
985 if (loose != NULL && returnValue == (int_u)None && !IsSerialName(name))
986 {
987 for (p = regProp; (p - regProp) < numItems; )
988 {
989 entry = p;
990 while (*p != 0 && !isspace(*p))
991 p++;
992 if (*p != 0 && IsSerialName(p + 1)
993 && STRNICMP(name, p + 1, STRLEN(name)) == 0)
994 {
995 sscanf((char *)entry, "%x", &returnValue);
996 *loose = vim_strsave(p + 1);
997 break;
998 }
999 while (*p != 0)
1000 p++;
1001 p++;
1002 }
1003 }
1004
1005 /*
1006 * Delete the property, if that is desired (copy down the
1007 * remainder of the registry property to overlay the deleted
1008 * info, then rewrite the property).
1009 */
1010 if (delete && returnValue != (int_u)None)
1011 {
1012 int count;
1013
1014 while (*p != 0)
1015 p++;
1016 p++;
1017 count = numItems - (p - regProp);
1018 if (count > 0)
1019 memcpy(entry, p, count);
1020 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING,
1021 8, PropModeReplace, regProp,
1022 (int)(numItems - (p - entry)));
1023 XSync(dpy, False);
1024 }
1025
1026 if (regProp != empty_prop)
1027 XFree(regProp);
1028 return (Window)returnValue;
1029}
1030
1031/*
1032 * Delete any lingering occurences of window id. We promise that any
1033 * occurences is not ours since it is not yet put into the registry (by us)
1034 *
1035 * This is necessary in the following scenario:
1036 * 1. There is an old windowid for an exit'ed vim in the registry
1037 * 2. We get that id for our commWindow but only want to send, not register.
1038 * 3. The window will mistakenly be regarded valid because of own commWindow
1039 */
1040 static void
1041DeleteAnyLingerer(dpy, win)
1042 Display *dpy; /* Display whose registry to check. */
1043 Window win; /* Window to remove */
1044{
1045 char_u *regProp, *entry = NULL;
1046 char_u *p;
1047 long_u numItems;
Bram Moolenaar7171abe2004-10-11 10:06:20 +00001048 int_u wwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049
1050 /*
1051 * Read the registry property.
1052 */
1053 if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL)
1054 return;
1055
1056 /* Scan the property for the window id. */
1057 for (p = regProp; (p - regProp) < numItems; )
1058 {
1059 if (*p != 0)
1060 {
Bram Moolenaar7171abe2004-10-11 10:06:20 +00001061 sscanf((char *)p, "%x", &wwin);
1062 if ((Window)wwin == win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 {
1064 int lastHalf;
1065
1066 /* Copy down the remainder to delete entry */
1067 entry = p;
1068 while (*p != 0)
1069 p++;
1070 p++;
1071 lastHalf = numItems - (p - regProp);
1072 if (lastHalf > 0)
1073 memcpy(entry, p, lastHalf);
1074 numItems = (entry - regProp) + lastHalf;
1075 p = entry;
1076 continue;
1077 }
1078 }
1079 while (*p != 0)
1080 p++;
1081 p++;
1082 }
1083
1084 if (entry != NULL)
1085 {
1086 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty,
1087 XA_STRING, 8, PropModeReplace, regProp,
1088 (int)(p - regProp));
1089 XSync(dpy, False);
1090 }
1091
1092 if (regProp != empty_prop)
1093 XFree(regProp);
1094}
1095
1096/*
1097 * Read the registry property. Delete it when it's formatted wrong.
1098 * Return the property in "regPropp". "empty_prop" is used when it doesn't
1099 * exist yet.
1100 * Return OK when successful.
1101 */
1102 static int
1103GetRegProp(dpy, regPropp, numItemsp, domsg)
1104 Display *dpy;
1105 char_u **regPropp;
1106 long_u *numItemsp;
1107 int domsg; /* When TRUE give error message. */
1108{
1109 int result, actualFormat;
1110 long_u bytesAfter;
1111 Atom actualType;
1112
1113 *regPropp = NULL;
1114 result = XGetWindowProperty(dpy, RootWindow(dpy, 0), registryProperty, 0L,
1115 (long)MAX_PROP_WORDS, False,
1116 XA_STRING, &actualType,
1117 &actualFormat, numItemsp, &bytesAfter,
1118 regPropp);
1119
1120 if (actualType == None)
1121 {
1122 /* No prop yet. Logically equal to the empty list */
1123 *numItemsp = 0;
1124 *regPropp = empty_prop;
1125 return OK;
1126 }
1127
1128 /* If the property is improperly formed, then delete it. */
1129 if (result != Success || actualFormat != 8 || actualType != XA_STRING)
1130 {
1131 if (*regPropp != NULL)
1132 XFree(*regPropp);
1133 XDeleteProperty(dpy, RootWindow(dpy, 0), registryProperty);
1134 if (domsg)
1135 EMSG(_("E251: VIM instance registry property is badly formed. Deleted!"));
1136 return FAIL;
1137 }
1138 return OK;
1139}
1140
1141/*
1142 * This procedure is invoked by the varous X event loops throughout Vims when
1143 * a property changes on the communication window. This procedure reads the
1144 * property and handles command requests and responses.
1145 */
1146 void
1147serverEventProc(dpy, eventPtr)
1148 Display *dpy;
1149 XEvent *eventPtr; /* Information about event. */
1150{
1151 char_u *propInfo;
1152 char_u *p;
1153 int result, actualFormat, code;
1154 long_u numItems, bytesAfter;
1155 Atom actualType;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001156 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157
1158 if (eventPtr != NULL)
1159 {
1160 if (eventPtr->xproperty.atom != commProperty
1161 || eventPtr->xproperty.state != PropertyNewValue)
1162 return;
1163 }
1164
1165 /*
1166 * Read the comm property and delete it.
1167 */
1168 propInfo = NULL;
1169 result = XGetWindowProperty(dpy, commWindow, commProperty, 0L,
1170 (long)MAX_PROP_WORDS, True,
1171 XA_STRING, &actualType,
1172 &actualFormat, &numItems, &bytesAfter,
1173 &propInfo);
1174
1175 /* If the property doesn't exist or is improperly formed then ignore it. */
1176 if (result != Success || actualType != XA_STRING || actualFormat != 8)
1177 {
1178 if (propInfo != NULL)
1179 XFree(propInfo);
1180 return;
1181 }
1182
1183 /*
1184 * Several commands and results could arrive in the property at
1185 * one time; each iteration through the outer loop handles a
1186 * single command or result.
1187 */
1188 for (p = propInfo; (p - propInfo) < numItems; )
1189 {
1190 /*
1191 * Ignore leading NULs; each command or result starts with a
1192 * NUL so that no matter how badly formed a preceding command
1193 * is, we'll be able to tell that a new command/result is
1194 * starting.
1195 */
1196 if (*p == 0)
1197 {
1198 p++;
1199 continue;
1200 }
1201
1202 if ((*p == 'c' || *p == 'k') && (p[1] == 0))
1203 {
1204 Window resWindow;
1205 char_u *name, *script, *serial, *end, *res;
1206 Bool asKeys = *p == 'k';
1207 garray_T reply;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001208 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209
1210 /*
1211 * This is an incoming command from some other application.
1212 * Iterate over all of its options. Stop when we reach
1213 * the end of the property or something that doesn't look
1214 * like an option.
1215 */
1216 p += 2;
1217 name = NULL;
1218 resWindow = None;
1219 serial = (char_u *)"";
1220 script = NULL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001221 enc = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 while (p - propInfo < numItems && *p == '-')
1223 {
1224 switch (p[1])
1225 {
1226 case 'r':
1227 end = skipwhite(p + 2);
1228 resWindow = 0;
1229 while (vim_isxdigit(*end))
1230 {
1231 resWindow = 16 * resWindow + (long_u)hex2nr(*end);
1232 ++end;
1233 }
1234 if (end == p + 2 || *end != ' ')
1235 resWindow = None;
1236 else
1237 {
1238 p = serial = end + 1;
1239 clientWindow = resWindow; /* Remember in global */
1240 }
1241 break;
1242 case 'n':
1243 if (p[2] == ' ')
1244 name = p + 3;
1245 break;
1246 case 's':
1247 if (p[2] == ' ')
1248 script = p + 3;
1249 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001250 case 'E':
1251 if (p[2] == ' ')
1252 enc = p + 3;
1253 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254 }
1255 while (*p != 0)
1256 p++;
1257 p++;
1258 }
1259
1260 if (script == NULL || name == NULL)
1261 continue;
1262
1263 /*
1264 * Initialize the result property, so that we're ready at any
1265 * time if we need to return an error.
1266 */
1267 if (resWindow != None)
1268 {
1269 ga_init2(&reply, 1, 100);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001270#ifdef FEAT_MBYTE
1271 ga_grow(&reply, 50 + STRLEN(p_enc));
1272 sprintf(reply.ga_data, "%cr%c-E %s%c-s %s%c-r ",
1273 0, 0, p_enc, 0, serial, 0);
1274#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275 ga_grow(&reply, 50);
1276 sprintf(reply.ga_data, "%cr%c-s %s%c-r ", 0, 0, serial, 0);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001277#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001278 reply.ga_len = 10 + STRLEN(serial);
1279 reply.ga_room -= reply.ga_len;
1280 }
1281 res = NULL;
1282 if (serverName != NULL && STRICMP(name, serverName) == 0)
1283 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001284 script = serverConvert(enc, script, &tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 if (asKeys)
1286 server_to_input_buf(script);
1287 else
1288 res = eval_client_expr_to_string(script);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001289 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290 }
1291 if (resWindow != None)
1292 {
1293 if (res != NULL)
1294 ga_concat(&reply, res);
1295 else if (asKeys == 0)
1296 {
1297 ga_concat(&reply, (char_u *)_(e_invexprmsg));
1298 ga_append(&reply, 0);
1299 ga_concat(&reply, (char_u *)"-c 1");
1300 }
Bram Moolenaar269ec652004-07-29 08:43:53 +00001301 ga_append(&reply, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001302 (void)AppendPropCarefully(dpy, resWindow, commProperty,
1303 reply.ga_data, reply.ga_len);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001304 ga_clear(&reply);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305 }
1306 vim_free(res);
1307 }
1308 else if (*p == 'r' && p[1] == 0)
1309 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001310 int serial, gotSerial;
1311 char_u *res;
1312 PendingCommand *pcPtr;
1313 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
1315 /*
1316 * This is a reply to some command that we sent out. Iterate
1317 * over all of its options. Stop when we reach the end of the
1318 * property or something that doesn't look like an option.
1319 */
1320 p += 2;
1321 gotSerial = 0;
1322 res = (char_u *)"";
1323 code = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001324 enc = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 while ((p-propInfo) < numItems && *p == '-')
1326 {
1327 switch (p[1])
1328 {
1329 case 'r':
1330 if (p[2] == ' ')
1331 res = p + 3;
1332 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001333 case 'E':
1334 if (p[2] == ' ')
1335 enc = p + 3;
1336 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 case 's':
1338 if (sscanf((char *)p + 2, " %d", &serial) == 1)
1339 gotSerial = 1;
1340 break;
1341 case 'c':
1342 if (sscanf((char *)p + 2, " %d", &code) != 1)
1343 code = 0;
1344 break;
1345 }
1346 while (*p != 0)
1347 p++;
1348 p++;
1349 }
1350
1351 if (!gotSerial)
1352 continue;
1353
1354 /*
1355 * Give the result information to anyone who's
1356 * waiting for it.
1357 */
1358 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
1359 {
1360 if (serial != pcPtr->serial || pcPtr->result != NULL)
1361 continue;
1362
1363 pcPtr->code = code;
1364 if (res != NULL)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001365 {
1366 res = serverConvert(enc, res, &tofree);
1367 if (tofree == NULL)
1368 res = vim_strsave(res);
1369 pcPtr->result = res;
1370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371 else
1372 pcPtr->result = vim_strsave((char_u *)"");
1373 break;
1374 }
1375 }
1376 else if (*p == 'n' && p[1] == 0)
1377 {
1378 Window win = 0;
1379 unsigned int u;
1380 int gotWindow;
1381 char_u *str;
1382 char_u winstr[30];
1383 struct ServerReply *r;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001384 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385
1386 /*
1387 * This is a (n)otification. Sent with serverreply_send in VimL.
1388 * Execute any autocommand and save it for later retrieval
1389 */
1390 p += 2;
1391 gotWindow = 0;
1392 str = (char_u *)"";
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001393 enc = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394 while ((p-propInfo) < numItems && *p == '-')
1395 {
1396 switch (p[1])
1397 {
1398 case 'n':
1399 if (p[2] == ' ')
1400 str = p + 3;
1401 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001402 case 'E':
1403 if (p[2] == ' ')
1404 enc = p + 3;
1405 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406 case 'w':
1407 if (sscanf((char *)p + 2, " %x", &u) == 1)
1408 {
1409 win = u;
1410 gotWindow = 1;
1411 }
1412 break;
1413 }
1414 while (*p != 0)
1415 p++;
1416 p++;
1417 }
1418
1419 if (!gotWindow)
1420 continue;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001421 str = serverConvert(enc, str, &tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422 if ((r = ServerReplyFind(win, SROP_Add)) != NULL)
1423 {
1424 ga_concat(&(r->strings), str);
Bram Moolenaar269ec652004-07-29 08:43:53 +00001425 ga_append(&(r->strings), NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426 }
1427#ifdef FEAT_AUTOCMD
1428 sprintf((char *)winstr, "0x%x", (unsigned int)win);
1429 apply_autocmds(EVENT_REMOTEREPLY, winstr, str, TRUE, curbuf);
1430#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001431 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 }
1433 else
1434 {
1435 /*
1436 * Didn't recognize this thing. Just skip through the next
1437 * null character and try again.
1438 * Even if we get an 'r'(eply) we will throw it away as we
1439 * never specify (and thus expect) one
1440 */
1441 while (*p != 0)
1442 p++;
1443 p++;
1444 }
1445 }
1446 XFree(propInfo);
1447}
1448
1449/*
1450 * Append a given property to a given window, but set up an X error handler so
1451 * that if the append fails this procedure can return an error code rather
1452 * than having Xlib panic.
1453 * Return: 0 for OK, -1 for error
1454 */
1455 static int
1456AppendPropCarefully(dpy, window, property, value, length)
1457 Display *dpy; /* Display on which to operate. */
1458 Window window; /* Window whose property is to be modified. */
1459 Atom property; /* Name of property. */
1460 char_u *value; /* Characters to append to property. */
1461 int length; /* How much to append */
1462{
1463 XErrorHandler old_handler;
1464
1465 old_handler = XSetErrorHandler(x_error_check);
1466 got_x_error = FALSE;
1467 XChangeProperty(dpy, window, property, XA_STRING, 8,
1468 PropModeAppend, value, length);
1469 XSync(dpy, False);
1470 (void) XSetErrorHandler(old_handler);
1471 return got_x_error ? -1 : 0;
1472}
1473
1474
1475/*
1476 * Another X Error handler, just used to check for errors.
1477 */
1478/* ARGSUSED */
1479 static int
1480x_error_check(dpy, error_event)
1481 Display *dpy;
1482 XErrorEvent *error_event;
1483{
1484 got_x_error = TRUE;
1485 return 0;
1486}
1487
1488/*
1489 * Check if "str" looks like it had a serial number appended.
1490 * Actually just checks if the name ends in a digit.
1491 */
1492 static int
1493IsSerialName(str)
1494 char_u *str;
1495{
1496 int len = STRLEN(str);
1497
1498 return (len > 1 && vim_isdigit(str[len - 1]));
1499}
1500#endif /* FEAT_CLIENTSERVER */