Docsity

Sintaxis de resaltado de código en un editor de texto, Exámenes de Programación C

Toggle sidebar
bg1
#define KILO_VERSION "0.0.1"
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <termios.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h>
/* Syntax highlight types */
#define HL_NORMAL 0
#define HL_NONPRINT 1
#define HL_COMMENT 2 /* Single line comment. */
#define HL_MLCOMMENT 3 /* Multi-line comment. */
#define HL_KEYWORD1 4
#define HL_KEYWORD2 5
#define HL_STRING 6
#define HL_NUMBER 7
#define HL_MATCH 8 /* Search match. */
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57

Vista previa parcial del texto

¡Descarga Sintaxis de resaltado de código en un editor de texto y más Exámenes en PDF de Programación C solo en Docsity!

#define KILO_VERSION "0.0.1" #define _BSD_SOURCE #define _GNU_SOURCE #include <termios.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/time.h> #include <unistd.h> #include <stdarg.h> #include <fcntl.h> /* Syntax highlight types / #define HL_NORMAL 0 #define HL_NONPRINT 1 #define HL_COMMENT 2 / Single line comment. / #define HL_MLCOMMENT 3 / Multi-line comment. / #define HL_KEYWORD1 4 #define HL_KEYWORD2 5 #define HL_STRING 6 #define HL_NUMBER 7 #define HL_MATCH 8 / Search match. */

#define HL_HIGHLIGHT_STRINGS (1<<0) #define HL_HIGHLIGHT_NUMBERS (1<<1) struct editorSyntax { char **filematch; char *keywords; char singleline_comment_start[2]; char multiline_comment_start[3]; char multiline_comment_end[3]; int flags; }; / This structure represents a single line of the file we are editing. / typedef struct erow { int idx; / Row index in the file, zero-based. / int size; / Size of the row, excluding the null term. / int rsize; / Size of the rendered row. */ char chars; / Row content. / char render; / Row content "rendered" for screen (for TABs). / unsigned char hl; / Syntax highlight type for each character in render./ int hl_oc; / Row had open comment at end in last syntax highlight check. */ } erow; typedef struct hlcolor { int r,g,b; } hlcolor;

CTRL_U = 21, /* Ctrl-u / ESC = 27, / Escape / BACKSPACE = 127, / Backspace / / The following are just soft codes, not really reported by the

  • terminal directly. */ ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, DEL_KEY, HOME_KEY, END_KEY, PAGE_UP, PAGE_DOWN }; void editorSetStatusMessage(const char fmt, ...); / =========================== Syntax highlights DB =========================
  • In order to add a new syntax, define two arrays with a list of file name
  • matches and keywords. The file name matches are used in order to match
  • a given syntax with a given file name: if a match pattern starts with a
  • dot, it is matched as the last past of the filename, for example ".c".
  • Otherwise the pattern is just searched inside the filenme, like "Makefile").
  • The list of keywords to highlight is just a list of words, however if they
  • a trailing '|' character is added at the end, they are highlighted in
  • a different color, so that you can have two different sets of keywords.
  • Finally add a stanza in the HLDB global variable with two two arrays
  • of strings, and a set of flags in order to enable highlighting of
  • comments and numbers.
  • The characters for single and multi line comments must be exactly two
  • and must be provided as well (see the C language example).
  • There is no support to highlight patterns currently. / / C / C++ */ char *C_HL_extensions[] = {".c",".cpp",NULL}; char C_HL_keywords[] = { / A few C / C++ keywords / "switch","if","while","for","break","continue","return","else", "struct","union","typedef","static","enum","class", / C types / "int|","long|","double|","float|","char|","unsigned|","signed|", "void|",NULL }; / Here we define an array of syntax highlights by extensions, keywords,
  • comments delimiters and flags. / struct editorSyntax HLDB[] = { { / C / C++ / C_HL_extensions, C_HL_keywords, "//","/","*/",

atexit(editorAtExit); if (tcgetattr(fd,&orig_termios) == -1) goto fatal; raw = orig_termios; /* modify the original mode / / input modes: no break, no CR to NL, no parity check, no strip char,

  • no start/stop output control. / raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); / output modes - disable post processing / raw.c_oflag &= ~(OPOST); / control modes - set 8 bit chars / raw.c_cflag |= (CS8); / local modes - choing off, canonical off, no extended functions,
  • no signal chars (^Z,^C) / raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); / control chars - set return condition: min number of bytes and timer. / raw.c_cc[VMIN] = 0; / Return each byte, or zero for timeout. / raw.c_cc[VTIME] = 1; / 100 ms timeout (unit is tens of second). / / put terminal in raw mode after flushing / if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal; E.rawmode = 1; return 0; fatal: errno = ENOTTY; return -1; } / Read a key from the terminal put in raw mode, trying to handle
  • escape sequences. / int editorReadKey(int fd) { int nread; char c, seq[3]; while ((nread = read(fd,&c,1)) == 0); if (nread == -1) exit(1); while(1) { switch(c) { case ESC: / escape sequence / / If this is just an ESC, we'll timeout here. / if (read(fd,seq,1) == 0) return ESC; if (read(fd,seq+1,1) == 0) return ESC; / ESC [ sequences. / if (seq[0] == '[') { if (seq[1] >= '0' && seq[1] <= '9') { / Extended escape, read additional byte. */ if (read(fd,seq+2,1) == 0) return ESC; if (seq[2] == '~') { switch(seq[1]) { case '3': return DEL_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; } } } else { switch(seq[1]) { case 'A': return ARROW_UP;

/* Report cursor location / if (write(ofd, "\x1b[6n", 4) != 4) return -1; / Read the response: ESC [ rows ; cols R / while (i < sizeof(buf)-1) { if (read(ifd,buf+i,1) != 1) break; if (buf[i] == 'R') break; i++; } buf[i] = '\0'; / Parse it. / if (buf[0] != ESC || buf[1] != '[') return -1; if (sscanf(buf+2,"%d;%d",rows,cols) != 2) return -1; return 0; } / Try to get the number of columns in the current terminal. If the ioctl()

  • call fails the function will try to query the terminal itself.
  • Returns 0 on success, -1 on error. */ int getWindowSize(int ifd, int ofd, int *rows, int cols) { struct winsize ws; if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { / ioctl() failed. Try to query the terminal itself. / int orig_row, orig_col, retval; / Get the initial position so we can restore it later. */

retval = getCursorPosition(ifd,ofd,&orig_row,&orig_col); if (retval == -1) goto failed; /* Go to right/bottom margin and get position. / if (write(ofd,"\x1b[999C\x1b[999B",12) != 12) goto failed; retval = getCursorPosition(ifd,ofd,rows,cols); if (retval == -1) goto failed; / Restore position. / char seq[32]; snprintf(seq,32,"\x1b[%d;%dH",orig_row,orig_col); if (write(ofd,seq,strlen(seq)) == -1) { / Can't recover... */ } return 0; } else { *cols = ws.ws_col; rows = ws.ws_row; return 0; } failed: return -1; } / ====================== Syntax highlight color scheme ==================== / int is_separator(int c) { return c == '\0' || isspace(c) || strchr(",.()+-/=~%[];",c) != NULL;

i = 0; /* Current char offset / while(p && isspace(p)) { p++; i++; } prev_sep = 1; / Tell the parser if 'i' points to start of word. / in_string = 0; / Are we inside "" or ''? / in_comment = 0; / Are we inside multi-line comment? / / If the previous line has an open comment, this line starts

  • with an open comment state. / if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx-1])) in_comment = 1; while(p) { /* Handle // comments. */ if (prev_sep && *p == scs[0] && (p+1) == scs[1]) { / From here to end is a comment / memset(row->hl+i,HL_COMMENT,row->size-i); return; } / Handle multi line comments. / if (in_comment) { row->hl[i] = HL_MLCOMMENT; if (p == mce[0] && *(p+1) == mce[1]) { row->hl[i+1] = HL_MLCOMMENT; p += 2; i += 2; in_comment = 0;

prev_sep = 1; continue; } else { prev_sep = 0; p++; i++; continue; } } else if (p == mcs[0] && (p+1) == mcs[1]) { row->hl[i] = HL_MLCOMMENT; row->hl[i+1] = HL_MLCOMMENT; p += 2; i += 2; in_comment = 1; prev_sep = 0; continue; } / Handle "" and '' / if (in_string) { row->hl[i] = HL_STRING; if (p == '\') { row->hl[i+1] = HL_STRING; p += 2; i += 2; prev_sep = 0; continue; } if (p == in_string) in_string = 0; p++; i++; continue; } else {

for (j = 0; keywords[j]; j++) { int klen = strlen(keywords[j]); int kw2 = keywords[j][klen-1] == '|'; if (kw2) klen--; if (!memcmp(p,keywords[j],klen) && is_separator((p+klen))) { / Keyword / memset(row->hl+i,kw2? HL_KEYWORD2 : HL_KEYWORD1,klen); p += klen; i += klen; break; } } if (keywords[j] != NULL) { prev_sep = 0; continue; / We had a keyword match / } } / Not special chars / prev_sep = is_separator(p); p++; i++; } /* Propagate syntax change to the next row if the open commen

  • state changed. This may recursively affect all the following rows
  • in the file. */

int oc = editorRowHasOpenComment(row); if (row->hl_oc != oc && row->idx+1 < E.numrows) editorUpdateSyntax(&E.row[row->idx+1]); row->hl_oc = oc; } /* Maps syntax highlight token types to terminal colors. / int editorSyntaxToColor(int hl) { switch(hl) { case HL_COMMENT: case HL_MLCOMMENT: return 36; / cyan / case HL_KEYWORD1: return 33; / yellow / case HL_KEYWORD2: return 32; / green / case HL_STRING: return 35; / magenta / case HL_NUMBER: return 31; / red / case HL_MATCH: return 34; / blu / default: return 37; / white / } } / Select the syntax highlight scheme depending on the filename,

  • setting it in the global state E.syntax. */ void editorSelectSyntaxHighlight(char *filename) { for (unsigned int j = 0; j < HLDB_ENTRIES; j++) { struct editorSyntax *s = HLDB+j; unsigned int i = 0; while(s->filematch[i]) { char *p; int patlen = strlen(s->filematch[i]);

} else { row->render[idx++] = row->chars[j]; } } row->rsize = idx; row->render[idx] = '\0'; /* Update the syntax highlighting attributes of the row. / editorUpdateSyntax(row); } / Insert a row at the specified position, shifting the other rows on the bottom

  • if required. / void editorInsertRow(int at, char s, size_t len) { if (at > E.numrows) return; E.row = realloc(E.row,sizeof(erow)(E.numrows+1)); if (at != E.numrows) { memmove(E.row+at+1,E.row+at,sizeof(E.row[0])(E.numrows-at)); for (int j = at+1; j <= E.numrows; j++) E.row[j].idx++; } E.row[at].size = len; E.row[at].chars = malloc(len+1); memcpy(E.row[at].chars,s,len+1); E.row[at].hl = NULL; E.row[at].hl_oc = 0; E.row[at].render = NULL; E.row[at].rsize = 0; E.row[at].idx = at; editorUpdateRow(E.row+at);

E.numrows++; E.dirty++; } /* Free row's heap allocated stuff. */ void editorFreeRow(erow row) { free(row->render); free(row->chars); free(row->hl); } / Remove the row at the specified position, shifting the remainign on the

  • top. / void editorDelRow(int at) { erow row; if (at >= E.numrows) return; row = E.row+at; editorFreeRow(row); memmove(E.row+at,E.row+at+1,sizeof(E.row[0])(E.numrows-at-1)); for (int j = at; j < E.numrows-1; j++) E.row[j].idx++; E.numrows--; E.dirty++; } / Turn the editor rows into a single heap-allocated string.
  • Returns the pointer to the heap-allocated string and populate the
  • integer pointed by 'buflen' with the size of the string, escluding
  • the final nulterm. */