[Question]
  [
Your task is simple: write a program (or function) that takes no input and outputs (or returns) its source code. The catch is that when the program is wrapped in `"quotes"` (Unicode character 34), it should again output its (now quoted) source code.
Standard rules for quines apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins.
  
[Answer]
# Python ~~2~~ 3, ~~181~~ ~~152~~ ~~130~~ ~~124~~ ~~122~~ ~~100~~ ~~98~~ ~~96~~ 84 bytes
*-12 bytes thanks to Jakque.*
```
a=1;""";a=0;" """;p='"a=1;""";a=0;" """;p=%r;print(p[a:~a]%%p)#".';print(p[a:~a]%p)#
```
[Try it online!](https://tio.run/##pU9BDoIwELzzimYNKQQkEm80fYQXL0jIAlWbNG0DJdGLX0cQOWg46WV3Mju7M2vv7mr0fmjEmdhWahdgmF2UqVAR0zvbOzY3jqwsq14qJ3VXlski9mrTCE4pHZCnDAAY8h0DMiHLKayxfsvmdZtj9sDC9224gYR@sSM5jIdnh6nkabZNC28lxzQNmbiJ@g1XNHDopRbkiEo2GcTzW0nbuVbaAE4aQv5y@aCW/4BGE4hG4DVCERvjHzmME@SnNMMT) The TIO comes with a header and footer that automatically test the validity of the quine. You can clear them to just run the quine.
This code works by (ab)using the triple-quoted strings and string literal concatenation in Python.
* `";b=""";b=" """;` ignores `';b='` and sets `b` to `' '`.
* `"";b=""";b=" """;` ignores the empty string and sets `b` to `';b=" '`.
The rest of the code then implements the traditional Python quine using `%r` string formatting, with some additional code that strips the extra quotes depending on `b`.
## Older version from 2017, 122 bytes
```
""" """>" "or exec("oct=0");p='"""" """>" "or exec("oct=0");p=%r;a=oct==0;print(p[a:~a]%%p)#".';a=oct==0;print(p[a:~a]%p)#
```
[Try it online!](https://tio.run/nexus/python3#nU/LCoMwELz7FWGLxGAr9mpI/6GXXqxI1LQEggkxQk/9dZsoHoQ@oId9zjIz24kbMlb2LuGkuCvdcIX06Mzo6FIYp3XdjFI52Q91na3HUas7wTDGEwAgHyeftUXiIdoEdOtYDoQahuE7HlvKWRhZThduU/Liyas4NmQHGf4Ee3Ty8ouPkMpjcThW0SwQZvLOOJxH2Qt04Up2BeyXHzM7OCtNAtceCJvJNqv1WcBpaFLfRMHTht8vfmtrJ9BfDqYX)
`""" """` is equal to `' '` and `"""" """` is equal to `'" '`.
The code does use `exec`, but not for the "non-quiney" way of executing data as code, just for setting a variable from inside an expression. The `exec` is properly encoded in the data, too.
The first statement compares the string, possibly with a quote prepended, to `" "`, and sets the variable `oct` accordingly. (The variable could've been any short builtin.) The final part then checks if `oct` is unchanged.
An alternative version using the "cheaty" `exec` comes in at 126 bytes with less repeated code:
```
""" """>" "and exec("oct=0");s='"""" """>" "and exec("oct=0");s=%r;p=%r;exec(p)#".';p='a=oct!=0;print(s[a:~a]%(s,p))';exec(p)#
```
[Try it online!](https://tio.run/nexus/python3#nU9BCsIwELz3FXFF0tBa9JoQ/@DFSy0ltlECJQlNCp78ek1aKhQEwUMmu7PD7kwr78j2SvtUEProzE10yAzeDp7NHxesrm@D6rzSrq6LRZw0ppUcYzwCAArvFFDoFsmnbFIwjecHIMxxDD8Eu57ZCBNvyRYKHAgseJBs@IHNF10p6EtUu9TllhD8UY/BwuwlQnmk@2OVTMPYk2/m4TwoLdFFdKqlkM85i975XtkUrhoIn5atqCUw4CwWWSiSmGG1PxC/bxsv0V8Oxjc)
[Answer]
# [StandardML](https://en.wikipedia.org/wiki/Standard_ML), ~~182 176~~ 108 bytes
```
";str(chr 34)^it;(print(it^it);fn x=>print(x^it^x^it))";str(chr 34)^it;(print(it^it);fn x=>print(x^it^x^it))
```
Unquoted version: [Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMckU4eUxMVV9VLW8)  
Quoted version: [Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMbWdVdVk5bWs3Njg)
Note that the output looks something like this
```
> val it = "{some string}" : string
> val it = "{some string}" : string
{output to stdout}> val it = fn : string -> unit
```
because the code is interpreted declaration by declaration (each `;` ends a declaration) and shows the value and type of each declaration.
---
### Background
In SML there is a quine of the form `<code>"<code in quotes>"`:
```
str(chr 34);(fn x=>print(x^it^x^it))"str(chr 34);(fn x=>print(x^it^x^it))" 
```
and one in the form `"<code in quotes>"<code>`:
```
";str(chr 34)^it;print(it^it)";str(chr 34)^it;print(it^it)
```
Both rely on the fact that the `<code>`-part contains no quotes and can thus be quoted with out the need for escaping anything, the `"` needed to output the quine are given by `str(chr 34)`.
They also heavily rely on the implicit identifier `it` which is used when no explicit identifier is given in a declaration.
In the first quine `str(chr 34);` binds `it` to the string containing `"`, `fn x=>` starts an anonymous function taking one argument `x`, then concatenates `x^it^x^it` and prints the resulting string. This anonymous function is directly applied to a string containing the program code, so the concatenation `x^it^x^it` yields `<code>"<code>"`.
The second quine starts with just the program code as string `";str(chr 34)^it;print(it^it)";` which is bound to `it`. Then `str(chr 34)^it;` concatenates a quote to the start of the string and as again no explicit identifier is given, the resulting string `"<code>` is bound to `it`. Finally `print(it^it)` concatenates the string with itself yielding `"<code>"<code>` which is then printed.
---
### Explanation
***Edit:** No longer up to date with the 108-byte version, however one might understand it too after reading this explanation.*
The quote-safe quine combines both of the above approaches and is itself of the form `"<code>"<code>`. Putting this in again in quotes yields `""<code>"<code>"`, so we get an empty string and then a quine of the other form.
That means the program is either given its own source in the form `"<code>` by the identifier `it`, or `it` is just `"` and we are given our own source `<code>` as argument and must thus be a function which handles such an argument.
```
(if size it>1then(print(it^it);fn _=>())else fn x=>print(it^it^x^it^x^it))
```
To identify in which case we are, we check whether the size of `it` is larger than 1. If not then `it` is `"` and we are in the second case, so the `else`-part returns an anonymous function `fn x=>print(it^it^x^it^x^it)` which is then called because its followed by source as string. Note the leading `it^it^` which is needed for the empty string at the start of the of the program.
If `size it` is larger than 1 we are in the `then`-part and just perform `print(it^it)`, right? Not quite, because I neglected to tell you that SML is strongly typed which means that a conditional `if <cond> then <exp_1> else <exp_2>` must always have the same type which again means that the expressions `<exp_1>` and `<exp_2>` need to have the same type. We already know the type of the `else` part: An anonymous function which takes a string and then calls `print` has type `string -> <return type of print>`, and `print` has type `string -> unit` (`unit` is in some way similar to `void` in other languages), so the resulting type is again `string -> unit`.
So if the `then` part was just `print(it^it)` which has type `unit`, we would get a type mismatch error. So how about `fn _=>print(it^it)`? (`_` is a wildcard for an argument that is not used) This anonymous function on its own has type `'a -> unit` where `'a` stands for an arbitrary type, so in the context of our conditional which enforces a `string -> unit` type this would work. (The type variable `'a` gets instantiated with type `string`.) However, in this case we would not print anything as the anonymous function is never called! Remember, when we go in the `then`-part the overall code is `"<code>"<code>`, so the `<code>`-part evaluates to a function but, as nothing comes after it, its not called.
Instead we use a sequentialisation which has the form `(<exp_1>; ...; <exp_n>)` where `<exp_1>` to `<exp_n-1>` may have arbitrary types and the type of `<exp_n>` provides the type of the whole sequentialisation. From a functional point of view the values of `<exp_1>` to `<exp_n-1>` are simply discarded, however SML also supports imperative constructs so the expressions may have side effects. In short, we take `(print(it^it);print)` as the `then`-part, thus printing first and then returning the function `print` which has the correct type.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~27~~, 23 bytes
```
éPñi"éP241"qpá"lxx|xÿ
```
[Try it online!](https://tio.run/nexus/v#@394ZcDhjZlKQErMyMRQWqmw4PBCpZyKipqKw/v//wcA "V – TIO Nexus")
Since this contains some unprintable characters, here is a readable version:
```
éPñi"éP<C-v>241<esc>"qpá"lxx|xÿ
```
and here is a hexdump:
```
00000000: e950 f169 22e9 5016 3234 311b 2271 70e1  .P.i".P.241."qp.
00000010: 226c 7878 7c78 ff                        "lxx|x.
```
So the very first thing we need to do is to determine if the first character is a quote. `éP` inserts a 'P' character, but `"éP` is a NOOP. After that, we run a slight modification on the standard extendable quine, which is:
```
ñi<C-v>241<esc>"qpÿ
```
We're going to do it slightly differently though. First off we need to insert the starting "éP" text. So we do
```
ñ                        " Start recording into register 'q'
 i                       " Enter insert mode
  "éP<C-v>241<esc>       " Enter the following text: '"éPñ'
                  "qp    " Paste the text in register 'q'
                     á"  " Append a '"'
```
Here is where the branching happens. The text currently in the buffer is 
```
"éPñi"éP<C-v>241<esc>"qpá"P
Cursor is here ----------^
```
Unless we wrapped it in quotes, in that case the 'P' would never have been inserted, and the buffer is:
```
"éPñi"éP<C-v>241<esc>"qpá"
Cursor is here ----------^
```
Since we are still recording, we can do whatever we want here, and it will get added to the buffer when the `"qp` happens. So from here it's pretty easy to conditionally delete the quotes:
```
l           " Move one character to the right. If there is no character to the right, 
            " then this is effectively a "break" statement, stopping playback of the recording
 xx         " Delete two characters (the '"P')
   |        " Move to the first character on this line
    x       " Delete one character
     ÿ      " End the program
```
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), ~~9~~ 7 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html)
This version works the same way as the other, just that I forgot that *Noodel* has a way to run a block of code once and I made the language...
~~`Ḷ1ḥ-Ð1ḥ@€`~~
```
ḷḥ-Ðḥ@ḅ
```
[Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%E1%B8%B7%E1%B8%A5-%C3%90%E1%B8%A5%40%E1%B8%85&input=&run=false)
---
### How it Works
```
ḷḥ-Ðḥ@ḅ # Single statement that builds itself as a string.
ḷ       # Loop the following block of code unconditionally.
 ḥ-     # Push the string literal of the token preceding this one which pushes "ḷ" onto the stack.
   Ð    # Push the stack as an array to stdout (since is an array it is done by reference).
    ḥ@  # Push the string literal for this block of code which pushes "ḥ-Ðḥ@ḅ" onto the stack.
      ḅ # Break out of the given loop. (The stack is now ["ḷ", "ḥ-Ðḥ@ḅ"]).
        # The top of the stack is popped off and displayed which modifies the array to produce {["ḷ"], "ḥ-Ðḥ@ḅ"} in stdout.
```
---
### Quote-Safety
Placing the `"` character before and after the program works because *Noodel* has a set of of characters dedicated to what I call *printables*. These are immediately parsed as string literals when placed by themselves and allow for easily printing something to the screen. So unlike most languages, *Noodel* sees the normal *ASCII* set that is considered print worthy as direct string literals (except for space and line feed) therein quoting the code is merely seen as pushing on strings.
```
"ḷḥ-Ðḥ@ḅ"
"         # Pushes on the string literal "\"" onto the stack.
 ḷḥ-Ðḥ@ḅ  # Same execution as before, simply builds the Quine for this loop.
 ḷ        # Loop the following block of code unconditionally.
  ḥ-      # Push the string literal of the token preceding this one which pushes "ḷ" onto the stack.
    Ð     # Push the stack as an array to stdout (since is an array it is done by reference).
     ḥ@   # Push the string literal for this block of code which pushes "ḥ-Ðḥ@ḅ" onto the stack.
       ḅ  # Break out of the given loop. (The stack is now ["\"", "ḷ", "ḥ-Ðḥ@ḅ"]).
        " # Pushes on the string literal "\"" onto the stack.
          # The top of the stack is popped off and displayed which modifies the array to produce {["\"", "ḷ", "ḥ-Ðḥ@ḅ"], "\""} in stdout.
```
["Try it:)"](https://tkellehe.github.io/noodel/editor.html?code=%22%E1%B8%B7%E1%B8%A5-%C3%90%E1%B8%A5%40%E1%B8%85%22&input=&run=false)
---
### Snippets
```
<div id="noodel" code='ḷḥ-Ðḥ@ḅ' input="" cols="10" rows="1"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
---
```
<div id="noodel" code='"ḷḥ-Ðḥ@ḅ"' input="" cols="10" rows="1"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# JavaScript (ES6), ~~239~~ 237 bytes
```
Set=``;eval(";a='Set=``;eval(~;a=1;S=String.fromCharCode;q=S(34);r=Set&&q;s=S(39);alert(r+a.replace(/[^ -}]/g,q).replace(1,s+a+s)+r);~)';S=String.fromCharCode;q=S(34);r=Set&&q;s=S(39);alert(r+a.replace(/[^ -}]/g,q).replace(1,s+a+s)+r);")
```
Take care to try each version in a fresh environment (e.g., a new browser tab)
There has got to be at least one way to simplify this...
[Answer]
# [Perl 5](https://www.perl.org/), 59 bytes
```
";$\=q;";;$_=q(print$\,'";$\=q;";;$_=q('."$_);eval#");eval#
```
[Try it online!](https://tio.run/##K0gtyjH9/1/JWiXGttBaydpaJd62UKOgKDOvRCVGRx1NXF1PSSVe0zq1LDFHWQlK//8PAA "Perl 5 – Try It Online")
## Quoted
```
"";$\=q;";;$_=q(print$\,'";$\=q;";;$_=q('."$_);eval#");eval#"
```
[Try it online!](https://tio.run/##K0gtyjH9/19JyVolxrbQWsnaWiXetlCjoCgzr0QlRkcdTVxdT0klXtM6tSwxR1kJRv//DwA "Perl 5 – Try It Online")
## Explanation
In the original, there is an unused string `";$\=q;"` separated by `;;` before the standard quine body which first `print`s `$\` (which is empty by default) followed by the unused string and the body followed by `#`.
In the quoted string, there is an unused string `""`, separated by `;` then `$\` is set to `q;";` which is Perl's custom quotes `q;...;` wrapping the double-quote char. Then the quine body is built and `$\` is automatically `print`ed after all content adding the final `"` in the quoted string.
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes & [Python 3](https://docs.python.org/3/), 70 bytes
## Python 2, 68 bytes:
```
x=""#";x='"'
s='x=""#";x=\'"\'\ns=%r;print x+s%%s+x#';print x+s%s+x#
```
[Try it online!](https://tio.run/##TY1BCoMwEEX3OcUwEn4luLDLypyk6UoDuomSuJiePo0KxeV7fN7fvvu8xmcZ1ymQUAJQVJgbHlTAMFnwZw/28DGLTcOWlriTumxtdtrgJg4uNfTuX13/MUHD@Dj6rTk3l6htcnTeOqrQlh8 "Python 2 – Try It Online")
## Python 3, 70 bytes:
```
x=""#";x='"'
s='x=""#";x=\'"\'\ns=%r;print(x+s%%s+x)#';print(x+s%s+x)#
```
[Try it online!](https://tio.run/##K6gsycjPM/6fnJ@SqmCrUKSurv6/wlZJSVnJusJWXUmdq9hWHc6PUVeKUY/JK7ZVLbIuKMrMK9Go0C5WVS3WrtBUVkcSAQv8BxoVbWilaxjLlVqRmqwBskGTC6JIEyIENF9BWwFstbYCkKP5HwA "Python 3 – Try It Online")
## How does it work? :
* Without quotes: `x=""#";x='"'` will stop the execution at the coment `#` char => `x=""`
* With quotes: `"x=""#";x='"'` have just 2 string concatened `"x="` and `"#"` which don't do anything, and an assignation : `x='"'`
Now `x` is filled with the good char (quote or empty).
We use then the standard python quine : `s='s=%r;print(s%%s)';print(s%s)` adding a few extras to make it work here, for example `#` at the end to avoid an EOF Error when a `"` is added at the end of the program
Then, we just print our quine adding `x` at the start and at the end of the string
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `D`, 29 bytes
```
`Dqp^≈[_\\"pǏ]₴`Dqp^≈[_\"pǏ]₴
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=D&code=%60Dqp%5E%E2%89%88%5B_%5C%5C%22p%C7%8F%5D%E2%82%B4%60Dqp%5E%E2%89%88%5B_%5C%22p%C7%8F%5D%E2%82%B4&inputs=&header=&footer=)
Explained:
```
`...`Dqp^≈[_\"pǏ]₴
`...`                 Push half the source code
     D                Make 3 copies of the source code
      qp              Uneval the first copy (quote, escape) and prepend it to the second
        ^             Reverse the stack
         ≈[_\"pǏ]     Execute if all elements are the same.
                      Since this is not the case, it just pops the third copy of the source code
                 ₴    Print the source
```
Quoted version: ("[Try it Online!](http://lyxal.pythonanywhere.com?flags=D&code=%22%60Dqp%5E%E2%89%88%5B_%5C%5C%22p%C7%8F%5D%E2%82%B4%60Dqp%5E%E2%89%88%5B_%5C%22p%C7%8F%5D%E2%82%B4%22&inputs=&header=&footer=)")
```
"`...`Dqp^≈[_\"pǏ]₴"
"                       Push the set [0, 0]
 `...`                  Push the source code
      D                 Make 3 copies of the source code
       qp               Uneval the first copy and prepend it to the second
         ^              Reverse the stack, putting [0, 0] on the top
          ≈[     ]      Execute if all elements of the top of the stack are the same.
                        This is the case because of the [0, 0] pushed by "
            _           Remove the third copy of the source from the stack
             \"         Push `"`
               pǏ       Prepend and enclose the source with `"`
                  ₴     Print the source
                   "    Push [0, 0], having no effect because the source is already printed
```
[Answer]
# [Haskell](https://www.haskell.org/), 142 bytes
```
--"#p=p['"']>>"--\""#p
k#p=p x>>print x>>p k;main="--"#putStr;x="--\"#p=p['\"']>>\"--\\\"\"#p\nk#p=p x>>print x>>p k;main=\"--\"#putStr;x="
--
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X1dXSbnAtiBaXUk91s5OSVc3RgkowJUNElSosLMrKMrMKwEzFLKtcxMz82yVwFpKS4JLiqwrbME6ICbEgI2IAYnExCiBRGPy8JgTA9UKN4lLV/f/fwA "Haskell – Try It Online")
```
"--"#p=p['"']>>"--\""#p
k#p=p x>>print x>>p k;main="--"#putStr;x="--\"#p=p['\"']>>\"--\\\"\"#p\nk#p=p x>>print x>>p k;main=\"--\"#putStr;x="
--"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X0lXV0m5wLYgWl1JPdbODsiNUQIKcGWDBBUq7OwKijLzSsAMhWzr3MTMPFuIltKS4JIi6wpbsA6ICTFgI2JAIjExSiDRmDw85sRAtcJN4gIa/P8/AA "Haskell – Try It Online")
This uses a pretty simple detection method.
The first line is normally a comment.
```
--"#p=p['"']>>"--\""#p
```
However when a quote is added to the front
```
"--"#p=p['"']>>"--\""#p
```
It becomes the declaration of an operator `(#)`. So what this program does is defines `(#)` such that it prints the normal source for when called with `"--"#putStr`, however when the quotes appear the new definition supersedes it and prints the source with quotes.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, ~~18~~ 17 bytes
## Normal
```
`q‛:Ė+$[‛""$j,`:Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHHigJs6xJYrJFvigJtcIlwiJGosYDrEliIsIiIsIiJd)
## Quoted
```
"`q‛:Ė+$[‛""$j,`:Ė"
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiXCJgceKAmzrEliskW+KAm1wiXCIkaixgOsSWXCIiLCIiLCIiXQ==)
## Explanation :
```
# Normal
`q‛:Ė+        `   # structure for a quine  => [ <quine> ]
               :Ė # add a copy of the structure on the stack and exec it
 q                # push the quoted string on the stack => [ `<quine>` ]
  ‛:Ė+            # add ':Ė' to the string on the stack => [ `<quine>`:Ė ]
      $           # swap the two values on top of he stack => [ `<quine>`:Ė , 0 ]
       [          # pop and check if it is nul (it is) => [ `<quine>`:Ė ]
        ‛""$j,    # irrevelent here
                  # implicit output
# Quoted
"                 # listify the two elements on top of the stack => [ [0,0] ]
`q‛:Ė+        `   # structure for a quine  => [ [0,0] , <quine> ]
               :Ė # add a copy of the structure on the stack and exec it
 q                # push the quoted string on the stack => [ [0,0] , `<quine>` ]
  ‛:Ė+            # add ':Ė' to the string on the stack => [ [0,0] , `<quine>`:Ė ]
      $           # swap the two values on top of he stack => [ `<quine>`:Ė , [0,0] ]
       [          # pop and check if it is nul (it is not as it's a list) => [ `<quine>`:Ė ]
        ‛""       # add `""` to the stack => [ `<quine>`:Ė, `""` ]
           $j     # swap the two elements and join => [ "`<quine>`:Ė" ]
             ,    # print => []
                " # listify the two elements on top of the stack => [ [0,0] ]
                  # no implicit output as it has already printed via ,
```
[Answer]
# [Zsh](https://www.zsh.org/), 76 bytes
```
: "||z=\" #"
s=': "||z=\" #"
s=\47%s\47
printf $z$s$z $s
'
printf $z$s$z $s
```
[Try it online!](https://tio.run/##qyrO@P/fSkGppqbKNkZJQVmJq9hWHY0fY2KuWgwkuAqKMvNK0hRUqlSKVaoUVIq51DGF/v8HAA "Zsh – Try It Online")
["Try it online!"](https://tio.run/##qyrO@P9fyUpBqaamyjZGSUFZiavYVh2NH2NirloMJLgKijLzStIUVKpUilWqFFSKudQxhZT@/wcA "Zsh – Try It Online")
Note the trailing newline.
Without the quotes, the first line is a call to the built-in no-op `:`, which ignores its string argument `||z=" #`. The variable `z` remains empty.
With quotes, the first line is:
* `": "`: execute `:`  (note the space), which is a non-existent command
* `||`: if this fails (which it will, since `:`  doesn't exist), then:
* `z=\"`: set the variable `z` to a single double-quote `"`
* `#"`: comment; ignored
The extra `"` on the last line is unmatched, but zsh helpfully ignores that until after the program has executed because it's a separate command line.
The rest is a pretty standard shell quine, but we surround the string with `$z` so it gets double quotes if necessary.
]