Here document: Difference between revisions

From Rosetta Code
Content added Content deleted
 
(44 intermediate revisions by 23 users not shown)
Line 9: Line 9:
;Task:
;Task:
Demonstrate the use of   ''here documents''   within the language.
Demonstrate the use of   ''here documents''   within the language.



;Related task:
;Related task:
*   [[Documentation]]
*   [[Documentation]]
<br><br>
<br><br>

{{omit from|Delphi}}


=={{header|11l}}==
=={{header|11l}}==
11l does not have here-docs. It does however have raw strings which can be used similarly.
11l does not have here-docs. It does however have raw strings which can be used similarly.
<lang 11l>print(‘
<syntaxhighlight lang="11l">print(‘
here
here
doc
doc
’)</lang>
’)</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
Multiline strings are simply parsed using "quote", which parses first a character to use as a separator, and scans until that character is found:
Multiline strings are simply parsed using "quote", which parses first a character to use as a separator, and scans until that character is found:
<lang forth>
<syntaxhighlight lang="forth">
quote *
quote *
Hi
Hi
there
there
* .
* .
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 41: Line 42:
A workaround is to use containers of strings:
A workaround is to use containers of strings:


<lang Ada>with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;


procedure Here_Doc is
procedure Here_Doc is
Line 60: Line 61:
Ada.Text_IO.Put_Line(Document.Element(I));
Ada.Text_IO.Put_Line(Document.Element(I));
end loop;
end loop;
end Here_Doc;</lang>
end Here_Doc;</syntaxhighlight>


{{out}}
{{out}}
Line 75: Line 76:
It can be crudely achieved using an array of strings:
It can be crudely achieved using an array of strings:


<lang algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #


[]STRING help = (
[]STRING help = (
Line 92: Line 93:
"Dammit. Janet, I love you."
"Dammit. Janet, I love you."
))
))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 106: Line 107:
Dammit. Janet, I love you.</pre>
Dammit. Janet, I love you.</pre>


=={{header|APL}}==
{{works with|GNU APL}}
See the GNU APL docs: [https://www.gnu.org/software/apl/apl.html#Section-2_002e1 2.1.4 Helpful Features for Scripting]
<syntaxhighlight lang="apl">
BODY←⎕INP 'END-OF-⎕INP'
First line
Second line
Third line
...
END-OF-⎕INP
</syntaxhighlight>
A related concept is multi-line strings (note the 6 space indent of APL interactive input vs. output):
<syntaxhighlight lang="apl">
]boxing 8
s ← """
→ abc
→ def
→ GHIJK
→ """
s</syntaxhighlight>
{{out}}
<pre>┌┌→────────────────────────────────────────┐
│┌→──────┐ ┌→────────┐ ┌⊖┐ ┌→────────────┐ │
││ abc│ │ def│ │ │ │ GHIJK│ │
│└───────┘ └─────────┘ └─┘ └─────────────┘ │
└∊─────────────────────────────────────────┘</pre>

=={{header|Applesoft BASIC}}==
Strings are limited to 255 characters. The double quote character delimits strings, so double quote cannot be embedded directly. The double quote can be included in a DATA statement if the text is not wrapped in quotes. Most control characters, with the exception of Return ^M, Backspace ^H, Forward-space ^U and Escape ^[, can be typed into strings. Control characters are not usually visible. The line feed character ^J moves the cursor position down one line, and the ^G character is audible!
<syntaxhighlight lang="gwbasic"> 0 Q$ = CHR$ (34)
1 M$ = CHR$ (13)
2 PRINT Q$"Oh, Danny Boy,"M$"The pipes, the pipes are calling"M$"From glen to glen and down the mountainside"Q$</syntaxhighlight>
There are tools and tricks to embed control characters like Return directly into the program.
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program heredoc.s */
/* program heredoc.s */
Line 165: Line 200:
pop {r0,r1,r2,r7,lr} @ restaur registers
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
bx lr @ return
</syntaxhighlight>
</lang>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">print {:
The “Red Death” had long devastated the country.
No pestilence had ever been so fatal, or so hideous.

Blood was its Avator and its seal—
the redness and the horror of blood.

There were sharp pains,
and sudden dizziness,
and then profuse bleeding at the pores,
with dissolution.
The scarlet stains upon the body
and especially upon the face of the victim,
were the pest ban
which shut him out from the aid
and from the sympathy of his fellow-men.

And the whole seizure,
progress and termination of the disease,
were the incidents of half an hour.
:}</syntaxhighlight>

{{out}}

<pre> The “Red Death” had long devastated the country.
No pestilence had ever been so fatal, or so hideous.

Blood was its Avator and its seal—
the redness and the horror of blood.

There were sharp pains,
and sudden dizziness,
and then profuse bleeding at the pores,
with dissolution.
The scarlet stains upon the body
and especially upon the face of the victim,
were the pest ban
which shut him out from the aid
and from the sympathy of his fellow-men.

And the whole seizure,
progress and termination of the disease,
were the incidents of half an hour.</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
AutoHotkey uses "continuation sections" for literal text:
AutoHotkey uses "continuation sections" for literal text:


<lang AutoHotkey>MyVar = "This is the text inside MyVar"
<syntaxhighlight lang="autohotkey">MyVar = "This is the text inside MyVar"
MyVariable =
MyVariable =
(
(
Line 178: Line 261:
Variable references such as %MyVar% are expanded.
Variable references such as %MyVar% are expanded.
)
)
MsgBox % MyVariable</lang>
MsgBox % MyVariable</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


The awk extraction and reporting language does not provide any markup facility for embedding here documents within an awk script. The awk utility is really a helper tool often used from within the Unix shell. The Unix shell in which awk scripts are usually embedded does support the use of here documents, and the way that here documents are used within the shell make them ideal for passing to awk as is, without the need for an additional facility in awk.
The awk extraction and reporting language does not provide any markup facility for embedding here documents within an awk script. The awk utility is really a helper tool often used from within the Unix shell. The Unix shell in which awk scripts are usually embedded does support the use of here documents, and the way that here documents are used within the shell make them ideal for passing to awk as is, without the need for an additional facility in awk.

=={{header|BQN}}==
Works in: [[CBQN]]

The default string syntax in BQN allows multiline strings. Strings start and end with a double quote, and quotes within the text can be escaped by typing two quotes.

<syntaxhighlight lang="bqn">•Out "dsdfsdfsad
""fsadf""sdf"</syntaxhighlight><syntaxhighlight lang="text">dsdfsdfsad
"fsadf"sdf</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Strings in Bracmat can continue over many lines. They start and end with a quote. Quotes in the text must be escaped with a reverse solidus, like the reverse solidus itself.
Strings in Bracmat can continue over many lines. They start and end with a quote. Quotes in the text must be escaped with a reverse solidus, like the reverse solidus itself.


<lang bracmat>( {Multiline string:}
<syntaxhighlight lang="bracmat">( {Multiline string:}
"
"
Second line
Second line
Line 196: Line 288:
& out$("Multiline string:")
& out$("Multiline string:")
& out$(!stringA)
& out$(!stringA)
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>Multiline string:
<pre>Multiline string:
Line 206: Line 298:
</pre>
</pre>


=={{header|C}}==
=={{header|BaCon}}==
<syntaxhighlight lang="freebasic">
The program speaks for itself ;)
'--- we dont have a print here doc built-in command in BaCon
<lang C>
'--- we can get the end result like this with the newline NL$
#include <stdio.h>


PRINT "To use Bacon your system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available." NL$ \
int main() {
"If none of these shells are available on your platform, download and install the free Public Domain Korn Shell which can" NL$ \
puts(
"execute BaCon also. Furthermore BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell." NL$ NL$ \
"The Heredoc task was marked not implementable in C.\n"
"BaCon intends to be a programming aid in creating tools which can be compiled on different platforms" NL$ \
"Frankly the person who did so seems to have little idea\n"
"(including 64bit environments). It tries to revive the days of the good old BASIC." NL$
"of what C is capable of.\n"
"After all, what would one call this multiline string?\n"
"I may be old, but do not forget that it all started with me.\n"
"Ever enigmatic...\n\n"
"C "
);


</syntaxhighlight>
return 0;
}
</lang>
Output:
Output:
<pre>To use Bacon your system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available.
If none of these shells are available on your platform, download and install the free Public Domain Korn Shell which can
execute BaCon also. Furthermore BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell.

BaCon intends to be a programming aid in creating tools which can be compiled on different platforms
(including 64bit environments). It tries to revive the days of the good old BASIC.</pre>


=={{header|BASIC}}==
BASIC no tiene heredocs ni cadenas de varias líneas. Una solución
alternativa es unir varias cadenas en una línea con CHR$(10).
<syntaxhighlight lang="basic">
text1$ = " " + CHR$(10) + "<<'FOO' " + CHR$(10) + " 'jaja', `esto`" + CHR$(10) + " <simula>" + CHR$(10) + " \un\" + CHR$(10) + " ${ejemplo} de 'heredoc'" + CHR$(10) + " en QBASIC."

text2$ = "Esta es la primera línea." + CHR$(10) + "Esta es la segunda línea." + CHR$(10) + "Esta 'línea' contiene comillas."

PRINT text1$
PRINT
PRINT text2$
END
</syntaxhighlight>
{{out}}
<pre>
<pre>
Igual que la entrada de FreeBASIC.
The Heredoc task was marked not implementable in C.
</pre>
Frankly the person who did so seems to have little idea
of what C is capable of.
After all, what would one call this multiline string?
I may be old, but do not forget that it all started with me.
Ever enigmatic...



C
=={{header|BASIC256}}==
BASIC256 no tiene heredocs ni cadenas de varias líneas. Una solución
alternativa es unir varias cadenas en una línea con chr(10).
<syntaxhighlight lang="basic256">
text1$ = " " & chr(10) & "<<#FOO# " & chr(10) & " #jaja#, `esto`" & chr(10) & " <simula>" & chr(10) & " \un\" & chr(10) & " ${ejemplo} de 'heredoc'" & chr(10) & " en BASIC256."

text2$ = "Esta es la primera linea." & chr(10) & "Esta es la segunda linea." & chr(10) & "Esta 'linea' contiene comillas."

print text1$
print
print text2$
end
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
</pre>

=={{header|Blade}}==
<syntaxhighlight lang="blade">echo 'All strings
support
multiline
in Blade'</syntaxhighlight>
{{out}}
<pre>
All strings
support
multiline
in Blade
</pre>



=={{header|C sharp}}==
=={{header|C sharp}}==
C# has a string literal call which is used for heredoc functionality
C# has a string literal call which is used for heredoc functionality


<lang C sharp>using System;
<syntaxhighlight lang="c sharp">using System;


class Program
class Program
Line 252: Line 385:
in C#");
in C#");
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 258: Line 391:
C++11 raw string literals are similar to heredocs, except there is no newline after the opening token or before the ending token (unless you actually want newlines there).
C++11 raw string literals are similar to heredocs, except there is no newline after the opening token or before the ending token (unless you actually want newlines there).


<lang cpp>#include <iostream> // Only for cout to demonstrate
<syntaxhighlight lang="cpp">#include <iostream> // Only for cout to demonstrate


int main()
int main()
Line 275: Line 408:
or recognized, and all whitespace is preserved.
or recognized, and all whitespace is preserved.
)EOF";
)EOF";
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 285: Line 418:
CoffeeScript borrows the triple-quoted string syntax from Python. Note that these strings strip leading whitespace in CoffeeScript, to allow you to neatly align the heredoc string.
CoffeeScript borrows the triple-quoted string syntax from Python. Note that these strings strip leading whitespace in CoffeeScript, to allow you to neatly align the heredoc string.


<lang coffeescript>myDoc = '''
<syntaxhighlight lang="coffeescript">myDoc = '''
Single-quoted heredocs allows no '#{foo}' interpolation.
Single-quoted heredocs allows no '#{foo}' interpolation.
This behavior is similar to single-quoted strings.
This behavior is similar to single-quoted strings.
Line 295: Line 428:
"""
"""


console.log doc2</lang>
console.log doc2</syntaxhighlight>


{{out}}
{{out}}
Line 311: Line 444:
[https://github.com/e-user/cl-heredoc cl-heredoc] provide read-macro for heredoc:
[https://github.com/e-user/cl-heredoc cl-heredoc] provide read-macro for heredoc:


<lang lisp>;; load cl-heredoc with QuickLisp
<syntaxhighlight lang="lisp">;; load cl-heredoc with QuickLisp
(ql:quickload 'cl-heredoc)
(ql:quickload 'cl-heredoc)


Line 321: Line 454:
no matter how many lines or what characters until
no matter how many lines or what characters until
the magic end sequence has been reached!eof1)
the magic end sequence has been reached!eof1)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 331: Line 464:


Note: <code>NIL</code> is the return value of function <code>format</code> when first argument is <code>t</code>
Note: <code>NIL</code> is the return value of function <code>format</code> when first argument is <code>t</code>

=={{header|Crystal}}==
<syntaxhighlight lang="ruby">puts <<-DOC
this is a heredoc
it preserves indents and newlines
the DOC identifier is completely arbitrary
it can be lowercase, a keyword, or even a number (but not a float)
DOC</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.string;
<syntaxhighlight lang="d">import std.stdio, std.string;


void main() {
void main() {
Line 353: Line 494:


// std.string.outdent is used to remove the four spaces indent.
// std.string.outdent is used to remove the four spaces indent.
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>a string that you "don't" have to escape
<pre>a string that you "don't" have to escape
Line 363: Line 504:
=={{header|DWScript}}==
=={{header|DWScript}}==
Double-quotes (") denote a multi-line string, to include a double-quote in such a string, you need to double it.
Double-quotes (") denote a multi-line string, to include a double-quote in such a string, you need to double it.
<lang delphi>PrintLn("This is
<syntaxhighlight lang="delphi">PrintLn("This is
a multiline
a multiline
""string""
""string""
sample");</lang>
sample");</syntaxhighlight>
{{out}}
{{out}}
<pre>This is
<pre>This is
Line 372: Line 513:
"string"
"string"
sample</pre>
sample</pre>

=={{header|EasyLang}}==
<syntaxhighlight>
# The here-document is not here, but at the end of the program
repeat
s$ = input
until error = 1
print s$
.
input_data
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
- """ is also interpreted literally.

`Have fun!`
</syntaxhighlight>
{{out}}
<pre>
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
- """ is also interpreted literally.

`Have fun!`
</pre>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
Line 425: Line 594:
=={{header|Elixir}}==
=={{header|Elixir}}==
In Elixir, one can use either a pair of triple single-quotation marks or a pair of triple double-quotation marks, but in both cases, string interpolation occurs:
In Elixir, one can use either a pair of triple single-quotation marks or a pair of triple double-quotation marks, but in both cases, string interpolation occurs:
<lang elixir>IO.puts """
<syntaxhighlight lang="elixir">IO.puts """
привет
привет
мир
мир
"""</lang>
"""</syntaxhighlight>
produces:<lang sh>привет
produces:<syntaxhighlight lang="sh">привет
мир</lang>
мир</syntaxhighlight>


Here is an illustrative iex transcript:
Here is an illustrative iex transcript:
<lang elixir>iex(1)> a=2
<syntaxhighlight lang="elixir">iex(1)> a=2
2
2
iex(2)> '''
iex(2)> '''
Line 443: Line 612:
** (SyntaxError) iex:3: heredoc start must be followed by a new line after '''
** (SyntaxError) iex:3: heredoc start must be followed by a new line after '''
iex(3)></lang>
iex(3)></syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Multiline strings look like this in the Erlang shell:
Multiline strings look like this in the Erlang shell:
<syntaxhighlight lang="erlang">
<lang Erlang>
2> S = " ad
2> S = " ad
2> 123
2> 123
Line 455: Line 624:
123
123
the end
the end
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Line 470: Line 639:


=={{header|Factor}}==
=={{header|Factor}}==
Factor strings surround by '"' are multiline, but accept escape sequences (like "\n", "\uxxxxxxxx"). Strings surrounded by '"""' don't have to escape '"'. Use HEREDOC: (and other variants) for verbatim text
Factor strings surround by '"' are multiline, but accept escape sequences (like "\n", "\uxxxxxxxx"). Strings surrounded by '"""' don't have to escape '"'. Use HEREDOC: (and other variants, like <pre>[[</pre>) for verbatim text
<lang factor>" a multiline
<syntaxhighlight lang="factor">" a multiline
string\n(with escape sequences: \u{greek-capital-letter-sigma})
string\n(with escape sequences: \u{greek-capital-letter-sigma})
"
"
"""this is "easier".."""
"""this is "easier".."""



HEREDOC: EOF
HEREDOC: EOF
this
this
is not \n escaped at all
is not \n escaped at all
EOF</lang>
EOF</syntaxhighlight>

[[ this also works , but needs a space at the start (but not the end)]]
[[this won't work]]
[=[ this works like [[, but I can write [[ and ]] without restriction]=]
[==[ it keeps going]==]
[===[ like this]===]
[====[ for a while]====]


=={{header|Forth}}==
=={{header|Forth}}==
Line 484: Line 663:
===version 1===
===version 1===
{{works with|GForth}}
{{works with|GForth}}
<lang Forth>\ GForth specific words:
<syntaxhighlight lang="forth">\ GForth specific words:
\ under+ ( a b c -- a+c b) , latest ( -- nt ) , name>string ( nt -- ca u )
\ under+ ( a b c -- a+c b) , latest ( -- nt ) , name>string ( nt -- ca u )
\ Should not be a problem to modify it to work with other Forth implementation:
\ Should not be a problem to modify it to work with other Forth implementation:
Line 532: Line 711:
>> RABBIT
>> RABBIT
RABBIT
RABBIT
ALICE type ." --" cr RABBIT type</lang>
ALICE type ." --" cr RABBIT type</syntaxhighlight>


<pre>
<pre>
Line 550: Line 729:


It's written to works with Forth's default implementation of counted strings. Those are limited to 255 characters, which is fine in many cases, but on the short side for here documents, so therefore we temporarily redefine them to use a full cell for size (16 bits would probably be ideal) while compiling the here document words.
It's written to works with Forth's default implementation of counted strings. Those are limited to 255 characters, which is fine in many cases, but on the short side for here documents, so therefore we temporarily redefine them to use a full cell for size (16 bits would probably be ideal) while compiling the here document words.
<lang Forth>get-current get-order wordlist swap 1+ set-order definitions
<syntaxhighlight lang="forth">get-current get-order wordlist swap 1+ set-order definitions
: place over >r rot over cell+ r> move ! ;
: place over >r rot over cell+ r> move ! ;
: +place 2dup >r >r dup @ cell+ + swap move r> r> dup @ rot + swap ! ;
: +place 2dup >r >r dup @ cell+ + swap move r> r> dup @ rot + swap ! ;
Line 577: Line 756:
~~ end ~~
~~ end ~~


Alice type bye</lang>
Alice type bye</syntaxhighlight>


{{out}}
{{out}}
Line 590: Line 769:


Producing a source file containing a block of text that will be presented as output in the same layout (new lines and all) is only possible if the added layout stuff (generating the required new line starts) and delimiters in the source are disregarded. But if one accepts a few constraints, the following shows a possible approach:
Producing a source file containing a block of text that will be presented as output in the same layout (new lines and all) is only possible if the added layout stuff (generating the required new line starts) and delimiters in the source are disregarded. But if one accepts a few constraints, the following shows a possible approach:
<syntaxhighlight lang="fortran">
<lang Fortran>
INTEGER I !A stepper.
INTEGER I !A stepper.
CHARACTER*666 I AM !Sufficient space.
CHARACTER*666 I AM !Sufficient space.
Line 608: Line 787:
END DO !On to the next line.
END DO !On to the next line.
END
END
</syntaxhighlight>
</lang>
With old-style fixed-format source, rather amusingly there is space for sixty-six characters of text per line and so this is the canvas. Any usage of tab characters must be resolved into spaces (and some compilers count up to 72 oddly when tabs are involved) and likewise with new lines. A surprise was provided to an old-time card flapper when it became apparent that trailing spaces were ''not'' being incorporated into the text literal unless the "<col72" markers were appended to column seventy-two of the source. An old-time card deck copied to disc and with the sequence numbers in columns 73-80 removed (as no-one is going to drop a disc file so some storage space can be saved) might thereby compile incorrectly! Similarly, the source text highlighter here does not fully recognise the odd tricks available for Fortran syntax, apparently deeming the comments a part of a text literal. The F90 compiler's highlighting does, and shows that text beyond column 72 is not Fortran code.
With old-style fixed-format source, rather amusingly there is space for sixty-six characters of text per line and so this is the canvas. Any usage of tab characters must be resolved into spaces (and some compilers count up to 72 oddly when tabs are involved) and likewise with new lines. A surprise was provided to an old-time card flapper when it became apparent that trailing spaces were ''not'' being incorporated into the text literal unless the "<col72" markers were appended to column seventy-two of the source. An old-time card deck copied to disc and with the sequence numbers in columns 73-80 removed (as no-one is going to drop a disc file so some storage space can be saved) might thereby compile incorrectly! Similarly, the source text highlighter here does not fully recognise the odd tricks available for Fortran syntax, apparently deeming the comments a part of a text literal. The F90 compiler's highlighting does, and shows that text beyond column 72 is not Fortran code.


Line 625: Line 804:
In Pascal, the only forbidden character in string literals is the newline character.
In Pascal, the only forbidden character in string literals is the newline character.
However, as of 2019‑09‑06 in a trunk version of the FPC (Free Pascal compiler) support for string literals spanning multiple lines can be enabled.
However, as of 2019‑09‑06 in a trunk version of the FPC (Free Pascal compiler) support for string literals spanning multiple lines can be enabled.


=={{header|FreeBASIC}}==
FreeBASIC no tiene heredocs ni cadenas de varias líneas. Una solución
alternativa es unir varias líneas con NL, LF, \n o Chr(10).
<syntaxhighlight lang="freebasic">
Dim As String text1 = " " & Chr(10) & _
"<<'FOO' " & Chr(10) & _
" 'jaja', `esto`" & Chr(10) & _
" <simula>" & Chr(10) & _
" \un\" & Chr(10) & _
!" ${ejemplo} de \"heredoc\"" & Chr(10) & _
" en FreeBASIC."

Dim As String text2 = "Esta es la primera linea." & Chr(10) & _
"Esta es la segunda linea." & Chr(10) & _
!"Esta \"linea\" contiene comillas."

Print text1
Print Chr(10) + text2
Sleep
</syntaxhighlight>
{{out}}
<pre>
<<'FOO'
'jaja', `esto`
<simula>
\un\
${ejemplo} de "heredoc"
en FreeBASIC.

Esta es la primera linea.
Esta es la segunda linea.
Esta "linea" contiene comillas.
</pre>



=={{header|Frink}}==
=={{header|Frink}}==
Frink does not have awkward here-docs. Triple-quoted strings serve the same purpose, but more concisely. (The Perl, PHP, etc. syntax for here-documents is a violation of the "define everything at most once" principle of software engineering.) Variable interpolation is allowed within triple-quoted strings.
Frink does not have awkward here-docs. Triple-quoted strings serve the same purpose, but more concisely. (The Perl, PHP, etc. syntax for here-documents is a violation of the "define everything at most once" principle of software engineering.) Variable interpolation is allowed within triple-quoted strings.
<lang frink>
<syntaxhighlight lang="frink">
lyrics = """Oh, Danny Boy,
lyrics = """Oh, Danny Boy,
The pipes, the pipes are calling
The pipes, the pipes are calling
From glen to glen and down the mountainside"""
From glen to glen and down the mountainside"""
</syntaxhighlight>
</lang>


=={{header|Genie}}==
=={{header|Genie}}==
Genie includes triple quoted verbatim strings and "at" quoted template strings, which can be used as Heredoc data in source. Given the limitation of terminating quotes not being a user defined sequence, inner quotations will need to be escaped or transcluded.
Genie includes triple quoted verbatim strings and "at" quoted template strings, which can be used as Heredoc data in source. Given the limitation of terminating quotes not being a user defined sequence, inner quotations will need to be escaped or transcluded.


<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
Here documents, as template and verbatim strings in Genie
Here documents, as template and verbatim strings in Genie
Line 655: Line 870:


stdout.printf("%s", multilineString)
stdout.printf("%s", multilineString)
stdout.printf("%s", templateString)</lang>
stdout.printf("%s", templateString)</syntaxhighlight>


{{out}}
{{out}}
Line 669: Line 884:
Go does not have here documents. Multiline string literals serve this purpose.
Go does not have here documents. Multiline string literals serve this purpose.


<lang go>var m = ` leading spaces
<syntaxhighlight lang="go">var m = ` leading spaces


and blank lines`</lang>
and blank lines`</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Line 678: Line 893:
===Multi-line String literal===
===Multi-line String literal===
The literal text, preserving lines and spacing
The literal text, preserving lines and spacing
<lang groovy>println '''
<syntaxhighlight lang="groovy">println '''
Time's a strange fellow;
Time's a strange fellow;
more he gives than takes
more he gives than takes
Line 685: Line 900:
losing, gaining
losing, gaining
--love! if a world ends
--love! if a world ends
'''</lang>
'''</syntaxhighlight>


{{out}}
{{out}}
Line 699: Line 914:
===Multi-line GString expression===
===Multi-line GString expression===
Like single-line GString expressions, any subexpression delimited with ${ } is substituted with its "toString()" value. Preserves lines and spacing outside of the subexpressions.
Like single-line GString expressions, any subexpression delimited with ${ } is substituted with its "toString()" value. Preserves lines and spacing outside of the subexpressions.
<lang groovy>def expired='defunct'
<syntaxhighlight lang="groovy">def expired='defunct'
def horse='stallion'
def horse='stallion'
def christ='Jesus'
def christ='Jesus'
Line 716: Line 931:
how do you like your blueeyed boy
how do you like your blueeyed boy
Mister Death
Mister Death
"""</lang>
"""</syntaxhighlight>


{{out}}
{{out}}
Line 736: Line 951:
=={{header|Haskell}}==
=={{header|Haskell}}==


You could use [https://hackage.haskell.org/package/raw-strings-qq raw-strings-qq], or alternatively:
<lang Haskell>

<syntaxhighlight lang="haskell">


main :: IO ()
main :: IO ()
Line 755: Line 972:
]
]


</syntaxhighlight>
</lang>


Output:
Output:
Line 772: Line 989:


=={{header|J}}==
=={{header|J}}==
<lang j>here=:0 :0
<syntaxhighlight lang="j">here=:0 :0
0 :0 will be replaced by the text on the following lines.
0 :0 will be replaced by the text on the following lines.
This is three tokens: two instances of the number 0 and
This is three tokens: two instances of the number 0 and
Line 811: Line 1,028:
note that this mechanism is significantly more verbose than using
note that this mechanism is significantly more verbose than using
the underlying 0 :0 mechanism directly.
the underlying 0 :0 mechanism directly.
)
)</lang>

also_here=: {{)n
J902 introduced {{ blocks which may be {{ nested }} arbitrarily }} to
the J interpreter. This includes {{)n blocks which are here documents.
These {{)n blocks are not further nestable (they represent
literal text with no internal structure), and the terminating }}
must appear at the beginning of a line (or on the same line as
the opening {{)n -- but that would not be a "here doc").

If text does not appear after the )n on the initial line, the
initial (first) linefeed does not appear in the here doc. If
text follows the {{)n, that text (and optional newline) would
be included.
}}</syntaxhighlight>

=={{Header|Java}}==
[[User:Sjharper79|Sjharper79]] ([[User talk:Sjharper79|talk]])

====Compatibility====
The Java feature 'Text Blocks' is only available with JDK 15 and above.

====Syntax====
You must include a newline character after the opening """, you cannot include any Strings after the opening """. The closing """ does not have to be on its own line.

See [https://www.demo2s.com/java/java-17-string-block-for-multiline-java-string.html Java 17 String block for Multiline Java String].

<syntaxhighlight lang=java>
package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
</syntaxhighlight>

====Output====
<pre>
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 817: Line 1,080:
ES6 introduced template literals. These are string literals that suport multi-line text and can include
ES6 introduced template literals. These are string literals that suport multi-line text and can include
interpolated expressions using ${···} syntax. It is indicated with the backtich character [`]
interpolated expressions using ${···} syntax. It is indicated with the backtich character [`]
<lang JavaScript>const myVar = 123;
<syntaxhighlight lang="javascript">const myVar = 123;
const tempLit = `Here is some
const tempLit = `Here is some
multi-line string. And here is
multi-line string. And here is
Line 823: Line 1,086:
That's all.`;
That's all.`;
console.log(tempLit)
console.log(tempLit)
</syntaxhighlight>
</lang>


<pre>Here is some
<pre>Here is some
Line 833: Line 1,096:
No special syntax is required to support "here documents" in jq in that any JSON string, and indeed any string specifier (as explained below), can be presented using a multiline format.
No special syntax is required to support "here documents" in jq in that any JSON string, and indeed any string specifier (as explained below), can be presented using a multiline format.


For example, consider:<lang jq>
For example, consider:<syntaxhighlight lang="jq">
def s:
def s:
"x
"x
Line 839: Line 1,102:
z";
z";


s</lang>
s</syntaxhighlight>
{{Out}}
{{Out}}
<lang sh>$ jq -n s.jq
<syntaxhighlight lang="sh">$ jq -n s.jq
"x\ny\nz"</lang>
"x\ny\nz"</syntaxhighlight>


String specifiers, that is possibly non-JSON strings which incorporate references to jq expressions, are handled in the same way. For example, the following program produces the same result:
String specifiers, that is possibly non-JSON strings which incorporate references to jq expressions, are handled in the same way. For example, the following program produces the same result:
<lang jq>def specifier(a):
<syntaxhighlight lang="jq">def specifier(a):
"x
"x
\(a)
\(a)
z";
z";


specifier("y")</lang>
specifier("y")</syntaxhighlight>


Most control characters, such as Control-A and Control-Z, can also be presented literally, but the RosettaCode.org editor disallows them in general, so the next example only shows an embedded literal tab:
Most control characters, such as Control-A and Control-Z, can also be presented literally, but the RosettaCode.org editor disallows them in general, so the next example only shows an embedded literal tab:
<lang jq>"a
<syntaxhighlight lang="jq">"a
tab: end
tab: end
parens:()
parens:()
Line 859: Line 1,122:
double quotation mark must be escaped:\"
double quotation mark must be escaped:\"
b
b
d"</lang>
d"</syntaxhighlight>
{{out}}
{{out}}
<lang sh>"a\ntab:\tend\nparens:()\nsingle quotation mark:'\ndouble quotation mark must be escaped:\"\nb\nd"</lang>
<syntaxhighlight lang="sh">"a\ntab:\tend\nparens:()\nsingle quotation mark:'\ndouble quotation mark must be escaped:\"\nb\nd"</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Like Python, Julia has triple-quoted string literals, which are similar to here-docs:
Like Python, Julia has triple-quoted string literals, which are similar to here-docs:


<lang julia>print("""\
<syntaxhighlight lang="julia">print("""\
Usage: thingy [OPTIONS]
Usage: thingy [OPTIONS]
-h Display this usage message
-h Display this usage message
-H hostname Hostname to connect to
-H hostname Hostname to connect to
""")</lang>
""")</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 880: Line 1,143:


Here's an example of all this:
Here's an example of all this:
<lang scala>// version 1.1.0
<syntaxhighlight lang="scala">// version 1.1.0


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 907: Line 1,170:


println(here)
println(here)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 931: Line 1,194:


</pre>
</pre>

=={{header|Lambdatalk}}==
Lambdatalk inverts the standard evaluation process, nothing is evaluated out of S-expressions {first rest}.

<syntaxhighlight lang="scheme">
1) defining a variable:
{def myVar 123}

2) defining some text:
Here is some
multi-line string. And here is
the value of "myVar": '{myVar}
That's all.

3) displays :

Here is some
multi-line string. And here is
the value of "myVar": 123
That's all.
</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
Use a block modifier on a string literal using the qs or QS form to generate a blockquote. The block modifier must be the last modifier.
{{works with|langur|0.6}}


<syntaxhighlight lang="langur">val .s = qs:block END
Use a block modifier on a string literal using the q or Q form. The block modifier must be the last modifier.
We put our text here.
Here we are, Doc.
END</syntaxhighlight>


Use the lead modifier to strip leading white space on each line.
<lang langur>val .s = q:block END

<syntaxhighlight lang="langur">val .s = qs:lead:block END
We put our text here.
We put our text here.
Here we are, doc.
Here we are, Doc.
END</lang>
END</syntaxhighlight>


We can also use this with a regex literal. Note that this does not make the regex pattern "free-spacing."
We can also use this with a regex literal. Note that this does not make the regex pattern "free-spacing." Use the x modifier for that.


<lang langur>val .s = re:block END
<syntaxhighlight lang="langur">val .re = re:block END
a regex pattern here
a regex pattern here
Still here, doc.
Still here, Doc.
END</lang>
END</syntaxhighlight>

<syntaxhighlight lang="langur">val .re = re:x:block END
a free-spacing regex pattern here
Somewhere, Doc.
END</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
Line 953: Line 1,247:
But you can define multi-line strings using the line continuation character "\":
But you can define multi-line strings using the line continuation character "\":


<lang lingo>str = "This is the first line.\
<syntaxhighlight lang="lingo">str = "This is the first line.\
This is the second line.\
This is the second line.\
This "&QUOTE&"line"&QUOTE&" contains quotes."
This "&QUOTE&"line"&QUOTE&" contains quotes."


put str</lang>
put str</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 965: Line 1,259:
</pre>
</pre>


For longer text it's more comfortable to put it into a named "field member" (=asset container) and load its text into a variable when needed:<lang lingo>str = member("my long text").text
For longer text it's more comfortable to put it into a named "field member" (=asset container) and load its text into a variable when needed:<syntaxhighlight lang="lingo">str = member("my long text").text
put str</lang>
put str</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Lua uses the [ [ to mark the start of a dochere block and ] ] to mark the end. It can be used directly or while assigning strings to a variable. An arbitrary but matching number of = may be placed between the brackets in both delimiters to allow ] ] to appear in the string.
Lua uses the [ [ to mark the start of a dochere block and ] ] to mark the end. It can be used directly or while assigning strings to a variable. An arbitrary but matching number of = may be placed between the brackets in both delimiters to allow ] ] to appear in the string.
<lang lua>
<syntaxhighlight lang="lua">
print([[
print([[
This is a long paragraph of text
This is a long paragraph of text
Line 988: Line 1,282:
print(msg)
print(msg)


</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
A block of { } can be used for code and for text. Editor in M2000 environment can color code/string on the fly, analyzing the first line, where the block start.
A block of { } can be used for code and for text. Editor in M2000 environment can color code/string on the fly, analyzing the first line, where the block start.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
a$={This is the first line
a$={This is the first line
Line 1,001: Line 1,295:
}
}
CheckIt
CheckIt
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>Print["Mathematica
<syntaxhighlight lang="mathematica">Print["Mathematica
is an
is an
interesing
interesing
Line 1,016: Line 1,310:
when not
when not
back\
back\
s\\ashed!"];</lang>
s\\ashed!"];</syntaxhighlight>
{{out}}
{{out}}
<pre>Mathematica
<pre>Mathematica
Line 1,029: Line 1,323:
when not
when not
backs\ashed!</pre>
backs\ashed!</pre>

=={{header|MATLAB}}==
Matlab has no built-in heredoc syntax. The closest thing you can do is the following:
<syntaxhighlight lang="matlab">sprintf('%s\n',...
'line1 text',...
' line2 text',...
' line3 text',...
' line4 text')

sprintf('%s\n',...
'Usage: thingy [OPTIONS]',...
' -h Display this usage message',...
' -H hostname Hostname to connect to')</syntaxhighlight>
{{out}}
<pre>
'line1 text
line2 text
line3 text
line4 text
'

'Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
'</pre>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>; here-document.lsp
<syntaxhighlight lang="newlisp">; here-document.lsp
; oofoe 2012-01-19
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Here_document
; http://rosettacode.org/wiki/Here_document
Line 1,041: Line 1,360:
[/text] "James" "magician" "doctor" "L. McCoy"))
[/text] "James" "magician" "doctor" "L. McCoy"))


(exit)</lang>
(exit)</syntaxhighlight>


{{out}}
{{out}}
Line 1,053: Line 1,372:


There are no heredocs, but triple-quoted-strings can be used:
There are no heredocs, but triple-quoted-strings can be used:
<lang nim>echo """Usage: thingy [OPTIONS]
<syntaxhighlight lang="nim">echo """Usage: thingy [OPTIONS]
-h Display this usage message
-h Display this usage message
-H hostname Hostname to connect to
-H hostname Hostname to connect to
"""</lang>
"""</syntaxhighlight>


=={{header|NMAKE.EXE}}==
=={{header|NMAKE.EXE}}==
<lang nmake.exe>target0: dependent0
<syntaxhighlight lang="nmake.exe">target0: dependent0
command0 <<
command0 <<
temporary, discarded inline file
temporary, discarded inline file
Line 1,081: Line 1,400:
named and preserved inline file
named and preserved inline file
...
...
<<KEEP</lang>
<<KEEP</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>
<syntaxhighlight lang="ocaml">
print_string {whatever|
print_string {whatever|
'hahah', `this`
'hahah', `this`
Line 1,094: Line 1,413:
|whatever}
|whatever}
;;
;;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,121: Line 1,440:
In Perl, there must not be a space between the "<<" and the token string. By default, the ending token must the entire end line (i.e. no surrounding spaces) for it to be recognized (but see exception below). Interpolation is allowed, like a double-quoted string:
In Perl, there must not be a space between the "<<" and the token string. By default, the ending token must the entire end line (i.e. no surrounding spaces) for it to be recognized (but see exception below). Interpolation is allowed, like a double-quoted string:


<lang perl>$address = <<END;
<syntaxhighlight lang="perl">$address = <<END;
1, High Street,
1, High Street,
$town_name,
$town_name,
West Midlands.
West Midlands.
WM4 5HD.
WM4 5HD.
END</lang>
END</syntaxhighlight>


If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:
If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:
<lang perl>$pancake = <<"NO MORE INGREDIENTS";
<syntaxhighlight lang="perl">$pancake = <<"NO MORE INGREDIENTS";
egg
egg
milk
milk
flour
flour
NO MORE INGREDIENTS</lang>
NO MORE INGREDIENTS</syntaxhighlight>


It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token. For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:
It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token. For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:


<lang perl>$x = <<'FOO';
<syntaxhighlight lang="perl">$x = <<'FOO';
No
No
$interpolation
$interpolation
here
here
FOO</lang>
FOO</syntaxhighlight>


Alternately, you can use backticks to cause the here document to be executed
Alternately, you can use backticks to cause the here document to be executed
and the result returned, just like a normal backtick operator:
and the result returned, just like a normal backtick operator:


<lang perl>$output = <<`BAR`;
<syntaxhighlight lang="perl">$output = <<`BAR`;
ls /home
ls /home
BAR</lang>
BAR</syntaxhighlight>


Note that in the above examples, that a semicolon was left
Note that in the above examples, that a semicolon was left
Line 1,160: Line 1,479:
nested expression:
nested expression:


<lang perl>print(<<EOF . "lamb\n");
<syntaxhighlight lang="perl">print(<<EOF . "lamb\n");
Mary had
Mary had
a little
a little
EOF</lang>
EOF</syntaxhighlight>


Since Perl 5.26, the here document can be indented by putting a '~' before the token. All spaces to the left of the ending token then become insignificant. This avoids having a disconcerting exdent in the middle of your code.
Since Perl 5.26, the here document can be indented by putting a '~' before the token. All spaces to the left of the ending token then become insignificant. This avoids having a disconcerting exdent in the middle of your code.


<lang perl>sub flibbertigibbet {
<syntaxhighlight lang="perl">sub flibbertigibbet {
print <<~END;
print <<~END;
Mary had
Mary had
Line 1,173: Line 1,492:
lamb
lamb
END
END
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Phix does not have here-docs. In Phix normal double quoted strings are single line and require escaping. Strings can also be entered by using triple doublequotes or single backticks to include linebreaks and avoid any backslash interpretation. If the literal begins with a newline, it is discarded and any immediately following leading underscores specify a (maximum) trimming that should be applied to all subsequent lines. Interpolation is left to printf and friends. Both """`""" and `"""` are valid. Examples:
Phix does not have here-docs. In Phix normal double quoted strings are single line and require escaping. Strings can also be entered by using triple doublequotes or single backticks to include linebreaks and avoid any backslash interpretation. If the literal begins with a newline, it is discarded and any immediately following leading underscores specify a (maximum) trimming that should be applied to all subsequent lines. Interpolation is left to printf and friends. Both """`""" and `"""` are valid. Examples:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>string ts1 = """
<span style="color: #004080;">string</span> <span style="color: #000000;">ts1</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
this
this
"string"\thing"""
"string"\thing"""</span>

string ts2 = """this
<span style="color: #004080;">string</span> <span style="color: #000000;">ts2</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""this
"string"\thing"""
"string"\thing"""</span>

string ts3 = """
<span style="color: #004080;">string</span> <span style="color: #000000;">ts3</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
_____________this
_____________this
"string"\thing"""
"string"\thing"""</span>

string ts4 = `
<span style="color: #004080;">string</span> <span style="color: #000000;">ts4</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
this
this
"string"\thing`
"string"\thing`</span>

string ts5 = `this
<span style="color: #004080;">string</span> <span style="color: #000000;">ts5</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`this
"string"\thing`
"string"\thing`</span>

string ts6 = `
<span style="color: #004080;">string</span> <span style="color: #000000;">ts6</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`
_____________this
_____________this
"string"\thing`
"string"\thing`</span>

string ts7 = "this\n\"string\"\\thing"
<span style="color: #004080;">string</span> <span style="color: #000000;">ts7</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"this\n\"string\"\\thing"</span>

constant tests={ts1,ts2,ts3,ts4,ts5,ts6,ts7}
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">={</span><span style="color: #000000;">ts1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ts7</span><span style="color: #0000FF;">}</span>
for i=1 to length(tests) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for j=1 to length(tests) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if tests[i]!=tests[j] then crash("error") end if
<span style="color: #008080;">if</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"""
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"""
____________Everything
____________Everything
(all %d tests)
works
(all %d tests)
just
works
file.""",length(tests))
just
file."""</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">))</span>
printf(1,"""`""")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"""`"""</span><span style="color: #0000FF;">)</span>
printf(1,`"""`)</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`"""`</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,232: Line 1,553:
Interpolation is allowed, like a double-quoted string:
Interpolation is allowed, like a double-quoted string:


<lang php>$address = <<<END
<syntaxhighlight lang="php">$address = <<<END
1, High Street,
1, High Street,
$town_name,
$town_name,
West Midlands.
West Midlands.
WM4 5HD.
WM4 5HD.
END;</lang>
END;</syntaxhighlight>


In PHP 5.3+, it is possible to make a here-document that does not interpolate
In PHP 5.3+, it is possible to make a here-document that does not interpolate
Line 1,243: Line 1,564:
(like in Perl):
(like in Perl):


<lang php>$x = <<<'FOO'
<syntaxhighlight lang="php">$x = <<<'FOO'
No
No
$interpolation
$interpolation
here
here
FOO;</lang>
FOO;</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
We can use the '[http://software-lab.de/doc/refH.html#here here]' function:
We can use the '[http://software-lab.de/doc/refH.html#here here]' function:


<lang PicoLisp>(out "file.txt" # Write to "file.txt"
<syntaxhighlight lang="picolisp">(out "file.txt" # Write to "file.txt"
(prinl "### This is before the text ###")
(prinl "### This is before the text ###")
(here "TEXT-END")
(here "TEXT-END")
Line 1,260: Line 1,581:
TEXT-END
TEXT-END


(in "file.txt" (echo)) # Show "file.txt"</lang>
(in "file.txt" (echo)) # Show "file.txt"</syntaxhighlight>


{{out}}
{{out}}
Line 1,275: Line 1,596:
The Key is the At symbol @.
The Key is the At symbol @.


<syntaxhighlight lang="powershell">
<lang PowerShell>
$XMLdata=@"
$XMLdata=@"
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
Line 1,293: Line 1,614:
</unattend>
</unattend>
"@
"@
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
Line 1,299: Line 1,620:
It does however have [http://docs.python.org/py3k/tutorial/introduction.html#strings triple-quoted strings] which can be used similarly.
It does however have [http://docs.python.org/py3k/tutorial/introduction.html#strings triple-quoted strings] which can be used similarly.


<lang python>print("""\
<syntaxhighlight lang="python">print("""\
Usage: thingy [OPTIONS]
Usage: thingy [OPTIONS]
-h Display this usage message
-h Display this usage message
-H hostname Hostname to connect to
-H hostname Hostname to connect to
""")</lang>
""")</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,310: Line 1,631:
that this implies (breaks code indentation, no "interpolation"):
that this implies (breaks code indentation, no "interpolation"):


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/base
#lang racket/base


Line 1,319: Line 1,640:
EOF
EOF
)
)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> Blah blah blah
<pre> Blah blah blah
Line 1,328: Line 1,649:
that works well with code:
that works well with code:


<syntaxhighlight lang="racket">
<lang Racket>
#lang at-exp racket/base
#lang at-exp racket/base


Line 1,349: Line 1,670:
(output @list|<<{And customizable delimiters
(output @list|<<{And customizable delimiters
so @foo{} is just plain text}>>|)
so @foo{} is just plain text}>>|)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Blah blah blah
<pre>Blah blah blah
Line 1,367: Line 1,688:
The indentation of the end marker is removed from every line.
The indentation of the end marker is removed from every line.


<lang perl6>my $color = 'green';
<syntaxhighlight lang="raku" line>my $color = 'green';
say qq :to 'END';
say qq :to 'END';
some line
some line
color: $color
color: $color
another line
another line
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>some line
<pre>some line
Line 1,383: Line 1,704:
Multiple here docs may be stacked on top of each other.
Multiple here docs may be stacked on top of each other.


<lang perl6>my $contrived_example = 'Dylan';
<syntaxhighlight lang="raku" line>my $contrived_example = 'Dylan';
sub freewheelin() {
sub freewheelin() {
print q :to 'QUOTE', '-- ', qq :to 'AUTHOR';
print q :to 'QUOTE', '-- ', qq :to 'AUTHOR';
Line 1,393: Line 1,714:
}
}


freewheelin;</lang>
freewheelin;</syntaxhighlight>


{{out}}
{{out}}
Line 1,404: Line 1,725:
Both q and qq are specialised forms of [http://design.raku.org/S02.html#Q_forms Q] which comes with many adverbs. Here a heredoc that only interpolates @-sigils.
Both q and qq are specialised forms of [http://design.raku.org/S02.html#Q_forms Q] which comes with many adverbs. Here a heredoc that only interpolates @-sigils.


<lang perl6>my @a = <1 2 3 4>;
<syntaxhighlight lang="raku" line>my @a = <1 2 3 4>;
say Q :array :to 'EOH';
say Q :array :to 'EOH';
123 \n '"`
123 \n '"`
@a$bc
@a$bc
@a[]
@a[]
EOH</lang>
EOH</syntaxhighlight>


{{out}}
{{out}}
Line 1,419: Line 1,740:
=={{header|Raven}}==
=={{header|Raven}}==
As a list:
As a list:
<lang Raven>'Buffy the Vampire Slayer' as sender
<syntaxhighlight lang="raven">'Buffy the Vampire Slayer' as sender
'Spike' as recipient
'Spike' as recipient


Line 1,430: Line 1,751:
"%(sender)s
"%(sender)s
] "\n" join print
] "\n" join print
</syntaxhighlight>
</lang>
Using group to place the data on the stack:
Using group to place the data on the stack:
<lang Raven>'Buffy the Vampire Slayer' as sender
<syntaxhighlight lang="raven">'Buffy the Vampire Slayer' as sender
'Spike' as recipient
'Spike' as recipient


Line 1,443: Line 1,764:
%(sender)s\n"
%(sender)s\n"
list "\n" join print
list "\n" join print
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Dear Spike,
<pre>Dear Spike,
Line 1,453: Line 1,774:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program demonstrates a method to use "here" documents in REXX. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates a method to use "here" documents in REXX. */
parse arg doc . /*"here" name is case sensitive. */
parse arg doc . /*"here" name is case sensitive. */


Line 1,513: Line 1,834:
└─────────┘
└─────────┘
◄◄.
◄◄.
────────────────────────────────────end of "here" docs──────────────────*/</lang>
────────────────────────────────────end of "here" docs──────────────────*/</syntaxhighlight>
{{out}} when using the input of: <tt> rs-232 </tt>
{{out}} when using the input of: <tt> rs-232 </tt>
<pre>
<pre>
Line 1,564: Line 1,885:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
text ="
text ="
<<'FOO'
<<'FOO'
Line 1,576: Line 1,897:
to come to the aid of their country."
to come to the aid of their country."
see text + nl
see text + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,595: Line 1,916:
Interpolation is allowed, like a double-quoted string:
Interpolation is allowed, like a double-quoted string:


<lang ruby>address = <<END
<syntaxhighlight lang="ruby">address = <<END
1, High Street,
1, High Street,
#{town_name},
#{town_name},
West Midlands.
West Midlands.
WM4 5HD.
WM4 5HD.
END</lang>
END</syntaxhighlight>


If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:
If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:


<lang ruby>pancake = <<"NO MORE INGREDIENTS"
<syntaxhighlight lang="ruby">pancake = <<"NO MORE INGREDIENTS"
egg
egg
milk
milk
flour
flour
NO MORE INGREDIENTS</lang>
NO MORE INGREDIENTS</syntaxhighlight>


It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token.
It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token.
For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:
For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:


<lang ruby>x = <<'FOO'
<syntaxhighlight lang="ruby">x = <<'FOO'
No
No
#{interpolation}
#{interpolation}
here
here
FOO</lang>
FOO</syntaxhighlight>


Alternately, you can use backticks to cause the here document to be executed
Alternately, you can use backticks to cause the here document to be executed
and the result returned, just like a normal backtick operator:
and the result returned, just like a normal backtick operator:


<lang ruby>output = <<`BAR`
<syntaxhighlight lang="ruby">output = <<`BAR`
ls /home
ls /home
BAR</lang>
BAR</syntaxhighlight>


The here document does not start immediately at the "<<END" token -- it starts on the next line.
The here document does not start immediately at the "<<END" token -- it starts on the next line.
Line 1,631: Line 1,952:
To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:
To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:


<lang ruby>puts <<EOF + "lamb"
<syntaxhighlight lang="ruby">puts <<EOF + "lamb"
Mary had
Mary had
a little
a little
EOF</lang>
EOF</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>text$ ="
<syntaxhighlight lang="runbasic">text$ ="
<<'FOO'
<<'FOO'
Now
Now
Line 1,647: Line 1,968:
good mem
good mem
to come to the aid of their country."
to come to the aid of their country."
print text$</lang>
print text$</syntaxhighlight>
{{out}}
{{out}}
<pre><<'FOO'
<pre><<'FOO'
Line 1,663: Line 1,984:
Similar to [[#C++|C++]], Rust offers raw strings. In a manner resembling [[#Lua|Lua]]'s delimiters, an arbitrary but matching number of # on both ends may be used to allow inclusion of # into the string:
Similar to [[#C++|C++]], Rust offers raw strings. In a manner resembling [[#Lua|Lua]]'s delimiters, an arbitrary but matching number of # on both ends may be used to allow inclusion of # into the string:


<lang rust>let x = r#"
<syntaxhighlight lang="rust">let x = r#"
This is a "raw string literal," roughly equivalent to a heredoc.
This is a "raw string literal," roughly equivalent to a heredoc.
"#;
"#;
Line 1,670: Line 1,991:
This string contains a #.
This string contains a #.
"##;
"##;
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
Line 1,678: Line 1,999:
Triple quotes (""") marks the beginning and end.
Triple quotes (""") marks the beginning and end.
Specially handy when using escape sequences in e.g. regular expressions.
Specially handy when using escape sequences in e.g. regular expressions.
{{libheader|Scala}}<lang Scala>object temp {
{{libheader|Scala}}<syntaxhighlight lang="scala">object temp {
val MemoriesOfHolland=
val MemoriesOfHolland=
"""Thinking of Holland
"""Thinking of Holland
Line 1,704: Line 2,025:
|with its lapping disasters
|with its lapping disasters
|is feared and hearkened.""".stripMargin
|is feared and hearkened.""".stripMargin
}</lang>
}</syntaxhighlight>
All control codes are transparent e.g. new lines.
All control codes are transparent e.g. new lines.
In order for a neat code each lines has as prefix spaces and a | symbol
In order for a neat code each lines has as prefix spaces and a | symbol
which will be removed by the stripMargin function.
which will be removed by the stripMargin function.

=={{header|sed}}==
<syntaxhighlight lang="sed">c\
The commands 'a', 'c', and 'i' can be followed\
by multi-line text. Each line break in the text\
is preceded by a backslash.</syntaxhighlight>
{{out}}
<pre>
$ echo | sed -f heredoc.sed
The commands 'a', 'c', and 'i' can be followed
by multi-line text. Each line break in the text
is preceded by a backslash.
</pre>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
SenseTalk has "block quotes" for large blocks of text, enclosed between <nowiki>"{{"</nowiki> (at the end of a line) and "}}" (at the beginning of a line). A tag can also be used after the <nowiki>"{{"</nowiki> and before the "}}" which allows for nesting of blocks, such as for a block of code containing other block quotes.
SenseTalk has "block quotes" for large blocks of text, enclosed between <nowiki>"{{"</nowiki> (at the end of a line) and "}}" (at the beginning of a line). A tag can also be used after the <nowiki>"{{"</nowiki> and before the "}}" which allows for nesting of blocks, such as for a block of code containing other block quotes.


<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set script to {{SCRIPT
set script to {{SCRIPT
put "Script demonstrating block quotes"
put "Script demonstrating block quotes"
Line 1,727: Line 2,061:
do script
do script


</syntaxhighlight>
</lang>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
<lang sequencel>main :=
<syntaxhighlight lang="sequencel">main :=
"In SequenceL
"In SequenceL
strings are
strings are
Line 1,738: Line 2,072:
characters are
characters are
valid for inclusion
valid for inclusion
in a string.";</lang>
in a string.";</syntaxhighlight>


{{out}}
{{out}}
Line 1,756: Line 2,090:
When the token string is double-quoted ("") or not quoted,
When the token string is double-quoted ("") or not quoted,
the content will be interpolated like a double-quoted string:
the content will be interpolated like a double-quoted string:
<lang ruby>var text = <<"EOF";
<syntaxhighlight lang="ruby">var text = <<"EOF";
a = #{1+2}
a = #{1+2}
b = #{3+4}
b = #{3+4}
EOF</lang>
EOF</syntaxhighlight>


If single quotes are used, then the here document will not support interpolation, like a normal single-quoted string:
If single quotes are used, then the here document will not support interpolation, like a normal single-quoted string:
<lang ruby>var x = <<'FOO';
<syntaxhighlight lang="ruby">var x = <<'FOO';
No
No
#{interpolation}
#{interpolation}
here
here
FOO</lang>
FOO</syntaxhighlight>
The here document does not start immediately at the "<<END" token -- it starts on the next line. The "<<END" is actually an expression, whose value will be substituted by the contents of the here document.
The here document does not start immediately at the "<<END" token -- it starts on the next line. The "<<END" is actually an expression, whose value will be substituted by the contents of the here document.
To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:
To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:
<lang ruby>say (<<EOF + "lamb");
<syntaxhighlight lang="ruby">say (<<EOF + "lamb");
Mary had
Mary had
a little
a little
EOF</lang>
EOF</syntaxhighlight>
which is equivalent with:
which is equivalent with:
<lang ruby>say (<<EOF
<syntaxhighlight lang="ruby">say (<<EOF
Mary had
Mary had
a little
a little
EOF
EOF
+ "lamb");</lang>
+ "lamb");</syntaxhighlight>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
With SQL only from command line. The single quote string is opened along the three lines:
With SQL only from command line. The single quote string is opened along the three lines:
<lang bash>
<syntaxhighlight lang="bash">
db2 "select 'This is the first line.
db2 "select 'This is the first line.
This is the second line.
This is the second line.
This is the third line.' from sysibm.sysdummy1"
This is the third line.' from sysibm.sysdummy1"
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,799: Line 2,133:
</pre>
</pre>
With SQL only from script with concat function (one row):
With SQL only from script with concat function (one row):
<lang sql pl>
<syntaxhighlight lang="sql pl">
select 'This is the first line.' || chr(10) ||
select 'This is the first line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the third line.' from sysibm.sysdummy1;
'This is the third line.' from sysibm.sysdummy1;
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,815: Line 2,149:
</pre>
</pre>
With SQL only from script with union operator (three rows):
With SQL only from script with union operator (three rows):
<lang sql pl>
<syntaxhighlight lang="sql pl">
select 'This is the first line.' from sysibm.sysdummy1
select 'This is the first line.' from sysibm.sysdummy1
union
union
Line 1,821: Line 2,155:
union
union
select 'This is the third line.' from sysibm.sysdummy1;
select 'This is the third line.' from sysibm.sysdummy1;
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,834: Line 2,168:
{{works with|Db2 LUW}} version 9.7 or higher.
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
With SQL PL:
<lang sql pl>
<syntaxhighlight lang="sql pl">
SET serveroutput ON
SET serveroutput ON
CALL DBMS_OUTPUT.PUT_LINE('This is the first line.' || chr(10) ||
CALL DBMS_OUTPUT.PUT_LINE('This is the first line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the third line.');
'This is the third line.');
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,851: Line 2,185:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set hereDocExample {
<syntaxhighlight lang="tcl">set hereDocExample {
In Tcl, the {curly brace} notation is strictly a here-document style notation
In Tcl, the {curly brace} notation is strictly a here-document style notation
as it permits arbitrary content inside it *except* for an unbalanced brace.
as it permits arbitrary content inside it *except* for an unbalanced brace.
Line 1,863: Line 2,197:
plus all whitespace at the start of the next line
plus all whitespace at the start of the next line
to be compressed to a single space.
to be compressed to a single space.
}</lang>
}</syntaxhighlight>


If substitution is desired within the document, it should either be written
If substitution is desired within the document, it should either be written
Line 1,883: Line 2,217:
to the resulting script which are interpreted by txr.
to the resulting script which are interpreted by txr.


<lang txr>#!/usr/bin/txr -f
<syntaxhighlight lang="txr">#!/usr/bin/txr -f
@(maybe)
@(maybe)
@(bind USER "Unknown User")
@(bind USER "Unknown User")
Line 1,895: Line 2,229:


The Computer
The Computer
@(end)</lang>
@(end)</syntaxhighlight>


Test runs
Test runs
Line 1,936: Line 2,270:
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}


<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
cat << ANARBITRARYTOKEN
cat << ANARBITRARYTOKEN
The river was deep but I swam it, Janet.
The river was deep but I swam it, Janet.
Line 1,943: Line 2,277:
I've one thing to say and that's ...
I've one thing to say and that's ...
Dammit. Janet, I love you.
Dammit. Janet, I love you.
ANARBITRARYTOKEN</lang>
ANARBITRARYTOKEN</syntaxhighlight>


<lang bash>cat << EOF
<syntaxhighlight lang="bash">cat << EOF
Here documents do parameter and command substitution:
Here documents do parameter and command substitution:
* Your HOME is $HOME
* Your HOME is $HOME
* 2 + 2 is `expr 2 + 2`
* 2 + 2 is `expr 2 + 2`
* Backslash quotes a literal \$, \` or \\
* Backslash quotes a literal \$, \` or \\
EOF</lang>
EOF</syntaxhighlight>


<lang bash>if true; then
<syntaxhighlight lang="bash">if true; then
cat <<- EOF
cat <<- EOF
The <<- variant deletes any tabs from start of each line.
The <<- variant deletes any tabs from start of each line.
EOF
EOF
fi</lang>
fi</syntaxhighlight>


<lang bash>cat << 'TOKEN'
<syntaxhighlight lang="bash">cat << 'TOKEN'
If TOKEN has any quoted characters (like 'TOKEN', "TOKEN" or \TOKEN),
If TOKEN has any quoted characters (like 'TOKEN', "TOKEN" or \TOKEN),
then all $ ` \ in the here document are literal characters.
then all $ ` \ in the here document are literal characters.


$PATH \$PATH `shutdown now`
$PATH \$PATH `shutdown now`
TOKEN</lang>
TOKEN</syntaxhighlight>
<lang bash>echo '
<syntaxhighlight lang="bash">echo '
In any unix shell, you specify a text block and can use all whitespace like
In any unix shell, you specify a text block and can use all whitespace like
(spaces) & (tab) in it, by using single quotes.
(spaces) & (tab) in it, by using single quotes.
Line 1,972: Line 2,306:
conform to the task definition.
conform to the task definition.
'
'
</syntaxhighlight>
</lang>


==={{header|C Shell}}===
==={{header|C Shell}}===
<lang csh>#!/bin/csh -f
<syntaxhighlight lang="csh">#!/bin/csh -f
cat << ANARBITRARYTOKEN
cat << ANARBITRARYTOKEN
* Your HOME is $HOME
* Your HOME is $HOME
Line 1,983: Line 2,317:
cat << 'ANARBITRARYTOKEN'
cat << 'ANARBITRARYTOKEN'
$PATH \$PATH `shutdown now`
$PATH \$PATH `shutdown now`
'ANARBITRARYTOKEN'</lang>
'ANARBITRARYTOKEN'</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>hd =
<syntaxhighlight lang="ursala">hd =


-[
-[
Line 2,035: Line 2,369:
the periods like this -[.. ~&]-. This one is a second order function
the periods like this -[.. ~&]-. This one is a second order function
that needs to be applied to another function in order to get a
that needs to be applied to another function in order to get a
first order function such as the previous three examples.]-</lang>
first order function such as the previous three examples.]-</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
Line 2,042: Line 2,376:


It will prompt you to select a Txt-based file and do its best to create VBScript code that will recreate that Txt-based file!
It will prompt you to select a Txt-based file and do its best to create VBScript code that will recreate that Txt-based file!
<syntaxhighlight lang="vbscript">
<lang VBScript>
'Purpose: Converts TXT files into VBS code with a function that returns a text string with the contents of the TXT file
'Purpose: Converts TXT files into VBS code with a function that returns a text string with the contents of the TXT file
' The TXT file can even be another VBS file.
' The TXT file can even be another VBS file.
Line 2,126: Line 2,460:


WshShell.Popup "created " & strFileNameOUT, 3, "Completed", 64
WshShell.Popup "created " & strFileNameOUT, 3, "Completed", 64
</syntaxhighlight>
</lang>

=={{header|V (Vlang)}}==
Vlang does not have here documents. Multiline string literals serve this purpose.

<syntaxhighlight lang="go">fn main() {
m := ' leading spaces
and blank lines'

println(m)
}</syntaxhighlight>

=={{header|Wren}}==
Wren does not have heredocs but (from v0.4.0) does have raw strings.

A raw string is any text delimited by triple quotes, """, and is interpreted literally i.e. any control codes and/or interpolations are not processed as such.

If a triple quote appears on its own line then any trailing whitespace on that line is ignored.

Borrowing the Ada example (appropriately adjusted) for an illustration of a raw string.
<syntaxhighlight lang="wren">var a = 42
var b = """
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(a) is also interpreted literally.
`Have fun!`
"""
System.print(b)</syntaxhighlight>

{{out}}
<pre>
This is a 'raw' string with the following properties:
- indention is preserved,
- an escape sequence such as a quotation mark "\\" is interpreted literally, and
- interpolation such as %(b) is also interpreted literally.
`Have fun!`
</pre>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code Text=12;
<syntaxhighlight lang="xpl0">code Text=12;
Text(0, " ^"Heredocs^" are pretty much automatic. Multiple lines and
Text(0, " ^"Heredocs^" are pretty much automatic. Multiple lines and
whitespace, such as indentations, are output exactly as written. Quote
whitespace, such as indentations, are output exactly as written. Quote
marks (^") and any carets (^^) within the string must be escaped.")</lang>
marks (^") and any carets (^^) within the string must be escaped.")</syntaxhighlight>


=={{header|XSLT}}==
=={{header|XSLT}}==
Line 2,138: Line 2,510:
Being a dialect of XML, XSLT inherits [http://www.w3.org/TR/REC-xml/#sec-cdata-sect CDATA sections]. Not quite heredocs, these are more like raw triple quotes in Python (<code>r"""…"""</code>) or Scala (<code>"""…"""</code>) in that anything except the end delimiter is treated literally.
Being a dialect of XML, XSLT inherits [http://www.w3.org/TR/REC-xml/#sec-cdata-sect CDATA sections]. Not quite heredocs, these are more like raw triple quotes in Python (<code>r"""…"""</code>) or Scala (<code>"""…"""</code>) in that anything except the end delimiter is treated literally.


<lang xml><?xml version="1.0" encoding="UTF-8"?>
<syntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>
<xsl:output method="text"/>
Line 2,162: Line 2,534:
]]>
]]>
</xsl:template>
</xsl:template>
</xsl:stylesheet></lang>
</xsl:stylesheet></syntaxhighlight>


Output from xsltproc (input is ignored):
Output from xsltproc (input is ignored):
Line 2,187: Line 2,559:


</pre>
</pre>


=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
text1$ = "Esta es la primera linea.
Esta es la segunda linea.
Esta \"linea\" contiene comillas.\n"

text2$ = "Blast it James! I'm a magician,
not a doctor!
--- L. McCoy\n"


print text1$
print text2$
end
</syntaxhighlight>
{{out}}
<pre>
Esta es la primera linea.
Esta es la segunda linea.
Esta "linea" contiene comillas.

Blast it James! I'm a magician,
not a doctor!
--- L. McCoy
</pre>



=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>x:=
<syntaxhighlight lang="zkl">x:=
#<<<
#<<<
"#<<< starts a block of lines that are concatenated verbatim
"#<<< starts a block of lines that are concatenated verbatim
Line 2,197: Line 2,597:
Note that is isn't a string, but arbitrary source " + 1 + 23;
Note that is isn't a string, but arbitrary source " + 1 + 23;
#<<<
#<<<
x.println();</lang>
x.println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,211: Line 2,611:
{{omit from|BASIC}}
{{omit from|BASIC}}
{{omit from|BBC BASIC}}
{{omit from|BBC BASIC}}
{{omit from|C|C's "multi-line strings" don't fulfill the requirements of this task}}
{{omit from|Déjà Vu}}
{{omit from|Déjà Vu}}
{{omit from|Gambas}}
{{omit from|Gambas}}

Latest revision as of 01:59, 14 April 2024

Task
Here document
You are encouraged to solve this task according to the task description, using any language you may know.

A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.

Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string.

The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.


Task

Demonstrate the use of   here documents   within the language.

Related task



11l

11l does not have here-docs. It does however have raw strings which can be used similarly.

print(‘
here
    doc
’)

8th

Multiline strings are simply parsed using "quote", which parses first a character to use as a separator, and scans until that character is found:

quote *
Hi
   there
* .
Output:
Hi
   there

Ada

Ada has neither heredocs nor multiline strings. A workaround is to use containers of strings:

with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;

procedure Here_Doc is

   package String_Vec is new Ada.Containers.Indefinite_Vectors
     (Index_Type   => Positive,
      Element_Type => String);

   use type String_Vec.Vector;

   Document: String_Vec.Vector := String_Vec.Empty_Vector
    & "This is a vector of strings with the following properties:"
    & "  - indention is preserved, and"
    & "  - a quotation mark '""' must be ""escaped"" by a double-quote '""""'.";
begin
   Document := Document & "Have fun!";
   for I in Document.First_Index .. Document.Last_Index loop
      Ada.Text_IO.Put_Line(Document.Element(I));
   end loop;
end Here_Doc;
Output:
This is a vector of strings with the following properties:
  - indention is preserved, and
  - a quotation mark '"' must be "escaped" by a double-quote '""'.
Have fun!

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.

Algol 68 does not have a "heredoc" feature. It can be crudely achieved using an array of strings:

#!/usr/local/bin/a68g --script #

[]STRING help = (
"Usage: thingy [OPTIONS]",
"     -h                        Display this usage message",
"     -H hostname               Hostname to connect to"
);

printf(($gl$,help,$l$));

printf(($gl$,
"The river was deep but I swam it, Janet.",
"The future is ours so let's plan it, Janet.",
"So please don't tell me to can it, Janet.",
"I've one thing to say and that's ...",
"Dammit. Janet, I love you."
))
Output:
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

The river was deep but I swam it, Janet.
The future is ours so let's plan it, Janet.
So please don't tell me to can it, Janet.
I've one thing to say and that's ...
Dammit. Janet, I love you.

APL

Works with: GNU APL

See the GNU APL docs: 2.1.4 Helpful Features for Scripting

BODY⎕INP 'END-OF-⎕INP'
First line
Second line
Third line
   ...
END-OF-⎕INP

A related concept is multi-line strings (note the 6 space indent of APL interactive input vs. output):

      ]boxing 8
      s  """
→          abc
→            def

→              GHIJK
→                       """
      s
Output:
┌┌→────────────────────────────────────────┐
│┌→──────┐ ┌→────────┐ ┌⊖┐ ┌→────────────┐ │
││    abc│ │      def│ │ │ │        GHIJK│ │
│└───────┘ └─────────┘ └─┘ └─────────────┘ │
└∊─────────────────────────────────────────┘

Applesoft BASIC

Strings are limited to 255 characters. The double quote character delimits strings, so double quote cannot be embedded directly. The double quote can be included in a DATA statement if the text is not wrapped in quotes. Most control characters, with the exception of Return ^M, Backspace ^H, Forward-space ^U and Escape ^[, can be typed into strings. Control characters are not usually visible. The line feed character ^J moves the cursor position down one line, and the ^G character is audible!

 0 Q$ =  CHR$ (34)
 1 M$ =  CHR$ (13)
 2  PRINT Q$"Oh, Danny Boy,"M$"The pipes, the pipes are calling"M$"From glen to glen and down the mountainside"Q$

There are tools and tricks to embed control characters like Return directly into the program.

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program heredoc.s   */

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall

.equ BUFFERSIZE,          100

/* Initialized data */
.data
szMessString:            .asciz "String :
 ABCD
            EFGH	TAB    \n"

szCarriageReturn:       .asciz "\n"

/* UnInitialized data */
.bss 

/*  code section */
.text
.global main 
main: 

    ldr r0,iAdrszMessString                     @ display message
    bl affichageMess
 

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc 0                                       @ perform system call
iAdrszMessString:         .int szMessString
iAdrszCarriageReturn:     .int szCarriageReturn

/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers 
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index 
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop 
                                                @ so here r2 contains the length of the message 
    mov r1,r0                                   @ address message in r1 
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write" 
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return

Arturo

print {:
    The “Red Death” had long devastated the country. 
    No pestilence had ever been so fatal, or so hideous. 

    Blood was its Avator and its seal—
        the redness and the horror of blood. 

    There were sharp pains, 
        and sudden dizziness, 
            and then profuse bleeding at the pores, 
                with dissolution. 
                
    The scarlet stains upon the body 
    and especially upon the face of the victim, 
    were the pest ban 
    which shut him out from the aid 
    and from the sympathy of his fellow-men. 

    And the whole seizure, 
    progress and termination of the disease, 
    were the incidents of half an hour.
:}
Output:
    The “Red Death” had long devastated the country. 
    No pestilence had ever been so fatal, or so hideous. 

    Blood was its Avator and its seal—
        the redness and the horror of blood. 

    There were sharp pains, 
        and sudden dizziness, 
            and then profuse bleeding at the pores, 
                with dissolution. 
                
    The scarlet stains upon the body 
    and especially upon the face of the victim, 
    were the pest ban 
    which shut him out from the aid 
    and from the sympathy of his fellow-men. 

    And the whole seizure, 
    progress and termination of the disease, 
    were the incidents of half an hour.

AutoHotkey

AutoHotkey uses "continuation sections" for literal text:

MyVar = "This is the text inside MyVar"
MyVariable =
(
   Note that whitespace is preserved
   As well as newlines.
   The LTrim option can be present to remove left whitespace.
   Variable references such as %MyVar% are expanded.
)
MsgBox % MyVariable

AWK

The awk extraction and reporting language does not provide any markup facility for embedding here documents within an awk script. The awk utility is really a helper tool often used from within the Unix shell. The Unix shell in which awk scripts are usually embedded does support the use of here documents, and the way that here documents are used within the shell make them ideal for passing to awk as is, without the need for an additional facility in awk.

BQN

Works in: CBQN

The default string syntax in BQN allows multiline strings. Strings start and end with a double quote, and quotes within the text can be escaped by typing two quotes.

•Out "dsdfsdfsad
	""fsadf""sdf"
dsdfsdfsad
	"fsadf"sdf

Bracmat

Strings in Bracmat can continue over many lines. They start and end with a quote. Quotes in the text must be escaped with a reverse solidus, like the reverse solidus itself.

( {Multiline string:}
"
Second line
Third line
\"quoted\"
A backslash: \\
":?stringA
& out$("Multiline string:")
& out$(!stringA)
)

Output:

Multiline string:

Second line
Third line
"quoted"
A backslash: \

BaCon

'--- we dont have a print here doc built-in command in BaCon 
'--- we can get the end result like this  with the newline NL$ 

PRINT "To use Bacon your system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available." NL$ \
"If none of these shells are available on your platform, download and install the free Public Domain Korn Shell which can"  NL$ \
"execute BaCon also. Furthermore BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell."  NL$ NL$ \
"BaCon intends to be a programming aid in creating tools which can be compiled on different platforms"  NL$ \
"(including 64bit environments). It tries to revive the days of the good old BASIC." NL$

Output:

To use Bacon your system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available.
If none of these shells are available on your platform, download and install the free Public Domain Korn Shell which can
execute BaCon also. Furthermore BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell.

BaCon intends to be a programming aid in creating tools which can be compiled on different platforms
(including 64bit environments). It tries to revive the days of the good old BASIC.


BASIC

BASIC no tiene heredocs ni cadenas de varias líneas. Una solución alternativa es unir varias cadenas en una línea con CHR$(10).

text1$ = " " + CHR$(10) + "<<'FOO' " + CHR$(10) + "  'jaja', `esto`" + CHR$(10) + "  <simula>" + CHR$(10) + "  \un\" + CHR$(10) + "  ${ejemplo} de 'heredoc'" + CHR$(10) + "  en QBASIC."

text2$ = "Esta es la primera línea." + CHR$(10) + "Esta es la segunda línea." + CHR$(10) + "Esta 'línea' contiene comillas."

PRINT text1$
PRINT
PRINT text2$
END
Output:
Igual que la entrada de FreeBASIC.


BASIC256

BASIC256 no tiene heredocs ni cadenas de varias líneas. Una solución alternativa es unir varias cadenas en una línea con chr(10).

text1$ = " " & chr(10) & "<<#FOO# " & chr(10) & "  #jaja#, `esto`" & chr(10) & "  <simula>" & chr(10) & "  \un\" & chr(10) & "  ${ejemplo} de 'heredoc'" & chr(10) & "  en BASIC256."

text2$ = "Esta es la primera linea." & chr(10) & "Esta es la segunda linea." & chr(10) & "Esta 'linea' contiene comillas."

print text1$
print 
print text2$
end
Output:
Igual que la entrada de FreeBASIC.

Blade

echo 'All strings
support
multiline
in Blade'
Output:
All strings
support
multiline
in Blade


C#

C# has a string literal call which is used for heredoc functionality

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.Write(@"
multiline
strings are easy
to put together
in C#");
    }
}

C++

Works with: C++11

C++11 raw string literals are similar to heredocs, except there is no newline after the opening token or before the ending token (unless you actually want newlines there).

#include <iostream> // Only for cout to demonstrate

int main()
{
  std::cout <<
R"EOF(  A  raw  string  begins  with  R,  then a double-quote ("),  then an optional
identifier (here I've used "EOF"),  then an opening parenthesis ('(').  If you
use  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot
contain a space,  either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.

  It  ends with a closing parenthesis (')'),  the identifer (if you used one),
and a double-quote.

  All  characters are okay in a raw string,  no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}

Clojure

There are no heredocs built in, but Clojure Strings themselves are multiline and whitespace/indentation is preserved. If your text has many characters that have to be escaped, it may make more sense to store it as a resource file and read it in.

For more information on the possibility of supporting a tripled-quoted syntax, see: alternate string quote syntaxes.

CoffeeScript

CoffeeScript borrows the triple-quoted string syntax from Python. Note that these strings strip leading whitespace in CoffeeScript, to allow you to neatly align the heredoc string.

myDoc = '''
        Single-quoted heredocs allows no '#{foo}' interpolation.
        This behavior is similar to single-quoted strings.
        '''
doc2  = """
        However, double-quoted heredocs *do* allow these.
        See it in action:
            Content: "#{myDoc}"
        """

console.log doc2
Output:
However, double-quoted heredocs *do* allow these.
See it in action:
    Content: "Single-quoted heredocs allows no '#{foo}' interpolation.
This behavior is similar to single-quoted strings."

Note how the extra indentation in the third line of doc2 is preserved.

Common Lisp

cl-heredoc provide read-macro for heredoc:

;; load cl-heredoc with QuickLisp
(ql:quickload 'cl-heredoc)

;; use #>xxx>yyyyyyyy!xxx as read-macro for heredoc
(set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)

;; example:
(format t "~A~%" #>eof1>Write whatever (you) "want",
  no matter how many lines or what characters until
the magic end sequence has been reached!eof1)
Output:
Write whatever (you) "want",
  no matter how many lines or what characters until
the magic end sequence has been reached!
NIL

Note: NIL is the return value of function format when first argument is t

Crystal

puts <<-DOC
this is a heredoc
  it preserves indents and newlines
  the DOC identifier is completely arbitrary
  it can be lowercase, a keyword, or even a number (but not a float)
DOC

D

import std.stdio, std.string;

void main() {
    // Delimited strings: a 'q' followed by double quotes and an
    // opening and closing delimiter of choice:

    q"[a string that you "don't" have to escape]"
    .writeln;

    // If the delimiter is an identifier, the identifier must be
    // immediately followed by a newline, and the matching delimiter
    // is the same identifier starting at the beginning of the line:

    q"EOS
    This
    is a multi-line
    heredoc string
EOS".outdent.writeln;

    // std.string.outdent is used to remove the four spaces indent.
}
Output:
a string that you "don't" have to escape
This
is a multi-line
heredoc string

DWScript

Double-quotes (") denote a multi-line string, to include a double-quote in such a string, you need to double it.

PrintLn("This is
a multiline
""string""
sample");
Output:
This is
a multiline
"string"
sample

EasyLang

# The here-document is not here, but at the end of the program
repeat
   s$ = input
   until error = 1
   print s$
.
input_data
This is a 'raw' string with the following properties:
  - indention is preserved, 
  - an escape sequence such as a quotation mark "\\" is interpreted literally, and
  - interpolation such as %(a) is also interpreted literally.
  - """ is also interpreted literally.

`Have fun!`
Output:
This is a 'raw' string with the following properties:
  - indention is preserved, 
  - an escape sequence such as a quotation mark "\\" is interpreted literally, and
  - interpolation such as %(a) is also interpreted literally.
  - """ is also interpreted literally.

`Have fun!`

EchoLisp

The delimiters are #<< .... >># for a here-doc string, which may include any special character: double quotes, new line, etc. and is read 'as is', i.e does not recognize escape sequences.

(string-delimiter "")
(writeln
#<<
A noir, E blanc, I rouge, U vert, O bleu : voyelles,
Je dirai quelque jour vos naissances latentes :
A, noir corset velu des mouches éclatantes
Qui bombinent autour des puanteurs cruelles,

Golfes d'ombre ; E, candeur des vapeurs et des tentes,
Lances des glaciers fiers, rois blancs, frissons d'ombelles ;
I, pourpres, sang craché, rire des lèvres belles
Dans la colère ou les ivresses pénitentes ;

U, cycles, vibrements divins des mers virides,
Paix des pâtis semés d'animaux, paix des rides
Que l'alchimie imprime aux grands fronts studieux ;

O, suprême Clairon plein des strideurs étranges,
Silences traversés des Mondes et des Anges :
- O l'Oméga, rayon violet de Ses Yeux ! -

A. Rimbaud "Voyelles"
>>#
Output:
A noir, E blanc, I rouge, U vert, O bleu : voyelles,
Je dirai quelque jour vos naissances latentes :
A, noir corset velu des mouches éclatantes
Qui bombinent autour des puanteurs cruelles,

Golfes d'ombre ; E, candeur des vapeurs et des tentes,
Lances des glaciers fiers, rois blancs, frissons d'ombelles ;
I, pourpres, sang craché, rire des lèvres belles
Dans la colère ou les ivresses pénitentes ;

U, cycles, vibrements divins des mers virides,
Paix des pâtis semés d'animaux, paix des rides
Que l'alchimie imprime aux grands fronts studieux ;

O, suprême Clairon plein des strideurs étranges,
Silences traversés des Mondes et des Anges :
- O l'Oméga, rayon violet de Ses Yeux ! -

A. Rimbaud "Voyelles"

Elixir

In Elixir, one can use either a pair of triple single-quotation marks or a pair of triple double-quotation marks, but in both cases, string interpolation occurs:

IO.puts """
привет
мир
"""

produces:

привет
мир

Here is an illustrative iex transcript:

iex(1)> a=2
2
iex(2)> '''
...(2)> 1 + 1 = #{a}
...(2)> '''
'1 + 1 = 2\n'
iex(3)> 
iex(3)> '''2'''
** (SyntaxError) iex:3: heredoc start must be followed by a new line after '''
    
iex(3)>

Erlang

Multiline strings look like this in the Erlang shell:

2> S = " ad
2> 123
2> the end".
3> io:fwrite( S ).
 ad
123
the end

F#

All the usual string variations are no HEREDOCs, because they don't comply to this requirement:

The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the textblock.

That said, as with other languages, F# has two string syntax variations which come close:

verbatim strings
begin with @" and end with the next single double quote ". A double quote in the string has to be quoted by doubling it. All other characters can be in such a string as-is, including newlines.
tripple-quoted strings
are delimited by """ on both ends and can contain any character other than the delimiter sequence of three double quote characters.

Full information on F# strings can be found in MSDN.

Factor

Factor strings surround by '"' are multiline, but accept escape sequences (like "\n", "\uxxxxxxxx"). Strings surrounded by '"""' don't have to escape '"'. Use HEREDOC: (and other variants, like

[[

) for verbatim text

"    a multiline
string\n(with escape sequences: \u{greek-capital-letter-sigma})
"
"""this is "easier".."""



HEREDOC: EOF
             this
 is not \n escaped at all
EOF

this also works , but needs a space at the start (but not the end) this won't work [=[ this works like [[, but I can write and without restriction]=] [==[ it keeps going]==] [===[ like this]===] [====[ for a while]====]

Forth

version 1

Works with: GForth
\ GForth specific words:
\ under+ ( a b c -- a+c b) , latest ( -- nt ) , name>string ( nt -- ca u )
\ Should not be a problem to modify it to work with other Forth implementation:

: $!   ( ca u -- a )
  dup >R dup , here swap move R> allot ;
: $@   ( a -- ca u )
  dup @ 1 cells under+ ;
: c!+   ( c ca - ca+1 )
  tuck c! 1+ ;
: $!+   ( a u a' -- a'+u ; string-store-plus )
  2dup + >R swap move R> ;

\ --- UNIX end-of-line adapted words
10 constant EOL
: input-fix   ( -- ; for interactive use ! )
  source-id 0= IF cr THEN ;
: get_line  ( -- ca u )  EOL parse input-fix ;
: EOL!+  ( a -- a' ; eol-store-plus )  EOL swap c!+ ;

: EOD   ( -- ca u ; end-of-doc )
  latest name>string ;

: >>   ( "doc-name" "doc-body" -- )   input-fix 
  CREATE 0 ,              \ post body length
  here dup >R
  BEGIN  refill >R
         get_line 2dup EOD compare
         R> AND           \ notEOD && input-stream ->
  WHILE  rot $!+ EOL!+
  REPEAT 2drop
  R> tuck - dup allot
  swap -1 cells + !       \ fixup body length
  DOES>  ( -- ca u )  $@ ;

\ TEST ;   excerpt from Project Gutenberg 'Alice in Wonderland'

>> ALICE
CHAPTER I. Down the Rabbit-Hole

Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversation?'
ALICE
>> RABBIT
RABBIT
ALICE type ." --" cr RABBIT type
CHAPTER I. Down the Rabbit-Hole

Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversation?'
--

version 2

Works with: GForth

Here's a slightly different implementation, with less stack juggling. It does not echo linefeeds in interactive mode, but that can easily be added.

It's written to works with Forth's default implementation of counted strings. Those are limited to 255 characters, which is fine in many cases, but on the short side for here documents, so therefore we temporarily redefine them to use a full cell for size (16 bits would probably be ideal) while compiling the here document words.

get-current get-order wordlist swap 1+ set-order definitions
: place		over >r rot over cell+ r> move ! ;
: +place	2dup >r >r dup @ cell+ + swap move r> r> dup @ rot + swap ! ;
: count		dup cell+ swap @ ;
set-current

CREATE eol	10 C,  DOES> 1 ;
CREATE eod	128 ALLOT  DOES> count ;
: seteod	0 parse ['] eod >body place ;
: start		0 0 here place ;
: read		refill  0= IF abort" Unterminated here document" THEN ;
: ~end		source eod compare ;
: store		source here +place  eol here +place ;
: slurp		BEGIN read ~end WHILE store REPEAT  refill drop ;
: totalsize	here count + here - ;
: finish	totalsize ALLOT  align ;
: <<		seteod  start slurp finish  DOES> count ;
previous

( Test )

CREATE Alice << ~~ end ~~
They got a building down New York City, it’s called Whitehall Street,
Where you walk in, you get injected, inspected, detected, infected,
Neglected and selected.
~~ end ~~

Alice type  bye
Output:
They got a building down New York City, it’s called Whitehall Street,
Where you walk in, you get injected, inspected, detected, infected,
Neglected and selected.

Fortran

In Fortran, spaces outside text literals are nowhere significant, not even within words, so that GOTO = G OTO = GO TO and there are no reserved words either so GOTO might be the name of a variable as well and both can be used in the same source. Statements were originally specified with a special format: columns one to five were for statement labels (integers only, not zero), column six specified a continuation line if not blank or zero, and columns 73-80 were for sequence numbers in case you dropped the deck of cards. Thus, source was found in columns 7-72, and layout of the source could be varied without effect on the results. Originally, the only way to produce text in the output (as for annotating the numerical results) was via the "Hollerith" format code, of the form nH where n specified the exact count of characters following the H. Any characters. Miscounts would cause a syntax error - if you were lucky! Happily, a quoted literal syntax was soon introduced, using apostrophes as delimiters with two apostrophes in a row signifying a contained apostrophe. Later, either an apostrophe or a double quote could be used to start a text string (and the same one must be used to end it) so that if one or the other were desired within a text literal, the other could be used as its delimiters. If both were desired, then there would be no escape from doubling for one.

Producing a source file containing a block of text that will be presented as output in the same layout (new lines and all) is only possible if the added layout stuff (generating the required new line starts) and delimiters in the source are disregarded. But if one accepts a few constraints, the following shows a possible approach:

      INTEGER I         !A stepper.
      CHARACTER*666 I AM    !Sufficient space.
      I AM =                                                           "<col72
C              111111111122222222223333333333444444444455555555556666666666
C     123456789012345678901234567890123456789012345678901234567890123456789
     1                                                                  <col72
     2              I AM                                                <col72
     3                                                                  <col72
     4           THAT I AM                                              <col72
     5"

Chug through the text blob.
      DO I = 0,600,66   !Known length.
        WRITE (6,1) I AM(I + 1:I + 66)  !Reveal one line.
    1   FORMAT (A66)            !No control characters are expected.
      END DO                !On to the next line.
      END

With old-style fixed-format source, rather amusingly there is space for sixty-six characters of text per line and so this is the canvas. Any usage of tab characters must be resolved into spaces (and some compilers count up to 72 oddly when tabs are involved) and likewise with new lines. A surprise was provided to an old-time card flapper when it became apparent that trailing spaces were not being incorporated into the text literal unless the "<col72" markers were appended to column seventy-two of the source. An old-time card deck copied to disc and with the sequence numbers in columns 73-80 removed (as no-one is going to drop a disc file so some storage space can be saved) might thereby compile incorrectly! Similarly, the source text highlighter here does not fully recognise the odd tricks available for Fortran syntax, apparently deeming the comments a part of a text literal. The F90 compiler's highlighting does, and shows that text beyond column 72 is not Fortran code.

The text blob could instead be an array, but in that case, each line would have to be delimited by quotes and a comma added, reducing the width of the canvas and adding more stuff to be disregarded. But with a single blob of text, the output statement must step through the parts of the blob to extract the lines. If the statement were WRITE (6,1) I AM then only the first 66 characters of I AM would be rolled forth. If the format code were just A instead of A66, then all the text would be rolled, but the output would not be presented with 66 characters per line. So, some complications lead to :


              I AM

           THAT I AM



Free Pascal

In Pascal, the only forbidden character in string literals is the newline character. However, as of 2019‑09‑06 in a trunk version of the FPC (Free Pascal compiler) support for string literals spanning multiple lines can be enabled.


FreeBASIC

FreeBASIC no tiene heredocs ni cadenas de varias líneas. Una solución alternativa es unir varias líneas con NL, LF, \n o Chr(10).

Dim As String text1 = " " & Chr(10) & _
"<<'FOO' " & Chr(10) & _
"  'jaja', `esto`" & Chr(10) & _
"  <simula>" & Chr(10) & _
"  \un\" & Chr(10) & _
!"  ${ejemplo} de \"heredoc\"" & Chr(10) & _
"  en FreeBASIC."

Dim As String text2 = "Esta es la primera linea." & Chr(10) & _
"Esta es la segunda linea." & Chr(10) & _
!"Esta \"linea\" contiene comillas."

Print text1
Print Chr(10) + text2
Sleep
Output:
<<'FOO'
  'jaja', `esto`
  <simula>
  \un\
  ${ejemplo} de "heredoc"
  en FreeBASIC.

Esta es la primera linea.
Esta es la segunda linea.
Esta "linea" contiene comillas.


Frink

Frink does not have awkward here-docs. Triple-quoted strings serve the same purpose, but more concisely. (The Perl, PHP, etc. syntax for here-documents is a violation of the "define everything at most once" principle of software engineering.) Variable interpolation is allowed within triple-quoted strings.

lyrics = """Oh, Danny Boy,
The pipes, the pipes are calling
From glen to glen and down the mountainside"""

Genie

Genie includes triple quoted verbatim strings and "at" quoted template strings, which can be used as Heredoc data in source. Given the limitation of terminating quotes not being a user defined sequence, inner quotations will need to be escaped or transcluded.

[indent=4]
/*
  Here documents, as template and verbatim strings in Genie
  valac heredoc.gs
*/
init
    test:string = "Genie string"

    var multilineString = """
this is a $test
"""

    var templateString = @"
this is a $test template
with math for six times seven = $(6 * 7)
"

    stdout.printf("%s", multilineString)
    stdout.printf("%s", templateString)
Output:
prompt$ valac heredoc.gs
prompt$ ./heredoc

this is a $test

this is a Genie string template
with math for six times seven = 42

Go

Go does not have here documents. Multiline string literals serve this purpose.

var m = `    leading spaces

and blank lines`

Groovy

Groovy has two types of multi-line strings, which behave similarly to "here documents"

Multi-line String literal

The literal text, preserving lines and spacing

println '''
Time's a strange fellow;
                        more he gives than takes
(and he takes all) nor any marvel finds
quite disappearance but some keener makes
losing, gaining
               --love! if a world ends
'''
Output:
Time's a strange fellow;
                        more he gives than takes
(and he takes all) nor any marvel finds
quite disappearance but some keener makes
losing, gaining
               --love! if a world ends

Multi-line GString expression

Like single-line GString expressions, any subexpression delimited with ${ } is substituted with its "toString()" value. Preserves lines and spacing outside of the subexpressions.

def expired='defunct'
def horse='stallion'
def christ='Jesus'

println """
Buffalo Bill's 
              ${expired} 
                          who used to 
                          ride a watersmooth-silver 
                                                                  ${horse} 
              and break onetwothreefourfive pigeonsjustlikethat 
                                                                                           ${christ}

              he was a handsome man 
                                                    and what i want to know is 
              how do you like your blueeyed boy 
              Mister Death
"""
Output:
Buffalo Bill's 
              defunct 
                          who used to 
                          ride a watersmooth-silver 
                                                                  stallion 
              and break onetwothreefourfive pigeonsjustlikethat 
                                                                                           Jesus

              he was a handsome man 
                                                    and what i want to know is 
              how do you like your blueeyed boy 
              Mister Death

Haskell

You could use raw-strings-qq, or alternatively:

main :: IO ()
main = do

-- multiline String
  putStrLn "Hello\
            \ World!\n"

-- more haskell-ish way
  putStrLn $ unwords ["This", "is", "an", "example", "text!\n"]

-- now with multiple lines
  putStrLn $ unlines [
             unwords ["This", "is", "the", "first" , "line."]
           , unwords ["This", "is", "the", "second", "line."]
           , unwords ["This", "is", "the", "third" , "line."]
           ]

Output:


Hello World!

This is an example text!

This is the first line.
This is the second line.
This is the third line.

J

here=:0 :0
  0 :0 will be replaced by the text on the following lines.
  This is three tokens: two instances of the number 0 and
  one instance of the explicit definition token ':'.
  Any indentation in the here document will be retained in the result.
  There must be a space to the left of : or it will combine with the
  0 on its left to form the token 0: which is something completely 
  different.

  The here document is terminated by a line which contains only a
  single right parenthesis ')' and optional white space.  In J's
  documentation the family of entities which include here documents
  (and verb definitions and so on) are called 'scripts'.

  When several scripts are referenced on the same line, they are used
  sequentially in an order determined by their appearance on the line.
  The leftmost 'script' reference gets the last script and the rightmost
  reference gets the first script.  But this is a rare usage.

  Typically, such values are assigned a name so that they can be
  used later.  However, they may also be discarded and/or ignored, in
  which case they are logically equivalent to multi-line comments.
)

and_here=:noun define
  'noun define' is an alternative and perhaps more "user friendly"
  way of declaring a here document.  It achieves the same thing as
  0 :0 and in fact 'noun' has the value 0 and 'define' has the value :0
  And, of course, there must be a space between the word 'noun' and
  the word 'define'.

  Other useful alternatives include verb (which has the value 3)
  and dyad (which has the value 4), and adverb (which has the value 1).
  In other words 'verb define' (if unquoted) would be replaced by a 
  verb whose definition is provided in the following 'script'.
  However, all of these names are normal variables which can
  be declared to have different values by the developer.  And, of course,
  note that this mechanism is significantly more verbose than using
  the underlying 0 :0 mechanism directly.
)

also_here=: {{)n
  J902 introduced {{ blocks which may be {{ nested }} arbitrarily }} to
  the J interpreter. This includes {{)n blocks which are here documents.
  These {{)n blocks are not further nestable (they represent
  literal text with no internal structure), and the terminating }}
  must appear at the beginning of a line (or on the same line as
  the opening {{)n -- but that would not be a "here doc").

  If text does not appear after the )n on the initial line, the
  initial (first) linefeed does not appear in the here doc. If
  text follows the {{)n, that text (and optional newline) would
  be included.
}}

Java

Sjharper79 (talk)

Compatibility

The Java feature 'Text Blocks' is only available with JDK 15 and above.

Syntax

You must include a newline character after the opening """, you cannot include any Strings after the opening """. The closing """ does not have to be on its own line.

See Java 17 String block for Multiline Java String.

package rosettacode.heredoc;
public class MainApp {
	public static void main(String[] args) {
		String hereDoc = """
				This is a multiline string.
				It includes all of this text,
				but on separate lines in the code.
				 """;
		System.out.println(hereDoc);
	}
}

Output

This is a multiline string.
It includes all of this text,
but on separate lines in the code.

JavaScript

ES6

ES6 introduced template literals. These are string literals that suport multi-line text and can include interpolated expressions using ${···} syntax. It is indicated with the backtich character [`]

const myVar = 123;
const tempLit = `Here is some
multi-line string. And here is
the value of "myVar": ${myVar}
That's all.`;
console.log(tempLit)
Here is some
multi-line string. And here is
the value of "myVar": 123
That's all.

jq

No special syntax is required to support "here documents" in jq in that any JSON string, and indeed any string specifier (as explained below), can be presented using a multiline format.

For example, consider:

def s:
"x
y
z";

s
Output:
$ jq -n s.jq
"x\ny\nz"

String specifiers, that is possibly non-JSON strings which incorporate references to jq expressions, are handled in the same way. For example, the following program produces the same result:

def specifier(a):
"x
\(a)
z";

specifier("y")

Most control characters, such as Control-A and Control-Z, can also be presented literally, but the RosettaCode.org editor disallows them in general, so the next example only shows an embedded literal tab:

"a
tab:    end
parens:()
single quotation mark:'
double quotation mark must be escaped:\"
b
d"
Output:
"a\ntab:\tend\nparens:()\nsingle quotation mark:'\ndouble quotation mark must be escaped:\"\nb\nd"

Julia

Like Python, Julia has triple-quoted string literals, which are similar to here-docs:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

Kotlin

Kotlin's 'raw string literals' behave in a similar way to 'here' documents in that line breaks, indentation and other whitespace is preserved within the string. They are distingished from normal strings by being surrounded by triple quote characters rather than by single quotes.

Escaped characters (such as \n, \t etc.) do not have a special meaning and so are treated literally.

It's also possible to embed variables and other expressions in a raw string literal using Kotlin's string interpolation facilities.

Here's an example of all this:

// version 1.1.0

fun main(args: Array<String>) {
    val ev = "embed variables"

    val here = """
               This is a raw string literal   
               which does not treat escaped characters 
               (\t, \b, \n, \r, \', \", \\, \$ and \u)
               specially and can contain new lines,
               indentation and other        whitespace
               within the string.
 
"Quotes" or doubled ""quotes"" can
be included without problem but not
tripled quotes.

           It's also possible to $ev
           in a raw string literal using string
           interpolation. 

  If you need to include a
  literal ${'$'} sign in a raw string literal then
  don't worry you've just done it!
               """

    println(here)
}
Output:
               This is a raw string literal
               which does not treat escaped characters
               (\t, \b, \n, \r, \', \", \\, \$ and \u)
               specially and can contain new lines,
               indentation and other        whitespace
               within the string.

"Quotes" or doubled ""quotes"" can
be included without problem but not
tripled quotes.

           It's also possible to embed variables
           in a raw string literal using string
           interpolation.

  If you need to include a
  literal $ sign in a raw string literal then
  don't worry you've just done it!

Lambdatalk

Lambdatalk inverts the standard evaluation process, nothing is evaluated out of S-expressions {first rest}.

1) defining a variable:
{def myVar 123}    

2) defining some text:
Here is some
multi-line string. And here is
the value of "myVar": '{myVar}
That's all.

3) displays :

Here is some
multi-line string. And here is
the value of "myVar": 123
That's all.

langur

Use a block modifier on a string literal using the qs or QS form to generate a blockquote. The block modifier must be the last modifier.

val .s = qs:block END
   We put our text here.
   Here we are, Doc.
END

Use the lead modifier to strip leading white space on each line.

val .s = qs:lead:block END
   We put our text here.
   Here we are, Doc.
END

We can also use this with a regex literal. Note that this does not make the regex pattern "free-spacing." Use the x modifier for that.

val .re = re:block END
a regex pattern here
Still here, Doc.
END
val .re = re:x:block END
    a free-spacing regex pattern here
    Somewhere, Doc.
END

Lingo

Lingo has no heredoc syntax. Quotes inside string literals have to be escaped with "&QUOTE&".
But you can define multi-line strings using the line continuation character "\":

str = "This is the first line.\
This is the second line.\
This "&QUOTE&"line"&QUOTE&" contains quotes."

put str
Output:
This is the first line.
This is the second line.
This "line" contains quotes.

For longer text it's more comfortable to put it into a named "field member" (=asset container) and load its text into a variable when needed:

str = member("my long text").text
put str

Lua

Lua uses the [ [ to mark the start of a dochere block and ] ] to mark the end. It can be used directly or while assigning strings to a variable. An arbitrary but matching number of = may be placed between the brackets in both delimiters to allow ] ] to appear in the string.

print([[
This is a long paragraph of text
it is the simplest while using it
with lua, however it will have the
same line breaks and spacing as
     you set in this block.
]])

print([=[by using equals signs, ]] may be embedded.]=])

local msg = [[this is a message that spans
multiple lines and will have the next lines
preserved as they were entered, so be careful
when using this]]

print(msg)

M2000 Interpreter

A block of { } can be used for code and for text. Editor in M2000 environment can color code/string on the fly, analyzing the first line, where the block start.

Module Checkit {
            a$={This is the first line
                  This is the second line
                  End bracket position declare indentation fortext (except for first line)
                  }
            Report a$  ' print all lines, without space at the left
}
CheckIt

Mathematica / Wolfram Language

Print["Mathematica
   is an
interesing
 language,
 with its
  strings
   being
 multiline
 by\
 default
 when not
back\
s\\ashed!"];
Output:
Mathematica
   is an
interesing
 language,
 with its
  strings
   being
 multiline
 by default
 when not
backs\ashed!

MATLAB

Matlab has no built-in heredoc syntax. The closest thing you can do is the following:

sprintf('%s\n',...
    'line1 text',...
    '      line2 text',...
    '            line3 text',...
    '            line4 text')

sprintf('%s\n',...
    'Usage: thingy [OPTIONS]',...
    '      -h                        Display this usage message',...
    '      -H hostname               Hostname to connect to')
Output:
    'line1 text
           line2 text
                 line3 text
                 line4 text
     '

    'Usage: thingy [OPTIONS]
           -h                        Display this usage message
           -H hostname               Hostname to connect to
     '

NewLISP

; here-document.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Here_document

(print (format [text]
    Blast it %s! I'm a %s,
    not a %s!
       --- %s
[/text] "James" "magician" "doctor" "L. McCoy"))

(exit)
Output:
    Blast it James! I'm a magician,
    not a doctor!
       --- L. McCoy

Nim

There are no heredocs, but triple-quoted-strings can be used:

echo """Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

NMAKE.EXE

target0: dependent0
    command0 <<
temporary, discarded inline file
...
<<

target1: dependent1
    command1 <<
temporary, but preserved inline file
...
<<KEEP

target2: dependent2
    command2 <<filename2
named, but discarded inline file
...
<<NOKEEP

target3: dependent3
    command3 <<filename3
named and preserved inline file
...
<<KEEP

OCaml

print_string {whatever|
  'hahah', `this`
  <is>
  \a\
  "Heredoc" ${example}
  in OCaml
|whatever}
;;
Output:
  'hahah', `this`
  <is>
  \a\
  "Heredoc" ${example}
  in OCaml

OxygenBasic

Use the keyword quote followed by a keyword or group of symbols to mark the beginning and end of text


s=quote
""""
    She said "He said 'I said `There is a rumour
    going around.` ' "
""""

print s

Perl

In Perl, there must not be a space between the "<<" and the token string. By default, the ending token must the entire end line (i.e. no surrounding spaces) for it to be recognized (but see exception below). Interpolation is allowed, like a double-quoted string:

$address = <<END;
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END

If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:

$pancake = <<"NO MORE INGREDIENTS";
egg
milk
flour
NO MORE INGREDIENTS

It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token. For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:

$x = <<'FOO';
No
$interpolation
here
FOO

Alternately, you can use backticks to cause the here document to be executed and the result returned, just like a normal backtick operator:

$output = <<`BAR`;
ls /home
BAR

Note that in the above examples, that a semicolon was left after the here document's token string. This is because (unlike PHP) the here document does not start immediately at the "<<END" token -- it starts on the next line. The "<<END" is actually an expression, whose value will be substituted by the contents of the here document. The "<<END" must still live inside a valid statement on the line that it's used. To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:

print(<<EOF . "lamb\n");
Mary had
  a little
EOF

Since Perl 5.26, the here document can be indented by putting a '~' before the token. All spaces to the left of the ending token then become insignificant. This avoids having a disconcerting exdent in the middle of your code.

sub flibbertigibbet {
    print <<~END;
        Mary had
          a little
        lamb
        END
}

Phix

Phix does not have here-docs. In Phix normal double quoted strings are single line and require escaping. Strings can also be entered by using triple doublequotes or single backticks to include linebreaks and avoid any backslash interpretation. If the literal begins with a newline, it is discarded and any immediately following leading underscores specify a (maximum) trimming that should be applied to all subsequent lines. Interpolation is left to printf and friends. Both """`""" and `"""` are valid. Examples:

string ts1 = """
this
"string"\thing"""

string ts2 = """this
"string"\thing"""

string ts3 = """
_____________this
             "string"\thing"""

string ts4 = `
this
"string"\thing`

string ts5 = `this
"string"\thing`

string ts6 = `
_____________this
             "string"\thing`

string ts7 = "this\n\"string\"\\thing"

constant tests={ts1,ts2,ts3,ts4,ts5,ts6,ts7}
for i=1 to length(tests) do
    for j=1 to length(tests) do
        if tests[i]!=tests[j] then crash("error") end if
    end for
end for
printf(1,"""
____________Everything
            (all %d tests)
            works
             just
            file.""",length(tests))
printf(1,"""`""")
printf(1,`"""`)
Output:
Everything
(all 7 tests)
works
 just
file.`"""

PHP

In PHP, the here document symbol is 3 less-than signs, not two: <<<

There must not be a space between the "<<<" and the token string. The ending token must always be the entire end line (i.e. no surrounding spaces) for it to be recognised, except for a possible semicolon. Interpolation is allowed, like a double-quoted string:

$address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;

In PHP 5.3+, it is possible to make a here-document that does not interpolate (PHP calls this a "nowdoc"), by surrounding the token with single-quotes (like in Perl):

$x = <<<'FOO'
No
$interpolation
here
FOO;

PicoLisp

We can use the 'here' function:

(out "file.txt"                        # Write to "file.txt"
   (prinl "### This is before the text ###")
   (here "TEXT-END")
   (prinl "### This is after the text ###") )
"There must be some way out of here", said the joker to the thief
"There's too much confusion, I can't get no relief"
TEXT-END

(in "file.txt" (echo))                 # Show "file.txt"
Output:
### This is before the text ###
"There must be some way out of here", said the joker to the thief
"There's too much confusion, I can't get no relief"
### This is after the text ###

PowerShell

In PowerShell, here-docs are known as "Here-Strings". The Key is the At symbol @.

$XMLdata=@"
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
    <servicing>
        <package action="configure">
            <assemblyIdentity name="Microsoft-Windows-Foundation-Package" version="${strFullVersion}" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="" />
            <selection name="RemoteServerAdministrationTools" state="true" />
            <selection name="RemoteServerAdministrationTools-Roles-AD" state="true" />
            <selection name="RemoteServerAdministrationTools-Roles-AD-DS" state="true" />
            <selection name="RemoteServerAdministrationTools-Roles-AD-DS-SnapIns" state="true" />
            <selection name="RemoteServerAdministrationTools-Features-StorageManager" state="true" />
            <selection name="RemoteServerAdministrationTools-Features-Wsrm" state="true" />
        </package>
    </servicing>
    <cpi:offlineImage cpi:source="wim:d:/2008r2wim/install.wim#Windows Server 2008 R2 SERVERSTANDARD" xmlns:cpi="urn:schemas-microsoft-com:cpi" />
</unattend>
"@

Python

Python does not have here-docs. It does however have triple-quoted strings which can be used similarly.

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

Racket

Racket has a raw built-in here-document syntax, with the usual problems that this implies (breaks code indentation, no "interpolation"):

#lang racket/base

(displayln #<<EOF
  Blah blah blah
    with indentation intact
    and "free" \punctuations\
EOF
)
Output:
  Blah blah blah
    with indentation intact
    and "free" \punctuations\

In addition, Racket has "@-forms", which are a syntax for free text (described here) that works well with code:

#lang at-exp racket/base

(require scribble/text)

(define excited "!!!")
(define (shout . text) @list{>>> @text <<<})

(output
 @list{Blah blah blah
         with indentation intact
           but respecting the indentation of
           the whole code
         and "free" \punctuations\
         and even string interpolation-like @excited
           but really @shout{any code}

       })

(output @list|<<{And customizable delimiters
                 so @foo{} is just plain text}>>|)
Output:
Blah blah blah
  with indentation intact
    but respecting the indentation of
    the whole code
  and "free" \punctuations\
  and even string interpolation-like !!!
    but really >>> any code <<<
And customizable delimiters
so @foo{} is just plain text

Raku

(formerly Perl 6) Heredocs in Raku use the :to modifier to a quoting operator, such as q or qq. The indentation of the end marker is removed from every line.

my $color = 'green';
say qq :to 'END';
    some line
    color: $color
    another line
    END
Output:
some line
color: green
another line

Note that the quotes around the "END" are not magic --- the marker is just a regular string; it's the `q` or `qq` that decides whether or not the heredoc interpolates.

Multiple here docs may be stacked on top of each other.

my $contrived_example = 'Dylan';
sub freewheelin() {
        print q :to 'QUOTE', '-- ', qq :to 'AUTHOR';
          I'll let you be in my dream,
            if I can be in yours.
        QUOTE
                Bob $contrived_example
                AUTHOR
}

freewheelin;
Output:
  I'll let you be in my dream,
    if I can be in yours.
-- Bob Dylan

Both q and qq are specialised forms of Q which comes with many adverbs. Here a heredoc that only interpolates @-sigils.

my @a = <1 2 3 4>;
say Q :array :to 'EOH';
    123 \n '"`
        @a$bc
        @a[]
    EOH
Output:
123 \n '"`
    @a$bc
    1 2 3 4

Raven

As a list:

'Buffy the Vampire Slayer' as sender
'Spike' as recipient

[
"Dear %(recipient)s,
"
"I wish you to leave Sunnydale and never return.
"
"Not Quite Love,
"%(sender)s
] "\n" join print

Using group to place the data on the stack:

'Buffy the Vampire Slayer' as sender
'Spike' as recipient

group
        "Dear %(recipient)s,
        "
        "I wish you to leave Sunnydale and never return.
        "
        "Not Quite Love,
        %(sender)s\n"
list "\n" join print
Output:
Dear Spike,

I wish you to leave Sunnydale and never return.

Not Quite Love,
Buffy the Vampire Slayer

REXX

/*REXX program demonstrates a method to use  "here"  documents in REXX. */
parse arg doc .                        /*"here" name is case sensitive. */

     do j=1  for sourceline()
     if sourceline(j)\=='◄◄'doc  then iterate
           do !=j+1  to sourceline()  while sourceline(!)\=='◄◄.'
           say sourceline(!)
           end   /*!*/
     exit                              /*stick a fork in it, we're done.*/
     end         /*j*/

say doc '"here" document not found.'
exit                                   /*stick a fork in it, we're done.*/
/*──────────────────────────────────start of "here" docs──────────────────
◄◄rs-232
RS─232 Signals and Pinouts  ┌─────────────────────────────────────────────────┐
                            │13  12  11  10  9   8   7   6   5   4   3   2   1│
──►  Interface between data └┐ 25  24  23  22  21  20  19  18  17  16  15  14┌┘
terminal equipment (DTE/male)└───────────────────────────────────────────────┘
and data communication equipment
[DCE/female]  employing  serial   ┌───────────────────────────────────────────┐
binary  data  interchange.        │ 12◄─secondary carrier detect   [SCD]  DCE │
┌─────────────────────────────────┤ 13◄─secondary clear to send    [SCS]  DCE │
│ 1◄─protective ground  [PG, GND] │ 14◄─secondary transmitted data [STD]  DTE │
│ 2◄─transmitted data   [TD]  DTE │ 15◄─transmit clock             [TC]   DCE │
│ 3◄─received data      [RD]  DCE │ 16◄─secondary received data    [SRD]  DCE │
│ 4◄─request to send    [RTS] DTE │ 17◄─receiver clock             [RC]   DCE │
│ 5◄─clear to send      [CTS] DCE │ 18◄─unassigned                            │
│ 6◄─data set ready     [DSR] DCE │ 19◄─secondary request to send  [SRS]  DTE │
│ 7◄─signal ground      [SG]      │ 20◄─data terminal ready        [DTR]  DTE │
│      (common return)            │ 21◄─signal quality detector    [SQD]  DCE │
│ 8◄─carrier detect     [CD]  DCE │ 22◄─ring indicator             [RI]   DCE │
│ 9◄─positive voltage   [-]       │ 23◄─data rate select       [DRS]  DCE/DTE │
│10◄─negative voltage   [-]       │ 24◄─external clock             [XTC]  DTE │
│11◄─unassigned                   │ 25◄─unassigned                            │
└─────────────────────────────────┴───────────────────────────────────────────┘
◄◄.
◄◄can
        ┌──────┐
        │      │
        │      ├┐
        │      ├┘
        │      │
        │      │
        │      │
        │      │
        │      │                                         ┌─────┐
        └──┬┬──┘                                         │┌───┐│
           ││                                            ├┤   ├┤
           ││    ┌───────────────┐                       ││   ││
           ││   ┌┴──────────────┬┘                       └┤   ├┘
           │└───┤               │                         └───┘
           └────┤            ┌──┘
                │            │
                └──┐         │
                   │         │
                   │         │
                   │         │
                   └─────────┘
◄◄.
────────────────────────────────────end of "here" docs──────────────────*/
Output:

when using the input of

rs-232
RS─232 Signals and Pinouts  ┌─────────────────────────────────────────────────┐
                            │13  12  11  10  9   8   7   6   5   4   3   2   1│
──►  Interface between data └┐ 25  24  23  22  21  20  19  18  17  16  15  14┌┘
terminal equipment (DTE/male)└───────────────────────────────────────────────┘
and data communication equipment
[DCE/female]  employing  serial   ┌───────────────────────────────────────────┐
binary  data  interchange.        │ 12◄─secondary carrier detect   [SCD]  DCE │
┌─────────────────────────────────┤ 13◄─secondary clear to send    [SCS]  DCE │
│ 1◄─protective ground  [PG, GND] │ 14◄─secondary transmitted data [STD]  DTE │
│ 2◄─transmitted data   [TD]  DTE │ 15◄─transmit clock             [TC]   DCE │
│ 3◄─received data      [RD]  DCE │ 16◄─secondary received data    [SRD]  DCE │
│ 4◄─request to send    [RTS] DTE │ 17◄─receiver clock             [RC]   DCE │
│ 5◄─clear to send      [CTS] DCE │ 18◄─unassigned                            │
│ 6◄─data set ready     [DSR] DCE │ 19◄─secondary request to send  [SRS]  DTE │
│ 7◄─signal ground      [SG]      │ 20◄─data terminal ready        [DTR]  DTE │
│      (common return)            │ 21◄─signal quality detector    [SQD]  DCE │
│ 8◄─carrier detect     [CD]  DCE │ 22◄─ring indicator             [RI]   DCE │
│ 9◄─positive voltage   [-]       │ 23◄─data rate select       [DRS]  DCE/DTE │
│10◄─negative voltage   [-]       │ 24◄─external clock             [XTC]  DTE │
│11◄─unassigned                   │ 25◄─unassigned                            │
└─────────────────────────────────┴───────────────────────────────────────────┘
Output:

when using the input of

can
        ┌──────┐
        │      │
        │      ├┐
        │      ├┘
        │      │
        │      │
        │      │
        │      │
        │      │                                         ┌─────┐
        └──┬┬──┘                                         │┌───┐│
           ││                                            ├┤   ├┤
           ││    ┌───────────────┐                       ││   ││
           ││   ┌┴──────────────┬┘                       └┤   ├┘
           │└───┤               │                         └───┘
           └────┤            ┌──┘
                │            │
                └──┐         │
                   │         │
                   │         │
                   │         │
                   └─────────┘

Ring

text ="
<<'FOO'
Now
   is
     the 
       time
            for
               all
                  good mem
to come to the aid of their country."
see text + nl

Output:

<<'FOO'
Now
   is
     the
       time
            for
               all
                  good mem
to come to the aid of their country.

Ruby

In Ruby, there must not be a space between the "<<" and the token string. The ending token must always be the entire end line (i.e. no surrounding spaces) for it to be recognised, unless you use "<<-" instead of "<<", in which case indentation before the ending token is allowed. Interpolation is allowed, like a double-quoted string:

address = <<END
1, High Street,
#{town_name},
West Midlands.
WM4 5HD.
END

If the token string contains spaces, the token after the "<<" must be quoted; otherwise the double-quotes is implicit:

pancake = <<"NO MORE INGREDIENTS"
egg
milk
flour
NO MORE INGREDIENTS

It is possible to make a here-document that behaves differently than a double-quoted string, by applying a different kind of quoting to the token. For example, if you use single quotes, then the here document will not support interpolation, like a normal single-quoted string:

x = <<'FOO'
No
#{interpolation}
here
FOO

Alternately, you can use backticks to cause the here document to be executed and the result returned, just like a normal backtick operator:

output = <<`BAR`
ls /home
BAR

The here document does not start immediately at the "<<END" token -- it starts on the next line. The "<<END" is actually an expression, whose value will be substituted by the contents of the here document. The "<<END" must still live inside a valid statement on the line that it's used. To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:

puts <<EOF + "lamb"
Mary had
  a little
EOF

Run BASIC

text$ ="
<<'FOO'
Now
   is
     the 
       time
            for
               all
                  good mem
to come to the aid of their country."
print text$
Output:
<<'FOO'
Now
   is
     the 
       time
            for
               all
                  good mem
to come to the aid of their country.

Rust

Similar to C++, Rust offers raw strings. In a manner resembling Lua's delimiters, an arbitrary but matching number of # on both ends may be used to allow inclusion of # into the string:

let x = r#"
    This is a "raw string literal," roughly equivalent to a heredoc.   
"#;

let y = r##"
  This string contains a #.
"##;

Scala

All versions

Scala multiline literal are called raw strings. Triple quotes (""") marks the beginning and end. Specially handy when using escape sequences in e.g. regular expressions.

Library: Scala
object temp {
val MemoriesOfHolland=
  """Thinking of Holland
    |I see broad rivers
    |slowly chuntering
    |through endless lowlands,
    |rows of implausibly
    |airy poplars
    |standing like tall plumes
    |against the horizon;
    |and sunk in the unbounded
    |vastness of space
    |homesteads and boweries
    |dotted across the land,
    |copses, villages,
    |couchant towers,
    |churches and elm-trees,
    |bound in one great unity.
    |There the sky hangs low,
    |and steadily the sun
    |is smothered in a greyly
    |iridescent smirr,
    |and in every province
    |the voice of water
    |with its lapping disasters
    |is feared and hearkened.""".stripMargin
}

All control codes are transparent e.g. new lines. In order for a neat code each lines has as prefix spaces and a | symbol which will be removed by the stripMargin function.

sed

c\
The commands 'a', 'c', and 'i' can be followed\
by multi-line text. Each line break in the text\
is preceded by a backslash.
Output:
$ echo | sed -f heredoc.sed                                                                                                                                                                                                                                       
The commands 'a', 'c', and 'i' can be followed
by multi-line text. Each line break in the text
is preceded by a backslash.

SenseTalk

SenseTalk has "block quotes" for large blocks of text, enclosed between "{{" (at the end of a line) and "}}" (at the beginning of a line). A tag can also be used after the "{{" and before the "}}" which allows for nesting of blocks, such as for a block of code containing other block quotes.

set script to {{SCRIPT
put "Script demonstrating block quotes"

set text to {{
"I wish it need not have happened in my time," said Frodo.
"So do I," said Gandalf, "and so do all who live to see such times. But that is not for them to decide. All we have to decide is what to do with the time that is given us."
}}

put the number of occurrences of "time" in text --> 3

SCRIPT}}

do script

SequenceL

main := 
"In SequenceL
strings are
multiline
by default.
'All' non-\"
characters are
valid for inclusion
in a string.";
Output:
"In SequenceL
strings are
multiline
by default.
'All' non-"
characters are
valid for inclusion
in a string."

Sidef

There must not be a space between the "<<" and the token string. When the token string is double-quoted ("") or not quoted, the content will be interpolated like a double-quoted string:

var text = <<"EOF";
a = #{1+2}
b = #{3+4}
EOF

If single quotes are used, then the here document will not support interpolation, like a normal single-quoted string:

var x = <<'FOO';
No
#{interpolation}
here
FOO

The here document does not start immediately at the "<<END" token -- it starts on the next line. The "<<END" is actually an expression, whose value will be substituted by the contents of the here document. To further illustrate this fact, we can use the "<<END" inside a complex, nested expression:

say (<<EOF + "lamb");
Mary had
  a little
EOF

which is equivalent with:

say (<<EOF
Mary had
  a little
EOF
+ "lamb");

SQL PL

Works with: Db2 LUW

With SQL only from command line. The single quote string is opened along the three lines:

db2 "select 'This is the first line.
This is the second line.
This is the third line.' from sysibm.sysdummy1"

Output:

1                                                                       
------------------------------------------------------------------------
This is the first line.
This is the second line.
This is the third line.

  1 record(s) selected.

With SQL only from script with concat function (one row):

select 'This is the first line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the third line.' from sysibm.sysdummy1;

Output:

1
------------------------------------------------------------------------
This is the first line.
This is the second line.
This is the third line.

  1 record(s) selected.

With SQL only from script with union operator (three rows):

select 'This is the first line.' from sysibm.sysdummy1
union
select 'This is the second line.' from sysibm.sysdummy1
union
select 'This is the third line.' from sysibm.sysdummy1;

Output:

1
------------------------
This is the first line.
This is the second line.
This is the third line.

  3 record(s) selected.
Works with: Db2 LUW

version 9.7 or higher.

With SQL PL:

SET serveroutput ON
CALL DBMS_OUTPUT.PUT_LINE('This is the first line.' || chr(10) ||
'This is the second line.' || chr(10) ||
'This is the third line.');

Output:


  Return Status = 0

This is the first line.
This is the second line.
This is the third line.

Tcl

set hereDocExample {
In Tcl, the {curly brace} notation is strictly a here-document style notation
as it permits arbitrary content inside it *except* for an unbalanced brace.
That is typically not a problem as seen in reality, as almost all content that
might be placed in a here-doc is either brace-free or balanced. 
The content of the braces is not interpreted at all; 
no substitutions are performed on it.

The sole exception is that there is limited processing of backslashes; 
a single backslash at the end of a line causes the end-of-line 
plus all whitespace at the start of the next line 
to be compressed to a single space.
}

If substitution is desired within the document, it should either be written inside "double quotes" (instead of {braces}) or it should be passed through the subst command, which performs another round of substitutions.

TXR

TXR was originally conceived out of the need to have "there documents": parse a document and extract variables, but in a style similar to generation of here documents. Here doc output was added later.

We use @(maybe)/@(or)/@(end) to set up some default values for variables which are overridden from the command line. Unification fails for an overridden variable, which is why we have to separate out the bind directives into the branches of a maybe.

By passing the script to txr using -f we can pass additional command arguments to the resulting script which are interpreted by txr.

#!/usr/bin/txr -f
@(maybe)
@(bind USER "Unknown User")
@(or)
@(bind MB "???")
@(end)
@(output)
Dear @USER

Your are over your disk quota by @MB megabytes.

The Computer
@(end)

Test runs

$ ./quota.txr -DMB=20
Dear Unknown User

Your are over your disk quota by 20 megabytes.

The Computer
$ ./quota.txr -DUSER=Bob
Dear Bob

Your are over your disk quota by ??? megabytes.

The Computer
$ ./quota.txr -DUSER=Bob -DMB=15
Dear Bob

Your are over your disk quota by 15 megabytes.

The Computer

Unbound variables throw exceptions:

$ txr -c '@(output)
@FOO
@(end)'
txr: unhandled exception of type query_error:
txr: (cmdline:2) bad substitution: FOO

UNIX Shell

In the shell, here document act as input to the command, rather than providing a string definition.

Works with: Bourne Shell
#!/bin/sh
cat << ANARBITRARYTOKEN
The river was deep but I swam it, Janet.
The future is ours so let's plan it, Janet.
So please don't tell me to can it, Janet.
I've one thing to say and that's ...
Dammit. Janet, I love you.
ANARBITRARYTOKEN
cat << EOF
Here documents do parameter and command substitution:
 * Your HOME is $HOME
 * 2 + 2 is `expr 2 + 2`
 * Backslash quotes a literal \$, \` or \\
EOF
if true; then
    cat <<- EOF
    The <<- variant deletes any tabs from start of each line.
    EOF
fi
cat << 'TOKEN'
If TOKEN has any quoted characters (like 'TOKEN', "TOKEN" or \TOKEN),
then all $ ` \ in the here document are literal characters.

$PATH \$PATH `shutdown now`
TOKEN
echo '
In any unix shell, you specify a text block and can use all whitespace like
  (spaces) &    (tab) in it, by using single quotes. 
As mentioned above, a Unix "here document" is a type of redirection.
In a literal Bash here document, the starting token must be
quoted, but the end token must not, so they are not the same, which does not
conform to the task definition.
'

C Shell

#!/bin/csh -f
cat << ANARBITRARYTOKEN
 * Your HOME is $HOME
 * 2 + 2 is `@ n = 2 + 2; echo \$n`
ANARBITRARYTOKEN

cat << 'ANARBITRARYTOKEN'
$PATH \$PATH `shutdown now`
'ANARBITRARYTOKEN'

Ursala

hd = 

-[
The text enclosed within the so called dash-brackets shown above
and below will be interpreted as a list of character strings. It
can contain anything except uninterpreted dash-brackets, and can
be used in any declaration or expression. The dash-brackets don't
have to be on a line by themselves.
]-


example =

-[Some additional facilities allow here-documents to be nested and
combined. Writing something like -[ hd ]- within a nested pair of
dash-brackets will cause the text declared above (having the
identifer hd) to be inserted at that point. The enclosed item can
be any expression that evaluates to a list of character strings.
We could therefore "escape" a literal dash-bracket within a
here-document by writing -[ <'-['> ]-. Dash-brackets can be nested
to any depth, alternating between literal text and compiled code
on each level.]-

template "x" =

-[A further use of this notation involves defining a text-valued
function. The output of this function will be this text, with
the argument inserted here -["x"]- and again here -["x"]-. The
argument type should be a list of character strings.]-

formletter ("x","y") =

-[Other calling conventions are possible. The left argument
comes out here -["x"]- and the right one here -["y"]-.]-

designpattern =

-[A point-free style of function declaration is also supported.
The argument comes out here -[. ~& ]-, after being fed through
the function appearing within the nested dash-brackets (in this
case the identity function). This usage is indicated by a period
after the left inner dash-bracket. Nesting is also allowed in
point free dash-bracket function specifications.]-

abstractionastronaut =

-[Higher order functions to any level are specified by piling on
the periods like this -[.. ~&]-. This one is a second order function
that needs to be applied to another function in order to get a
first order function such as the previous three examples.]-

VBScript

There is no such thing in VBScript but we need it, too. The following is a workaround tool.

It will prompt you to select a Txt-based file and do its best to create VBScript code that will recreate that Txt-based file!

'Purpose: Converts TXT files into VBS code with a function that returns a text string with the contents of the TXT file
'         The TXT file can even be another VBS file.

'History:
'   1.0 8may2009    Initial release
'
'
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TristateUseDefault = -2

set WshShell = CreateObject("WSCript.shell")

'File browse dialog box
Set objDialog = CreateObject("UserAccounts.CommonDialog")
objDialog.Filter = "All Files|*.*"
objDialog.InitialDir = WshShell.CurrentDirectory
intResult = objDialog.ShowOpen
 
If intResult = 0 Then
    WshShell.Popup "No file selected.", 2, " ", 64
    Wscript.Quit
Else
    strFileNameIN = objDialog.FileName
End If

strFileNameOUT= strFileNameIN & "_CONVERTED.Vbs"

'Check if strFileNameOUT exists already
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strFileNameOUT) then  'does the file EXIST?
'   WScript.Echo "found"
    OVRWT=MSGBOX(strFileNameOUT & " exists already"&vbCRLF&"Overwrite?",vbYesNoCancel,"Overwrite?")
    if OVRWT = 6 then
        'proceed
        objFSO.DeleteFile(strFileNameOUT)
    else
        WshShell.Popup "Exiting as requested.", 1, " ", 64
        Wscript.Quit
    End If 
Else
'   WScript.Echo "not found" 'strFileNameOUT does NOT exists already
    
END if

strBaseName=objFSO.GetBaseName(strFileNameIN)


'open strFileNameANSI file, and put entire file into a variable ****SIZE LIMIT ??*****
Set objFile = objFSO.OpenTextFile(strFileNameIN, ForReading)
strText = objFile.ReadAll
objFile.Close

'Start converting

'Convert " to ""
strOldText = Chr(34)
strNewText = Chr(34)&Chr(34)
strText = Replace(strText, strOldText, strNewText)

'Add objTXTFile.writeline ("
strOldText = VBCRLF
strNewText = """)  &vbCrLf"&VBCRLF&"    strText=strText& ("""
strText = Replace(strText, strOldText, strNewText)
'Converting done

strFileName=objFSO.GetFileName(strFileNameIN)

'Write to file
Set objFile = objFSO.OpenTextFile(strFileNameOUT, ForAppending, True)
objFile.WriteLine "'this Function will return a string containing the contents of the file called "&strFileName
objFile.WriteLine "msgbox "&strBaseName &"()"
objFile.WriteLine vbCrLf
objFile.WriteLine "Function "&strBaseName&"()"
objFile.WriteLine " 'returns a string containing the contents of the file called "&strFileName
objFile.WriteLine " Dim strText"
objFile.WriteLine " strText= ("""&strText&""") &vbCrLf"
objFile.WriteLine " "&strBaseName&"=strText"
objFile.WriteLine "End Function"
objFile.Close

WshShell.Popup "created " & strFileNameOUT, 3, "Completed", 64

V (Vlang)

Vlang does not have here documents. Multiline string literals serve this purpose.

fn main() {
    m := '    leading spaces
    
and blank lines'

    println(m)
}

Wren

Wren does not have heredocs but (from v0.4.0) does have raw strings.

A raw string is any text delimited by triple quotes, """, and is interpreted literally i.e. any control codes and/or interpolations are not processed as such.

If a triple quote appears on its own line then any trailing whitespace on that line is ignored.

Borrowing the Ada example (appropriately adjusted) for an illustration of a raw string.

var a = 42
var b = """
This is a 'raw' string with the following properties:
  - indention is preserved, 
  - an escape sequence such as a quotation mark "\\" is interpreted literally, and
  - interpolation such as %(a) is also interpreted literally.
`Have fun!`
"""
System.print(b)
Output:
This is a 'raw' string with the following properties:
  - indention is preserved, 
  - an escape sequence such as a quotation mark "\\" is interpreted literally, and
  - interpolation such as %(b) is also interpreted literally.
`Have fun!`

XPL0

code Text=12;
Text(0, "   ^"Heredocs^" are pretty much automatic. Multiple lines and
whitespace, such as indentations, are output exactly as written. Quote
marks (^") and any carets (^^) within the string must be escaped.")

XSLT

Being a dialect of XML, XSLT inherits CDATA sections. Not quite heredocs, these are more like raw triple quotes in Python (r"""…""") or Scala ("""…""") in that anything except the end delimiter is treated literally.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>

<xsl:template match="/">
<![CDATA[

This text is in a CDATA section. In here, it's okay to include <, >, &, ", and '
without any special treatment.

The section is terminated by a three-character sequence consisting of two right
brackets ("]]") followed by a greater-than (">"). If this sequence appears in
your text, a workaround is to drop out of the CDATA section, output part of the
terminator, then start a new CDATA section and output the rest. Let's do this
now:

    ]]>]]<![CDATA[>

Newlines and spacing are retained as well, as long as they're evaluated in a
context that bothers preserving them. Whether or not the spaces before and after
the CDATA section are also preserved may be application-dependent.

]]>
</xsl:template>
</xsl:stylesheet>

Output from xsltproc (input is ignored):




This text is in a CDATA section. In here, it's okay to include <, >, &, ", and '
without any special treatment.

The section is terminated by a three-character sequence consisting of two right
brackets ("]]") followed by a greater-than (">"). If this sequence appears in
your text, a workaround is to drop out of the CDATA section, output part of the
terminator, then start a new CDATA section and output the rest. Let's do this
now:

    ]]>

Newlines and spacing are retained as well, as long as they're evaluated in a
context that bothers preserving them. Whether or not the spaces before and after
the CDATA section are also preserved may be application-dependent.



Yabasic

text1$ = "Esta es la primera linea.
Esta es la segunda linea.
Esta \"linea\" contiene comillas.\n"

text2$ = "Blast it James! I'm a magician,
not a doctor!
   --- L. McCoy\n"


print text1$
print text2$
end
Output:
Esta es la primera linea.
Esta es la segunda linea.
Esta "linea" contiene comillas.

Blast it James! I'm a magician,
not a doctor!
   --- L. McCoy


zkl

x:=
#<<<
"#<<< starts a block of lines that are concatenated verbatim 
and fed into the parser as one line. #<<< ends the block.
Both #<<< tokens must start the line that is otherwise ignored

Note that is isn't a string, but arbitrary source " + 1 + 23;
#<<<
x.println();
Output:
#<<< starts a block of lines that are concatenated verbatim 
and fed into the parser as one line. #<<< ends the block.
Both #<<< tokens must start the line that is otherwise ignored

Note that is isn't a string, but arbitrary source 123