Ejemplo n.º 1
0
Archivo: ne.c Proyecto: hagenkaye/ne
void about()
{
    clear_entire_screen();
    displaying_info = true;
    int i;
    for (i = 0; NO_WARRANTY_msg[i]; i++)
    {
        if (i == ne_lines - 1)
        {
            break;
        }
        move_cursor(i, 0);
        output_string(NO_WARRANTY_msg[i], false);
    }
    if (++i < ne_lines - 1)
    {
        move_cursor(i, 0);
        if (exists_gprefs_dir())
        {
            output_string("Global Directory: ", false);
            output_string(exists_gprefs_dir(), false);
        }
        else
        {
            output_string("Global directory \"", false);
            output_string(get_global_dir(), false);
            output_string("\" not found!", false);
        }
    }
    reset_window();
    print_message(ABOUT_MSG);
}
Ejemplo n.º 2
0
vtn_filtro::vtn_filtro(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::vtn_filtro)
{
    ui->setupUi(this);
	allok = false;
	reset_window();
}
Ejemplo n.º 3
0
void stop_ne(void)
{
    unset_interactive_mode();
    kill(0, SIGTSTP);
    set_interactive_mode();
    clear_entire_screen();
    ttysize();
    reset_window();
}
Ejemplo n.º 4
0
 void handle_enabled() {
   if (settings.enabled) {
     reset_window();
     pid.SetMode(AUTOMATIC);
   } else {
     cancel_autotune();
     pid.SetMode(MANUAL);
     set_heat(false);
   }
 }
Ejemplo n.º 5
0
int request_document(void) {

	int i = -1, num_entries, max_name_len, total_len;
	char **entries, *names, *p, unnamed_name[] = UNNAMED_NAME;
	buffer *b = (buffer *)buffers.head;

	num_entries = max_name_len = total_len = 0;

	while(b->b_node.next) {
		p = b->filename ? b->filename : unnamed_name;

		if (strlen(p)>max_name_len) max_name_len = strlen(p);

		total_len += strlen(p) + 1;
		num_entries++;

		b = (buffer *)b->b_node.next;
	}

	max_name_len += 8;

	if (num_entries) {

		if (entries = malloc(sizeof(char *) * num_entries)) {
			if (names = malloc(sizeof(char) * total_len)) {

				p = names;

				b = (buffer *)buffers.head;

				for(i = 0; i < num_entries; i++) {
					entries[i] = p;
					strcpy(p, b->filename ? b->filename : unnamed_name);
					p += strlen(p) + 1;

					b = (buffer *)b->b_node.next;
				}

				i = request_strings((const char * const *)entries, num_entries, 0, max_name_len, '\0');
				reset_window();

				free(names);
			}
			free(entries);
		}
	}

	return i;
}
Ejemplo n.º 6
0
Archivo: request.c Proyecto: dmt4/ne
char *request_file(const buffer *b, const char *prompt, const char *default_name) {

	char *p = NULL;

	if (!b->opt.no_file_req) {
		print_message(info_msg[PRESSF1]);
		p = request_files(default_name, false);
		reset_window();
		draw_status_bar();
		if (p && *p) return p;
	}

	if (p = request_string(prompt, p ? p + 1 : default_name, false, COMPLETE_FILE, io_utf8)) return p;

	return NULL;
}
Ejemplo n.º 7
0
Archivo: ne.c Proyecto: vigna/ne
void about(void) {
	set_attr(0);
	clear_entire_screen();
	displaying_info = true;
	int i;
	for(i = 0; NO_WARRANTY_msg[i]; i++) {
		if (i == ne_lines - 1) break;
		move_cursor(i, 0);
		output_string(NO_WARRANTY_msg[i], false);
	}
	reset_window();

	char t[256] = ABOUT_MSG " Global directory";
	char * const gprefs_dir = exists_gprefs_dir();
	if (gprefs_dir) strncat(strncat(t, ": ", sizeof t - 1), gprefs_dir, sizeof t - 1);
	else strncat(strncat(strncat(t, " ", sizeof t - 1), get_global_dir(), sizeof t - 1), " not found!", sizeof t - 1);
	print_message(t);
}
Ejemplo n.º 8
0
Archivo: request.c Proyecto: dmt4/ne
int request_document(void) {

	int i = -1;
	req_list rl;
	buffer *b = (buffer *)buffers.head;

	if (b->b_node.next && req_list_init(&rl, NULL, true, true, '*')==OK) {
		i = 0;
		int cur_entry = 0;
		while(b->b_node.next) {
			if (b == cur_buffer) cur_entry = i;
			req_list_add(&rl, b->filename ? b->filename : UNNAMED_NAME, b->is_modified);
			b = (buffer *)b->b_node.next;
			i++;
		}
		rl.ignore_tab = true;
		req_list_finalize(&rl);
		print_message(info_msg[SELECT_DOC]);
		i = request_strings(&rl, cur_entry);
		reset_window();
		draw_status_bar();
		if (i >= 0 && rl.reordered) {
			/* We're going to cheat big time here. We have an array of pointers
				at rl.entries that's big enough to hold all the buffer pointers,
				and that's exactly what we're going to use it for now. */
			b = (buffer *)buffers.head;
			for (int j = 0; b->b_node.next; j++ ) {
				rl.entries[j] = (char *)b;
				b = (buffer *)b->b_node.next;
				rem(b->b_node.prev);
			}
			/* Ack! We're removed all our buffers! */
			for (int j = 0; j < rl.cur_entries; j++) {
				add_tail(&buffers, (node *)rl.entries[rl.orig_order[j]]);
			}
		}

		req_list_free(&rl);
	}

	return i;
}
Ejemplo n.º 9
0
  void update() {
    if (settings.enabled) {
      if (autotune_running) {
        if (pid_autotune.Runtime()) {
          autotune_running = false;

          settings.pid.kp = pid_autotune.GetKp();
          settings.pid.ki = pid_autotune.GetKi();
          settings.pid.kd = pid_autotune.GetKd();

          update_pid_tunings();
          write_settings();
        }
      }

      if (! autotune_running) {
        pid.Compute();
      }

      pid_output_sum += pid_output;
      pid_output_count++;

      unsigned long now = millis();
      if (now >= window_end_millis) {
        pid_output_average = pid_output_sum / pid_output_count;

        if (pid_output_average >= settings.heat_on.threshold) {
          set_heat(true);
        } else if (pid_output_average + settings.heat_on.delta <=
                   settings.heat_on.threshold) {
          set_heat(false);
        }

        reset_window();
      }
    }
  }
Ejemplo n.º 10
0
/**
 * @brief Main learning method that will change the model and learn the best actions to take
 *
 * @param [in] current date and time
 */
void pqos_learn_main(char* cb_time)
{
  int k = 0, stopper = 0, numOfSteps = 0;
  double reward = 0.0, old_checker = 0.0;
  stopper = 0;
  /* while not converged */
  while (stopper == 0){
    counter = 0;
    numOfSteps = 0;

    /* for each COS */
  for(k = 1; k < num_COS; k++){    
    /* reset all values for the start of the episode */
    int current_x_pos = 0, i = 0, numberOfSteps = 0, stuck_in_pos = 0;
    double this_Q = 0.0, max_Q = 0.0, new_Q = 0.0, step_change = 0.0;
    counter = 0;
    old_reward = 0;
    numOfSteps = 0;
    
    for(i = 0; i < 12; i++){
      real_world[k][i] = 0;
    }
    /* can not have a cos equal to 0, change to 1 */
    real_world[k][11] = 1;

    /* set the current pos */
    current_x_pos = (int) convert_to_mask(k);

    /* reset the mask to match the real world */
    set_new_mask(learning_sock_count, learning_sockets, (unsigned)k, current_x_pos);
    cos_change(learning_sock_count, learning_sockets);

    while(counter == 0){
      /* check to see if the COS has a core attached to it, no point in learning if it dosent */
      if(coses_used[k] == 0){
	    break;
      }
      reward = 0.0;
      int old_x_pos = current_x_pos;
      
      /* get the best action to play and save its Q value */
      int action = chooseAction( current_x_pos, epsilon, k);
      printf("Action picked is: %d\n" , action);
      this_Q = the_model[k][current_x_pos][action];
      /* now move into the new state */
      current_x_pos = change_bit_mask(action, k);
      printf("cos bits after change: ");
      print_cos_bits(k);

      /* sleep for a moment to let the changes take effect */
      usleep(20000);
      
      /* get the reward for the action taken */
      reward = calReward(k, current_x_pos, action);

      /* find the max q value available */
      max_Q = the_model[k][current_x_pos][0];
      for(i = 1; i < 2; i++){
	if(the_model[k][current_x_pos][i] > max_Q)
	  max_Q = the_model[k][current_x_pos][i];
      }//for

      /* Calculate new value for Q */
      new_Q = this_Q + (alpha * (reward + (gamma_2 * max_Q) - this_Q));
      
      /* Set the new Q value */
      the_model[k][old_x_pos][action] = new_Q;

      //stop getting stuck in an unmovable pos like 100000000000
      if(old_x_pos == current_x_pos){
	stuck_in_pos++;
      }else {
	stuck_in_pos = 0;
      }
      if(stuck_in_pos >= 10){
	counter = 1;
	target_ipc -= 0.01;
     }      
      numOfSteps++;
    }//while
    /**
     * testing ipc data for reports
     * testing environment is
     * core 0 used for OS tasks only and linked to COS 0
     * all the rest of the cores are used for test and are linked to COS 1
     * COS 0 is ignored as its only OS tasks
     */
    if(coses_used[k] != 0 && k == 1){
      numberOfNumbers++;
      print_cos_world(k);
      printf("Cos bits are: ");
      print_cos_bits(k);

      printf("Num of steps taken: %d\n", numOfSteps);
      printf("time/C-Reward/max/min/avg %s, %.2f, %.2f, %.2f, %.2f,\n",cb_time, currentIPC, maxIPC, minIPC, average);
      reset_window();

      printRangeOfStates(k);
      printGoalsOverStates(k);
      printHeatMap();
    }
    
  }//for

  /* cal step change to see if model has converged */
  double diff = 0.0;
  diff = cal_step_change(&old_checker, reward);
  printf("Step Change in main is %.2f\n", diff);
  if(diff > -2.00 &&
     diff < 2.00 ){
    stopper = 1;
  }
  
  }//while
}
Ejemplo n.º 11
0
Archivo: input.c Proyecto: dmt4/ne
char *request(const char *prompt, const char * const default_string, const bool alpha_allowed, const int completion_type, const bool prefer_utf8) {

	set_attr(0);

	input_buffer[pos = len = offset = 0] = 0;
	encoding = ENC_ASCII;
	x = start_x = print_prompt(prompt);

	init_history();

	if (default_string) {
		strncpy(input_buffer, default_string, MAX_INPUT_LINE_LEN);
		len = strlen(input_buffer);
		encoding = detect_encoding(input_buffer, len);
		input_refresh();
	}

	bool first_char_typed = true, last_char_completion = false, selection = false;

	while(true) {

		assert(input_buffer[len] == 0);

		move_cursor(ne_lines - 1, x);

		int c;
		input_class ic;
		do c = get_key_code(); while((ic = CHAR_CLASS(c)) == IGNORE);

		/* ISO 10646 characters *above 256* can be added only to UTF-8 lines, or ASCII lines (making them, of course, UTF-8). */
		if (ic == ALPHA && c > 0xFF && encoding != ENC_ASCII && encoding != ENC_UTF8) ic = INVALID;

		if (ic != TAB) last_char_completion = false;
		if (ic == TAB && !completion_type) ic = ALPHA;

		switch(ic) {

		case INVALID:
			alert();
			break;

		case ALPHA:

			if (first_char_typed) {
				input_buffer[len = 0] = 0;
				clear_to_eol();
			}

			if (encoding == ENC_ASCII && c > 0x7F) encoding = prefer_utf8 || c > 0xFF ? ENC_UTF8 : ENC_8_BIT;
			int c_len = encoding == ENC_UTF8 ? utf8seqlen(c) : 1;
			int c_width = output_width(c);
			assert(c_len > 0);

			if (len <= MAX_INPUT_LINE_LEN - c_len && (alpha_allowed || (c < 0x100 && isxdigit(c)) || c=='X' || c=='x')) {

				memmove(&input_buffer[pos + c_len], &input_buffer[pos], len - pos + 1);

				if (c_len == 1) input_buffer[pos] = c;
				else utf8str(c, &input_buffer[pos]);

				len += c_len;

				move_cursor(ne_lines - 1, x);

				if (x < ne_columns - c_width) {
					if (pos == len - c_len) output_char(c, 0, encoding);
					else if (char_ins_del_ok) insert_char(c, 0, encoding);
					else input_refresh();
				}

				input_move_right(true);
			}
			break;

		case RETURN:
			selection = true;
			break;

		case TAB:
			if (completion_type == COMPLETE_FILE || completion_type == COMPLETE_SYNTAX) {
				bool quoted = false;
				char *prefix, *completion, *p;
				if (len && input_buffer[len - 1] == '"') {
					input_buffer[len - 1] = 0;
					if (prefix = strrchr(input_buffer, '"')) {
						quoted = true;
						prefix++;
					}
					else input_buffer[len - 1] = '"';
				}

				if (!quoted) {
					prefix = strrchr(input_buffer, ' ');
					if (prefix) prefix++;
					else prefix = input_buffer;
				}

				if (last_char_completion || completion_type == COMPLETE_SYNTAX) {
					if (completion_type == COMPLETE_FILE )
						completion = p = request_files(prefix, true);
					else
						completion = p = request_syntax(prefix, true);
					reset_window();
					if (completion) {
						if (*completion) selection = true;
						else completion++;
					}
				}
				else {
					if (completion_type == COMPLETE_FILE )
						completion = p = complete_filename(prefix);
					else
						completion = p = request_syntax(prefix, true);
					last_char_completion = true;
					if (!completion) alert();
				}

				if (completion && (prefix - input_buffer) + strlen(completion) + 1 < MAX_INPUT_LINE_LEN) {
					const encoding_type completion_encoding = detect_encoding(completion, strlen(completion));
					if (encoding == ENC_ASCII || completion_encoding == ENC_ASCII || encoding == completion_encoding) {
						strcpy(prefix, completion);
						if (quoted) strcat(prefix, "\"");
						len = strlen(input_buffer);
						pos = offset = 0;
						x = start_x;
						if (encoding == ENC_ASCII) encoding = completion_encoding;
						input_move_to_eol();
						if (quoted) input_move_left(false);
						input_refresh();
					}
					else alert();
				}
				else if (quoted) strcat(prefix, "\"");

				free(p);
			}
			break;

		case COMMAND:
			if (c < 0) c = -c - 1;
			const int a = parse_command_line(key_binding[c], NULL, NULL, false);
			if (a >= 0) {
				switch(a) {

				case LINEUP_A:
				case LINEDOWN_A:
				case MOVESOF_A:
				case MOVEEOF_A:
				case PAGEUP_A:
				case PAGEDOWN_A:
				case NEXTPAGE_A:
				case PREVPAGE_A:
					if (history_buff) {
						switch(a) {
						case LINEUP_A: line_up(history_buff); break;
						case LINEDOWN_A: line_down(history_buff); break;
						case MOVESOF_A: move_to_sof(history_buff); break;
						case MOVEEOF_A: move_to_bof(history_buff); break;
						case PAGEUP_A:
						case PREVPAGE_A: prev_page(history_buff); break;
						case PAGEDOWN_A:
						case NEXTPAGE_A: next_page(history_buff); break;
						}

						/* In some cases, the default displayed on the command line will be the same as the 
							first history item. In that case we skip it. */

						if (first_char_typed == true 
							 && a == LINEUP_A 
							 && history_buff->cur_line_desc->line 
							 && !strncmp(history_buff->cur_line_desc->line, input_buffer, history_buff->cur_line_desc->line_len))
							line_up(history_buff);

						if (history_buff->cur_line_desc->line) {
							strncpy(input_buffer,
									  history_buff->cur_line_desc->line,
									  min(history_buff->cur_line_desc->line_len,MAX_INPUT_LINE_LEN));
							input_buffer[min(history_buff->cur_line_desc->line_len,MAX_INPUT_LINE_LEN)] = 0;
							len	 = strlen(input_buffer);
							encoding = detect_encoding(input_buffer, len);
						}
						else {
							input_buffer[len = 0] = 0;
							encoding = ENC_ASCII;
						}

						x		= start_x;
						pos	= 0;
						offset = 0;
						input_refresh();
					}
					break;

				case MOVELEFT_A:
					input_move_left(true);
					break;

				case MOVERIGHT_A:
					input_move_right(true);
					break;

				case BACKSPACE_A:
					if (pos == 0) break;
					input_move_left(true);

				case DELETECHAR_A:
					if (len > 0 && pos < len) {
						int c_len = encoding == ENC_UTF8 ? utf8len(input_buffer[pos]) : 1;
						int c_width = get_char_width(&input_buffer[pos], encoding);
						memmove(&input_buffer[pos], &input_buffer[pos + c_len], len - pos - c_len + 1);
						len -= c_len;
						if (input_buffer_is_ascii()) encoding = ENC_ASCII;

						if (char_ins_del_ok) {
							int i, j;

							move_cursor(ne_lines - 1, x);
							delete_chars(c_width);

							for(i = x, j = pos; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns - c_width; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));

							if (j < len) {
								move_cursor(ne_lines - 1, i);
								while(j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns) {
									output_char(get_char(&input_buffer[j], encoding), 0, encoding);
									i += get_char_width(&input_buffer[j], encoding);
									j = next_pos(input_buffer, j, encoding);
								}
							}
						}
						else input_refresh();
					}
					break;

				case DELETELINE_A:
					move_cursor(ne_lines - 1, start_x);
					clear_to_eol();
					input_buffer[len = pos = offset = 0] = 0;
					encoding = ENC_ASCII;
					x = start_x;
					break;

				case DELETEEOL_A:
					input_buffer[len = pos] = 0;
					clear_to_eol();
					if (input_buffer_is_ascii()) encoding = ENC_ASCII;
					break;

				case MOVEINCUP_A:
					if (x != start_x) {
						pos = offset;
						x = start_x;
						break;
					}

				case MOVESOL_A:
					input_move_to_sol();
					break;

				case MOVEINCDOWN_A: {
					int i, j;
					for(i = x, j = pos; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));
					if (j != pos && j < len) {
						pos = j;
						x = i;
						break;
					}
				}

				case MOVEEOL_A:
					input_move_to_eol();
					break;

				case TOGGLESEOL_A:
				case TOGGLESEOF_A:
					if (pos != 0) input_move_to_sol();
					else input_move_to_eol();
					break;

				case PREVWORD_A:
					input_prev_word();
					break;

				case NEXTWORD_A:
					input_next_word();
					break;

				case REFRESH_A:
					input_refresh();
					break;

				case PASTE_A:
					input_paste();
					break;

				case AUTOCOMPLETE_A:
					input_autocomplete();
					break;

				case ESCAPE_A:
					return NULL;

				default:
					break;
				}
			}
			break;

		default:
			break;
		}

		if (selection) {
			const line_desc * const last = (line_desc *)history_buff->line_desc_list.tail_pred->prev;
			assert(input_buffer[len] == 0);
			if (history_buff->num_lines == 0 || len != last->line_len || strncmp(input_buffer, last->line, last->line_len)) add_to_history(input_buffer);
			return input_buffer;
		}

		first_char_typed = false;
	}
}
Ejemplo n.º 12
0
Archivo: ne.c Proyecto: vigna/ne
int main(int argc, char **argv) {

	char *locale = setlocale(LC_ALL, "");
	for(int i = 0; i < 256; i++) localised_up_case[i] = toupper(i);

	if (locale) {
		struct re_pattern_buffer re_pb;
		struct re_registers re_reg;
		memset(&re_pb, 0, sizeof re_pb);
		memset(&re_reg, 0, sizeof re_reg);

		re_pb.translate = localised_up_case;
		re_compile_pattern(LOCALE_REGEX, strlen(LOCALE_REGEX), &re_pb);
		if (re_search(&re_pb, locale, strlen(locale), 0, strlen(locale), &re_reg) >= 0) {
			if (re_reg.start[1] >= 0) io_utf8 = true;
		}
		free(re_reg.start);
		free(re_reg.end);
	}

	bool no_config = false;
	char *macro_name = NULL, *key_bindings_name = NULL, *menu_conf_name = NULL, *startup_prefs_name = DEF_PREFS_NAME;

	char * const skiplist = calloc(argc, 1);
	if (!skiplist) exit(1);  /* We need this many flags. */

	for(int i = 1; i < argc; i++) {

		if (argv[i][0] == '-' && (!strcmp(&argv[i][1], "h") || !strcmp(&argv[i][1], "-help" "\0" VERSION_STRING))) {
			puts(ARG_HELP);
			exit(0);
		}

		/* Special arguments start with two dashes. If we find one, we
		   cancel its entry in argv[], so that it will be skipped when opening
		   the specified files. The only exception is +N for skipping to the
		   N-th line. */

		if (argv[i][0] == '-' && argv[i][1] == '-') {
			if (!argv[i][2]) i++; /* You can use "--" to force the next token to be a filename */
			else if (!strcmp(&argv[i][2], "noconfig") || !strcmp(&argv[i][2], "no-config")) {
				no_config = true;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "noansi") || !strcmp(&argv[i][2], "no-ansi")) {
				ansi = false;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "no-syntax")) {
				do_syntax = false;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "prefs")) {
				if (i < argc-1) {
					startup_prefs_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
			else if (!strcmp(&argv[i][2], "ansi")) {
				ansi = true;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "utf8")) {
				io_utf8 = true;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "no-utf8")) {
				io_utf8 = false;
				skiplist[i] = 1; /* argv[i] = NULL; */
			}
			else if (!strcmp(&argv[i][2], "macro")) {
				if (i < argc-1) {
					macro_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
			else if (!strcmp(&argv[i][2], "keys")) {
				if (i < argc-1) {
					key_bindings_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
			else if (!strcmp(&argv[i][2], "menus")) {
				if (i < argc-1) {
					menu_conf_name = argv[i+1];
					skiplist[i] = skiplist[i+1] = 1; /* argv[i] = argv[i+1] = NULL; */
				}
			}
		}
	}

#ifdef NE_TEST
	/* Dump the builtin menu and key bindings to compare to
	   doc/default.menus and doc/default.keys. */
	int dump_config(void);
	dump_config();
#endif

	/* Unless --noconfig was specified, we try to configure the
	   menus and the keyboard. Note that these functions can exit() on error. */

	if (!no_config) {
		get_menu_configuration(menu_conf_name);
		get_key_bindings(key_bindings_name);
	}

	/* If we cannot even create a buffer, better go... */

	if (!new_buffer()) exit(1);

	/* Now that key_bindings are loaded, try to fix up the message for NOT_FOUND. */
	{
		char *repeat_last_keystroke, *new_not_found;
		if ((repeat_last_keystroke = find_key_strokes(REPEATLAST_A, 1))) {
			if ((new_not_found = malloc(39+strlen(repeat_last_keystroke)))) {
				strcat(strcat(strcpy(new_not_found, "Not Found. (RepeatLast with "), repeat_last_keystroke), " to wrap.)");
				error_msg[NOT_FOUND] = new_not_found;
			}
			free(repeat_last_keystroke);
		}
	}

	clear_buffer(cur_buffer);

	/* The INT_MAX clip always exists, and it is used by the Through command. */

	clip_desc * const cd = alloc_clip_desc(INT_MAX, 0);
	if (!cd) exit(1);

	add_head(&clips, &cd->cd_node);

	/* General terminfo and cursor motion initalization. From here onwards,
	   we cannot exit() lightly. */

	term_init();

	/* We will be always using the last line for the status bar. */

	set_terminal_window(ne_lines-1);

	/* We read in all the key capabilities. */

	read_key_capabilities();

	/* Some initializations of other modules... */

	re_set_syntax(
		RE_CONTEXT_INDEP_ANCHORS |
		RE_CONTEXT_INDEP_OPS     | RE_HAT_LISTS_NOT_NEWLINE |
		RE_NEWLINE_ALT           | RE_NO_BK_PARENS          |
		RE_NO_BK_VBAR            | RE_NO_EMPTY_RANGES
	);

	bool first_file = true;

	load_virtual_extensions();
	load_auto_prefs(cur_buffer, startup_prefs_name);

	buffer *stdin_buffer = NULL;
	if (!isatty(fileno(stdin))) {
		first_file = false;
		const int error = load_fd_in_buffer(cur_buffer, fileno(stdin));
		print_error(error);
		stdin_buffer = cur_buffer;

		if (!(freopen("/dev/tty", "r", stdin))) {
			fprintf(stderr, "Cannot reopen input tty\n");
			abort();
		}
	}

	/* The terminal is prepared for interactive I/O. */

	set_interactive_mode();

	clear_entire_screen();

	/* This function sets fatal_code() as signal interrupt handler
	   for all the dangerous signals (SIGILL, SIGSEGV etc.). */

	set_fatal_code();

	if (argc > 1) {

		/* The first file opened does not need a NEWDOC_A action. Note that
		   file loading can be interrupted (wildcarding can sometimes produce
		   unwanted results). */

		uint64_t first_line = 0, first_col = 0;
		bool binary = false, skip_plus = false, read_only = false;
		stop = false;

		for(int i = 1; i < argc && !stop; i++) {
			if (argv[i] && !skiplist[i]) {
				if (argv[i][0] == '+' && !skip_plus) {       /* looking for "+", or "+N" or "+N,M"  */
					uint64_t tmp_l = INT64_MAX, tmp_c = 0;
					char *d;
					errno = 0;
					if (argv[i][1]) {
						if (isdigit((unsigned char)argv[i][1])) {
							tmp_l = strtoll(argv[i]+1, &d, 10);
							if (!errno) {
								if (*d) {  /* separator between N and M */
									if (isdigit((unsigned char)d[1])) {
										tmp_c = strtoll(d+1, &d, 10);
										if (*d) errno = ERANGE;
									}
									else errno = ERANGE;
								}
							}
						}
						else errno = ERANGE;
					}
					if (!errno) {
						first_line = tmp_l;
						first_col  = tmp_c;
					}
					else {
						skip_plus = true;
						i--;
					}
				}
				else if (!strcmp(argv[i], "--binary")) {
					binary = true;
				}
				else if (!strcmp(argv[i], "--read-only") || !strcmp(argv[i], "--readonly") || !strcmp(argv[i], "--ro")) {
					read_only = true;
				}
				else {
					if (!strcmp(argv[i], "-") && stdin_buffer) {
						stdin_buffer->opt.binary = binary;
						if (read_only) stdin_buffer->opt.read_only = read_only;
						if (first_line) do_action(stdin_buffer, GOTOLINE_A, first_line, NULL);
						if (first_col)  do_action(stdin_buffer, GOTOCOLUMN_A, first_col, NULL);
						stdin_buffer = NULL;
					}
					else {
						if (!strcmp(argv[i], "--")) i++;
						if (!first_file) do_action(cur_buffer, NEWDOC_A, -1, NULL);
						else first_file = false;
						cur_buffer->opt.binary = binary;
						if (i < argc) do_action(cur_buffer, OPEN_A, 0, str_dup(argv[i]));
						if (first_line) do_action(cur_buffer, GOTOLINE_A, first_line, NULL);
						if (first_col)  do_action(cur_buffer, GOTOCOLUMN_A, first_col, NULL);
						if (read_only) cur_buffer->opt.read_only = read_only;
					}
					first_line =
					first_col  = 0;
					skip_plus  =
					binary    =
					read_only  = false;
				}
			}
		}

		free(skiplist);

		/* This call makes current the first specified file. It is called
		   only if more than one buffer exist. */

		if (get_nth_buffer(1)) do_action(cur_buffer, NEXTDOC_A, -1, NULL);

	}

	/* We delay updates. In this way the macro activity does not cause display activity. */

	reset_window();
	delay_update();

	if (macro_name) do_action(cur_buffer, MACRO_A, -1, str_dup(macro_name));
	else if (first_file) {
		/* If there is no file to load, and no macro to execute, we display
		   the "NO WARRANTY" message. */
		about();
	}

	while(true) {
		/* If we are displaying the "NO WARRANTY" info, we should not refresh the
		   window now */
		if (!displaying_info) {
			refresh_window(cur_buffer);
			if (cur_buffer->opt.automatch) automatch_bracket(cur_buffer, true);
		}

		draw_status_bar();
		move_cursor(cur_buffer->cur_y, cur_buffer->cur_x);

		int c = get_key_code();

		if (window_changed_size) {
			print_error(do_action(cur_buffer, REFRESH_A, 0, NULL));
			window_changed_size = displaying_info = false;
			cur_buffer->automatch.shown = 0;
		}

		if (c == INVALID_CHAR) continue; /* Window resizing. */
		const input_class ic = CHAR_CLASS(c);

		if (displaying_info) {
			refresh_window(cur_buffer);
			displaying_info = false;
		}

		if (cur_buffer->automatch.shown) automatch_bracket(cur_buffer, false);

		switch(ic) {
		case INVALID:
			print_error(INVALID_CHARACTER);
			break;

		case ALPHA:
			print_error(do_action(cur_buffer, INSERTCHAR_A, c, NULL));
			break;

		case TAB:
			print_error(do_action(cur_buffer, INSERTTAB_A, 1, NULL));
			break;

		case RETURN:
			print_error(do_action(cur_buffer, INSERTLINE_A, -1, NULL));
			break;

		case COMMAND:
			if (c < 0) c = -c - 1;
			if (key_binding[c]) print_error(execute_command_line(cur_buffer, key_binding[c]));
			break;

		default:
			break;
		}
	}
}
Ejemplo n.º 13
0
Archivo: autocomp.c Proyecto: vigna/ne
char *autocomplete(char *p, char *req_msg, const int ext, int * const error) {
	int max_len = 0, min_len = INT_MAX, prefix_len = strlen(p);

	assert(p);

	req_list_init(&rl, (cur_buffer->opt.case_search ? strcmp : strdictcmp), false, false, EXTERNAL_FLAG_CHAR);
	count_scanned = 0;

	search_buff(cur_buffer, p, cur_buffer->encoding, cur_buffer->opt.case_search, false);
	if (stop) {
		req_list_free(&rl);
		free(p);
		return NULL;
	}

	if (ext) {
		buffer *b = (buffer *)buffers.head;
		while (b->b_node.next) {
			if (b != cur_buffer) {
				search_buff(b, p, cur_buffer->encoding, cur_buffer->opt.case_search, true);
				if (stop) {
					req_list_free(&rl);
					free(p);
					return NULL;
				}
			}
			b = (buffer *)b->b_node.next;
		}
 	}

	for(int i = 0; i < rl.cur_entries; i++) {
		const int l = strlen(rl.entries[i]);
		if (max_len < l) max_len = l;
		if (min_len > l) min_len = l;
	}
	/* We compact the table into a vector of char pointers. */
	req_list_finalize(&rl);


	free(p);
	p = NULL;

#ifdef NE_TEST
	/* During tests, we always output the middle entry. */
	if (rl.cur_entries) {
		if (rl.entries[rl.cur_entries/2][strlen(rl.entries[rl.cur_entries/2]) - 1] == EXTERNAL_FLAG_CHAR) rl.entries[rl.cur_entries/2][strlen(rl.entries[rl.cur_entries/2]) - 1] = 0;
		p = str_dup(rl.entries[rl.cur_entries/2]);
	}
	*error = AUTOCOMPLETE_COMPLETED;
	req_list_free(&rl);
	return p;
#endif

	if (rl.cur_entries > 0) {
		qsort(rl.entries, rl.cur_entries, sizeof(char *), strdictcmpp);
		/* Find maximum common prefix. */
		int m = strlen(rl.entries[0]);
		if (rl.entries[0][m-1] == EXTERNAL_FLAG_CHAR) m--;
		for(int i = 1; i < rl.cur_entries; i++) {
			int j;
			for(j = 0; j < m; j++) 
				if (rl.entries[i][j] != rl.entries[0][j]) break;
			m = j;
		}

		/* If we can output more characters than the prefix len, we do so without
			starting the requester. */
		if (m > prefix_len) {
			p = malloc(m + 1);
			strncpy(p, rl.entries[0], m);
			p[m] = 0;
			*error = min_len == m ? AUTOCOMPLETE_COMPLETED : AUTOCOMPLETE_PARTIAL;
		}
		else {
			if (req_msg) print_message(req_msg);
			int result = request_strings(&rl, 0);
			if (result != ERROR) {
				result = result >= 0 ? result : -result - 2;
				/* Delete EXTERNAL_FLAG_CHAR at the end of the strings if necessary. */
				if (rl.entries[result][strlen(rl.entries[result]) - 1] == EXTERNAL_FLAG_CHAR) rl.entries[result][strlen(rl.entries[result]) - 1] = 0;
				p = str_dup(rl.entries[result]);
				*error = AUTOCOMPLETE_COMPLETED;
			}
			else *error = AUTOCOMPLETE_CANCELLED;
			reset_window();
		}
	}
	else *error = AUTOCOMPLETE_NO_MATCH;

	req_list_free(&rl);
	D(fprintf(stderr, "autocomp returning '%s', entries: %d\n", p, rl.cur_entries);)
	return p;