Chet Ramey | ac50fba | 2014-02-26 09:36:43 -0500 | [diff] [blame] | 1 | /* wcsnwidth.c - compute display width of wide character string, up to max |
| 2 | specified width, return length. */ |
| 3 | |
| 4 | /* Copyright (C) 2012 Free Software Foundation, Inc. |
| 5 | |
| 6 | This file is part of GNU Bash, the Bourne Again SHell. |
| 7 | |
| 8 | Bash is free software: you can redistribute it and/or modify |
| 9 | it under the terms of the GNU General Public License as published by |
| 10 | the Free Software Foundation, either version 3 of the License, or |
| 11 | (at your option) any later version. |
| 12 | |
| 13 | Bash is distributed in the hope that it will be useful, |
| 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | GNU General Public License for more details. |
| 17 | |
| 18 | You should have received a copy of the GNU General Public License |
| 19 | along with Bash. If not, see <http://www.gnu.org/licenses/>. |
| 20 | */ |
| 21 | |
| 22 | #include <config.h> |
| 23 | |
| 24 | #if defined (HANDLE_MULTIBYTE) |
| 25 | |
| 26 | #include <stdc.h> |
| 27 | #include <wchar.h> |
| 28 | #include <bashansi.h> |
| 29 | |
| 30 | /* Return the number of wide characters that will be displayed from wide string |
| 31 | PWCS. If the display width exceeds MAX, return the number of wide chars |
| 32 | from PWCS required to display MAX characters on the screen. */ |
| 33 | int |
| 34 | wcsnwidth(pwcs, n, max) |
| 35 | const wchar_t *pwcs; |
| 36 | size_t n, max; |
| 37 | { |
| 38 | wchar_t wc, *ws; |
| 39 | int len, l; |
| 40 | |
| 41 | len = 0; |
| 42 | ws = (wchar_t *)pwcs; |
| 43 | while (n-- > 0 && (wc = *ws++) != L'\0') |
| 44 | { |
| 45 | l = wcwidth (wc); |
| 46 | if (l < 0) |
| 47 | return (-1); |
| 48 | else if (l == max - len) |
| 49 | return (ws - pwcs); |
| 50 | else if (l > max - len) |
| 51 | return (--ws - pwcs); |
| 52 | len += l; |
| 53 | } |
| 54 | return (ws - pwcs); |
| 55 | } |
| 56 | #endif |