xref: /freebsd/contrib/less/prompt.c (revision dafba19e42e78cd3d7c9264ece49ddd3d7d70da5)
1 /*
2  * Copyright (C) 1984-2025  Mark Nudelman
3  *
4  * You may distribute under the terms of either the GNU General Public
5  * License or the Less License, as specified in the README file.
6  *
7  * For more information, see the README file.
8  */
9 
10 
11 /*
12  * Prompting and other messages.
13  * There are three flavors of prompts, SHORT, MEDIUM and LONG,
14  * selected by the -m/-M options.
15  * There is also the "equals message", printed by the = command.
16  * A prompt is a message composed of various pieces, such as the
17  * name of the file being viewed, the percentage into the file, etc.
18  */
19 
20 #include "less.h"
21 #include "position.h"
22 
23 extern int pr_type;
24 extern lbool new_file;
25 extern int linenums;
26 extern int hshift;
27 extern int sc_width;
28 extern int sc_height;
29 extern int jump_sline;
30 extern int less_is_more;
31 extern int header_lines;
32 extern int utf_mode;
33 extern IFILE curr_ifile;
34 #if OSC8_LINK
35 extern char *osc8_path;
36 #endif
37 #if EDITOR
38 extern constant char *editor;
39 extern constant char *editproto;
40 #endif
41 
42 /*
43  * Prototypes for the three flavors of prompts.
44  * These strings are expanded by pr_expand().
45  */
46 static constant char s_proto[] =
47   "?n?f%f .?m(%T %i of %m) ..?e(END) ?x- Next\\: %x..%t";
48 static constant char m_proto[] =
49   "?n?f%f .?m(%T %i of %m) ..?e(END) ?x- Next\\: %x.:?pB%pB\\%:byte %bB?s/%s...%t";
50 static constant char M_proto[] =
51   "?f%f .?n?m(%T %i of %m) ..?ltlines %lt-%lb?L/%L. :byte %bB?s/%s. .?e(END) ?x- Next\\: %x.:?pB%pB\\%..?c (column %c).%t";
52 static constant char e_proto[] =
53   "?f%f .?m(%T %i of %m) .?ltlines %lt-%lb?L/%L. .byte %bB?s/%s. ?e(END) :?pB%pB\\%..?c (column %c).%t";
54 static constant char h_proto[] =
55   "HELP -- ?eEND -- Press g to see it again:Press RETURN for more., or q when done";
56 static constant char w_proto[] =
57   "Waiting for data";
58 static constant char more_proto[] =
59   "--More--(?eEND ?x- Next\\: %x.:?pB%pB\\%:byte %bB?s/%s...%t)";
60 
61 public char *prproto[3];
62 public char constant *eqproto = e_proto;
63 public char constant *hproto = h_proto;
64 public char constant *wproto = w_proto;
65 
66 static char message[PROMPT_SIZE];
67 static char *mp;
68 static int longest_line;
69 
70 /*
71  * Initialize the prompt prototype strings.
72  */
init_prompt(void)73 public void init_prompt(void)
74 {
75 	prproto[0] = save(s_proto);
76 	prproto[1] = save(less_is_more ? more_proto : m_proto);
77 	prproto[2] = save(M_proto);
78 	eqproto = save(e_proto);
79 	hproto = save(h_proto);
80 	wproto = save(w_proto);
81 }
82 
83 /*
84  * Get width of longest line currently on screen.
85  * Calling longest_line_width() is expensive, so we cache its value here
86  * in case it is called more than once per prompt expansion.
87  */
pr_longest_line(void)88 static int pr_longest_line(void)
89 {
90 	if (longest_line < 0)
91 		longest_line = longest_line_width();
92 	return longest_line;
93 }
94 
95 /*
96  * Append a string to the end of the message.
97  * nprt means the character *may* be nonprintable
98  * and should be converted to printable form.
99  */
ap_estr(constant char * s,lbool nprt)100 static void ap_estr(constant char *s, lbool nprt)
101 {
102 	constant char *es = s + strlen(s);
103 	while (*s != '\0')
104 	{
105 		LWCHAR ch = step_charc(&s, +1, es);
106 		constant char *ps;
107 		char ubuf[MAX_UTF_CHAR_LEN+1];
108 		size_t plen;
109 
110 		if (nprt)
111 		{
112 			ps = utf_mode ? prutfchar(ch) : prchar(ch);
113 		} else
114 		{
115 			char *up = ubuf;
116 			put_wchar(&up, ch);
117 			*up = '\0';
118 			ps = ubuf;
119 		}
120 		plen = strlen(ps);
121 		if (mp + plen >= message + PROMPT_SIZE)
122 			break;
123 		strcpy(mp, ps);
124 		mp += plen;
125 	}
126 	*mp = '\0';
127 }
128 
ap_str(constant char * s)129 static void ap_str(constant char *s)
130 {
131 	ap_estr(s, FALSE);
132 }
133 
134 /*
135  * Append a character to the end of the message.
136  */
ap_char(char c)137 static void ap_char(char c)
138 {
139 	if (mp + 1 >= message + PROMPT_SIZE)
140 		return;
141 	*mp++ = c;
142 	*mp = '\0';
143 }
144 
145 /*
146  * Append a POSITION (as a decimal integer) to the end of the message.
147  */
ap_pos(POSITION pos)148 static void ap_pos(POSITION pos)
149 {
150 	char buf[INT_STRLEN_BOUND(pos) + 2];
151 
152 	postoa(pos, buf, 10);
153 	ap_str(buf);
154 }
155 
156 /*
157  * Append a line number to the end of the message.
158  */
ap_linenum(LINENUM linenum)159 static void ap_linenum(LINENUM linenum)
160 {
161 	char buf[INT_STRLEN_BOUND(linenum) + 2];
162 
163 	linenumtoa(linenum, buf, 10);
164 	ap_str(buf);
165 }
166 
167 /*
168  * Append an integer to the end of the message.
169  */
ap_int(int num)170 static void ap_int(int num)
171 {
172 	char buf[INT_STRLEN_BOUND(num) + 2];
173 
174 	inttoa(num, buf, 10);
175 	ap_str(buf);
176 }
177 
178 /*
179  * Append a question mark to the end of the message.
180  */
ap_quest(void)181 static void ap_quest(void)
182 {
183 	ap_str("?");
184 }
185 
186 /*
187  * Return the "current" byte offset in the file.
188  */
curr_byte(int where)189 static POSITION curr_byte(int where)
190 {
191 	POSITION pos;
192 
193 	pos = position(where);
194 	while (pos == NULL_POSITION && where >= 0 && where < sc_height-1)
195 		pos = position(++where);
196 	if (pos == NULL_POSITION)
197 		pos = ch_length();
198 	return (pos);
199 }
200 
201 /*
202  * Return the value of a prototype conditional.
203  * A prototype string may include conditionals which consist of a
204  * question mark followed by a single letter.
205  * Here we decode that letter and return the appropriate boolean value.
206  */
cond(char c,int where)207 static lbool cond(char c, int where)
208 {
209 	POSITION len;
210 
211 	switch (c)
212 	{
213 	case 'a': /* Anything in the message yet? */
214 		return (mp > message);
215 	case 'b': /* Current byte offset known? */
216 		return (curr_byte(where) != NULL_POSITION);
217 	case 'c':
218 		return (hshift != 0);
219 	case 'e': /* At end of file? */
220 		return (eof_displayed(FALSE));
221 	case 'f': /* Filename known? */
222 	case 'g':
223 		return (strcmp(get_filename(curr_ifile), "-") != 0);
224 	case 'l': /* Line number known? */
225 	case 'd': /* Same as l */
226 		if (!linenums)
227 			return FALSE;
228 		return (currline(where) != 0);
229 	case 'L': /* Final line number known? */
230 	case 'D': /* Final page number known? */
231 		return (linenums && ch_length() != NULL_POSITION);
232 	case 'm': /* More than one file? */
233 #if TAGS
234 		return (ntags() ? (ntags() > 1) : (nifile() > 1));
235 #else
236 		return (nifile() > 1);
237 #endif
238 	case 'n': /* First prompt in a new file? */
239 #if TAGS
240 		return (ntags() ? TRUE : new_file ? TRUE : FALSE);
241 #else
242 		return (new_file ? TRUE : FALSE);
243 #endif
244 	case 'p': /* Percent into file (bytes) known? */
245 		return (curr_byte(where) != NULL_POSITION && ch_length() > 0);
246 	case 'P': /* Percent into file (lines) known? */
247 		return (currline(where) != 0 &&
248 				(len = ch_length()) > 0 &&
249 				find_linenum(len) != 0);
250 	case 'Q': /* Any on-screen line truncated? */
251 		return (hshift + sc_width < pr_longest_line());
252 	case 's': /* Size of file known? */
253 	case 'B':
254 		return (ch_length() != NULL_POSITION);
255 	case 'x': /* Is there a "next" file? */
256 #if TAGS
257 		if (ntags())
258 			return (FALSE);
259 #endif
260 		return (next_ifile(curr_ifile) != NULL_IFILE);
261 	}
262 	return (FALSE);
263 }
264 
265 /*
266  * Decode a "percent" prototype character.
267  * A prototype string may include various "percent" escapes;
268  * that is, a percent sign followed by a single letter.
269  * Here we decode that letter and take the appropriate action,
270  * usually by appending something to the message being built.
271  */
protochar(char c,int where)272 static void protochar(char c, int where)
273 {
274 	POSITION pos;
275 	POSITION len;
276 	LINENUM linenum;
277 	LINENUM last_linenum;
278 	IFILE h;
279 	char *s;
280 
281 #undef  PAGE_NUM
282 #define PAGE_NUM(linenum)  ((((linenum) - 1) / (sc_height - header_lines - 1)) + 1)
283 
284 	switch (c)
285 	{
286 	case 'b': /* Current byte offset */
287 		pos = curr_byte(where);
288 		if (pos != NULL_POSITION)
289 			ap_pos(pos);
290 		else
291 			ap_quest();
292 		break;
293 	case 'c':
294 		ap_int(hshift+1);
295 		break;
296 	case 'C':
297 		ap_int(hshift + sc_width);
298 		break;
299 	case 'd': /* Current page number */
300 		linenum = currline(where);
301 		if (linenum > 0 && sc_height > header_lines + 1)
302 			ap_linenum(PAGE_NUM(linenum));
303 		else
304 			ap_quest();
305 		break;
306 	case 'D': /* Final page number */
307 		/* Find the page number of the last byte in the file (len-1). */
308 		len = ch_length();
309 		if (len == NULL_POSITION)
310 			ap_quest();
311 		else if (len == 0)
312 			/* An empty file has no pages. */
313 			ap_linenum(0);
314 		else
315 		{
316 			linenum = find_linenum(len - 1);
317 			if (linenum <= 0)
318 				ap_quest();
319 			else
320 				ap_linenum(PAGE_NUM(linenum));
321 		}
322 		break;
323 #if EDITOR
324 	case 'E': /* Editor name */
325 		ap_str(editor);
326 		break;
327 #endif
328 	case 'f': /* File name */
329 		ap_estr(get_filename(curr_ifile), TRUE);
330 		break;
331 	case 'F': /* Last component of file name */
332 		ap_estr(last_component(get_filename(curr_ifile)), TRUE);
333 		break;
334 	case 'g': /* Shell-escaped file name */
335 		s = shell_quote(get_filename(curr_ifile));
336 		ap_str(s);
337 		free(s);
338 		break;
339 	case 'i': /* Index into list of files */
340 #if TAGS
341 		if (ntags())
342 			ap_int(curr_tag());
343 		else
344 #endif
345 			ap_int(get_index(curr_ifile));
346 		break;
347 	case 'l': /* Current line number */
348 		linenum = currline(where);
349 		if (linenum != 0)
350 			ap_linenum(vlinenum(linenum));
351 		else
352 			ap_quest();
353 		break;
354 	case 'L': /* Final line number */
355 		len = ch_length();
356 		if (len == NULL_POSITION || len == ch_zero() ||
357 		    (linenum = find_linenum(len)) <= 0)
358 			ap_quest();
359 		else
360 			ap_linenum(vlinenum(linenum-1));
361 		break;
362 	case 'm': { /* Number of files */
363 #if TAGS
364 		int n = ntags();
365 		if (n)
366 			ap_int(n);
367 		else
368 #endif
369 			ap_int(nifile());
370 		break; }
371 	case 'o': /* path (URI without protocol) of selected OSC8 link */
372 #if OSC8_LINK
373 		if (osc8_path != NULL)
374 			ap_str(osc8_path);
375 		else
376 #endif
377 			ap_quest();
378 		break;
379 	case 'p': /* Percent into file (bytes) */
380 		pos = curr_byte(where);
381 		len = ch_length();
382 		if (pos != NULL_POSITION && len > 0)
383 			ap_int(percentage(pos,len));
384 		else
385 			ap_quest();
386 		break;
387 	case 'P': /* Percent into file (lines) */
388 		linenum = currline(where);
389 		if (linenum == 0 ||
390 		    (len = ch_length()) == NULL_POSITION || len == ch_zero() ||
391 		    (last_linenum = find_linenum(len)) <= 0)
392 			ap_quest();
393 		else
394 			ap_int(percentage(linenum, last_linenum));
395 		break;
396 	case 'Q': /* Percent shifted horizontally */
397 		ap_int(percentage(hshift + sc_width, pr_longest_line()));
398 		break;
399 	case 's': /* Size of file */
400 	case 'B':
401 		len = ch_length();
402 		if (len != NULL_POSITION)
403 			ap_pos(len);
404 		else
405 			ap_quest();
406 		break;
407 	case 't': /* Truncate trailing spaces in the message */
408 		while (mp > message && mp[-1] == ' ')
409 			mp--;
410 		*mp = '\0';
411 		break;
412 	case 'T': /* Type of list */
413 #if TAGS
414 		if (ntags())
415 			ap_str("tag");
416 		else
417 #endif
418 			ap_str("file");
419 		break;
420 	case 'W': /* Width of longest line on screen */
421 		ap_int(pr_longest_line());
422 		break;
423 	case 'x': /* Name of next file */
424 		h = next_ifile(curr_ifile);
425 		if (h != NULL_IFILE)
426 			ap_str(get_filename(h));
427 		else
428 			ap_quest();
429 		break;
430 	}
431 }
432 
433 /*
434  * Skip a false conditional.
435  * When a false condition is found (either a false IF or the ELSE part
436  * of a true IF), this routine scans the prototype string to decide
437  * where to resume parsing the string.
438  * We must keep track of nested IFs and skip them properly.
439  */
skipcond(constant char * p)440 static constant char * skipcond(constant char *p)
441 {
442 	int iflevel;
443 
444 	/*
445 	 * We came in here after processing a ? or :,
446 	 * so we start nested one level deep.
447 	 */
448 	iflevel = 1;
449 
450 	for (;;) switch (*++p)
451 	{
452 	case '?':
453 		/*
454 		 * Start of a nested IF.
455 		 */
456 		iflevel++;
457 		break;
458 	case ':':
459 		/*
460 		 * Else.
461 		 * If this matches the IF we came in here with,
462 		 * then we're done.
463 		 */
464 		if (iflevel == 1)
465 			return (p);
466 		break;
467 	case '.':
468 		/*
469 		 * Endif.
470 		 * If this matches the IF we came in here with,
471 		 * then we're done.
472 		 */
473 		if (--iflevel == 0)
474 			return (p);
475 		break;
476 	case '\\':
477 		/*
478 		 * Backslash escapes the next character.
479 		 */
480 		if (p[1] != '\0')
481 			++p;
482 		break;
483 	case '\0':
484 		/*
485 		 * Whoops.  Hit end of string.
486 		 * This is a malformed conditional, but just treat it
487 		 * as if all active conditionals ends here.
488 		 */
489 		return (p-1);
490 	}
491 	/*NOTREACHED*/
492 }
493 
494 /*
495  * Decode a char that represents a position on the screen.
496  */
wherechar(char constant * p,int * wp)497 static constant char * wherechar(char constant *p, int *wp)
498 {
499 	switch (*p)
500 	{
501 	case 'b': case 'd': case 'l': case 'p': case 'P':
502 		switch (*++p)
503 		{
504 		case 't':   *wp = TOP;                  break;
505 		case 'm':   *wp = MIDDLE;               break;
506 		case 'b':   *wp = BOTTOM;               break;
507 		case 'B':   *wp = BOTTOM_PLUS_ONE;      break;
508 		case 'j':   *wp = sindex_from_sline(jump_sline); break;
509 		default:    *wp = TOP;  p--;            break;
510 		}
511 	}
512 	return (p);
513 }
514 
515 /*
516  * Construct a message based on a prototype string.
517  */
pr_expand(constant char * proto)518 public constant char * pr_expand(constant char *proto)
519 {
520 	constant char *p;
521 	char c;
522 	int where;
523 
524 	if (*proto == '\0')
525 		return ("");
526 
527 	mp = message;
528 	longest_line = -1;
529 
530 	for (p = proto;  *p != '\0';  p++)
531 	{
532 		switch (*p)
533 		{
534 		default: /* Just put the character in the message */
535 			ap_char(*p);
536 			break;
537 		case '\\': /* Backslash escapes the next character */
538 			if (p[1] != '\0')
539 				ap_char(*++p);
540 			break;
541 		case '?': /* Conditional (IF) */
542 			if ((c = *++p) == '\0')
543 				--p;
544 			else
545 			{
546 				where = 0;
547 				p = wherechar(p, &where);
548 				if (!cond(c, where))
549 					p = skipcond(p);
550 			}
551 			break;
552 		case ':': /* ELSE */
553 			p = skipcond(p);
554 			break;
555 		case '.': /* ENDIF */
556 			break;
557 		case '%': /* Percent escape */
558 			if ((c = *++p) == '\0')
559 				--p;
560 			else
561 			{
562 				where = 0;
563 				p = wherechar(p, &where);
564 				protochar(c, where);
565 			}
566 			break;
567 		}
568 	}
569 
570 	if (mp == message)
571 		return ("");
572 	return (message);
573 }
574 
575 /*
576  * Return a message suitable for printing by the "=" command.
577  */
eq_message(void)578 public constant char * eq_message(void)
579 {
580 	return (pr_expand(eqproto));
581 }
582 
583 /*
584  * Return a prompt.
585  * This depends on the prompt type (SHORT, MEDIUM, LONG), etc.
586  * If we can't come up with an appropriate prompt, return NULL
587  * and the caller will prompt with a colon.
588  */
pr_string(void)589 public constant char * pr_string(void)
590 {
591 	constant char *prompt;
592 	int type;
593 
594 	type = (!less_is_more) ? pr_type : pr_type ? 0 : 1;
595 	prompt = pr_expand((ch_getflags() & CH_HELPFILE) ?
596 				hproto : prproto[type]);
597 	new_file = FALSE;
598 	return (prompt);
599 }
600 
601 /*
602  * Return a message suitable for printing while waiting in the F command.
603  */
wait_message(void)604 public constant char * wait_message(void)
605 {
606 	return (pr_expand(wproto));
607 }
608