Commits

Yuya Nishihara committed 9b5bd5b

qscilib: add option to read/write file in the specified encoding (refs #3314)

Comments (0)

Files changed (1)

tortoisehg/hgqt/qscilib.py

             return True
     return False # Use spaces for indents default
 
-def readFile(editor, filename):
+def readFile(editor, filename, encoding=None):
     f = QFile(filename)
     if not f.open(QIODevice.ReadOnly):
         qtlib.WarningMsgBox(_('Unable to read file'),
                             _('An error occurred while reading the file.'),
                             f.errorString(), parent=editor)
         return False
-    text = hglib.tounicode(data)
+    if encoding:
+        try:
+            text = data.decode(encoding)
+        except UnicodeDecodeError, inst:
+            qtlib.WarningMsgBox(_('Text Translation Failure'),
+                                _('Could not translate the file content from '
+                                  'native encoding.'),
+                                (_('Several characters would be lost.')
+                                 + '\n\n' + hglib.tounicode(str(inst))),
+                                parent=editor)
+            text = data.decode(encoding, 'replace')
+    else:
+        text = hglib.tounicode(data)
     editor.setText(text)
     editor.setDefaultEolMode()
     editor.setModified(False)
     return True
 
-def writeFile(editor, filename):
+def writeFile(editor, filename, encoding=None):
     text = editor.text()
     try:
-        data = hglib.fromunicode(text)
+        if encoding:
+            data = unicode(text).encode(encoding)
+        else:
+            data = hglib.fromunicode(text)
     except UnicodeEncodeError, inst:
         qtlib.WarningMsgBox(_('Unable to write file'),
                             _('Could not translate the file content to '