Template:Short description {{#invoke:other uses|otheruses}} Template:Redirect Template:Use dmy dates Template:More citations needed
A newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in character encoding specifications such as ASCII, EBCDIC, Unicode, etc. This character, or a sequence of characters, is used to signify the end of a line of text and the start of a new one.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>
HistoryEdit
In the mid-1800s, long before the advent of teleprinters and teletype machines, Morse code operators or telegraphists invented and used Morse code prosigns to encode white space text formatting in formal written text messages. In particular, the Morse prosign Template:Overline (mnemonic break text), represented by the concatenation of literal textual Morse codes "B" and "T" characters, sent without the normal inter-character spacing, is used in Morse code to encode and indicate a new line or new section in a formal text message.
Later, in the age of modern teleprinters, standardized character set control codes were developed to aid in white space text formatting. ASCII was developed simultaneously by the International Organization for Standardization (ISO) and the American Standards Association (ASA), the latter being the predecessor organization to American National Standards Institute (ANSI). During the period of 1963 to 1968, the ISO draft standards supported the use of either [[#Representation|Template:Mono+Template:Mono]] or [[#Representation|Template:Mono]] alone as a newline, while the ASA drafts supported only Template:Mono+Template:Mono.
The sequence Template:Mono+Template:Mono was commonly used on many early computer systems that had adopted Teletype machines—typically a Teletype Model 33 ASR—as a console device, because this sequence was required to position those printers at the start of a new line. The separation of newline into two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in time to print the next character. Any character printed after a Template:Mono would often print as a smudge in the middle of the page while the print head was still moving the carriage back to the first position. "The solution was to make the newline two characters: Template:Mono to move the carriage to column one, and Template:Mono to move the paper up."<ref>Template:Cite book</ref> In fact, it was often necessary to send extra padding characters—extraneous CRs or NULs—which are ignored but give the print head time to move to the left margin. Many early video displays also required multiple character times to scroll the display.
On such systems, applications had to talk directly to the Teletype machine and follow its conventions since the concept of device drivers hiding such hardware details from the application was not yet well developed. Therefore, text was routinely composed to satisfy the needs of Teletype machines. Most minicomputer systems from DEC used this convention. CP/M also used it in order to print on the same terminals that minicomputers used. From there MS-DOS (1981) adopted CP/M's Template:Mono+Template:Mono in order to be compatible, and this convention was inherited by Microsoft's later Windows operating system.
The Multics operating system began development in 1964 and used Template:Mono alone as its newline. Multics used a device driver to translate this character to whatever sequence a printer needed (including extra padding characters), and the single byte was more convenient for programming. What seems like a more obvious choice – Template:Mono – was not used, as Template:Mono provided the useful function of overprinting one line with another to create boldface, underscore and strikethrough effects. Perhaps more importantly, the use of Template:Mono alone as a line terminator had already been incorporated into drafts of the eventual ISO/IEC 646 standard. Unix followed the Multics practice, and later Unix-like systems followed Unix. This created conflicts between Windows and Unix-like operating systems, whereby files composed on one operating system could not be properly formatted or interpreted by another operating system (for example a UNIX shell script written in a Windows text editor like Notepad<ref>Template:Cite news</ref><ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>).
RepresentationEdit
The concepts of carriage return (CR) and line feed (LF) are closely associated and can be considered either separately or together. In the physical media of typewriters and printers, two axes of motion, "down" and "across", are needed to create a new line on the page. Although the design of a machine (typewriter or printer) must consider them separately, the abstract logic of software can combine them together as one event. This is why a newline in character encoding can be defined as <syntaxhighlight lang="text" class="" style="" inline="1">CR</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">LF</syntaxhighlight> combined into one (commonly called <syntaxhighlight lang="text" class="" style="" inline="1">CR+LF</syntaxhighlight> or <syntaxhighlight lang="text" class="" style="" inline="1">CRLF</syntaxhighlight>).
Some character sets provide a separate newline character code. EBCDIC, for example, provides an Template:Mono character code in addition to the Template:Mono and Template:Mono codes. Unicode, in addition to providing the ASCII Template:Mono and Template:Mono control codes, also provides a "next line" (Template:Mono) control code, as well as control codes for "line separator" and "paragraph separator" markers. Unicode also contains printable characters for visually representing line feed ␊, carriage return ␍, and other C0 control codes (as well as a generic newline, ) in the Control Pictures block.
- EBCDIC systems—mainly IBM mainframe systems, including z/OS (OS/390) and IBM i (OS/400)—use Template:Mono (New Line, Template:Mono)<ref>IBM System/360 Reference Data Card, Publication GX20-1703, IBM Data Processing Division, White Plains, NY</ref> as the character combining the functions of line feed and carriage return. The equivalent Unicode character (<syntaxhighlight lang="text" class="" style="" inline="1">0x85</syntaxhighlight>) is called Template:Mono (Next Line). EBCDIC also has control characters called Template:Mono and Template:Mono, but the numerical value of Template:Mono (Template:Mono) differs from the one used by ASCII (Template:Mono). Additionally, some EBCDIC variants also use Template:Mono but assign a different numeric code to the character. However, those operating systems use a record-based file system, which stores text files as one record per line. In most file formats, no line terminators are actually stored.
- Operating systems for the CDC 6000 series defined a newline as two or more zero-valued six-bit characters at the end of a 60-bit word. Some configurations also defined a zero-valued character as a colon character, with the result that multiple colons could be interpreted as a newline depending on position.
- RSX-11 and OpenVMS also use a record-based file system, which stores text files as one record per line. In most file formats, no line terminators are actually stored, but the Record Management Services facility can transparently add a terminator to each line when it is retrieved by an application. The records themselves can contain the same line terminator characters, which can either be considered a feature or a nuisance depending on the application. RMS not only stores records, but also stores metadata about the record separators in different bits for the file to complicate matters even more (since files can have fixed length records, records that are prefixed by a count or records that are terminated by a specific character). The bits are not generic, so while they can specify that Template:MonoTemplate:Mono or Template:Mono or even Template:Mono is the line terminator, they can not substitute some other code.
- Fixed line length was used by some early mainframe operating systems. In such a system, an implicit end-of-line was assumed every 72 or 80 characters, for example. No newline character was stored. If a file was imported from the outside world, lines shorter than the line length had to be padded with spaces, while lines longer than the line length had to be truncated. This mimicked the use of punched cards, on which each line was stored on a separate card, usually with 80 columns on each card, often with sequence numbers in columns 73–80. Many of these systems added a carriage control character to the start of the next record; this could indicate whether the next record was a continuation of the line started by the previous record, or a new line, or should overprint the previous line (similar to a Template:Mono). Often this was a normal printing character such as <syntaxhighlight lang="text" class="" style="" inline="1">#</syntaxhighlight> that thus could not be used as the first character in a line. Some early line printers interpreted these characters directly in the records sent to them.
Communication protocolsEdit
Many communications protocols have some sort of new line convention. In particular, protocols published by the Internet Engineering Task Force (IETF) typically use the ASCII CRLF sequence.
In some older protocols, the new line may be followed by a checksum or parity character.
UnicodeEdit
Template:Redir The Unicode standard defines a number of characters that conforming applications should recognize as line terminators:<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>
Template:Mono: | Line Feed, Template:Mono |
Template:Mono: | Vertical Tab, Template:Mono |
Template:Mono: | Form Feed, Template:Mono |
Template:Mono: | Carriage Return, Template:Mono |
Template:Mono+Template:Mono: | Template:Mono (Template:Mono) followed by Template:Mono (Template:Mono) |
Template:Mono: | Next Line, Template:Mono |
Template:Mono: | Line Separator, Template:Mono |
Template:Mono: | Paragraph Separator, Template:Mono |
While it may seem overly complicated compared to an approach such as converting all line terminators to a single character (e.g. Template:Mono), because Unicode is designed to preserve all information when converting a text file from any existing encoding to Unicode and back (round-trip integrity), Unicode needs to make the same distinctions between line breaks made by other encodings. For instance EBCDIC has Template:Mono, Template:Mono, and Template:Mono characters, so all three have to also exist in Unicode.
Most newline characters and sequences are in ASCII's C0 controls (i.e. have Unicode code points up to Template:Mono). The three newline characters outside of this range—Template:Mono, Template:Mono and Template:Mono—are often not recognized as newlines by software. For example:
- JSON recognizes Template:Mono and Template:Mono as whitespace, but not any other newline characters.<ref>Template:Cite IETF</ref> C0 controls cannot appear unescaped within strings, but any other line break characters can.<ref>Template:Cite IETF</ref>
- ECMAScript only recognizes Template:Mono, Template:Mono, Template:Mono and Template:Mono as line terminators.<ref name="ES 2019">{{#invoke:citation/CS1|citation
|CitationClass=web }}</ref> Historically, unescaped line terminators were not permitted in string literals,<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> but this was changed in Template:Pslink to allow unescaped Template:Mono and Template:Mono in strings<ref name="ES 2019"/> for compatibility with JSON.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>
- YAML 1.1 recognized all three as line breaks; YAML 1.2 no longer recognizes them as line breaks in order to be compatible with JSON.<ref>{{#invoke:citation/CS1|citation
|CitationClass=web }}</ref>
- Windows Notepad, the default text editor of Microsoft Windows, does not treat any of Template:Mono, Template:Mono, or Template:Mono as line breaks.
- gedit, the default text editor of the GNOME desktop environment, treats Template:Mono and Template:Mono as line breaks, but not Template:Mono.
Unicode includes some glyphs intended for presenting a user-visible character to the reader of the document, and are thus not recognized themselves as a newline:
In programming languagesEdit
Template:Redir To facilitate creating portable programs, programming languages provide some abstractions to deal with the different types of newline sequences used in different environments.
The C language provides the escape sequences \n
(newline) and \r
(carriage return). However, these are not required to be equivalent to the ASCII Template:Mono and Template:Mono control characters. The C standard only guarantees two traits:
- Each of these escape sequences maps to a unique implementation-defined number that can be stored in one Template:Mono value.
- When writing to a file, device node, or socket/fifo in text mode,
\n
is transparently translated to the native newline sequence used by the system, which may be longer than one character. When reading in text mode, the native newline sequence is translated back to\n
. In binary mode, no translation is performed, and the internal representation produced by\n
is output directly.
On Unix operating system platforms, where C originated, the native newline sequence is ASCII Template:Mono (Template:Mono), so \n
was simply defined to be that value. With the internal and external representation being identical, the translation performed in text mode is a no-op, and Unix has no notion of text mode or binary mode. This has caused many programmers who developed their software on Unix systems simply to ignore the distinction completely, resulting in code that is not portable to different platforms.
The C standard library function Template:Mono is best avoided in binary mode because any file not written with the Unix newline convention will be misread. Also, in text mode, any file not written with the system's native newline sequence (such as a file created on a Unix system, then copied to a Windows system) will be misread as well.
Another common problem is the use of \n
when communicating using an Internet protocol that mandates the use of ASCII Template:Mono+Template:Mono for ending lines. Writing \n
to a text mode stream works correctly on Windows systems, but produces only Template:Mono on Unix, and something completely different on more exotic systems. Using \r\n
in binary mode is slightly better.
Many languages, such as C++, Perl,<ref>{{#invoke:citation/CS1|citation
|CitationClass=web
}}</ref> and Haskell provide the same interpretation of \n
as C. C++ has an alternative input/output (I/O) model where the manipulator Template:Mono can be used to output a newline (and flushes the stream buffer).
Java, PHP,<ref>{{#invoke:citation/CS1|citation
|CitationClass=web
}}</ref> and Python<ref>{{#invoke:citation/CS1|citation
|CitationClass=web
}}</ref> provide the \r\n
sequence (for ASCII Template:Mono+Template:Mono). In contrast to C, these are guaranteed to represent the values Template:Mono and Template:Mono, respectively.
The Java Class Library input/output (I/O) methods do not transparently translate these into platform-dependent newline sequences on input or output. Instead, they provide functions for writing a full line that automatically add the native newline sequence, and functions for reading lines that accept any of Template:Mono, Template:Mono, or Template:Mono+Template:Mono as a line terminator (see Template:Mono). The Template:Mono method can be used to retrieve the underlying line separator.
Example: <syntaxhighlight lang="java">
String eol = System.lineSeparator(); String lineColor = "Color: Red" + eol;
</syntaxhighlight>
Python permits "Universal Newline Support" when opening a file for reading, when importing modules, and when executing a file.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>
Some languages have created special variables, constants, and subroutines to facilitate newlines during program execution. In some languages such as PHP and Perl, double quotes are required to perform escape substitution for all escape sequences, including \n
and \r
. In PHP, to avoid portability problems, newline sequences should be issued using the PHP_EOL constant.<ref>{{#invoke:citation/CS1|citation
|CitationClass=web
}}</ref>
Example in C#: <syntaxhighlight lang="C#">
string eol = Environment.NewLine; string lineColor = "Color: Red" + eol; string eol2 = "\n"; string lineColor2 = "Color: Blue" + eol2;
</syntaxhighlight>
Issues with different newline formatsEdit
The different newline conventions cause text files that have been transferred between systems of different types to be displayed incorrectly.
Text in files created with programs which are common on Unix-like or classic Mac OS, appear as a single long line on most programs common to MS-DOS and Microsoft Windows because these do not display a single <syntaxhighlight lang="text" class="" style="" inline="1">line feed</syntaxhighlight> or a single <syntaxhighlight lang="text" class="" style="" inline="1">carriage return</syntaxhighlight> as a line break.
Conversely, when viewing a file originating from a Windows computer on a Unix-like system, the extra Template:Mono may be displayed as a second line break, as Template:Mono, or as Template:Mono at the end of each line.
Furthermore, programs other than text editors may not accept a file, e.g. some configuration file, encoded using the foreign newline convention, as a valid file.
The problem can be hard to spot because some programs handle the foreign newlines properly while others do not. For example, a compiler may fail with obscure syntax errors even though the source file looks correct when displayed on the console or in an editor. Modern text editors generally recognize all flavours of Template:Mono+Template:Mono newlines and allow users to convert between the different standards. Web browsers are usually also capable of displaying text files and websites which use different types of newlines.
Even if a program supports different newline conventions, these features are often not sufficiently labeled, described, or documented. Typically a menu or combo-box enumerating different newline conventions will be displayed to users without an indication if the selection will re-interpret, temporarily convert, or permanently convert the newlines. Some programs will implicitly convert on open, copy, paste, or save—often inconsistently.
Most textual Internet protocols (including HTTP, SMTP, FTP, IRC, and many others) mandate the use of ASCII Template:Mono+Template:Mono (\r\n
, Template:Mono) on the protocol level, but recommend that tolerant applications recognize lone Template:Mono (\n
, Template:Mono) as well. Despite the dictated standard, many applications erroneously use the C newline escape sequence \n
(Template:Mono) instead of the correct combination of carriage return escape and newline escape sequences \r\n
(Template:Mono+Template:Mono) (see section Newline in programming languages above). This accidental use of the wrong escape sequences leads to problems when trying to communicate with systems adhering to the stricter interpretation of the standards instead of the suggested tolerant interpretation. One such intolerant system is the qmail mail transfer agent that actively refuses to accept messages from systems that send bare Template:Mono instead of the required Template:Mono+Template:Mono.<ref>{{#invoke:citation/CS1|citation
|CitationClass=web
}}</ref>
The standard Internet Message Format<ref>Template:Cite IETF</ref> for email states: "CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body". Differences between SMTP implementations in how they treat bare LF and/or bare CR characters have led to SMTP spoofing attacks referred to as "SMTP smuggling".<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>
The File Transfer Protocol can automatically convert newlines in files being transferred between systems with different newline representations when the transfer is done in "ASCII mode". However, transferring binary files in this mode usually has disastrous results: any occurrence of the newline byte sequence—which does not have line terminator semantics in this context, but is just part of a normal sequence of bytes—will be translated to whatever newline representation the other system uses, effectively corrupting the file. FTP clients often employ some heuristics (for example, inspection of filename extensions) to automatically select either binary or ASCII mode, but in the end it is up to users to make sure their files are transferred in the correct mode. If there is any doubt as to the correct mode, binary mode should be used, as then no files will be altered by FTP, though they may display incorrectly.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>
Conversion between newline formatsEdit
Text editors are often used for converting a text file between different newline formats; most modern editors can read and write files using at least the different ASCII Template:Mono/Template:Mono conventions.
For example, the editor Vim can make a file compatible with the Windows Notepad text editor. Within vim <syntaxhighlight lang="vim">
:set fileformat=dos :wq
</syntaxhighlight> Editors can be unsuitable for converting larger files or bulk conversion of many files. For larger files (on Windows NT) the following command is often used: <syntaxhighlight lang="doscon"> D:\>TYPE unix_file | FIND /V "" > dos_file </syntaxhighlight> Special purpose programs to convert files between different newline conventions include [[unix2dos|Template:Mono and Template:Mono]], Template:Mono and Template:Mono, Template:Mono and Template:Mono, and Template:Mono.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> The Template:Mono command is available on virtually every Unix-like system and can be used to perform arbitrary replacement operations on single characters. A DOS/Windows text file can be converted to Unix format by simply removing all ASCII Template:Mono characters with
$ tr -d '\r' < inputfile > outputfile
or, if the text has only Template:Mono newlines, by converting all Template:Mono newlines to Template:Mono with
$ tr '\r' '\n' < inputfile > outputfile
The same tasks are sometimes performed with awk, sed, or in Perl if the platform has a Perl interpreter: <syntaxhighlight lang="console"> $ awk '{sub("$","\r\n"); printf("%s",$0);}' inputfile > outputfile # UNIX to DOS (adding CRs on Linux and BSD based OS that haven't GNU extensions) $ awk '{gsub("\r",""); print;}' inputfile > outputfile # DOS to UNIX (removing CRs on Linux and BSD based OS that haven't GNU extensions) $ sed -e 's/$/\r/' inputfile > outputfile # UNIX to DOS (adding CRs on Linux based OS that use GNU extensions) $ sed -e 's/\r$//' inputfile > outputfile # DOS to UNIX (removing CRs on Linux based OS that use GNU extensions) $ perl -pe 's/\r?\n|\r/\r\n/g' inputfile > outputfile # Convert to DOS $ perl -pe 's/\r?\n|\r/\n/g' inputfile > outputfile # Convert to UNIX $ perl -pe 's/\r?\n|\r/\r/g' inputfile > outputfile # Convert to old Mac </syntaxhighlight> The Template:Mono command can identify the type of line endings: <syntaxhighlight lang="console">
$ file myfile.txt myfile.txt: ASCII English text, with CRLF line terminators
</syntaxhighlight> The Unix egrep (extended grep) command can be used to print filenames of Unix or DOS files (assuming Unix and DOS-style files only, no classic Mac OS-style files): <syntaxhighlight lang="console"> $ egrep -L '\r\n' myfile.txt # show UNIX style file (LF terminated) $ egrep -l '\r\n' myfile.txt # show DOS style file (CRLF terminated) </syntaxhighlight>
Other tools permit the user to visualise the EOL characters: <syntaxhighlight lang="console"> $ od -a myfile.txt $ cat -e myfile.txt $ cat -v myfile.txt $ hexdump -c myfile.txt </syntaxhighlight>
InterpretationEdit
Two ways to view newlines, both of which are self-consistent, are that newlines either separate lines or that they terminate lines. If a newline is considered a separator, there will be no newline after the last line of a file. Some programs have problems processing the last line of a file if it is not terminated by a newline. On the other hand, programs that expect newline to be used as a separator will interpret a final newline as starting a new (empty) line. Conversely, if a newline is considered a terminator, all text lines including the last are expected to be terminated by a newline. If the final character sequence in a text file is not a newline, the final line of the file may be considered to be an improper or incomplete text line, or the file may be considered to be improperly truncated.
In text intended primarily to be read by humans using software which implements the word wrap feature, a newline character typically only needs to be stored if a line break is required independent of whether the next word would fit on the same line, such as between paragraphs and in vertical lists. Therefore, in the logic of word processing and most text editors, newline is used as a paragraph break and is known as a "hard return", in contrast to "soft returns" which are dynamically created to implement word wrapping and are changeable with each display instance. In many applications a separate control character called "manual line break" exists for forcing line breaks inside a single paragraph. The glyph for the control character for a hard return is usually a pilcrow (¶), and for the manual line break is usually a carriage return arrow (↵).
Reverse and partial line feedsEdit
Template:Mono (U+008D REVERSE LINE FEED,<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> ISO/IEC 6429 8D, decimal 141) is used to move the printing position back one line (by reverse feeding the paper, or by moving a display cursor up one line) so that other characters may be printed over existing text. This may be done to make them bolder, or to add underlines, strike-throughs or other characters such as diacritics.
Similarly, Template:Mono (U+008B PARTIAL LINE FORWARD, decimal 139) and Template:Mono (U+008C PARTIAL LINE BACKWARD, decimal 140) can be used to advance or reverse the text printing position by some fraction of the vertical line spacing (typically, half). These can be used in combination for subscripts (by advancing and then reversing) and superscripts (by reversing and then advancing), and may also be useful for printing diacritics.
See alsoEdit
ReferencesEdit
External linksEdit
- The Unicode reference; see paragraph 5.8 in Chapter 5 of the Unicode 4.0 standard (PDF)
- {{#invoke:citation/CS1|citation
|CitationClass=web }}