Skip to main content
3 of 3
added 8 characters in body
Ben Izd
  • 9.5k
  • 1
  • 15
  • 47

To test your case I'd done the following in Windows 10 with Mathematica 12.3:

Use Python to generate 3 files, each with a different form (\n, \r and \r\n):

with open('file1.txt','w',newline='') as f:
    f.write('sample\n')

with open('file2.txt','w',newline='') as f:
    f.write('sample\r')

with open('file3.txt','w',newline='') as f:
    f.write('sample\r\n')

I used Windows notepad and Notepad++, which both copied the exact same content that was written.

Also in Mathematica, if we read those file using ReadString, we'll see the original content:

ReadString["file1.txt"] // FullForm
(*Out: "sample\n" *)

ReadString["file2.txt"] // FullForm
(*Out: "sample\r" *)

ReadString["file3.txt"] // FullForm
(*Out: "sample\r\n" *)

After pasting in Mathematica, all forms (\n, \r and \r\n) becomes \n:

(* copied from file1.txt content*)
file1 = "sample
";

(* copied from file2.txt content*)
file2 = "sample
";

(* copied from file3.txt content*)
file3 = "sample
";


FullForm[file1]
(*Out: "sample\n" *)

FullForm[file2]
(*Out: "sample\n" *)

FullForm[file3]
(*Out: "sample\n" *)


file1 == file2 == file3
(*Out: True *)

Solution

We can change the paste function in the menu bar to insert the raw format like sample\r instead of sample with a new line. If you're on Windows, open MenuSetup.tr in the Mathematica_Directory\12.3\SystemFiles\FrontEnd\TextResources\Windows.

If you're using other languages in Mathematica, go into the language folder for example for Spanish the file exists in Mathematica_Directory\12.3\SystemFiles\FrontEnd\TextResources\Spanish\Windows

If you're a Mac user, we face some problems in this post. If you find a workaround, please comment it, so all of us could enjoy it.

In the file, search for paste to reach this line (Windows and Mac seem to have little difference):

MenuItem["&Paste", FrontEnd`Paste[Automatic], MenuKey["v", Modifiers->{"Control"}]],

Add this code which was inspired by @kglr post after the above line to have two methods of pasting in Mathematica:

MenuItem["Paste 2", KernelExecute[NotebookApply[InputNotebook[],StringReplace[StringTake[RunProcess[{"powershell", "(get-clipboard -raw) -replace '\\r','\\r' -replace '\\n','\\n' -replace '\\t','\\t'"}, "StandardOutput"], {1, -3}], {RegularExpression["(?<!\\\\)\n"] -> "\\n", RegularExpression["(?<!\\\\)\r"] -> "\\r", RegularExpression["(?<!\\\\)\t"] -> "\\t"}]]],MenuEvaluator -> Automatic],

Save the file, restart the Mathematica and use the new Paste 2:

enter image description here

Because Paste 2 runs a PowerShell code to get the clipboard content, it's a little bit slow.

Ben Izd
  • 9.5k
  • 1
  • 15
  • 47