Herramientas de usuario

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Próxima revisión
Revisión previa
kilo.c [2024/11/26 17:13] – creado peronkilo.c [2026/04/21 16:07] (actual) – editor externo 127.0.0.1
Línea 1: Línea 1:
-<code c>+<file c kilo.c>
 /* Kilo -- Un editor muy simple en menos de 1000 líneaas de código /* Kilo -- Un editor muy simple en menos de 1000 líneaas de código
  * (como las contó "cloc"). No depende de libcurses, emite secuencias  * (como las contó "cloc"). No depende de libcurses, emite secuencias
Línea 79: Línea 79:
 }; };
  
-/* This structure represents a single line of the file we are editing. */+/* Esta estructura representa una unica línea del fichero que editamos. */
 typedef struct erow { typedef struct erow {
-    int idx;            /* Row index in the filezero-based. */ +    int idx;            /* Indice de fila en el ficherobasado en cero. */ 
-    int size;           /Size of the rowexcluding the null term. */ +    int size;           /Tamaño de la filaexpliyendo el term nulo. */ 
-    int rsize;          /* Size of the rendered row. */ +    int rsize;          /* Tamaño de la fila renderizada. */ 
-    char *chars;        /* Row content. */ +    char *chars;        /* Contenido de la fila. */ 
-    char *render;       /Row content "renderedfor screen (for TABs). */ +    char *render;       /Contenido de la fila "renderizadapara pantalla (para TABs). */ 
-    unsigned char *hl;  /* Syntax highlight type for each character in render.*/ +    unsigned char *hl;  /* Tipo de resaltado de sintaxis para cada caracter en render.*/ 
-    int hl_oc;          /* Row had open comment at end in last syntax highlight +    int hl_oc;          /* La fila tiene comentario abierto al final en la ultima revisión de sintaxis. */
-                           check. */+
 } erow; } erow;
  
Línea 96: Línea 95:
  
 struct editorConfig { struct editorConfig {
-    int cx,cy;  /* Cursor and position in characters */ +    int cx,cy;  /* Posición del cursor en caracteres */ 
-    int rowoff;     /* Offset of row displayed. */ +    int rowoff;     /* Offset de linea presentada. */ 
-    int coloff;     /* Offset of column displayed. */ +    int coloff;     /* Offset de columna presentada. */ 
-    int screenrows; /* Number of rows that we can show */ +    int screenrows; /* Nro. de filas que podemos mostrar */ 
-    int screencols; /* Number of cols that we can show */ +    int screencols; /* Nro. de columnas que podemos mostrar */ 
-    int numrows;    /* Number of rows */ +    int numrows;    /* Nro de filas */ 
-    int rawmode;    /* Is terminal raw mode enabled? */ +    int rawmode;    /* Esta el modo crudo de terminal activo? */ 
-    erow *row;      /* Rows */ +    erow *row;      /* Filas */ 
-    int dirty;      /* File modified but not saved. */ +    int dirty;      /* Archivo modificado pero no guardado. */ 
-    char *filename; /* Currently open filename */+    char *filename; /* Nombre de archivo actualmente abierto */
     char statusmsg[80];     char statusmsg[80];
     time_t statusmsg_time;     time_t statusmsg_time;
-    struct editorSyntax *syntax;    /* Current syntax highlightor NULL. */+    struct editorSyntax *syntax;    /* Resaltado de sintaxis actualNULL. */
 }; };
  
Línea 127: Línea 126:
         ESC = 27,           /* Escape */         ESC = 27,           /* Escape */
         BACKSPACE =  127,   /* Backspace */         BACKSPACE =  127,   /* Backspace */
-        /* The following are just soft codes, not really reported by the +        /* Los siguientes sólo son soft codes, no reportados realmente por la terminal directamente. */
-         terminal directly. */+
         ARROW_LEFT = 1000,         ARROW_LEFT = 1000,
         ARROW_RIGHT,         ARROW_RIGHT,
Línea 142: Línea 140:
 void editorSetStatusMessage(const char *fmt, ...); void editorSetStatusMessage(const char *fmt, ...);
  
-/* =========================== Syntax highlights DB =========================+/* ====================== BD de Resaltado Sintáctico =========================
  *  *
- In order to add a new syntaxdefine two arrays with a list of file name + Para agregar nueva sintaxisdefina dos arrays con una lista de 
- matches and keywords. The file name matches are used in order to match + coincidencias de nombres de archivo y keywords. Las coincidencias de 
- a given syntax with a given file nameif a match pattern starts with a + nombre de archivo se usan para coincidir una sintaxis dada con un 
- dotit is matched as the last past of the filename, for example ".c"+ * nombre de fichero dadosi comienza un patrón coincidente con un punto, 
- Otherwise the pattern is just searched inside the filenmelike "Makefile").+ coincidirá como la última parte del nombre de ficheropor ejemplo ".c"
 + De otro modo el patrón sólo se busca dentro del nombre de ficherocomo 
 + "Makefile").
  *  *
- The list of keywords to highlight is just list of wordshowever if they + La lista de keywords a resaltar es simplemente una lista de palabras
- a trailing '|' character is added at the endthey are highlighted in + sin embargo si tiene al ginal un caracter '|', se las resalta en color 
- a different colorso that you can have two different sets of keywords.+ diferentede modo que podrá contar con dos conjuntos de keywords.
  *  *
- Finally add a stanza in the HLDB global variable with two two arrays + Finalmente agregue una stanza en la variable global HLDB con dos arrays 
- of stringsand a set of flags in order to enable highlighting of + de cadenasy un conjunto de flags para activar el resaltado de comentarios 
- comments and numbers.+ y números.
  *  *
- The characters for single and multi line comments must be exactly two + Los caracteres para comentarios de una linea y multilineas debe ser 
- and must be provided as well (see the language example).+ exactamente dos, y deben ser indicados también (ver ejemplo de lenguaje 
 + C).
  *  *
- There is no support to highlight patterns currently. */ + Actualmente no se soportan el resaltado de patrones */
- +
-/* C / C++ */+
 char *C_HL_extensions[] = {".c",".h",".cpp",".hpp",".cc",NULL}; char *C_HL_extensions[] = {".c",".h",".cpp",".hpp",".cc",NULL};
 char *C_HL_keywords[] = { char *C_HL_keywords[] = {
- /* Keywords */+ /* Keywords para C */
  "auto","break","case","continue","default","do","else","enum",  "auto","break","case","continue","default","do","else","enum",
  "extern","for","goto","if","register","return","sizeof","static",  "extern","for","goto","if","register","return","sizeof","static",
  "struct","switch","typedef","union","volatile","while","NULL",  "struct","switch","typedef","union","volatile","while","NULL",
  
- /* C++ Keywords */+ /* Keywords para C++ */
  "alignas","alignof","and","and_eq","asm","bitand","bitor","class",  "alignas","alignof","and","and_eq","asm","bitand","bitor","class",
  "compl","constexpr","const_cast","deltype","delete","dynamic_cast",  "compl","constexpr","const_cast","deltype","delete","dynamic_cast",
Línea 180: Línea 179:
  "typeid","typename","virtual","xor","xor_eq",  "typeid","typename","virtual","xor","xor_eq",
  
- /* C types */+ /* tipos para C */
         "int|","long|","double|","float|","char|","unsigned|","signed|",         "int|","long|","double|","float|","char|","unsigned|","signed|",
         "void|","short|","auto|","const|","bool|",NULL         "void|","short|","auto|","const|","bool|",NULL
 }; };
  
-/* Here we define an array of syntax highlights by extensions, keywords+/* Aqui defino un array de resaltadores de sintaxis para extensiones
- comments delimiters and flags. */+ keywords, delimitadores de comentarios y flags. */
 struct editorSyntax HLDB[] = { struct editorSyntax HLDB[] = {
     {     {
Línea 199: Línea 198:
 #define HLDB_ENTRIES (sizeof(HLDB)/sizeof(HLDB[0])) #define HLDB_ENTRIES (sizeof(HLDB)/sizeof(HLDB[0]))
  
-/* ======================= Low level terminal handling ====================== */+/* ================== Manejo de Terminal de bajo nivel====================== */
  
-static struct termios orig_termios; /* In order to restore at exit.*/+static struct termios orig_termios; /* Para restaurar a la salida. */
  
 void disableRawMode(int fd) { void disableRawMode(int fd) {
-    /* Don't even check the return value as it's too late. */+    /* Ni siquiera revises este valor de retorno, ya que es muy tarde. */
     if (E.rawmode) {     if (E.rawmode) {
         tcsetattr(fd,TCSAFLUSH,&orig_termios);         tcsetattr(fd,TCSAFLUSH,&orig_termios);
Línea 211: Línea 210:
 } }
  
-/* Called at exit to avoid remaining in raw mode. */+/* Llamado al salir para evitar permanecer en modo raw. */
 void editorAtExit(void) { void editorAtExit(void) {
     disableRawMode(STDIN_FILENO);     disableRawMode(STDIN_FILENO);
 } }
  
-/* Raw mode1960 magic shit. */+/* Modo Raw: magia de los 60s. */
 int enableRawMode(int fd) { int enableRawMode(int fd) {
     struct termios raw;     struct termios raw;
  
-    if (E.rawmode) return 0; /* Already enabled. */+    if (E.rawmode) return 0; /* Ya activado */
     if (!isatty(STDIN_FILENO)) goto fatal;     if (!isatty(STDIN_FILENO)) goto fatal;
     atexit(editorAtExit);     atexit(editorAtExit);
     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
  
-    raw = orig_termios;  /* modify the original mode */ +    raw = orig_termios;  /* modifica el modo original */ 
-    /* input modesno break, no CR to NL, no parity check, no strip char, +    /* modos de entradasin break, no CR NL, sin parity check, sin strip char, 
-     no start/stop output control. */+     sin control start/stop. */
     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
-    /* output modes disable post processing */+    /* modos de salida desactivar post procesado */
     raw.c_oflag &= ~(OPOST);     raw.c_oflag &= ~(OPOST);
-    /* control modes set 8 bit chars */+    /* modos de control - activa chars de 8 bits */
     raw.c_cflag |= (CS8);     raw.c_cflag |= (CS8);
-    /* local modes - choing off, canonical off, no extended functions+    /* local modes - choing off, canonical off, sin funciones extendidas
-     no signal chars (^Z,^C) */+     sin caracteres de señal (^Z,^C) */
     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
-    /* control chars - set return condition: min number of bytes and timer. */ +    /* chars de control establece condicion de retornonro. min de bytes timer. */ 
-    raw.c_cc[VMIN] = 0; /* Return each byte, or zero for timeout. */ +    raw.c_cc[VMIN] = 0; /* Devuelve cada byte, zero para el timeout. */ 
-    raw.c_cc[VTIME] = 1; /* 100 ms timeout (unit is tens of second). */+    raw.c_cc[VTIME] = 1; /* timeout de 100 ms (la unidad es décimas de seg). */
  
-    /* put terminal in raw mode after flushing */+    /* pongo temrinal en modo raw antes de descartar */
     if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;     if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
     E.rawmode = 1;     E.rawmode = 1;
Línea 250: Línea 249:
 } }
  
-/* Read a key from the terminal put in raw modetrying to handle +/* Leo una tecla desde terminal puesta en modo raw, intento doimnar 
- * escape sequences. */+ secuencias de escape. */
 int editorReadKey(int fd) { int editorReadKey(int fd) {
     int nread;     int nread;
Línea 260: Línea 259:
     while(1) {     while(1) {
         switch(c) {         switch(c) {
-        case ESC:    /* escape sequence */ +        case ESC:    /* secuencia de escape */ 
-            /* If this is just an ESC, we'll timeout here. */+            /* Si es  un solo  ESC, hacemos un timeout. */
             if (read(fd,seq,1) == 0) return ESC;             if (read(fd,seq,1) == 0) return ESC;
             if (read(fd,seq+1,1) == 0) return ESC;             if (read(fd,seq+1,1) == 0) return ESC;
  
-            /* ESC [ sequences. */+            /* ESC [ secuencias. */
             if (seq[0] == '[') {             if (seq[0] == '[') {
                 if (seq[1] >= '0' && seq[1] <= '9') {                 if (seq[1] >= '0' && seq[1] <= '9') {
-                    /* Extended escaperead additional byte. */+                    /* Escape extendidolee byte adicional. */
                     if (read(fd,seq+2,1) == 0) return ESC;                     if (read(fd,seq+2,1) == 0) return ESC;
                     if (seq[2] == '~') {                     if (seq[2] == '~') {
Línea 303: Línea 302:
 } }
  
-/* Use the ESC [6n escape sequence to query the horizontal cursor position +/* Usa la secuencia de escape ESC [6n para consultar la posicion horizontal 
- and return itOn error -1 is returnedon success the position of the + del cursor y la retornaEn error -1 se retorna, en éxitola posición 
- * cursor is stored at *rows and *cols and is returned. */+ del cursor se almacena en *rows *cols y se retorna 0. */
 int getCursorPosition(int ifd, int ofd, int *rows, int *cols) { int getCursorPosition(int ifd, int ofd, int *rows, int *cols) {
     char buf[32];     char buf[32];
     unsigned int i = 0;     unsigned int i = 0;
  
-    /* Report cursor location */+    /* Reporta posición del cursor */
     if (write(ofd, "\x1b[6n", 4) != 4) return -1;     if (write(ofd, "\x1b[6n", 4) != 4) return -1;
  
-    /* Read the response: ESC [ rows cols R */+    /* Read the response: ESC [ filas columnas R */
     while (i < sizeof(buf)-1) {     while (i < sizeof(buf)-1) {
         if (read(ifd,buf+i,1) != 1) break;         if (read(ifd,buf+i,1) != 1) break;
Línea 321: Línea 320:
     buf[i] = '\0';     buf[i] = '\0';
  
-    /* Parse it. */+    /* Lo parsea. */
     if (buf[0] != ESC || buf[1] != '[') return -1;     if (buf[0] != ESC || buf[1] != '[') return -1;
     if (sscanf(buf+2,"%d;%d",rows,cols) != 2) return -1;     if (sscanf(buf+2,"%d;%d",rows,cols) != 2) return -1;
Línea 327: Línea 326:
 } }
  
-/* Try to get the number of columns in the current terminal. If the ioctl() +/* Intenta obtener la cantidad de columnas de la terminal actualSi el 
- * call fails the function will try to query the terminal itself+ * llamada ioctl() falla, la función intentará consultar a la terminal en si
- Returns on success, -1 on error. */+ Devuelve al éxito, -1 al error. */
 int getWindowSize(int ifd, int ofd, int *rows, int *cols) { int getWindowSize(int ifd, int ofd, int *rows, int *cols) {
     struct winsize ws;     struct winsize ws;
Línea 337: Línea 336:
         int orig_row, orig_col, retval;         int orig_row, orig_col, retval;
  
-        /* Get the initial position so we can restore it later. */+        /* Obtiene posición inicial para poder volver a ella luego. */
         retval = getCursorPosition(ifd,ofd,&orig_row,&orig_col);         retval = getCursorPosition(ifd,ofd,&orig_row,&orig_col);
         if (retval == -1) goto failed;         if (retval == -1) goto failed;
  
-        /* Go to right/bottom margin and get position. */+        /* Va al máergen derecho/inferior y obtiene posición. */
         if (write(ofd,"\x1b[999C\x1b[999B",12) != 12) goto failed;         if (write(ofd,"\x1b[999C\x1b[999B",12) != 12) goto failed;
         retval = getCursorPosition(ifd,ofd,rows,cols);         retval = getCursorPosition(ifd,ofd,rows,cols);
         if (retval == -1) goto failed;         if (retval == -1) goto failed;
  
-        /* Restore position. */+        /* Restaura posición. */
         char seq[32];         char seq[32];
         snprintf(seq,32,"\x1b[%d;%dH",orig_row,orig_col);         snprintf(seq,32,"\x1b[%d;%dH",orig_row,orig_col);
         if (write(ofd,seq,strlen(seq)) == -1) {         if (write(ofd,seq,strlen(seq)) == -1) {
-            /* Can't recover... */+            /* No puedo recupera... */
         }         }
         return 0;         return 0;
Línea 363: Línea 362:
 } }
  
-/* ====================== Syntax highlight color scheme  ==================== */+/* ================ Esquema de color resaltado de Sintaxis ============== */
  
 int is_separator(int c) { int is_separator(int c) {
Línea 411: Línea 410:
  
     while(*p) {     while(*p) {
-        /* Handle // comments. */+        /* Resuelve comentarios //. */
         if (prev_sep && *p == scs[0] && *(p+1) == scs[1]) {         if (prev_sep && *p == scs[0] && *(p+1) == scs[1]) {
-            /* From here to end is a comment */+            /* De aquí al final es un comentario */
             memset(row->hl+i,HL_COMMENT,row->size-i);             memset(row->hl+i,HL_COMMENT,row->size-i);
             return;             return;
Línea 552: Línea 551:
 } }
  
-/* ======================= Editor rows implementation ======================= */+/* ======================= Implementación de filas del editor ============ */
  
-/* Update the rendered version and the syntax highlight of a row. */+/* Actualizar la versión renderizada y el resaltado de sintaxis de una linea. */
 void editorUpdateRow(erow *row) { void editorUpdateRow(erow *row) {
     unsigned int tabs = 0, nonprint = 0;     unsigned int tabs = 0, nonprint = 0;
     int j, idx;     int j, idx;
  
-   /Create a version of the row we can directly print on the screen, +   /Crea una versión de la linea que podemos imprimir directamente en 
-     respecting tabs, substituting non printable characters with '?'. */+    pantalla respetando tabs, substituyendo caracteres no imprimibles con 
 +    * '?'. */
     free(row->render);     free(row->render);
     for (j = 0; j < row->size; j++)     for (j = 0; j < row->size; j++)
Línea 568: Línea 568:
         (unsigned long long) row->size + tabs*8 + nonprint*9 + 1;         (unsigned long long) row->size + tabs*8 + nonprint*9 + 1;
     if (allocsize > UINT32_MAX) {     if (allocsize > UINT32_MAX) {
-        printf("Some line of the edited file is too long for kilo\n");+        printf("Cierta línea del fichero editado es muy larga para Kilo\n");
         exit(1);         exit(1);
     }     }
Línea 585: Línea 585:
     row->render[idx] = '\0';     row->render[idx] = '\0';
  
-    /* Update the syntax highlighting attributes of the row. */+    /* Actualiza atributos de resaltado de sintaxis de la fila. */
     editorUpdateSyntax(row);     editorUpdateSyntax(row);
 } }
Línea 692: Línea 692:
 } }
  
-/* Delete the character at offset 'at' from the specified row. */+/* Borrar el caracter en offset 'at' desde la fila especificada. */
 void editorRowDelChar(erow *row, int at) { void editorRowDelChar(erow *row, int at) {
     if (row->size <= at) return;     if (row->size <= at) return;
Línea 736: Línea 736:
         return;         return;
     }     }
-    /* If the cursor is over the current line sizewe want to conceptually +    /* Si el cursor está sobre el tamaño de línea actualqueremos pensar 
-     think it's just over the last character. */+     cpmce´tiañ,emte qie est+a sólo sobre el último caracter. */
     if (filecol >= row->size) filecol = row->size;     if (filecol >= row->size) filecol = row->size;
     if (filecol == 0) {     if (filecol == 0) {
         editorInsertRow(ficherofilas,"",0);         editorInsertRow(ficherofilas,"",0);
     } else {     } else {
-        /* We are in the middle of a lineSplit it between two rows. */+        /* Estamos en el medio de una líneaDividirla en dos lineas. */
         editorInsertRow(ficherofilas+1,row->chars+filecol,row->size-filecol);         editorInsertRow(ficherofilas+1,row->chars+filecol,row->size-filecol);
         row = &E.row[ficherofilas];         row = &E.row[ficherofilas];
Línea 759: Línea 759:
 } }
  
-/* Delete the char at the current prompt position. */+/* Borra el char en la posición del prompt actual. */
 void editorDelChar() { void editorDelChar() {
     int ficherofilas = E.rowoff+E.cy;     int ficherofilas = E.rowoff+E.cy;
Línea 794: Línea 794:
 } }
  
-/* Load the specified program in the editor memory and returns on success +/* Carga el programa especificado en la memoria del editor y devuelve 
- or on error. */+ si tiene éxito, o si da error. */
 int editorOpen(char *filename) { int editorOpen(char *filename) {
     FILE *fp;     FILE *fp;
Línea 879: Línea 879:
 } }
  
-/* Esta función escribe la pantalla completa usando caracterede escape VT100+/* Esta función escribe la pantalla completa usando caracterede escape VT100
  * comenzando del estado lógicodel editor en el estado global 'E'. */  * comenzando del estado lógicodel editor en el estado global 'E'. */
 void editorRefreshScreen(void) { void editorRefreshScreen(void) {
Línea 896: Línea 896:
                 char welcome[80];                 char welcome[80];
                 int welcomelen = snprintf(welcome,sizeof(welcome),                 int welcomelen = snprintf(welcome,sizeof(welcome),
-                    "Kilo editor -- verison %s\x1b[0K\r\n", KILO_VERSION);+                    "Editor Kilo -- versión %s\x1b[0K\r\n", KILO_VERSION);
                 int padding = (E.screencols-welcomelen)/2;                 int padding = (E.screencols-welcomelen)/2;
                 if (padding) {                 if (padding) {
Línea 1081: Línea 1081:
             find_next = 0;             find_next = 0;
  
-            /* Highlight */+            /* Resaltar */
             FIND_RESTORE_HL;             FIND_RESTORE_HL;
  
Línea 1097: Línea 1097:
                 E.rowoff = current;                 E.rowoff = current;
                 E.coloff = 0;                 E.coloff = 0;
-                /* Scroll horizontally as needed. */+                /* Desplazar horizontalmente según se necesite. */
                 if (E.cx > E.screencols) {                 if (E.cx > E.screencols) {
                     int diff = E.cx - E.screencols;                     int diff = E.cx - E.screencols;
Línea 1170: Línea 1170:
         break;         break;
     }     }
-    /* Fix cx if the current line has not enough chars. */+    /* Corrige cx si la línea actual no tiene suficientes chars. */
     ficherofilas = E.rowoff+E.cy;     ficherofilas = E.rowoff+E.cy;
     filecol = E.coloff+E.cx;     filecol = E.coloff+E.cx;
Línea 1308: Línea 1308:
     return 0;     return 0;
 } }
-</code>+</file>

Este sitio web utiliza cookies para guardar datos esenciales de su actividad, como su autenticación. Al entrar acepta el uso de cookies.

Más información