Below is the Addon
code which saves text to file.
This works perfectly on *nix
systems.
The code grabs the current selected text from UI (which may contain newline
characters) and saves this string to a file.
The problem is that on Windows
, no newline
characters are preserved when text file is opened in Notepad
.
I understand \r\n
is the correct carriage return on Windows
but how can I support both Windows
and *nix
systems without having to parse/replace the user's selected string?
var {Cc,Ci,Cu,components} = require("chrome"),
ContextMenu = require("sdk/context-menu");
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile),
ostream,
string;
file.initWithPath('C:\Users\rob');
file.append('Test.txt');
try{
if (file.exists() === false) {file.create(Ci.nsIFile.NORMAL_FILE_TYPE, 420);}
ostream = FileUtils.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
string += 'First' + '\n\n';
string += 'Second' + '\n\n';
var istream = converter.convertToInputStream(string + ContextMenu.SelectionContext());
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!components.isSuccessCode(status)) {
alert('failure');
}else{
alert('success');
}
});
} catch (e) {
return false;
}
}
This is the result on Windows
:
And this is the result on Linux
: