hexer.c 23.4 KB
Newer Older
1 2 3 4
/* hexer.c	8/19/1995
 */

/* Copyright (c) 1995,1996 Sascha Demetrio
5
 * Copyright (c) 2009, 2010, 2015, 2016 Peter Pentchev
6 7 8 9 10 11 12
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
13
 *    If you modify any part of HEXER and redistribute it, you must add
14 15 16 17 18 19
 *    a notice to the `README' file and the modified source files containing
 *    information about the  changes you made.  I do not want to take
 *    credit or be blamed for your modifications.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
20
 *    If you modify any part of HEXER and redistribute it in binary form,
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
 *    you must supply a `README' file containing information about the
 *    changes you made.
 * 3. The name of the developer may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * HEXER WAS DEVELOPED BY SASCHA DEMETRIO.
 * THIS SOFTWARE SHOULD NOT BE CONSIDERED TO BE A COMMERCIAL PRODUCT.
 * THE DEVELOPER URGES THAT USERS WHO REQUIRE A COMMERCIAL PRODUCT
 * NOT MAKE USE OF THIS WORK.
 *
 * DISCLAIMER:
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPER ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE DEVELOPER BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>

#include <sys/types.h>
#include <sys/param.h>

#ifndef PATH_MAX
#define PATH_MAX 63
#endif

62
#include "buffer.h"
63
#include "hexer.h"
64 65 66
#include "commands.h"
#include "exh.h"
#include "readline.h"
67 68
#include "regex.h"
#include "set.h"
69 70
#include "tio.h"
#include "util.h"
71 72 73 74 75 76 77 78 79

const struct buffer_s NO_BUFFER = { 0, 0, 0, 0, 0, 0 };

const char *hexer_ext = ".hexer";

struct buffer_s *current_buffer;
struct buffer_s *buffer_list = 0;
struct he_message_s *he_messages;
char *alternate_buffer;
80
const char *he_pagerprg;
81 82

  void
83
he_message(const int beep, const char * const fmt, ...)
84 85 86 87 88 89 90
{
  va_list ap;
  struct he_message_s *m;
  /* int length; */

  va_start(ap, fmt);
  /* length = tio_nprintf(fmt, ap); */
91
  m = (struct he_message_s *)malloc_fatal(sizeof(struct he_message_s));
92 93
  m->next = he_messages;
  m->beep = beep;
94 95
  /* m->message = (char *)malloc_fatal(length + 1); */
  m->message = (char *)malloc_fatal(512); /* FIXME */
96 97 98 99 100 101 102 103 104 105 106
  vsprintf(m->message, fmt, ap);
  he_messages = m;
  va_end(ap);
}
/* he_message */


/* hexer options
 */

  static void
107
action_ascii(int current_value)
108 109 110 111 112 113 114 115 116 117
{
  he_refresh_all(current_buffer->hedit);
  if (current_value)
    s_set_option("iso", "false", 1);
  else
    s_set_option("iso", "true", 1);
}
/* action_ascii */

  static void
118
action_iso(int current_value)
119 120 121 122 123 124 125 126 127 128
{
  he_refresh_all(current_buffer->hedit);
  if (current_value)
    s_set_option("ascii", "false", 1);
  else
    s_set_option("ascii", "true", 1);
}
/* action_iso */

  static void
129
action_maxmatch(long current_value)
130 131 132 133 134 135
{
  rx_maxmatch = current_value;
}
/* action_maxmatch */

  static void
136
action_TERM(void)
137 138 139 140 141 142 143
{
  tio_init(0);
  he_refresh_all(current_buffer->hedit);
}
/* action_TERM */

  static void
144
action_specialnl(int current_value)
145 146 147 148 149 150
{
  rx_special_nl = current_value;
}
/* action_specialnl */

  static void
151
action_mapmagic(int current_value)
152 153 154 155 156 157
{
  he_map_special = current_value;
}
/* action_mapmagic */

static const struct hexer_options_s {
158
  const char *option;
159
  enum s_option_e type;
160
  const char *default_value;
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  set_fn action;
} hexer_options[] = {
  { "ascii", S_BOOL, "true", (set_fn)action_ascii },
  { "iso", S_BOOL, "false", (set_fn)action_iso },
  { "maxmatch", S_INTEGER, "1024", (set_fn)action_maxmatch },
  { "TERM", S_STRING, "", (set_fn)action_TERM }, /* set in `hexer_init()' */
  { "specialnl", S_BOOL, "false", (set_fn)action_specialnl },
  { "mapmagic", S_BOOL, "false", (set_fn)action_mapmagic },
  { "fg", S_INTEGER, "7", (set_fn)0 },
  { "bg", S_INTEGER, "4", (set_fn)0 },
  { 0, (enum s_option_e)0, 0, 0 }
};


/* hexer buffers
 */

  int
179
he_open_buffer(const char * const name, const char * const path)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
{
  struct buffer_s *buffer;
  int no_file_f = 0, read_only = 0;
  struct buffer_s *i;
  FILE *fp;
  char cwd[PATH_MAX + 1];

  if (path) {
    /* check out the read/write permissions */
    if (access(path, R_OK))
      switch (errno) {
      case ENOENT: /* file doesn't exist */
        no_file_f = 1;
        break;
      default:
195
        he_message(1, "`%s': @Ab%s@~", path, strerror(errno));
196 197 198 199 200 201 202 203
        return -1;
      }
    if (!no_file_f ? access(path, W_OK) : 0)
      switch (errno) {
      case EACCES: /* write permission denied */
        read_only = 1;
        break;
      default:
204
        he_message(1, "`%s': @Ab%s@~", path, strerror(errno));
205 206 207
        return -1;
      }
  }
208 209
  *(buffer = (struct buffer_s *)malloc_fatal(sizeof(struct buffer_s))) = NO_BUFFER;
  buffer->hedit = (struct he_s *)malloc_fatal(sizeof(struct he_s));
210 211 212 213
  memset(buffer->hedit, 0, sizeof (struct he_s));
  buffer->hedit->begin_selection = -1;
  buffer->hedit->end_selection = -1;
  buffer->hedit->insert_position = -1;
214
  buffer->hedit->buffer_name = strdup_fatal(name);
215 216
  if (path && !no_file_f) {
    if (!(fp = fopen(path, "r"))) {
217
      he_message(1, "`%s': @Ab%s@~", path, strerror(errno));
218 219 220 221 222 223 224 225 226 227 228 229
      free((char *)buffer->hedit->buffer_name);
      free((char *)buffer->hedit);
      free((char *)buffer);
      return -1;
    } else
      fclose(fp);
  } else {
    buffer->hedit->buffer = new_buffer(0);
    buffer->loaded_f = 1;
    buffer->visited_f = 1;
  }
  if (path) {
230
    buffer->path = strdup_fatal(path);
231
    if (!getcwd(cwd, PATH_MAX)) {
232
      he_message(0, "@Abcan't get cwd: %s@~", strerror(errno));
233
      buffer->fullpath = strdup_fatal(path);
234 235
    } else {
      buffer->fullpath =
236
        (char *)malloc_fatal(strlen(path) + strlen(cwd) + 2);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
      sprintf(buffer->fullpath, "%s/%s", cwd, path);
    }
  }
  buffer->hedit->read_only = read_only;
  if (!buffer_list)
    current_buffer = buffer_list = buffer;
  else {
    for (i = buffer_list; i->next; i = i->next);
    i->next = buffer;
  }
  return 0;
}
/* he_open_buffer */

  int
252
he_select_buffer_(const struct buffer_s * const buffer)
253
  /* Set `current_buffer' to `buffer'.  The file for `buffer' is loaded if
Peter Pentchev's avatar
Peter Pentchev committed
254
   * necessary.
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
   */
{
  struct buffer_s *i;
  char swap_template[8];
  
  strcpy(swap_template, ".XXXXXX");
  for (i = buffer_list; i != buffer && i; i = i->next);
  if (!i) return -1;
  current_buffer = i;
  if (!i->loaded_f) {
    i->hedit->buffer = new_buffer(0);
    /* read the file */
    if (b_read_buffer_from_file(i->hedit->buffer, i->path) < 0) {
      delete_buffer(i->hedit->buffer);
      i->hedit->buffer = 0;
      he_close_buffer(0);
      return -1;
    }
    /* check out if we can open a swapfile */
    i->hedit->swapfile =
275
      (char *)malloc_fatal(strlen(hexer_ext) + strlen(i->path) + 1);
276 277 278 279
    strcpy(i->hedit->swapfile, i->path);
    strcat(i->hedit->swapfile, hexer_ext);
    if (access(i->hedit->swapfile, R_OK)) {
      if (errno == ENOENT) /* swapfile doesn't exist -- fine */
280
        if (access(i->hedit->swapfile, W_OK)) {
281 282 283 284 285
          if (errno == ENOENT) {
            if ((i->hedit->undo.swapfile = fopen(i->hedit->swapfile, "w+")))
              i->hedit->swapping = 1;
          } else
            he_message(0, "@Abno swapfile@~");
286
        }
287 288 289 290 291 292
    } else {
      /* a swapfile does exist */
      int swapfd;
      he_message(1, "@Abwarning: swapfile@~ `%s' @Abexists@~",
                 i->hedit->swapfile);
      i->hedit->swapfile =
293
        (char *)realloc_fatal(i->hedit->swapfile,
294 295 296 297 298 299 300 301 302 303 304 305
                      strlen(i->hedit->swapfile) + strlen(swap_template) + 1);
        strcat(i->hedit->swapfile, swap_template);
      if ((swapfd = mkstemp(i->hedit->swapfile)) < 0)
        he_message(0, "@Abno swapfile@~");
      else {
        i->hedit->undo.swapfile = fdopen(swapfd, "r+");
        i->hedit->swapping = 1;
        he_message(0, "@Abswapping to@~ `%s'", i->hedit->swapfile);
      }
    }
    if (i->hedit->swapping) {
      /* write the swap-header to the swapfile */
306 307 308 309 310 311
      size_t len;
      char *buf;

      len = 6 + strlen(HEXER_VERSION) + 1 + strlen(i->fullpath) + 1 + 4;
      buf = alloca(len + 1);
      if (snprintf(buf, len + 1, "hexer %s\n%s\n%c%c%c%c",
312
	  HEXER_VERSION, i->fullpath, 0, 0, 0, 0) != (int)len ||
313 314 315 316 317 318
	  fwrite(buf, 1, len, i->hedit->undo.swapfile) != len ||
	  fflush(i->hedit->undo.swapfile) == EOF) {
	/* TODO: some kind of error output */
	fclose(i->hedit->undo.swapfile);
	i->hedit->swapping = 0;
      }
319 320 321 322 323 324 325 326 327 328
    }
    i->hedit->buffer->modified = 0;
    i->loaded_f = 1;
    i->visited_f = 1;
  }
  return 0;
}
/* he_select_buffer_ */

  int
329
he_select_buffer(const char * const name)
330 331 332 333 334 335 336 337 338 339 340
{
  struct buffer_s *i;

  for (i = buffer_list; i; i = i->next)
    if (!strcmp(name, i->hedit->buffer_name)) break;
  if (!i) return -1;
  return he_select_buffer_(i);
}
/* he_select_buffer */

  int
341
he_alternate_buffer(void)
342 343 344 345 346 347 348 349 350 351 352 353 354
{
  char *ab = alternate_buffer;

  alternate_buffer = current_buffer->hedit->buffer_name;
  if (ab ? he_select_buffer(ab) < 0 : 0) {
    alternate_buffer = 0;
    return -1;
  }
  return 0;
}
/* he_alternate_buffer */

  int
355
he_set_buffer_readonly(const char * const name)
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
  /* Return values:
   * -1: no buffer named `name'
   * 0:  ok
   */
{
  struct buffer_s *i;

  for (i = buffer_list; i; i = i->next)
    if (!strcmp(name, i->hedit->buffer_name)) break;
  if (!i) return -1;
  i->hedit->read_only = 1;
  return 0;
}
/* he_set_buffer_readonly */

  int
372
he_buffer_readonly(char *name)
373 374
  /* Return values:
   * -1: no buffer named `name'
375 376
   * 0:  buffer is read/write
   * 1:  buffer is read-only
377 378 379 380 381 382 383 384 385 386 387 388
   */
{
  struct buffer_s *i;

  for (i = buffer_list; i; i = i->next)
    if (!strcmp(name, i->hedit->buffer_name)) break;
  if (!i) return -1;
  return !!i->hedit->read_only;
}
/* he_buffer_readonly */

  int
389
he_buffer_modified(char *name)
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  /* Return values:
   * -1: no buffer named `name'
   * 0:  buffer saved
   * 1:  buffer modified
   */
{
  struct buffer_s *i;

  for (i = buffer_list; i; i = i->next)
    if (!strcmp(name, i->hedit->buffer_name)) break;
  if (!i) return -1;
  return !!i->hedit->buffer->modified;
}
/* he_buffer_modified */

  int
406
he_close_buffer(const char * const name)
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  /* Close the buffer named `name'. If `name == 0', the current buffer
   * is closed.  The return value is 0 if all goes well, 1 if the named
   * buffer doesn't exist and -1 if the `buffer_list' is empty.
   */
{
  struct buffer_s *i, *j;
  int empty = 0;
  int buffer_switched = 0;

  if (!buffer_list) return -1;
  if (!name)
    i = current_buffer;
  else {
    for (i = buffer_list; i; i = i->next)
      if (!strcmp(i->hedit->buffer_name, name)) break;
    if (!i) return -1;
  }
  if (i != buffer_list) {
    for (j = buffer_list; j->next != i; j = j->next);
    if (alternate_buffer
        ? !strcmp(alternate_buffer, i->hedit->buffer_name) : 0)
      alternate_buffer = 0;
    j->next = i->next;
    if (i == current_buffer) {
      if (i->next)
        he_select_buffer_(i->next);
      else
        he_select_buffer_(j);
      buffer_switched = 1;
    }
  } else
    if (!(buffer_list = current_buffer = i->next))
      empty = 1;
    else {
      he_select_buffer_(buffer_list);
      buffer_switched = 1;
    }
  if (i->hedit->buffer_name) free((char *)i->hedit->buffer_name);
  if (i->hedit->buffer) delete_buffer(i->hedit->buffer);
  if (i->hedit->swapping) {
    fclose(i->hedit->undo.swapfile);
    unlink(i->hedit->swapfile);
  } else
    if (i->hedit->undo.list) he_free_command(i->hedit->undo.list);
  free((char *)i->hedit);
  if (i->path) free((char *)i->path);
  free((char *)i);
  if (empty) buffer_list = 0, current_buffer = 0;
  if (buffer_switched) {
    alternate_buffer = 0;
    he_refresh_all(current_buffer->hedit);
  }
  return empty ? -1 : 0;
}
/* he_close_buffer */


/* misc
 */

  void
468
he_status_message(int verbose)
469 470 471 472 473 474
  /* display name and size of the current buffer.  if `verbose' is set,
   * the current position is also displayed.
   */
{
  struct he_s *hedit = current_buffer->hedit;

475 476
  if (hedit->buffer->size) {
    if (verbose) {
477 478 479 480 481 482 483
      he_message(0, "\"%s\" %s%sat 0x%lx (%li) of 0x%lx (%li) bytes  (%li %%)",
                 hedit->buffer_name,
                 hedit->buffer->modified ? "[modified] " : "",
                 hedit->read_only ? "[readonly] " : "",
                 hedit->position, hedit->position,
                 hedit->buffer->size, hedit->buffer->size,
                 (hedit->position * 100) / hedit->buffer->size);
484
    } else {
485 486 487 488 489 490 491 492 493 494
    if (hedit->buffer->size)
      he_message(0, "\"%s\" %s%s0x%lx (%li) bytes",
                 hedit->buffer_name,
                 hedit->buffer->modified ? "[modified] " : "",
                 hedit->read_only ? "[readonly] " : "",
                 hedit->buffer->size, hedit->buffer->size);
  else
    he_message(0, "\"%s\" %s%s(empty)", hedit->buffer_name,
               hedit->buffer->modified ? "[modified] " : "",
               hedit->read_only ? "[readonly] " : "");
495 496
    }
  }
497 498 499 500
}
/* he_status_message */

  char *
501
he_query_command(const char *prompt, const char *dfl, int context)
502 503 504 505 506 507 508
  /* Convention:
   * `context == 0': exh-command;
   * `context == 1': shell-command;
   * `context == 2': search-command.
   * `context == 3': calculator.
   */
{
509
  tio_goto_line(hx_lines - 1);
510 511 512 513 514 515
  tio_return();
  return readline(prompt, dfl, context);
}
/* he_query_command */

  int
516
he_query_yn(int dfl, const char *fmt, ...)
517 518 519 520 521 522 523 524
{
  va_list ap;
  int key;
  int choice;

  va_start(ap, fmt);
  tio_keypad(0);
restart:
525
  tio_goto_line(hx_lines - 1);
526 527 528 529 530 531 532 533 534 535 536 537 538
  tio_return();
  tio_clear_to_eol();
  if (dfl < 0) { /* no default answer */
    tio_vprintf(fmt, ap);
    tio_printf("? ");
  } else {
    dfl = !!dfl;
    tio_vprintf(fmt, ap);
    tio_printf("? [%c] ", dfl ? 'y' : 'n');
  }
  for (;;) {
    key = tio_getch();
    switch (key) {
539
    case HXKEY_NONE:
540 541 542 543 544 545
      if (window_changed) he_refresh_screen(current_buffer->hedit);
      goto restart;
    case 'q': case 'Q':
      tio_printf("quit");
      choice = -1;
      goto exit_he_query_yn;
546
    case HXKEY_ESCAPE:
547 548 549
      tio_printf("escape");
      choice = -1;
      goto exit_he_query_yn;
550
    case HXKEY_RETURN:
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
      if (dfl < 0) break;
      choice = dfl;
      switch (choice) {
      case -1: tio_printf("quit"); break;
      case 0: tio_printf("no"); break;
      case 1: tio_printf("yes"); break;
      case 2: tio_printf("always"); break;
      }
      goto exit_he_query_yn;
    case 'y': case 'Y':
      tio_printf("yes");
      choice = 1;
      goto exit_he_query_yn;
    case 'n': case 'N':
      tio_printf("no");
      choice = 0;
      goto exit_he_query_yn;
    case 'a': case 'A':
      tio_printf("always");
      choice = 2;
      goto exit_he_query_yn;
    default:
      break;
    }
  }

exit_he_query_yn:
  tio_return();
  tio_keypad(1);
  tio_flush();
  va_end(ap);
  return choice;
}
/* he_query_yn */


/* I/O wrap-functions for `regex_match()':
 */

static Buffer *rxwrap_current_buffer;
static long rxwrap_position;

  static long
594
rxwrap_read(char *buf, long count)
595 596 597 598 599 600 601 602
{
  long rval = b_read(rxwrap_current_buffer, buf, rxwrap_position, count);
  rxwrap_position += rval;
  return rval;
}
/* rxwrap_read */

  static long
603
rxwrap_seek(long position)
604 605 606 607 608 609
{
  return rxwrap_position = position;
}
/* rxwrap_seek */

  static long
610
rxwrap_tell(void)
611 612 613 614 615 616
{
  return rxwrap_position;
}
/* rxwrap_tell */

  long
617 618
he_search(struct he_s *hedit, const char *exp, const char *replace, int direction, int wrap, int increment, long end,
          char **replace_str, long *replace_len, long *match_len)
619 620 621 622 623 624 625 626
    /* regular expression.
     */
    /* replace template.  the replace template may contain back references to
     * the regular expression (`\0', ... `\9').
     */
    /* `direction >= 0': forward search.
     * `direction < 0': reverse search.
     */
627 628
    /* if `wrap' is set, the search continues from the top of the buffer/file
     * once the bottom has been passed (or vice versa, depending on `direction').
629 630 631
     */
    /* if `increment' is set, the search starts at `hedit->position + 1'
     * rather than at `hedit->position'.  if the direction is set to reverse
632
     * search, the `increment' flag has no effect.
633 634 635 636 637 638 639
     */
    /* if `wrap' is not set and `end' is not negative, the search ends at
     * position `end'.
     */
    /* if `replace_str' is non-zero and a match was found, the replace
     * string generated from `replace' will be copied to `*replace_str'.
     * the memory for that replace string will be allocated via `malloc()'.
640
     * NOTE: the replace string won't be terminated with a null character
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
     *   since it may contain null characters.
     */
    /* the length of the replace sting is written to `*replace_len'.
     */
    /* the length of the match is written to `*replace_len'.
     */
  /* RETURN VALUE:  if a match was found, the position of the match is
   *   returned;  -1: search failed;  -2: illegal expression (check out
   *   `rx_error'/`rx_error_msg').
   * NOTE:  if the returned value is positive, `*replace_str' has to be 
   *   `free()'d by the caller.
   */
{
  static long *regex;
  long position;

  /* setup the regex I/O */
  regex_init(rxwrap_read, rxwrap_seek, rxwrap_tell);
  rxwrap_current_buffer = hedit->buffer;
  regex_reset();

  if (wrap || end < 0) end = hedit->buffer->size;

  if (exp) if (!(regex = regex_compile(exp, replace))) return -2;
  if (direction < 0) direction = -1; else direction = 1;
  if (direction > 0) {
    position = regex_search(regex, 0, end, hedit->position + !!increment,
                            1, replace_str, replace_len, match_len);
    if (wrap && position < 0) {
      position = regex_search(regex, 0, end, 0, 1,
                              replace_str, replace_len, match_len);
      if (position >= 0) he_message(0, "@Abwrapped@~");
    }
  } else {
    position = regex_search(regex, 0, end, hedit->position - !!hedit->position,
                            -1, replace_str, replace_len, match_len);
    if (wrap && position < 0) {
      position = regex_search(regex, 0, end, hedit->buffer->size - 1,
                              -1, replace_str, replace_len, match_len);
      if (position >= 0) he_message(0, "@Abwrapped@~");
    }
  }
  return position;
}
/* he_search */

  void
688
he_search_command(struct he_s *hedit, char *exp, int dir)
689 690 691 692 693 694
{
  long position;
  char *rs;
  long rl, ml;
  static char last_exp[4096] = "";

695
  if (!*exp) {
696 697 698 699 700
    if (!*last_exp) {
      he_message(0, "@Abno previous expression@~");
      goto exit;
    } else
      exp = last_exp;
701
  }
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
  switch ((position = he_search(hedit, exp, "", dir, 1, 1, -1,
                                &rs, &rl, &ml))) {
  case -2:  /* invalid expression */
    he_message(0, "@Abinvalid expression:@~ %s", rx_error_msg[rx_error]);
    goto exit;
  case -1:  /* no match */
    if (!rx_error)
      he_message(0, "no match");
    else
      he_message(0, "@Abregexp error:@~ %s", rx_error_msg[rx_error]);
    break;
  default:  /* match */
    hedit->position = position;
    free((char *)rs);
    break;
  }
  if (exp != last_exp) strcpy(last_exp, exp);

exit:
  return;
}
/* he_search_command */

  static void
726
he_refresh(void)
727 728 729 730 731 732 733
{
  he_refresh_all(current_buffer->hedit);
  he_update_screen(current_buffer->hedit);
}
/* he_refresh */

  void
734
hexer_version(void)
735 736 737 738 739 740
{
  he_message(0, "@AbHexer@~ version @U%s@u", HEXER_VERSION);
}
/* hexer_version */

  void
741
hexer_init(void)
742 743 744 745 746
  /* this function is called by `process_args()' (main.c) before executing
   * the commands given at the command line.
   */
{
  int i;
747
  const char *hexerinit, *home;
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  char path[1024];
  char line[1024];
  FILE *fp;

  he_pagerprg = getenv("PAGER");
  if (!he_pagerprg) he_pagerprg = HE_DEFAULT_PAGER;
  for (i = 0; hexer_options[i].option; ++i) {
    s_set_type(hexer_options[i].option, hexer_options[i].type);
    s_set_option(hexer_options[i].option, hexer_options[i].default_value, 1);
    s_set_action(hexer_options[i].option, hexer_options[i].action);
  }
  s_set_option("TERM", terminal_name, 1);

  he_map_special = 1;
  for (i = 0; exh_initialize[i]; ++i)
    exh_command(current_buffer->hedit, exh_initialize[i]);

  if (!(home = getenv("HOME"))) home = ".";
  if (!(hexerinit = getenv("HEXERRC"))) hexerinit = HEXERINIT_FILE;
  strcpy(path, home);
  strcat(path, "/");
  strcat(path, hexerinit);
  if ((fp = fopen(path, "r"))) {
    while (!feof(fp)) {
772 773
      if (fgets(line, 1024, fp) == NULL || !*line)
	break;
774 775
      line[strlen(line) - 1] = 0; /* discard the trailing newline */
      if (*line && *line != '"')
776
        exh_command(current_buffer->hedit, line);
777 778 779 780 781 782 783 784
      /* the command might have quit the editor, so we gotta check */
      if (!current_buffer) {
        fprintf(stderr,
                "warning: a command in your `%s' causes the editor to quit.\n",
                hexerinit);
        break;
      }
    }
785
    fclose(fp);
786 787 788 789 790
  }
}
/* hexer_init */

  int
791
hexer(void)
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
{
  int key;
  char *cmd;
  char dfl[256], buf[256];
  long begin, end;
  int anchor, anchor_f = 0;
  int redisplay;

  tio_winch = rl_winch = he_refresh;
  he_refresh_part(current_buffer->hedit, 0, -1);
  for (; buffer_list;) {
    key = he_mainloop(current_buffer->hedit);
    redisplay = 0;
    switch (key) {
    case '!':  /* shell-command. */
      he_cancel_selection(current_buffer->hedit);
      he_update_screen(current_buffer->hedit);
      cmd = he_query_command("!", "", 1);
      redisplay = rl_redisplay;
      if (cmd) {
        strcpy(buf + 1, cmd);
        *buf = '!';
        exh_command(current_buffer->hedit, buf);
      }
      break;
    case ':':  /* exh command. */
      begin = current_buffer->hedit->begin_selection;
      end = current_buffer->hedit->end_selection;
      anchor = current_buffer->hedit->anchor_selection;
      if (begin >= 0 && end >= begin) {
        anchor_f = 1;
	sprintf(dfl, "0x%lx,0x%lx ", begin, end);
      } else {
	*dfl = 0;
        anchor_f = 0;
      }
      he_cancel_selection(current_buffer->hedit);
      cmd = he_query_command(":", dfl, 0);
      redisplay = rl_redisplay;
      if (cmd ? *cmd : 0)
        exh_command(current_buffer->hedit, cmd);
      if (current_buffer && anchor_f)
        if (current_buffer->hedit->begin_selection >= 0)
          current_buffer->hedit->anchor_selection = anchor;
      break;
    case '^' & 0x1f: /* C-^ - switch to alternate buffer */
      he_cancel_selection(current_buffer->hedit);
      if (he_alternate_buffer() < 0) 
	he_message(0, "no alternate buffer");
      else {
	he_refresh_part(current_buffer->hedit, 0, -1);
	tio_ungetch('g' & 0x1f);  /* FIXME */
      }
      break;
    default:
      he_cancel_selection(current_buffer->hedit);
      he_update_screen(current_buffer->hedit);
    }
    if (current_buffer) {
      if (redisplay) he_refresh_all(current_buffer->hedit);
      he_update_screen(current_buffer->hedit);
    }
  }
  return 0;
}
/* hexer */

/* end of hexer.c */


/* VIM configuration: (do not delete this line)
 *
864 865
 * vim:bk:nodg:efm=%f\:%l\:%m:hid:icon:
 * vim:sw=2:sm:textwidth=79:ul=1024:wrap:
866
 */