summaryrefslogtreecommitdiff
path: root/src/main/search-replace.c
blob: 4def77af988a2b3e2138725bab2447c4b3eb8b4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#include <stdbool.h>
#include <stdint.h>
#include <string.h>

#include "dged/binding.h"
#include "dged/buffer.h"
#include "dged/buffer_view.h"
#include "dged/command.h"
#include "dged/minibuffer.h"
#include "dged/window.h"

#include "bindings.h"
#include "search-replace.h"

enum replace_state {
  Todo,
  Replaced,
  Skipped,
};

struct match {
  struct region region;
  enum replace_state state;
};

static struct replace {
  char *replace;
  struct match *matches;
  uint32_t nmatches;
  uint32_t current_match;
  buffer_keymap_id keymap_id;
  struct window *window;
} g_current_replace = {0};

void abort_replace() {
  buffer_remove_keymap(g_current_replace.keymap_id);
  free(g_current_replace.matches);
  free(g_current_replace.replace);
  g_current_replace.matches = NULL;
  g_current_replace.replace = NULL;
  g_current_replace.nmatches = 0;
  g_current_replace.window = NULL;
  minibuffer_abort_prompt();
}

uint64_t matchdist(struct region *match, struct location loc) {
  struct location begin = match->begin;

  int64_t linedist = (int64_t)begin.line - (int64_t)loc.line;

  // if the match is on a different line, score it by how far
  // into the line it is, otherwise check the distance from location
  int64_t coldist = begin.col;
  if (linedist == 0) {
    int64_t coldist = (int64_t)begin.col - (int64_t)loc.col;
  }

  // arbitrary row scaling, best effort to avoid counting line length
  return (linedist * linedist) * 1e6 + coldist * coldist;
}

static void highlight_matches(struct buffer *buffer, struct match *matches,
                              uint32_t nmatches, uint32_t current) {
  for (uint32_t matchi = 0; matchi < nmatches; ++matchi) {
    struct match *m = &matches[matchi];
    if (m->state != Todo) {
      continue;
    }

    if (matchi == current) {
      buffer_add_text_property(
          buffer, m->region.begin, m->region.end,
          (struct text_property){.type = TextProperty_Colors,
                                 .colors = (struct text_property_colors){
                                     .set_bg = true,
                                     .bg = 3,
                                     .set_fg = true,
                                     .fg = 0,
                                 }});

    } else {
      buffer_add_text_property(
          buffer, m->region.begin, m->region.end,
          (struct text_property){.type = TextProperty_Colors,
                                 .colors = (struct text_property_colors){
                                     .set_bg = true,
                                     .bg = 6,
                                     .set_fg = true,
                                     .fg = 0,
                                 }});
    }
  }
}

static int32_t replace_next(struct command_ctx ctx, int argc,
                            const char *argv[]) {
  struct replace *state = &g_current_replace;
  struct buffer_view *buffer_view = window_buffer_view(state->window);
  struct buffer *buffer = buffer_view->buffer;

  struct match *match = &state->matches[state->current_match];

  // buffer_delete is not inclusive
  struct region to_delete = match->region;
  ++to_delete.end.col;

  struct location loc = buffer_delete(buffer, to_delete);
  struct location after = buffer_add(buffer, loc, (uint8_t *)state->replace,
                                     strlen(state->replace));
  match->state = Replaced;

  // update all following matches
  int64_t linedelta = (int64_t)after.line - (int64_t)to_delete.end.line;
  int64_t coldelta = linedelta == 0
                         ? (int64_t)after.col - (int64_t)to_delete.end.col
                         : (int64_t)after.col;
  for (uint32_t matchi = state->current_match; matchi < state->nmatches;
       ++matchi) {
    struct match *m = &state->matches[matchi];

    m->region.begin.line += linedelta;
    m->region.end.line += linedelta;

    if (after.line == m->region.begin.line) {
      m->region.begin.col += coldelta;
    }

    if (after.line == m->region.end.line) {
      m->region.end.col += coldelta;
    }
  }

  // advance to the next match
  ++state->current_match;
  if (state->current_match == state->nmatches) {
    abort_replace();
  } else {
    struct match *m = &state->matches[state->current_match];
    buffer_view_goto(buffer_view,
                     (struct location){.line = m->region.begin.line,
                                       .col = m->region.begin.col});
    highlight_matches(buffer_view->buffer, state->matches, state->nmatches,
                      state->current_match);
  }

  return 0;
}

static int32_t skip_next(struct command_ctx ctx, int argc, const char *argv[]) {
  struct replace *state = &g_current_replace;

  struct buffer_view *buffer_view = window_buffer_view(state->window);
  struct match *m = &state->matches[state->current_match];
  buffer_view_goto(buffer_view,
                   (struct location){.line = m->region.end.line,
                                     .col = m->region.end.col + 1});
  m->state = Skipped;

  ++state->current_match;

  if (state->current_match == state->nmatches) {
    abort_replace();
  } else {
    m = &state->matches[state->current_match];
    buffer_view_goto(buffer_view,
                     (struct location){.line = m->region.begin.line,
                                       .col = m->region.begin.col});
    highlight_matches(buffer_view->buffer, state->matches, state->nmatches,
                      state->current_match);
  }

  return 0;
}

COMMAND_FN("replace-next", replace_next, replace_next, NULL);
COMMAND_FN("skip-next", skip_next, skip_next, NULL);

static int cmp_matches(const void *m1, const void *m2) {
  struct region *match1 = (struct region *)m1;
  struct region *match2 = (struct region *)m2;
  struct location dot = window_buffer_view(windows_get_active())->dot;
  uint64_t dist1 = matchdist(match1, dot);
  uint64_t dist2 = matchdist(match2, dot);

  int loc1 = location_compare(match1->begin, dot);
  int loc2 = location_compare(match2->begin, dot);

  int64_t score1 = dist1 * loc1;
  int64_t score2 = dist2 * loc2;

  if (score1 > 0 && score2 > 0) {
    return score1 < score2 ? -1 : score1 > score2 ? 1 : 0;
  } else if (score1 < 0 && score2 > 0) {
    return 1;
  } else if (score1 > 0 && score2 < 0) {
    return -1;
  } else {
    return score1 < score2 ? -1 : score1 > score2 ? 1 : 0;
  }
}

static int32_t replace(struct command_ctx ctx, int argc, const char *argv[]) {
  if (argc == 0) {
    return minibuffer_prompt(ctx, "find: ");
  }

  if (argc == 1) {
    command_ctx_push_arg(&ctx, argv[0]);
    return minibuffer_prompt(ctx, "replace with: ");
  }

  struct buffer_view *buffer_view = window_buffer_view(windows_get_active());
  struct region *matches = NULL;
  uint32_t nmatches = 0;
  buffer_find(buffer_view->buffer, argv[0], &matches, &nmatches);

  if (nmatches == 0) {
    minibuffer_echo_timeout(4, "%s not found", argv[0]);
    free(matches);
    return 0;
  }

  // sort matches
  qsort(matches, nmatches, sizeof(struct region), cmp_matches);

  struct match *match_states = calloc(nmatches, sizeof(struct match));
  for (uint32_t matchi = 0; matchi < nmatches; ++matchi) {
    match_states[matchi].region = matches[matchi];
    match_states[matchi].state = Todo;
  }
  free(matches);

  g_current_replace = (struct replace){
      .replace = strdup(argv[1]),
      .matches = match_states,
      .nmatches = nmatches,
      .current_match = 0,
      .window = ctx.active_window,
  };

  // goto first match
  struct region *m = &g_current_replace.matches[0].region;
  buffer_view_goto(buffer_view, (struct location){.line = m->begin.line,
                                                  .col = m->begin.col});
  highlight_matches(buffer_view->buffer, g_current_replace.matches,
                    g_current_replace.nmatches, 0);

  struct binding bindings[] = {
      ANONYMOUS_BINDING(None, 'y', &replace_next_command),
      ANONYMOUS_BINDING(None, 'n', &skip_next_command),
      ANONYMOUS_BINDING(Ctrl, 'M', &replace_next_command),
  };
  struct keymap km = keymap_create("replace", 8);
  keymap_bind_keys(&km, bindings, sizeof(bindings) / sizeof(bindings[0]));
  g_current_replace.keymap_id = buffer_add_keymap(minibuffer_buffer(), km);

  return minibuffer_prompt(ctx, "replace? [yn] ");
}

static char *g_last_search = NULL;
static bool g_last_search_interactive = false;
static buffer_keymap_id g_search_keymap;

const char *search_prompt(bool reverse) {
  const char *txt = "search (down): ";
  if (reverse) {
    txt = "search (up): ";
  }

  return txt;
}

struct closest_match {
  bool found;
  struct region closest;
};

static struct closest_match find_closest(struct buffer_view *view,
                                         const char *pattern, bool highlight,
                                         bool reverse) {
  struct region *matches = NULL;
  uint32_t nmatches = 0;
  struct closest_match res = {
      .found = false,
      .closest = {0},
  };

  buffer_find(view->buffer, pattern, &matches, &nmatches);

  // find the "nearest" match
  if (nmatches > 0) {
    res.found = true;
    struct region *closest = &matches[0];
    int64_t closest_dist = INT64_MAX;
    for (uint32_t matchi = 0; matchi < nmatches; ++matchi) {
      struct region *m = &matches[matchi];

      if (highlight) {
        buffer_add_text_property(
            view->buffer, m->begin, m->end,
            (struct text_property){.type = TextProperty_Colors,
                                   .colors = (struct text_property_colors){
                                       .set_bg = true,
                                       .bg = 6,
                                       .set_fg = true,
                                       .fg = 0,
                                   }});
      }
      int res = location_compare(m->begin, view->dot);
      uint64_t dist = matchdist(m, view->dot);
      if (((res < 0 && reverse) || (res > 0 && !reverse)) &&
          dist < closest_dist) {
        closest_dist = dist;
        closest = m;
      }
    }

    if (highlight) {
      buffer_add_text_property(
          view->buffer, closest->begin, closest->end,
          (struct text_property){.type = TextProperty_Colors,
                                 .colors = (struct text_property_colors){
                                     .set_bg = true,
                                     .bg = 3,
                                     .set_fg = true,
                                     .fg = 0,
                                 }});
    }
    res.closest = *closest;
  }

  free(matches);
  return res;
}

void do_search(struct buffer_view *view, const char *pattern, bool reverse) {
  g_last_search = strdup(pattern);

  struct closest_match m = find_closest(view, pattern, true, reverse);

  // find the "nearest" match
  if (m.found) {
    buffer_view_goto(view, (struct location){.line = m.closest.begin.line,
                                             .col = m.closest.begin.col});
  } else {
    minibuffer_echo_timeout(4, "%s not found", pattern);
  }
}

int32_t search_interactive(struct command_ctx ctx, int argc,
                           const char *argv[]) {
  g_last_search_interactive = true;
  const char *pattern = NULL;
  if (minibuffer_content().nbytes == 0) {
    // recall the last search, if any
    if (g_last_search != NULL) {
      struct buffer_view *view = window_buffer_view(minibuffer_window());
      buffer_set_text(view->buffer, (uint8_t *)g_last_search,
                      strlen(g_last_search));
      pattern = g_last_search;
    }
  } else {
    struct text_chunk content = minibuffer_content();
    char *p = malloc(content.nbytes + 1);
    strncpy(p, (const char *)content.text, content.nbytes);
    p[content.nbytes] = '\0';
    pattern = p;
  }

  minibuffer_set_prompt(search_prompt(*(bool *)ctx.userdata));

  if (pattern != NULL) {
    do_search(window_buffer_view(minibuffer_target_window()), pattern,
              *(bool *)ctx.userdata);
    free((char *)pattern);
  }
  return 0;
}

static bool search_dir_backward = true;
static bool search_dir_forward = false;

COMMAND_FN("search-forward", search_forward, search_interactive,
           &search_dir_forward);
COMMAND_FN("search-backward", search_backward, search_interactive,
           &search_dir_backward);

int32_t find(struct command_ctx ctx, int argc, const char *argv[]) {
  bool reverse = *(bool *)ctx.userdata;
  if (argc == 0) {
    g_last_search_interactive = false;
    struct binding bindings[] = {
        ANONYMOUS_BINDING(Ctrl, 'S', &search_forward_command),
        ANONYMOUS_BINDING(Ctrl, 'R', &search_backward_command),
    };
    struct keymap m = keymap_create("search", 8);
    keymap_bind_keys(&m, bindings, sizeof(bindings) / sizeof(bindings[0]));
    g_search_keymap = buffer_add_keymap(minibuffer_buffer(), m);
    return minibuffer_prompt(ctx, search_prompt(reverse));
  }

  buffer_remove_keymap(g_search_keymap);
  if (g_last_search_interactive) {
    g_last_search_interactive = false;
    return 0;
  }

  struct text_chunk content = minibuffer_content();
  char *pattern = malloc(content.nbytes + 1);
  strncpy(pattern, (const char *)content.text, content.nbytes);
  pattern[content.nbytes] = '\0';

  do_search(window_buffer_view(ctx.active_window), pattern, reverse);
  free(pattern);

  return 0;
}

void register_search_replace_commands(struct commands *commands) {
  struct command search_replace_commands[] = {
      {.name = "find-next", .fn = find, .userdata = &search_dir_forward},
      {.name = "find-prev", .fn = find, .userdata = &search_dir_backward},
      {.name = "replace", .fn = replace},
  };

  register_commands(commands, search_replace_commands,
                    sizeof(search_replace_commands) /
                        sizeof(search_replace_commands[0]));
}