aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/strings.c
diff options
context:
space:
mode:
authorJosh Rahm <joshuarahm@gmail.com>2022-08-03 00:08:17 -0600
committerJosh Rahm <joshuarahm@gmail.com>2022-08-03 00:08:17 -0600
commit9449e1b8d273ff78eb894c588110ffa0c17d6ee3 (patch)
tree9e4470c33bd4187d9f42f0b2c4aaa995310c5be8 /src/nvim/strings.c
parent308e1940dcd64aa6c344c403d4f9e0dda58d9c5c (diff)
parentb8dcbcc732baf84fc48d6b272c3ade0bcb129b3b (diff)
downloadrneovim-9449e1b8d273ff78eb894c588110ffa0c17d6ee3.tar.gz
rneovim-9449e1b8d273ff78eb894c588110ffa0c17d6ee3.tar.bz2
rneovim-9449e1b8d273ff78eb894c588110ffa0c17d6ee3.zip
Merge remote-tracking branch 'upstream/master' into rahm
Diffstat (limited to 'src/nvim/strings.c')
-rw-r--r--src/nvim/strings.c44
1 files changed, 43 insertions, 1 deletions
diff --git a/src/nvim/strings.c b/src/nvim/strings.c
index 5c2721536d..22effaade0 100644
--- a/src/nvim/strings.c
+++ b/src/nvim/strings.c
@@ -501,7 +501,7 @@ static int sort_compare(const void *s1, const void *s2)
return STRCMP(*(char **)s1, *(char **)s2);
}
-void sort_strings(char_u **files, int count)
+void sort_strings(char **files, int count)
{
qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
}
@@ -1528,3 +1528,45 @@ char_u *reverse_text(char_u *s)
return rev;
}
+
+/// Replace all occurrences of "what" with "rep" in "src". If no replacement happens then NULL is
+/// returned otherwise return a newly allocated string.
+///
+/// @param[in] src Source text
+/// @param[in] what Substring to replace
+/// @param[in] rep Substring to replace with
+///
+/// @return [allocated] Copy of the string.
+char *strrep(const char *src, const char *what, const char *rep)
+{
+ char *pos = (char *)src;
+ size_t whatlen = STRLEN(what);
+
+ // Count occurrences
+ size_t count = 0;
+ while ((pos = strstr(pos, what)) != NULL) {
+ count++;
+ pos += whatlen;
+ }
+
+ if (count == 0) {
+ return NULL;
+ }
+
+ size_t replen = STRLEN(rep);
+ char *ret = xmalloc(STRLEN(src) + count * (replen - whatlen) + 1);
+ char *ptr = ret;
+ while ((pos = strstr(src, what)) != NULL) {
+ size_t idx = (size_t)(pos - src);
+ memcpy(ptr, src, idx);
+ ptr += idx;
+ STRCPY(ptr, rep);
+ ptr += replen;
+ src = pos + whatlen;
+ }
+
+ // Copy remaining
+ STRCPY(ptr, src);
+
+ return ret;
+}