From 23ffaf32cda0ced7a34c98f5720990ffe6d4b662 Mon Sep 17 00:00:00 2001 From: Rodrigo Arias Mallo Date: Fri, 8 Aug 2025 17:27:33 +0200 Subject: Add dStr_shorten() to make strings shorter Some URLs are very long and would cause long lines when being displayed. To avoid this problem, we introduce dStr_shorten() to cut them and use "..." in the middle so they fit in the specified character count. --- dlib/dlib.c | 30 +++++++++++++++++++++++++++++- dlib/dlib.h | 13 +++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) (limited to 'dlib') diff --git a/dlib/dlib.c b/dlib/dlib.c index 2cbd083e..ed967b3a 100644 --- a/dlib/dlib.c +++ b/dlib/dlib.c @@ -2,7 +2,7 @@ * File: dlib.c * * Copyright (C) 2006-2007 Jorge Arellano Cid - * Copyright (C) 2024 Rodrigo Arias Mallo + * Copyright (C) 2024-2025 Rodrigo Arias Mallo * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -538,6 +538,34 @@ const char *dStr_printable(Dstr *in, int maxlen) return out->str; } +/** Shorten string so it fits in n characters. + * + * Cuts the string src so that it fits in n by replacing the middle of + * the string with "...", but leaving both the start and the end. + * + * The length n must be at least 9. If the src string is already shorter + * than n, it is appended as-is. + * + * The resulting string is appended to out. + */ +void dStr_shorten(Dstr *dst, const char *src, int n) +{ + if (n < 9) + n = 9; + + int len = strlen(src); + if (len > n) { + int m = n - 3; + int n1 = m / 2; /* First half */ + int n2 = m - n1; /* Second half */ + dStr_append_l(dst, src, n1); + dStr_append(dst, "..."); + dStr_append(dst, &src[len - n2]); + } else { + dStr_append(dst, src); + } +} + /* *- dList --------------------------------------------------------------------- */ diff --git a/dlib/dlib.h b/dlib/dlib.h index 351294ff..6c4b018a 100644 --- a/dlib/dlib.h +++ b/dlib/dlib.h @@ -1,3 +1,15 @@ +/* + * File: dlib.h + * + * Copyright (C) 2006-2007 Jorge Arellano Cid + * Copyright (C) 2025 Rodrigo Arias Mallo + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + */ + #ifndef __DLIB_H__ #define __DLIB_H__ @@ -124,6 +136,7 @@ void dStr_sprintfa (Dstr *ds, const char *format, ...); int dStr_cmp(Dstr *ds1, Dstr *ds2); char *dStr_memmem(Dstr *haystack, Dstr *needle); const char *dStr_printable(Dstr *in, int maxlen); +void dStr_shorten(Dstr *dst, const char *src, int n); /* *-- dList -------------------------------------------------------------------- -- cgit v1.2.3