Exemplo n.º 1
0
int main(int argc, char* argv[]) {
    int err;
    text_t text;

    err = (argc != 2);
    if (err) { 
        printf("ERROR: Wrong number of arguments.\n");
        exit(EXIT_FAILURE); 
    }

    /* STACK TEST */
    err = text_from_file(&text, argv[1]);
    if (err) {
        printf("ERROR: Error reading text file.\n");
        exit(EXIT_FAILURE);
    }

    text_print(&text);
    text_free(&text, false);

    /* HEAP TEST */
    text_t* textp = text_alloc();
    err = text_from_file(textp, argv[1]);
    if (err) {
        printf("ERROR: Error reading text lines.\n");
        exit(EXIT_FAILURE);
    }

    text_print(textp);
    text_free(textp, true);

    return EXIT_SUCCESS;
}
Exemplo n.º 2
0
void editor_exit(void)
{
    Text *txt = editor.txt;
    if(text_modified(txt)){
        int choice = judgebox_manager("File not save,save?");
        switch(choice)
        {
        case 0:
            return;
        case 1:
            text_free(txt);
            break;
        case 2:
            if(text_save(txt) == 2){
                char * f = inputbox_manager("please input filename:");
                text_saveas(txt,f);
                free(f);
                text_free(txt);
            }
        }
    }
    FreeMenu(editor.root);
    clipborad_close(editor.cli);
    print_close();
    vga_close();
}
Exemplo n.º 3
0
Text *editor_newfile(const char *filename)
{
    Text *newtxt;
    Text *txt = editor.txt;
    if(text_modified(txt)){
        int choice = judgebox_manager("File not save,save?");
        switch(choice)
        {
        case 0:
            return NULL;
        case 1:
            text_free(txt);
            break;
        case 2:
            if(text_save(txt) == 2){
                char * f = inputbox_manager("please input filename:");
                text_saveas(txt,f);
                free(f);
                text_free(txt);
            }
            break;
        }
    }
	newtxt = text_load(filename);
    if(!newtxt)
        messagebox_manager("open new file failed");
    editor.txt = newtxt;
    return newtxt;
}
Exemplo n.º 4
0
void editor_init(void)
{
    Text *txt = text_load(NULL);

    vga_init();
    print_init();
	view_main_window();

    editor.root =  GetMenu(CHINESE);
    if(!(editor.root)){
        messagebox_manager("load menu failed.");
        getch();
        text_free(txt);
        exit(1);
    }
    view_main_menu(editor.root);
    if(!txt){
        messagebox_manager("open empty file failed.");
    }
    editor.cli = clipborad_init();

    initmouse();
    fprintf(stderr,"logging...\n");
    showmouseptr();
    editor.txt = txt;
    editor.mode = MENU;
}
Exemplo n.º 5
0
int main () {
    FILE *input;
    input = fopen ("input.txt","r");

    text_t *text;
    text = text_new();

    int stringCount, i, format;
    char string[L];
    fscanf (input, "%i", &stringCount);

    for (i = 0; i < stringCount; i++) {
        fscanf (input, "%i", &format);
        fscanf (input, "%s", string);
        text_insert(text, i, string, format);
    }

    text_delete (text, 3);

    printf ("%i\n", text_getCount(text));
    text_writeFormat (text, 0);

    text_free (text);

    fclose (input);
    return 0;
}
Exemplo n.º 6
0
Arquivo: vis.c Projeto: ewqasd200g/vis
static File *file_new(Vis *vis, const char *filename) {
	if (filename) {
		/* try to detect whether the same file is already open in another window
		 * TODO: do this based on inodes */
		for (File *file = vis->files; file; file = file->next) {
			if (file->name && strcmp(file->name, filename) == 0) {
				return file;
			}
		}
	}

	Text *text = text_load(filename);
	if (!text && filename && errno == ENOENT)
		text = text_load(NULL);
	if (!text)
		return NULL;

	File *file = file_new_text(vis, text);
	if (!file) {
		text_free(text);
		return NULL;
	}

	if (filename)
		file->name = strdup(filename);
	if (!file->internal && vis->event && vis->event->file_open)
		vis->event->file_open(vis, file);
	return file;
}
Exemplo n.º 7
0
static File *file_new(Editor *ed, const char *filename) {
	if (filename) {
		/* try to detect whether the same file is already open in another window
		 * TODO: do this based on inodes */
		for (File *file = ed->files; file; file = file->next) {
			const char *name = text_filename_get(file->text);
			if (name && strcmp(name, filename) == 0) {
				file->refcount++;
				return file;
			}
		}
	}

	Text *text = text_load(filename);
	if (!text && filename && errno == ENOENT)
		text = text_load(NULL);
	if (!text)
		return NULL;
	if (filename)
		text_filename_set(text, filename);
	
	File *file = file_new_text(ed, text);
	if (!file) {
		text_free(text);
		return NULL;
	}

	return file;
}
Exemplo n.º 8
0
int main(void)
{
    text_t * text = text_t_new();
    sentence_t * sentence = sentence_t_new();
    file_read ("input.txt", text, sentence);
    fprint(text);
    text_free(text);
    return 0;
}
Exemplo n.º 9
0
int main()
{   int i,j;
    char str[20] = "do1.txt";
    text_t * text = text_new(str);
   // if (text != NULL)
        //text_print(text);
    sentense_t * tmp = NULL;
    int flag = 0;
    for ( i = 0; i < text_sentence_count(text); i++)
    {
        tmp = text_get_sentence(text, i);
        for ( j = 0; j < sentence_word_count(tmp); j++)
        {
            flag = 0;
            while (strcmp(word_get_str(sentence_get_word(tmp, j)), "not") == 0)
            {
                j++;
                if (j == sentence_word_count(tmp))
                    break;
                    flag = 1;
            }
            if (flag == 1)
                flag = 0;
            else
            {
                sentence_del_word(tmp, j);
                j--;
            }
        }
    }

    FILE * file_out = NULL;
    file_out = fopen("posle.txt", "w");
    if (file_out == NULL)
        return 1;

    for ( i = 0; i < text_sentence_count(text); i++)
    {
        tmp = text_get_sentence(text, i);
        for ( j = 0; j < sentence_word_count(tmp); j++)
        {
            if (j < sentence_word_count(tmp) - 1)
                fprintf(file_out, "%s, ", word_get_str(sentence_get_word(tmp, j)));
            else
                fprintf(file_out, "%s\n", word_get_str(sentence_get_word(tmp, j)));
        }
    }
    text_print(text);
    text_free(text);
    fclose(file_out);

    return 0;
}
Exemplo n.º 10
0
JavaDocStructure* parse_text(const char* java_text, 
                             gboolean extract_package, 
                             gboolean extract_imports) {
  JavaParseOptions opts;
  java_parse_opts_init(&opts);
  opts.extract_package = extract_package;
  opts.extract_imports = extract_imports;
  Text* text = string_text_new(java_text);
  JavaDocStructure* java_doc = java_parse(text, &opts);
  text_free(text);
  return java_doc;
}
Exemplo n.º 11
0
int main (){
    FILE *input;
    input = fopen("text.txt", "r");

    char *str = strnew();

    sentence_t *currSentence = sentence_create();
    text_t *text = text_create();

    while (1) {
        char c = fgetc(input);
        if (c == EOF || isspace(c) || c == ',' || c == '.' || c == '!' || c == '?' || c == ';') {
            if (strlen(str) != 0) {
                word_t *word = word_new(str);
                sentence_add(currSentence, word);
                free (str);
                word_free (word);
                str = strnew();
            }
        }
        if (c == EOF || c == '.' || c == '!' || c == '?') {
            text_add (text, currSentence);
            sentence_free(currSentence);
            currSentence = sentence_create();
        }
        if (c == EOF) break;
        if (isalpha(c)) {
            c = tolower(c);
            char *w = stradd(str, c);
            free (str);
            str = w;
        }
    }
    fclose (input);
    FILE *output;
    output = fopen("result.txt", "w");
    input = fopen ("stopwords.txt", "r");

    int stopCount, i;
    fscanf (input, "%d", &stopCount);
    for (i = 0; i < stopCount; i++) {
        char s[15];
        fscanf (input, "%s", s);
        fprintf (output, "%s: %d\n", s, text_find (text, s));
    }

    fclose (input);
    fclose (output);
    free (str);
    sentence_free(currSentence);
    text_free(text);
    return 0;
}
Exemplo n.º 12
0
static void insert_oneSentence_countOnePlaceZeroFormatTwo(void **state)
{
    text_t * text = text_new();

    int place = 0, format = 2;
    char sentence[L];
    strcpy (sentence, "Zhenya");

    text_insert (text, place, sentence, format);
    assert_int_equal (text_getCount(text), 1);
    assert_int_equal (text_getFormat(text, place), format);
    assert_string_equal (text_getString(text, place), sentence);
    text_free(text);
}
Exemplo n.º 13
0
END_TEST

START_TEST (test_text_line)
{
  text *text;
  int i;
  char buf[128];
  const char *p;
  int ret;
  int len;

  text = text_create ();
  fail_unless (text != NULL);

  for (i = 0; i < 120; i++)
    {
      sprintf (buf, "Line nr %d", i);
      ret = text_add_line (text, buf);
      fail_unless (ret == i + 1);
      fail_unless (text_nr_of_lines (text) == i + 1);
    }

  for (i = 0; i < 120; i++)
    {
      sprintf (buf, "Line nr %d", i);
      p = text_get_line (text, i, &len);
      fail_unless (p != NULL);
      fail_unless (strlen (buf) == len);
      fail_unless (strcmp (p, buf) == 0);
    }
  p = text_get_line (text, 500, &len);
  fail_unless (p == NULL);
  p = text_get_line (text, -50, &len);
  fail_unless (p == NULL);

  text_clear (text);
  fail_unless (text_nr_of_lines (text) == 0);
  ret = text_add_line (text, "\001");
  fail_unless (ret < 0);
  fail_unless (text_nr_of_lines (text) == 0);
  ret = text_add_line (text, "\t");
  fail_unless (ret == 1);
  fail_unless (text_nr_of_lines (text) == 1);
  p = text_get_line (text, 0, &len);
  fail_unless (p != NULL);
  fail_unless (len == 2);
  fail_unless (strcmp (p, "  ") == 0);

  text_free (text);
}
Exemplo n.º 14
0
static void delete_hasOneInertedSentence_CountZero(void **state)
{
    text_t * text = text_new();

    int place = 0, format = 2;
    char sentence[L];
    strcpy (sentence, "Zhenya");

    text_insert (text, place, sentence, format);

    text_delete (text, place);

    assert_int_equal(text_getCount(text), 0);
    text_free(text);
}
Exemplo n.º 15
0
static void file_free(Editor *ed, File *file) {
	if (!file)
		return;
	if (--file->refcount > 0)
		return;
	
	text_free(file->text);
	
	if (file->prev)
		file->prev->next = file->next;
	if (file->next)
		file->next->prev = file->prev;
	if (ed->files == file)
		ed->files = file->next;
	free(file);
}
Exemplo n.º 16
0
void free_graphic(void) {
	window* window_handle = global_get(global_get_singleton(), GLOBAL_WINDOW);
	hl_render* hl_render_handle = global_get(global_get_singleton(), GLOBAL_HL_RENDER);
	camera* camera_handle = global_get(global_get_singleton(), GLOBAL_CAMERA);
	input* input_handle = global_get(global_get_singleton(), GLOBAL_INPUT);
	shader* shader_texture_handle = global_get(global_get_singleton(), GLOBAL_SHADER_TEXTURE);
	text* text_handle = global_get(global_get_singleton(), GLOBAL_TEXT);
	debug_draw* debug_draw_handle = global_get(global_get_singleton(), GLOBAL_DEBUG_DRAW);

	window_free(&window_handle);
	hl_render_free(&hl_render_handle);
	camera_free(&camera_handle);
	input_free(&input_handle);
	shader_free(&shader_texture_handle);
	text_free(&text_handle);
	debug_draw_free(&debug_draw_handle);
}
Exemplo n.º 17
0
int main(){
    const char name[] = "text.txt";
    FILE * file;
    file = fopen(name, "r");
    if(NULL == file)
        return 1;
    char c;
    int len = 0;
    char word[25] = "";
    text_t * text = text_new();
    sen_t * sen = sen_new();
    while((c = fgetc(file)) != EOF){
        //printf("%c", c);
        if(ispunct(c)){
            if(c == '.' || c == '!' || c == '?'){
                if(len == 0)
                    continue;
                addWord(sen, word_new(word));
                addSen(text, sen);
                sen = sen_new();
                memset(word, 0, 25);
                len = 0;
            }
            continue;
        }
        else if(isspace(c)){
            if(len == 0)
                continue;
            addWord(sen, word_new(word));
            memset(word, 0, 25);
            len = 0;
        }
        else{
            word[len] = c;
            len++;
        }
    }

    fclose(file);
    fprint(text);
    text_free(text);
    return 0;
}
Exemplo n.º 18
0
/* Free the given fragment and all storage to which it points. */
static void fragment_free(struct code_fragment *fragment)
{
	assert(fragment->type > FRAGMENT_NONE);
	assert(fragment->type < FRAGMENT_NUM_TYPES);
	switch (fragment->type) {
	case FRAGMENT_NONE:
	case FRAGMENT_NUM_TYPES:
		assert(!"bad code fragment type");
		break;
	case FRAGMENT_TEXT:
		text_free(fragment->contents.text);
		break;
	case FRAGMENT_DATA:
		data_free(fragment->contents.data);
		break;
	/* omitting default so compiler catches missing cases */
	}
	free(fragment);
}
Exemplo n.º 19
0
Arquivo: vis.c Projeto: ewqasd200g/vis
static void file_free(Vis *vis, File *file) {
	if (!file)
		return;
	if (file->refcount > 1) {
		--file->refcount;
		return;
	}
	if (!file->internal && vis->event && vis->event->file_close)
		vis->event->file_close(vis, file);
	text_free(file->text);
	free((char*)file->name);

	if (file->prev)
		file->prev->next = file->next;
	if (file->next)
		file->next->prev = file->prev;
	if (vis->files == file)
		vis->files = file->next;
	free(file);
}
Exemplo n.º 20
0
int main()
{
    FILE * input = file_new("input.txt","r");
    FILE * output = file_new("output.txt","w");
    char buffer[100000];
    sentence_t * sentence;
    word_t * word;
    fread(buffer,1,100000,input);
    text_t * text = text_new(buffer);
    removeSymbols(buffer);
    text_divide(text);
    int sentences_count = text_getSentencesCount(text);
    for (int i = 0; i < sentences_count; i++)
    {
        sentence = text_getSentence(text,i);
        sentence_divide(sentence);
        int words_count = sentence_getWordsCount(sentence);
        if (words_count < 5) sentence_deleteSentence(sentence);
        else {

                for (int j = 0; j < words_count; j++)
                {
                    word = sentence_getWords(sentence,j);
                    if (word_getWord(word) != NULL) fprintf(output,"%s,",word_getWord(word));
                }

        fprintf(output,"\n");
        }


    }
    word_free(word);
    sentence_free(sentence);
    text_free(text);
    file_free(input);
    file_free(output);
    printf("DONE");
    return 0;
}
Exemplo n.º 21
0
Arquivo: vis.c Projeto: 5paceToast/vis
static File *file_new(Vis *vis, const char *name) {
	char *name_absolute = NULL;
	if (name) {
		if (!(name_absolute = absolute_path(name)))
			return NULL;
		File *existing = NULL;
		/* try to detect whether the same file is already open in another window
		 * TODO: do this based on inodes */
		for (File *file = vis->files; file; file = file->next) {
			if (file->name && strcmp(file->name, name_absolute) == 0) {
				existing = file;
				break;
			}
		}
		if (existing) {
			free(name_absolute);
			return existing;
		}
	}

	File *file = NULL;
	Text *text = text_load(name);
	if (!text && name && errno == ENOENT)
		text = text_load(NULL);
	if (!text)
		goto err;
	if (!(file = file_new_text(vis, text)))
		goto err;
	file->name = name_absolute;
	if (!file->internal && vis->event && vis->event->file_open)
		vis->event->file_open(vis, file);
	return file;
err:
	free(name_absolute);
	text_free(text);
	file_free(vis, file);
	return NULL;
}
Exemplo n.º 22
0
void prepare_bpft(void)
{
    unsigned  udp10_mbs, udp10_mbc, udp11_mbs, udp11_mbc;
    text_list bpfl;
    text_ptr  text;
    size_t    len;

    /* Prepare the must-be-set and must-be-clear tests. */
    udp10_mbs = udp10_mbc = udp11_mbs = udp11_mbc = 0U;
    if ((dir_wanted & DIR_INITIATE) != 0) {
        if ((dir_wanted & DIR_RESPONSE) == 0)
            udp10_mbc |= UDP10_QR_MASK;
    } else if ((dir_wanted & DIR_RESPONSE) != 0) {
        udp10_mbs |= UDP10_QR_MASK;
    }
    if ((msg_wanted & MSG_UPDATE) != 0) {
        if ((msg_wanted & (MSG_QUERY | MSG_NOTIFY)) == 0)
            udp10_mbs |= (ns_o_update << UDP10_OP_SHIFT);
    } else if ((msg_wanted & MSG_NOTIFY) != 0) {
        if ((msg_wanted & (MSG_QUERY | MSG_UPDATE)) == 0)
            udp10_mbs |= (ns_o_notify << UDP10_OP_SHIFT);
    } else if ((msg_wanted & MSG_QUERY) != 0) {
        udp10_mbc |= UDP10_OP_MASK;
    }
    if (err_wanted == ERR_NO) {
        udp10_mbc |= UDP10_TC_MASK;
        udp11_mbc |= UDP11_RC_MASK;
    }

    /*
 * Model
 * (vlan) and (transport)
 * (vlan) and ((icmp) or (frags) or (dns))
 * (vlan) and ((icmp) or (frags) or ((ports) and (hosts)))
 * (vlan) and ((icmp) or (frags) or (((tcp) or (udp)) and (hosts)))
 * [(vlan) and] ( [(icmp) or] [(frags) or] ( ( [(tcp) or] (udp) ) [and (hosts)] ) )
 */

    /* Make a BPF program to do early course kernel-level filtering. */
    INIT_LIST(bpfl);
    len = 0;
    if (!EMPTY(vlans_excl))
        len += text_add(&bpfl, "vlan and ("); /* vlan and ( transports ...  */
    else
        len += text_add(&bpfl, "("); /* ( transports ...  */
    if (wanticmp) {
        len += text_add(&bpfl, " ( ip proto 1 or ip proto 58 ) or");
    }
    if (wantfrags) {
        len += text_add(&bpfl, " ( ip[6:2] & 0x1fff != 0 or ip6[6] = 44 ) or");
    }
    len += text_add(&bpfl, " ("); /* ( dns ...  */
    len += text_add(&bpfl, " ("); /* ( ports ...  */
    if (wanttcp) {
        len += text_add(&bpfl, " ( tcp port %d ) or", dns_port);
        /* tcp packets can be filtered by initiators/responders, but
         * not mbs/mbc. */
    }
    len += text_add(&bpfl, " ( udp port %d", dns_port);
    if (!v6bug) {
        if (udp10_mbc != 0)
            len += text_add(&bpfl, " and udp[10] & 0x%x = 0",
                udp10_mbc);
        if (udp10_mbs != 0)
            len += text_add(&bpfl, " and udp[10] & 0x%x = 0x%x",
                udp10_mbs, udp10_mbs);
        if (udp11_mbc != 0)
            len += text_add(&bpfl, " and udp[11] & 0x%x = 0",
                udp11_mbc);
        /* Dead code, udp11_mbs never set
        if (udp11_mbs != 0)
            len += text_add(&bpfl, " and udp[11] & 0x%x = 0x%x",
                    udp11_mbs, udp11_mbs);
*/

        if (err_wanted != ERR_NO) {
            len += text_add(&bpfl, " and (");
            if ((err_wanted & ERR_TRUNC) != 0) {
                len += text_add(&bpfl, " udp[10] & 0x%x = 0x%x or", UDP10_TC_MASK, UDP10_TC_MASK);
            }
            len += text_add(&bpfl, " 0x%x << (udp[11] & 0xf) & 0x%x != 0 )", ERR_RCODE_BASE, err_wanted);
        }
    }
    len += text_add(&bpfl, " )"); /*  ... udp 53 ) */
    len += text_add(&bpfl, " )"); /*  ... ports ) */
    if (options.bpf_hosts_apply_all) {
        len += text_add(&bpfl, " )"); /*  ... dns ) */
        len += text_add(&bpfl, " )"); /* ... transport ) */
    }
    if (!EMPTY(initiators) || !EMPTY(responders)) {
        const char* or = "or", *lp = "(", *sep;
        endpoint_ptr ep;

        len += text_add(&bpfl, " and host");
        sep = lp;
        for (ep = HEAD(initiators);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        for (ep = HEAD(responders);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        len += text_add(&bpfl, " )");
    }
    if (!EMPTY(not_initiators) || !EMPTY(not_responders)) {
        const char* or = "or", *lp = "(", *sep;
        endpoint_ptr ep;

        len += text_add(&bpfl, " and not host");
        sep = lp;
        for (ep = HEAD(not_initiators);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        for (ep = HEAD(not_responders);
             ep != NULL;
             ep = NEXT(ep, link)) {
            len += text_add(&bpfl, " %s %s", sep, ia_str(ep->ia));
            sep = or ;
        }
        len += text_add(&bpfl, " )");
    }
    if (!options.bpf_hosts_apply_all) {
        len += text_add(&bpfl, " )"); /*  ... dns ) */
        len += text_add(&bpfl, " )"); /* ... transport ) */
    }
    if (extra_bpf)
        len += text_add(&bpfl, " and ( %s )", extra_bpf);

    bpft = calloc(len + 1, sizeof(char));
    assert(bpft != NULL);
    for (text = HEAD(bpfl);
         text != NULL;
         text = NEXT(text, link))
        strcat(bpft, text->text);
    text_free(&bpfl);
    if (!EMPTY(vlans_incl)) {
        static char* bpft_vlan;
        len       = (2 * strlen(bpft)) + 64; /* add enough for the extra in snprintf() below */
        bpft_vlan = calloc(len, sizeof(char));
        assert(bpft_vlan != NULL);
        snprintf(bpft_vlan, len, "( %s ) or ( vlan and ( %s ) )", bpft, bpft);
        bpft = realloc(bpft, len);
        assert(bpft != NULL);
        strcpy(bpft, bpft_vlan);
        free(bpft_vlan);
    }
    if (dumptrace >= 1)
        fprintf(stderr, "%s: \"%s\"\n", ProgramName, bpft);
}
Exemplo n.º 23
0
END_TEST

START_TEST (test_text_load)
{
  text *text;
  int i;
  int ret;
  char buf[64];
  const char *p;
  int len;

  text = text_load_file (CONFDIR "/text_WRONG.txt");
  fail_unless (text == NULL);

  text = text_load_file (CONFDIR "/text_test.txt");
  fail_unless (text != NULL);
  for (i = 0; i < 120; i++)
    {
      sprintf (buf, "  Line %d", i);
      p = text_get_line (text, i, &len);
      fail_unless (p != NULL);
      fail_unless (strlen (buf) == len, "%d len = %d != %d", i, len,
		   strlen (buf));
      fail_unless (strcmp (p, buf) == 0);
    }
  fail_unless (text_nr_of_lines (text) == 120);

  text_clear (text);
  fail_unless (text_nr_of_lines (text) == 0);

  ret = text_update_from_file (text, CONFDIR "/text_WRONG.txt");
  fail_unless (ret < 0);

  ret = text_update_from_file (text, CONFDIR "/text_test.txt");
  fail_unless (ret == 0);
  for (i = 0; i < 120; i++)
    {
      sprintf (buf, "  Line %d", i);
      p = text_get_line (text, i, &len);
      fail_unless (p != NULL);
      fail_unless (strlen (buf) == len);
      fail_unless (strcmp (p, buf) == 0);
    }
  fail_unless (text_nr_of_lines (text) == 120);

  ret = text_update_from_file (text, CONFDIR "/text_test.txt");
  fail_unless (ret == 0);
  for (i = 0; i < 120; i++)
    {
      sprintf (buf, "  Line %d", i);
      p = text_get_line (text, i, &len);
      fail_unless (p != NULL);
      fail_unless (strlen (buf) == len);
      fail_unless (strcmp (p, buf) == 0);
    }
  fail_unless (text_nr_of_lines (text) == 120);

  ret = text_update_from_file (text, CONFDIR "/text_test_bad.txt");
  fail_unless (ret < 0);

  text_free (text);
}
Exemplo n.º 24
0
/*
 * v_replace -- [count]r<char>
 *
 * !!!
 * The r command in historic vi was almost beautiful in its badness.  For
 * example, "r<erase>" and "r<word erase>" beeped the terminal and deleted
 * a single character.  "Nr<carriage return>", where N was greater than 1,
 * inserted a single carriage return.  "r<escape>" did cancel the command,
 * but "r<literal><escape>" erased a single character.  To enter a literal
 * <literal> character, it required three <literal> characters after the
 * command.  This may not be right, but at least it's not insane.
 *
 * PUBLIC: int v_replace __P((SCR *, VICMD *));
 */
int
v_replace(SCR *sp, VICMD *vp)
{
	EVENT ev;
	VI_PRIVATE *vip;
	TEXT *tp;
	size_t blen, len;
	u_long cnt;
	int quote, rval;
	CHAR_T *bp;
	CHAR_T *p;

	vip = VIP(sp);

	/*
	 * If the line doesn't exist, or it's empty, replacement isn't
	 * allowed.  It's not hard to implement, but:
	 *
	 *	1: It's historic practice (vi beeped before the replacement
	 *	   character was even entered).
	 *	2: For consistency, this change would require that the more
	 *	   general case, "Nr", when the user is < N characters from
	 *	   the end of the line, also work, which would be a bit odd.
	 *	3: Replacing with a <newline> has somewhat odd semantics.
	 */
	if (db_get(sp, vp->m_start.lno, DBG_FATAL, &p, &len))
		return (1);
	if (len == 0) {
		msgq(sp, M_BERR, "186|No characters to replace");
		return (1);
	}

	/*
	 * Figure out how many characters to be replace.  For no particular
	 * reason (other than that the semantics of replacing the newline
	 * are confusing) only permit the replacement of the characters in
	 * the current line.  I suppose we could append replacement characters
	 * to the line, but I see no compelling reason to do so.  Check this
	 * before we get the character to match historic practice, where Nr
	 * failed immediately if there were less than N characters from the
	 * cursor to the end of the line.
	 */
	cnt = F_ISSET(vp, VC_C1SET) ? vp->count : 1;
	vp->m_stop.lno = vp->m_start.lno;
	vp->m_stop.cno = vp->m_start.cno + cnt - 1;
	if (vp->m_stop.cno > len - 1) {
		v_eol(sp, &vp->m_start);
		return (1);
	}

	/*
	 * If it's not a repeat, reset the current mode and get a replacement
	 * character.
	 */
	quote = 0;
	if (!F_ISSET(vp, VC_ISDOT)) {
		sp->showmode = SM_REPLACE;
		if (vs_refresh(sp, 0))
			return (1);
next:		if (v_event_get(sp, &ev, 0, 0))
			return (1);

		switch (ev.e_event) {
		case E_CHARACTER:
			/*
			 * <literal_next> means escape the next character.
			 * <escape> means they changed their minds.
			 */
			if (!quote) {
				if (ev.e_value == K_VLNEXT) {
					quote = 1;
					goto next;
				}
				if (ev.e_value == K_ESCAPE)
					return (0);
			}
			vip->rlast = ev.e_c;
			vip->rvalue = ev.e_value;
			break;
		case E_ERR:
		case E_EOF:
			F_SET(sp, SC_EXIT_FORCE);
			return (1);
		case E_INTERRUPT:
			/* <interrupt> means they changed their minds. */
			return (0);
		case E_WRESIZE:
			/* <resize> interrupts the input mode. */
			v_emsg(sp, NULL, VIM_WRESIZE);
			return (0);
		case E_REPAINT:
			if (vs_repaint(sp, &ev))
				return (1);
			goto next;
		default:
			v_event_err(sp, &ev);
			return (0);
		}
	}

	/* Copy the line. */
	GET_SPACE_RETW(sp, bp, blen, len);
	MEMMOVE(bp, p, len);
	p = bp;

	/*
	 * Versions of nvi before 1.57 created N new lines when they replaced
	 * N characters with <carriage-return> or <newline> characters.  This
	 * is different from the historic vi, which replaced N characters with
	 * a single new line.  Users complained, so we match historic practice.
	 */
	if ((!quote && vip->rvalue == K_CR) || vip->rvalue == K_NL) {
		/* Set return line. */
		vp->m_stop.lno = vp->m_start.lno + 1;
		vp->m_stop.cno = 0;

		/* The first part of the current line. */
		if (db_set(sp, vp->m_start.lno, p, vp->m_start.cno))
			goto err_ret;

		/*
		 * The rest of the current line.  And, of course, now it gets
		 * tricky.  If there are characters left in the line and if
		 * the autoindent edit option is set, white space after the
		 * replaced character is discarded, autoindent is applied, and
		 * the cursor moves to the last indent character.
		 */
		p += vp->m_start.cno + cnt;
		len -= vp->m_start.cno + cnt;
		if (len != 0 && O_ISSET(sp, O_AUTOINDENT))
			for (; len && isblank(*p); --len, ++p);

		if ((tp = text_init(sp, p, len, len)) == NULL)
			goto err_ret;

		if (len != 0 && O_ISSET(sp, O_AUTOINDENT)) {
			if (v_txt_auto(sp, vp->m_start.lno, NULL, 0, tp))
				goto err_ret;
			vp->m_stop.cno = tp->ai ? tp->ai - 1 : 0;
		} else
			vp->m_stop.cno = 0;

		vp->m_stop.cno = tp->ai ? tp->ai - 1 : 0;
		if (db_append(sp, 1, vp->m_start.lno, tp->lb, tp->len))
err_ret:		rval = 1;
		else {
			text_free(tp);
			rval = 0;
		}
	} else {
		STRSET(bp + vp->m_start.cno, vip->rlast, cnt);
		rval = db_set(sp, vp->m_start.lno, bp, len);
	}
	FREE_SPACEW(sp, bp, blen);

	vp->m_final = vp->m_stop;
	return (rval);
}
Exemplo n.º 25
0
/**
 * @brief ui_loop_ggs
 *
 * GGS main loop. Here the input from both the user and
 * GGS server is interpreted.
 *
 * @param ui User Interface.
 */
void ui_loop_ggs(UI *ui) {
	char *cmd = NULL, *param = NULL;
	Text text[1];
	GGSClient *client = ui->ggs;

	ui->mode = 3;

	text_init(text);
	for (;;) {
		relax(10);

		/* look for a user event */
		if (ui_event_peek(ui, &cmd, &param)) {
			/* stop the search */
			if (strcmp(cmd, "stop") == 0) { 
				if (ui->play[0].state == IS_THINKING) play_stop(ui->play);
				else if (ui->play[1].state == IS_THINKING) play_stop(ui->play + 1);

			/* repeat a cmd <n> times */			
			} else if (strcmp(cmd, "loop") == 0) { 
				free(client->loop->cmd);
				errno = 0;
				client->loop->cmd = string_duplicate(parse_int(param, &client->loop->i));
				if (errno) client->loop->i = 100;
				if (client->loop->i > 0) {
					info("<loop %d>\n", client->loop->i);
					--client->loop->i;
					ggs_client_send(client, "%s\n", client->loop->cmd);
				}

			/* exit from ggs */
			} else if (strcmp(cmd, "quit") == 0 || strcmp(cmd, "q") == 0) { 
				ggs_client_send(client, "tell .%s Bye bye!\n", client->me);
				ggs_client_send(client, "quit\n");
				free(cmd); free(param);
				return;

			/* send the command to ggs */
			} else {
				ggs_client_send(client, "%s %s\n", cmd, param);
			}
		}
		
		/* stay on line... */
		ggs_client_refresh(client);

		/* look for a ggs event */
		if (!ggs_event_peek(&client->event, text)) {
			continue;
		}

		text_print(text, stdout);
		if (ggs_log->f) text_print(text, ggs_log->f);

		/* login */
		if (ggs_login(text)) {
			ggs_client_send(client, "%s\n", options.ggs_login);

		/* password */
		} else if (ggs_password(text)) {
			ggs_client_send(client, "%s\n", options.ggs_password);

			ggs_client_send(client, "vt100 -\n");
			ggs_client_send(client, "bell -t -tc -tg -n -nc -ng -ni -nn\n");
			ggs_client_send(client, "verbose -news -faq -help -ack\n");
			ggs_client_send(client, "chann %%\n");
			ggs_client_send(client, "chann + .chat\n");
			ggs_client_send(client, "chann + .%s\n", client->me);
			ggs_client_send(client, "tell .%s Hello!\n", client->me);

		/* os on */
		} else if (ggs_os_on(text)) {
			printf("[received GGS_OS_ON]\n");
			ggs_client_send(client, "tell /os trust +\n" );
			ggs_client_send(client, "tell /os rated +\n" );
			ggs_client_send(client, "tell /os request +\n" );
			ggs_client_send(client, "tell /os client -\n" );
			ggs_client_send(client, "tell /os open %d\n", options.ggs_open);
			ggs_client_send(client, "mso\n" );
	
		/* os off */
		} else if (ggs_os_off(text)) {
			printf("[received GGS_OS_OFF]\n");

		/* match on */
		} else if (ggs_match_on(client->match_on, text)) {
			if (ggs_has_player(client->match_on->player, client->me)) {
				printf("[received GGS_MATCH_ON]\n");
				client->is_playing = true;
				ggs_client_send(client, "tell /os open 0\n" );
			} else {
				printf("[received GGS_WATCH_ON]\n");
			}

		/* match off */
		} else if (ggs_match_off(client->match_off, text)) {
			if (ggs_has_player(client->match_off->player, client->me)) {
				printf("[received GGS_MATCH_OFF]\n");

				if (!client->match_on->match_type->is_rand) {
					if (client->match_on->match_type->is_synchro) {
						printf("[store match #1]\n");
						play_store(ui->play);
						printf("[store match #2]\n");
						play_store(ui->play + 1);
					} else {
						printf("[store match]\n");
						play_store(ui->play);
					}
					if (ui->book->need_saving) {
						book_save(ui->book, options.book_file);
						ui->book->need_saving = false;
					}
				}

				client->is_playing = false;
				ggs_client_send(client, "tell /os open %d\n", options.ggs_open);
				if (client->loop->i > 0) {
					info("<loop %d>\n", client->loop->i);
					--client->loop->i;
					client->loop->delay = 10000 + real_clock(); // wait 10 sec.
				}
			} else {
				printf("[received GGS_WATCH_OFF]\n");
			}

		/* board join/update */
		} else if (ggs_board(client->board,  text)) {
			if (ggs_has_player(client->board->player, client->me)) {
				if (client->board->is_join) ui_ggs_join(ui);
				else ui_ggs_update(ui);
			} else {
				printf("[received GGS_WATCH_BOARD]\n");
			}

		/* request */
		} else if (ggs_request(client->request, text)) {
			printf("[received GGS_REQUEST]\n");

		/* admin on */
		} else if (ggs_admin(client->admin, text)) {
			printf("[received GGS_ADMIN_CMD]\n");
			ggs_client_send(client, client->admin->command);
			ggs_client_send(client, "\ntell %s command processed\n", client->admin->name);

		/* To request Saio a game later */
		} else if (ggs_saio_delay(text, &client->once->delay)) {
			printf("[received GGS_SAIO_DELAY]\n");
			free(client->once->cmd); client->once->cmd = NULL;
			if (cmd != NULL && param != NULL) {
				if (strcmp(cmd, "loop") == 0) {
					client->once->cmd = string_duplicate(client->loop->cmd);
				} else {
					client->once->cmd = (char*) malloc(strlen(cmd) + strlen(param) + 3);
					sprintf(client->once->cmd, "%s %s\n", cmd, param);
				}	
				printf("[received GGS_SAIO_DELAY, retry request in %.1f s]\n", 0.001 * (client->once->delay - real_clock()));
			} else {
				client->once->delay = 0;
			}

		/* READY */
		} else if (ggs_ready(text)) {

		/* ALERT */
		} else if (ggs_alert(text)) {
			printf("[received ALERT]\n");

		/* Other messages */
		} else {
		}
		text_free(text);
	}
}
Exemplo n.º 26
0
/*
 * ex_txt --
 *	Get lines from the terminal for ex.
 *
 * PUBLIC: int ex_txt(SCR *, TEXTH *, ARG_CHAR_T, u_int32_t);
 */
int
ex_txt(SCR *sp, TEXTH *tiqh, ARG_CHAR_T prompt, u_int32_t flags)
{
	EVENT ev;
	GS *gp;
	TEXT ait, *ntp, *tp;
	carat_t carat_st;
	size_t cnt;
	int rval;
	int nochange;

	rval = 0;

	/*
	 * Get a TEXT structure with some initial buffer space, reusing the
	 * last one if it's big enough.  (All TEXT bookkeeping fields default
	 * to 0 -- text_init() handles this.)
	 */
	if (!TAILQ_EMPTY(tiqh)) {
		tp = TAILQ_FIRST(tiqh);
		if (TAILQ_NEXT(tp, q) != NULL || tp->lb_len < 32) {
			text_lfree(tiqh);
			goto newtp;
		}
		tp->len = 0;
	} else {
newtp:		if ((tp = text_init(sp, NULL, 0, 32)) == NULL)
			goto err;
		TAILQ_INSERT_HEAD(tiqh, tp, q);
	}

	/* Set the starting line number. */
	tp->lno = sp->lno + 1;

	/*
	 * If it's a terminal, set up autoindent, put out the prompt, and
	 * set it up so we know we were suspended.  Otherwise, turn off
	 * the autoindent flag, as that requires less special casing below.
	 *
	 * XXX
	 * Historic practice is that ^Z suspended command mode (but, because
	 * it ran in cooked mode, it was unaffected by the autowrite option.)
	 * On restart, any "current" input was discarded, whether in insert
	 * mode or not, and ex was in command mode.  This code matches historic
	 * practice, but not 'cause it's easier.
	 */
	gp = sp->gp;
	if (F_ISSET(gp, G_SCRIPTED))
		LF_CLR(TXT_AUTOINDENT);
	else {
		if (LF_ISSET(TXT_AUTOINDENT)) {
			LF_SET(TXT_EOFCHAR);
			if (v_txt_auto(sp, sp->lno, NULL, 0, tp))
				goto err;
		}
		txt_prompt(sp, tp, prompt, flags);
	}

	for (carat_st = C_NOTSET, nochange = 0;;) {
		if (v_event_get(sp, &ev, 0, 0))
			goto err;

		/* Deal with all non-character events. */
		switch (ev.e_event) {
		case E_CHARACTER:
			break;
		case E_ERR:
			goto err;
		case E_REPAINT:
		case E_WRESIZE:
			continue;
		case E_EOF:
			rval = 1;
			/* FALLTHROUGH */
		case E_INTERRUPT:
			/*
			 * Handle EOF/SIGINT events by discarding partially
			 * entered text and returning.  EOF returns failure,
			 * E_INTERRUPT returns success.
			 */
			goto notlast;
		default:
			v_event_err(sp, &ev);
			goto notlast;
		}

		/*
		 * Deal with character events.
		 *
		 * Check to see if the character fits into the input buffer.
		 * (Use tp->len, ignore overwrite and non-printable chars.)
		 */
		BINC_GOTOW(sp, tp->lb, tp->lb_len, tp->len + 1);

		switch (ev.e_value) {
		case K_CR:
			/*
			 * !!!
			 * Historically, <carriage-return>'s in the command
			 * weren't special, so the ex parser would return an
			 * unknown command error message.  However, if they
			 * terminated the command if they were in a map.  I'm
			 * pretty sure this still isn't right, but it handles
			 * what I've seen so far.
			 */
			if (!F_ISSET(&ev.e_ch, CH_MAPPED))
				goto ins_ch;
			/* FALLTHROUGH */
		case K_NL:
			/*
			 * '\' can escape <carriage-return>/<newline>.  We
			 * don't discard the backslash because we need it
			 * to get the <newline> through the ex parser.
			 */
			if (LF_ISSET(TXT_BACKSLASH) &&
			    tp->len != 0 && tp->lb[tp->len - 1] == '\\')
				goto ins_ch;

			/*
			 * CR returns from the ex command line.
			 *
			 * XXX
			 * Terminate with a nul, needed by filter.
			 */
			if (LF_ISSET(TXT_CR)) {
				tp->lb[tp->len] = '\0';
				goto done;
			}

			/*
			 * '.' may terminate text input mode; free the current
			 * TEXT.
			 */
			if (LF_ISSET(TXT_DOTTERM) && tp->len == tp->ai + 1 &&
			    tp->lb[tp->len - 1] == '.') {
notlast:			TAILQ_REMOVE(tiqh, tp, q);
				text_free(tp);
				goto done;
			}

			/* Set up bookkeeping for the new line. */
			if ((ntp = text_init(sp, NULL, 0, 32)) == NULL)
				goto err;
			ntp->lno = tp->lno + 1;

			/*
			 * Reset the autoindent line value.  0^D keeps the ai
			 * line from changing, ^D changes the level, even if
			 * there were no characters in the old line.  Note, if
			 * using the current tp structure, use the cursor as
			 * the length, the autoindent characters may have been
			 * erased.
			 */
			if (LF_ISSET(TXT_AUTOINDENT)) {
				if (nochange) {
					nochange = 0;
					if (v_txt_auto(sp,
					    OOBLNO, &ait, ait.ai, ntp))
						goto err;
					free(ait.lb);
				} else
					if (v_txt_auto(sp,
					    OOBLNO, tp, tp->len, ntp))
						goto err;
				carat_st = C_NOTSET;
			}
			txt_prompt(sp, ntp, prompt, flags);

			/*
			 * Swap old and new TEXT's, and insert the new TEXT
			 * into the queue.
			 */
			tp = ntp;
			TAILQ_INSERT_TAIL(tiqh, tp, q);
			break;
		case K_CARAT:			/* Delete autoindent chars. */
			if (tp->len <= tp->ai && LF_ISSET(TXT_AUTOINDENT))
				carat_st = C_CARATSET;
			goto ins_ch;
		case K_ZERO:			/* Delete autoindent chars. */
			if (tp->len <= tp->ai && LF_ISSET(TXT_AUTOINDENT))
				carat_st = C_ZEROSET;
			goto ins_ch;
		case K_CNTRLD:			/* Delete autoindent char. */
			/*
			 * !!!
			 * Historically, the ^D command took (but then ignored)
			 * a count.  For simplicity, we don't return it unless
			 * it's the first character entered.  The check for len
			 * equal to 0 is okay, TXT_AUTOINDENT won't be set.
			 */
			if (LF_ISSET(TXT_CNTRLD)) {
				for (cnt = 0; cnt < tp->len; ++cnt)
					if (!isblank(tp->lb[cnt]))
						break;
				if (cnt == tp->len) {
					tp->len = 1;
					tp->lb[0] = ev.e_c;
					tp->lb[1] = '\0';

					/*
					 * Put out a line separator, in case
					 * the command fails.
					 */
					(void)putchar('\n');
					goto done;
				}
			}

			/*
			 * POSIX 1003.1b-1993, paragraph 7.1.1.9, states that
			 * the EOF characters are discarded if there are other
			 * characters to process in the line, i.e. if the EOF
			 * is not the first character in the line.  For this
			 * reason, historic ex discarded the EOF characters,
			 * even if occurring in the middle of the input line.
			 * We match that historic practice.
			 *
			 * !!!
			 * The test for discarding in the middle of the line is
			 * done in the switch, because the CARAT forms are N+1,
			 * not N.
			 *
			 * !!!
			 * There's considerable magic to make the terminal code
			 * return the EOF character at all.  See that code for
			 * details.
			 */
			if (!LF_ISSET(TXT_AUTOINDENT) || tp->len == 0)
				continue;
			switch (carat_st) {
			case C_CARATSET:		/* ^^D */
				if (tp->len > tp->ai + 1)
					continue;

				/* Save the ai string for later. */
				ait.lb = NULL;
				ait.lb_len = 0;
				BINC_GOTOW(sp, ait.lb, ait.lb_len, tp->ai);
				MEMCPY(ait.lb, tp->lb, tp->ai);
				ait.ai = ait.len = tp->ai;

				carat_st = C_NOTSET;
				nochange = 1;
				goto leftmargin;
			case C_ZEROSET:			/* 0^D */
				if (tp->len > tp->ai + 1)
					continue;

				carat_st = C_NOTSET;
leftmargin:			(void)gp->scr_ex_adjust(sp, EX_TERM_CE);
				tp->ai = tp->len = 0;
				break;
			case C_NOTSET:			/* ^D */
				if (tp->len > tp->ai)
					continue;

				if (txt_dent(sp, tp))
					goto err;
				break;
			default:
				abort();
			}

			/* Clear and redisplay the line. */
			(void)gp->scr_ex_adjust(sp, EX_TERM_CE);
			txt_prompt(sp, tp, prompt, flags);
			break;
		default:
			/*
			 * See the TXT_BEAUTIFY comment in vi/v_txt_ev.c.
			 *
			 * Silently eliminate any iscntrl() character that was
			 * not already handled specially, except for <tab> and
			 * <ff>.
			 */
ins_ch:			if (LF_ISSET(TXT_BEAUTIFY) && ISCNTRL(ev.e_c) &&
			    ev.e_value != K_FORMFEED && ev.e_value != K_TAB)
				break;

			tp->lb[tp->len++] = ev.e_c;
			break;
		}
	}
	/* NOTREACHED */

done:	return (rval);

err:	
alloc_err:
	return (1);
}
Exemplo n.º 27
0
// unit-test function
static void new_void_zeroCount(void **state)
{
    text_t * text = text_new();
    assert_int_equal(text_getCount(text), 0);
    text_free(text);
}