aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/strings.c
diff options
context:
space:
mode:
authorLewis Russell <lewis6991@gmail.com>2022-08-01 12:02:53 +0100
committerGitHub <noreply@github.com>2022-08-01 12:02:53 +0100
commitbcb4186cf67b22dab238248a809f6c3f09a5424d (patch)
tree139ad47c10deda09a68d87f7d93940a21891c023 /src/nvim/strings.c
parent8952def50afa8308e044c0100e6d4fa367d0a9c2 (diff)
downloadrneovim-bcb4186cf67b22dab238248a809f6c3f09a5424d.tar.gz
rneovim-bcb4186cf67b22dab238248a809f6c3f09a5424d.tar.bz2
rneovim-bcb4186cf67b22dab238248a809f6c3f09a5424d.zip
refactor: replace_makeprg (#19570)
Diffstat (limited to 'src/nvim/strings.c')
-rw-r--r--src/nvim/strings.c42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/nvim/strings.c b/src/nvim/strings.c
index 867fa73419..22effaade0 100644
--- a/src/nvim/strings.c
+++ b/src/nvim/strings.c
@@ -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;
+}