xref: /freebsd/contrib/less/cvt.c (revision 0e6acb26)
1 /*
2  * Copyright (C) 1984-2015  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  * Routines to convert text in various ways.  Used by search.
12  */
13 
14 #include "less.h"
15 #include "charset.h"
16 
17 extern int utf_mode;
18 
19 /*
20  * Get the length of a buffer needed to convert a string.
21  */
22 	public int
23 cvt_length(int len, int ops)
24 {
25 	if (utf_mode)
26 		/*
27 		 * Just copying a string in UTF-8 mode can cause it to grow
28 		 * in length.
29 		 * Four output bytes for one input byte is the worst case.
30 		 */
31 		len *= 4;
32 	return (len + 1);
33 }
34 
35 /*
36  * Allocate a chpos array for use by cvt_text.
37  */
38 	public int *
39 cvt_alloc_chpos(int len)
40 {
41 	int i;
42 	int *chpos = (int *) ecalloc(sizeof(int), len);
43 	/* Initialize all entries to an invalid position. */
44 	for (i = 0;  i < len;  i++)
45 		chpos[i] = -1;
46 	return (chpos);
47 }
48 
49 /*
50  * Convert text.  Perform the transformations specified by ops.
51  * Returns converted text in odst.  The original offset of each
52  * odst character (when it was in osrc) is returned in the chpos array.
53  */
54 	public void
55 cvt_text(char *odst, char *osrc, int *chpos, int *lenp, int ops)
56 {
57 	char *dst;
58 	char *edst = odst;
59 	char *src;
60 	char *src_end;
61 	LWCHAR ch;
62 
63 	if (lenp != NULL)
64 		src_end = osrc + *lenp;
65 	else
66 		src_end = osrc + strlen(osrc);
67 
68 	for (src = osrc, dst = odst;  src < src_end;  )
69 	{
70 		int src_pos = (int) (src - osrc);
71 		int dst_pos = (int) (dst - odst);
72 		ch = step_char((constant char **)&src, +1, src_end);
73 		if ((ops & CVT_BS) && ch == '\b' && dst > odst)
74 		{
75 			/* Delete backspace and preceding char. */
76 			do {
77 				dst--;
78 			} while (dst > odst &&
79 				!IS_ASCII_OCTET(*dst) && !IS_UTF8_LEAD(*dst));
80 		} else if ((ops & CVT_ANSI) && IS_CSI_START(ch))
81 		{
82 			/* Skip to end of ANSI escape sequence. */
83 			src++;  /* skip the CSI start char */
84 			while (src < src_end)
85 				if (!is_ansi_middle(*src++))
86 					break;
87 		} else
88 		{
89 			/* Just copy the char to the destination buffer. */
90 			if ((ops & CVT_TO_LC) && IS_UPPER(ch))
91 				ch = TO_LOWER(ch);
92 			put_wchar(&dst, ch);
93 			/* Record the original position of the char. */
94 			if (chpos != NULL)
95 				chpos[dst_pos] = src_pos;
96 		}
97 		if (dst > edst)
98 			edst = dst;
99 	}
100 	if ((ops & CVT_CRLF) && edst > odst && edst[-1] == '\r')
101 		edst--;
102 	*edst = '\0';
103 	if (lenp != NULL)
104 		*lenp = (int) (edst - odst);
105 	/* FIXME: why was this here?  if (chpos != NULL) chpos[dst - odst] = src - osrc; */
106 }
107