Share to: share facebook share twitter share wa share telegram print page

Syntax highlighting

HTML syntax highlighting

Syntax highlighting is a feature of text editors that is used for programming, scripting, or markup languages, such as HTML. The feature displays text, especially source code, in different colours and fonts according to the category of terms.[1] This feature facilitates writing in a structured language such as a programming language or a markup language as both structures and syntax errors are visually distinct. This feature is also employed in many programming related contexts (such as programming manuals), either in the form of colorful books or online websites to make understanding code snippets easier for readers. Highlighting does not affect the meaning of the text itself; it is intended only for human readers.

Syntax highlighting is a form of secondary notation, since the highlights are not part of the text meaning, but serve to reinforce it. Some editors also integrate syntax highlighting with other features, such as spell checking or code folding, as aids to editing which are external to the language.

Practical benefits

Highlighting the effect of missing delimiter (after watch='false) in JavaScript

Syntax highlighting is one strategy to improve the readability and context of the text; especially for code that spans several pages. The reader can easily ignore large sections of comments or code, depending on what they are looking for. Syntax highlighting also helps programmers find errors in their program. For example, most editors highlight string literals in a different color. Consequently, spotting a missing delimiter is much easier because of the contrasting color of the text. Brace matching is another important feature with many popular editors. This makes it simple to see if a brace has been left out or locate the match of the brace the cursor is on by highlighting the pair in a different color.

A study published in the conference PPIG evaluated the effects of syntax highlighting on the comprehension of short programs, finding that the presence of syntax highlighting significantly reduces the time taken for a programmer to internalise the semantics of a program.[2] Additionally, data gathered from an eye-tracker during the study suggested that syntax highlighting enables programmers to pay less attention to standard syntactic components such as keywords.

Support in text editors

gedit supports syntax highlighting

Some text editors can also export the coloured markup in a format that is suitable for printing or for importing into word-processing and other kinds of text-formatting software; for instance as a HTML, colorized LaTeX, PostScript or RTF version of its syntax highlighting. There are several syntax highlighting libraries or "engines" that can be used in other applications, but are not complete programs in themselves, for example the Generic Syntax Highlighter (GeSHi) extension for PHP.

For editors that support more than one language, the user can usually specify the language of the text, such as C, LaTeX, HTML, or the text editor can automatically recognize it based on the file extension or by scanning contents of the file. This automatic language detection presents potential problems. For example, a user may want to edit a document containing:

  • more than one language (for example when editing an HTML file that contains embedded JavaScript code),
  • a language that is not recognized (for example when editing source code for an obscure or relatively new programming language),
  • a language that differs from the file type (for example when editing source code in an extension-less file in an editor that uses file extensions to detect the language).

In these cases, it is not clear what language to use, and a document may not be highlighted or be highlighted incorrectly.

Syntax elements

Most editors with syntax highlighting allow different colors and text styles to be given to dozens of different lexical sub-elements of syntax. These include keywords, comments, control-flow statements, variables, and other elements. Programmers often heavily customize their settings in an attempt to show as much useful information as possible without making the code difficult to read.

Called syntax decoration, some editors also display certain syntactical elements in more visually pleasing ways, for example by replacing a pointer operator like -> in source code by an actual arrow symbol (→), or changing text decoration clues like /italics/, *boldface*, or _underline_ in source code comments by an actual italics, boldface, or underlined presentation.

Examples

Below is a comparison of a snippet of C code:

Standard rendering Syntax highlighting
/* Hello World */
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("Hello World\n");
    return 0;
}
/* Hello World */
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("Hello World\n");
    return 0;
}

Below is another snippet of syntax highlighted C++ code:

// Create "window_count" Window objects:
const auto window_count = int{10};
auto windows = std::array<std::shared_ptr<Window>, max_window_count>{};
for (auto i = int{0}; i < window_count; ++i) {
    windows[i] = std::make_shared<Window>();
}

In the C++ example, the editor has recognized the keywords const, auto, int, and for. The comment at the beginning is also highlighted in a specific manner to distinguish it from working code.

History and limitations

The ideas of syntax highlighting overlap significantly with those of syntax-directed editors. One of the first such editors for code was Wilfred Hansen's 1969 code editor, Emily.[3][4] It provided advanced language-independent code completion facilities, and unlike modern editors with syntax highlighting, actually made it impossible to create syntactically incorrect programs.

In 1982, Anita H. Klock and Jan B. Chodak filed a patent for the first known syntax highlighting system,[5] which was used in the Intellivision's Entertainment Computer System (ECS) peripheral, released in 1983.[6] It would highlight different elements of BASIC programs and was implemented in an attempt to make it easier for beginners, especially children, to start writing code.[7] Later, the Live Parsing Editor (LEXX) written for the VM operating system for the computerization of the Oxford English Dictionary in 1985 was one of the first to use color syntax highlighting. Its live parsing capability allowed user-supplied parsers to be added to the editor, for text, programs, data file, etc.[8] On microcomputers, MacPascal 1.0 (October 10, 1985) recognized Pascal syntax as it was typed and used font changes (e.g., bold for keywords) to highlight syntax on the monochrome compact Macintosh and automatically indented code to match its structure.[9]

Some text editors and code formatting tools perform syntax highlighting using pattern matching heuristics (e.g. Regular expressions) rather than implementing a parser for each possible language.[10] This can result in a text rendering system displaying somewhat inaccurate syntax highlighting and in some cases performing slowly. A solution used by text editors to overcome this problem is not always parsing the whole file but rather just the visible area, sometimes scanning backwards in the text up to a limited number of lines for "syncing".

On the other hand, the editor often displays code during its creation, while it is incomplete or incorrect, and the strict parsers (like ones used in compilers) would fail to parse the code most of the time.

Some modern, language-specific IDEs (in contrast to text editors) perform full language parsing which results in very accurate understanding of code. An extension of syntax highlighting was called "semantic highlighting" in 2009 by David Nolden[11] for the open-source C++ IDE KDevelop. For example, semantic highlighting may give local variables unique distinct colors to improve the comprehensibility of code. In 2014 the idea of colored local variables was further popularized due to a blog post by Evan Brooks,[12] and after that, the idea was transferred to other popular IDEs like Visual Studio,[13] Xcode,[14] and others.

Color in a user interface is less useful if the user has some degree of color blindness.

See also

References

  1. ^ Jim D'Anjou; Sherry Shavor; Scott Fairbrother; Dan Kehn; John Kellerman; Pat McCarthy (2005). The Java developer's guide to Eclipse (2nd ed.). Boston: Addison-Wesley. ISBN 978-0-321-30502-2.
  2. ^ Sarkar, Advait (2015). "The impact of syntax colouring on program comprehension". Proceedings of the 26th Annual Conference of the Psychology of Programming Interest Group: 49–58. Archived from the original on 24 September 2015. Retrieved 27 September 2023.
  3. ^ Hansen, Wilfred J. (1971). "User engineering principles for interactive systems". Proceedings of the Fall Joint Computer Conference FJCC 39. AFIPS. pp. 5623–532.
  4. ^ Hansen, Wilfred. "Emily - An Editor for Structured Text". Retrieved 17 June 2013.
  5. ^ Syntax error correction method and apparatus, 1982-10-29, retrieved 2018-04-12
  6. ^ Mattel Intellivision: Intellivision Computer Module Owner's Guide (1983)(Mattel)(US). 1983.
  7. ^ "Intellivision Classic Video Game System / Entertainment Computer System". www.intellivisionlives.com. Archived from the original on 2018-07-17. Retrieved 2018-04-12.
  8. ^ Cowlishaw, M. F. (1987). "LEXX – A programmable structured editor" (PDF). IBM Journal of Research and Development, Vol 31, No. 1, IBM Reprint order number G322-0151. IBM.
  9. ^ Allen, Dan (2011-10-10). "A Trio of Historical Recollections". mpw-dev (Mailing list). Archived from the original on 2017-08-21. Retrieved 12 September 2019.
  10. ^ "KEDIT Language Definition Files". Kedit. Mansfield Software Group, Inc. 2012. Retrieved 2016-04-07.
  11. ^ "2009 blog post on Semantic Highlighting introduced in KDevelop by David Nolden". 8 January 2009.
  12. ^ "2014 blog post on Semantic Highlighting by Evan Brooks". 17 April 2017.
  13. ^ "Visual Studio Magazine article on semantic highlighting".
  14. ^ "Github page of a plugin which implements semantic highlighting for Xcode". GitHub. 14 September 2022.

Read other articles:

«IEC» redirigeix aquí. Vegeu-ne altres significats a «IEC (desambiguació)». Institut d'Estudis Catalans DadesNom curtIEC Tipussocietat científica institut editor en accés obert Idioma oficialcatalà Forma jurídicafundació HistòriaCreació18 juny 1907, Barcelona FundadorEnric Prat de la Riba i Sarrà ActivitatMembre deConsell de Protecció de la Natura All European Academies (en) Governança corporativa Seu «Casa de Convalescència»Carrer del Carme, 47Barcelona Presidènc...

Questa voce sull'argomento schermidori francesi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Nicolas Beaudan Nazionalità  Francia Altezza 175 cm Peso 70 kg Scherma Specialità Fioretto Palmarès Competizione Ori Argenti Bronzi Mondiali 3 0 1 Europei 0 1 0 Per maggiori dettagli vedi qui Statistiche aggiornate al 21 luglio 2010 Modifica dati su Wikidata · Manuale Nicolas Beaudan (13 dicembre 1975) è un ex schermidore francese, special...

Heiligenblut am Großglockner Lambang kebesaranKoordinat: Coordinates: Missing longitude{{#coordinates:}}: lintang salahNegaraAustriaNegara bagianInvalid state: KärntenDistrikSpittal an der DrauPemerintahan • WalikotaJosef Schachner (independen)Luas • Total193,15 km2 (7,458 sq mi)Ketinggian1.288 m (4,226 ft)Populasi (1 Januari 2014)[1] • Total1.022 • Kepadatan0,053/km2 (0,14/sq mi)Zona waktuUTC+1 (WET)...

Uzbekistan Przydomek Oq boʻrilar (Białe wilki), Turanlılar (Turańczycy) Związek Oʻzbekiston Futbol Federatsiyasi Sponsor techniczny Joma Trener Srečko Katanec(od 2021) Asystent trenera Timur Kapadze Skrót FIFA UZB Ranking FIFA 77. (1306.63 pkt.)[a] Miejsce w rankingu Elo 56. (1 lutego 2019) (1612 pkt.) Zawodnicy Kapitan Odil Ahmedov Najwięcej występów Server Jeparov (126) Najwięcej bramek Maksim Shatskix (34) Strojedomowe Strojewyjazdowe Mecze Pierwszy mecz Tadżykistan 2:2 U...

Slottsparken UbicaciónPaís  NoruegaCoordenadas 59°55′03″N 10°43′42″E / 59.9175, 10.7283[editar datos en Wikidata] La parte trasera del Palacio Real vista desde el parque. El Parque del Palacio (en noruego: Slottsparken) es un parque público situado en el centro de Oslo (Noruega) que rodea el Palacio Real. Tiene una superficie de 22 hectáreas.[1]​[2]​ Historia El parque fue construido durante la década de 1840 y fue diseñado por Hans D...

Gusnul Yakin (lahir 17 Maret 1956) adalah pelatih sepak bola berkewarganegaraan Indonesia. Dia adalah mantan pelatih klub Liga Super 2008/09 Arema Malang dari 13 Agustus 2008 hingga 30 Juni 2009.[1] Gusnul merupakan mantan pemain sepak bola. Sebelumnya Gusnul melatih Persibo Bojonegoro dan berhasil membawa klub tersebut menjadi juara Divisi Satu 2007 yang membuat Persibo berkompetisi di Divisi Utama musim 2008. Karier di Arema Malang Menggantikan Bambang Nurdiansyah saat musim kompeti...

Голконда: Султанат Голконда — один з мусульманських султанатів Центральної Індії. Фортеця Голконда — древня столиця цього султанату. Уранова Голконда — за братами Стругацькими регіон на Венері, описаний у повісті «Країна багряних хмар». Топонім англ. Golconda Голконда ...

Aerial military force of Ethiopia Ethiopian Air Forceየኢትዮጵያ አየር ኃይልYe-Ītyōṗṗyā āyer ḫayiliEmblem of the Ethiopian Air ForceFounded18 August 1929; 94 years ago (1929-08-18)Country EthiopiaTypeAir forceRoleAerial warfareSize5,000 personnelPart ofEthiopian National Defense ForceEquipment79 aircraft[1]Engagements Gugsa Wale's Rebellion Second Italo-Ethiopian War Eritrean War of Independence 1964 Ethiopian-Somali Border War Ethi...

リトルアンバサダーとして活動する日本人の少女と交流するシアム代表(左)、於パレスチナ常駐代表公邸(2013年) ワリード・アリ・シアム[1](アラビア語: وليد علي صيام‎ Walīd ʿAlī Ṣiyām ワリード・アリー・スィヤーム、英語: Waleed Ali Siam、1955年6月1日 - )は、パレスチナ国の外交官、大使級。2003年6月より、駐日パレスチナ常駐総代表部代表(正

Mercedes-Benz Mercedes-Benz GLC 220 d 4MATIC AMG Line (2015–2019)Mercedes-Benz GLC 220 d 4MATIC AMG Line (2015–2019) X 253 Verkaufsbezeichnung: GLC Produktionszeitraum: 06/2015–07/2022 Klasse: SUV Karosserieversionen: Kombi Motoren: Ottomotoren:2,0–4,0 Liter(155–375 kW)Otto-Hybrid:2,0 Liter(235 kW)Dieselmotoren:2,0–3,0 Liter(120–243 kW)Diesel-Hybrid:2,0 Liter(225 kW) Länge: 4655–4682 mm Breite: 1890–1930 mm Höhe: 1620–1644 mm Radstand: 2873 mm Leergew...

German politics since the fall of Nazism The far-right in Germany (German: rechtsextrem) slowly reorganised itself after the fall of Nazi Germany and the dissolution of the Nazi Party in 1945. Denazification was carried out in Germany from 1945 to 1949 by the Allied forces of World War II, with an attempt of eliminating Nazism from the country. However, various far-right parties emerged in the post-war period, with varying success. Most parties only lasted a few years before either dissolving...

Free software license This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: LaTeX Project Public License – news · newspapers · books · scholar · JSTOR (April 2011) (Learn how and when to remove this template message) LaTeX Project Public LicenseAuthorLaTeX projectLatest version1.3cPublisherLaTeX projectPublishedMa...

Park Chan-wook, lauréat du prix de la mise en scène en 2022 pour Decision to Leave. Le prix de la mise en scène (ou Best Director Award, selon la dénomination internationale) est une récompense décernée par le jury des longs métrages du Festival de Cannes. Il honore un cinéaste jugé comme étant le meilleur réalisateur parmi les films de la compétition. Palmarès Année Réalisateur Film Titre original Pays 1946 René Clément La Bataille du rail France 1947 Non décerné 1948 Pas...

For other uses, see Church of the Gesu (disambiguation). Catholic church in Philadelphia Church in Pennsylvania, United StatesChurch of the GesúFacade of the Church of the Gesú in 200939°58′25″N 75°09′55″W / 39.97361°N 75.16528°W / 39.97361; -75.16528LocationPhiladelphia, PennsylvaniaCountryUnited StatesDenominationCatholicReligious instituteSociety of JesusHistoryStatusChapel, former parish churchFounded1868Founder(s)Burchard VilligerConsecratedDecember ...

Zeniya Gohei Zeniya Gohei (銭屋五兵衛, 1774-1852) was a Japanese merchant and engineer in the Edo period. Gohei was born to a family of money-changers in Kaga province.[1] Coastal shipping Gohei was put in charge of developing a coastal shipping fleet (kitamae ships) for the Tokugawa shogunate; and he became very rich from trading,[1] especially rice and lumber. Land reclamation project In the summer of 1851, Gohei attempted a land reclamation project in Kahoku Lake, whic...

New Zealand footballer Betsy Hassett Hassett in 2011Personal informationFull name Betsy Doon Hassett[1]Date of birth (1990-08-04) 4 August 1990 (age 33)[1]Place of birth Auckland, New Zealand[2]Height 1.58 m (5 ft 2 in)[1]Position(s) Attacking midfielder, right wingerTeam informationCurrent team StjarnanNumber 11College careerYears Team Apps (Gls)2009–2012 California Golden Bears 64 (7)Senior career*Years Team Apps (Gls)2013 SC Sand 10 (11...

本條目存在以下問題,請協助改善本條目或在討論頁針對議題發表看法。 此條目疑似为广告或包含宣传性内容。 (2020年4月9日)请协助使用中立的观点重写这篇条目。明显的广告请加入{{Delete|G11}}來提请删除。 此條目之中立性有争议。其內容、語調可能帶有明顯的個人觀點或地方色彩。 (2023年6月3日)加上此模板的編輯者需在討論頁說明此文中立性有爭議的原因,以便讓各...

Method of mitigating the detrimental effects of a channel with limited dynamic range A signal before (top) and after μ-law compression (bottom) In telecommunication and signal processing, companding (occasionally called compansion) is a method of mitigating the detrimental effects of a channel with limited dynamic range. The name is a portmanteau of the words compressing and expanding, which are the functions of a compander at the transmitting and receiving ends, respectively. The use of com...

Museum Fauna Indonesia KomodoBangunan utama Museum Fauna Indonesia KomodoDidirikan20 April 1978LokasiTaman Mini Indonesia Indah, Jakarta, IndonesiaJenisMuseum sejarah alamSitus webMuseum Fauna Indonesia Komodo & Taman ReptilMuseum Fauna Indonesia “Komodo” dan Taman Reptilia menampilkan pesona satwa langka dalam bentuk awetan dan reptilia hidup. Arsitektur bangunannya mengambil bentuk komodo, satwa yang hanya hidup di Pulau Komodo, Nusa Tenggara Timur, berdiri di atas lahan seluas 10.1...

American musician Bruce PurseBackground informationBirth nameBruce Clayton PurseBornBirmingham, Alabama, U.S.GenresJazz, soul, R&B, blues, avant-garde jazz, hip hop soul, urban, reggaeOccupation(s)Musician, composer, writer, artist, producerLabelsNext PlateauWebsitewww.brucepurse.comMusical artist Bruce Purse is an American musician, composer, producer, vocalist, bandleader, arranger, performer, music educator, and guest lecturer. Proficient at various wind instruments, including the trum...

Kembali kehalaman sebelumnya