Kate
python_encoding.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026 #ifndef KTEXTEDITOR_PYTHON_ENCODING
00027 #define KTEXTEDITOR_PYTHON_ENCODING
00028
00029 #include <ktexteditor/loadsavefiltercheckplugin.h>
00030 #include <ktexteditor/view.h>
00031 #include <kmessagebox.h>
00032 #include <klocale.h>
00033 #include <QList>
00034 #include <QVariant>
00035
00036 class KTextEditorPythonEncodingCheck: public KTextEditor::LoadSaveFilterCheckPlugin {
00037 Q_OBJECT
00038 public:
00039 KTextEditorPythonEncodingCheck(QObject *parent, QList<QVariant>):KTextEditor::LoadSaveFilterCheckPlugin(parent){interpreterLine=QRegExp(QString("#!.*$"));}
00040 virtual ~KTextEditorPythonEncodingCheck(){}
00041 virtual bool postSaveFilterCheck(KTextEditor::Document *document,bool saveas) {return true;}
00042 virtual bool preSavePostDialogFilterCheck(KTextEditor::Document *document)
00043 {
00044 kDebug(13020)<<"KTextEditorPythonEncodingCheck::preSavePostDialogCheck";
00045
00046 QString codec=document->encoding().toLower();
00047 codec.replace(' ','-');
00048
00049 bool firstIsInterpreter=false;
00050 QRegExp encoding_regex(QString("#\\s*-\\*\\-\\s*coding[:=]\\s*%1\\s*-\\*-\\s*$").arg(codec));
00051 bool correctencoding=false;
00052 if (document->lines()>0)
00053 {
00054 if (encoding_regex.exactMatch(document->line(0))) correctencoding=true;
00055 else if (document->lines()>1) {
00056 if (interpreterLine.exactMatch(document->line(0)))
00057 {
00058 firstIsInterpreter=true;
00059 if (encoding_regex.exactMatch(document->line(1))) correctencoding=true;
00060 }
00061 }
00062 }
00063 if (!correctencoding) {
00064 QString addLine(QString("# -*- coding: %1 -*-").arg(codec));
00065 int what=KMessageBox::warningYesNoCancel (document->activeView()
00066 , i18n ("You are trying to save a python file as non ASCII, without specifiying a correct source encoding line for encoding \"%1\"", codec)
00067 , i18n ("No encoding header")
00068 , KGuiItem(i18n("Insert: %1",addLine))
00069 , KGuiItem(i18n("Save Nevertheless"))
00070 , KStandardGuiItem::cancel(), "OnSave-WrongPythonEncodingHeader");
00071 switch (what) {
00072 case KMessageBox::Yes:
00073 {
00074 int line=firstIsInterpreter?1:0;
00075 QRegExp checkReplace_regex(QString("#\\s*-\\*\\-\\s*coding[:=]\\s*[-\\w]+\\s*-\\*-\\s*$"));
00076 if (checkReplace_regex.exactMatch(document->line(line)))
00077 document->removeLine(line);
00078 document->insertLine(line,addLine);
00079 break;
00080 }
00081 case KMessageBox::No:
00082 return true;
00083 break;
00084 default:
00085 return false;
00086 break;
00087 }
00088 }
00089 return true;
00090 }
00091 virtual void postLoadFilter(KTextEditor::Document*){ }
00092 private:
00093 QRegExp interpreterLine;
00094 };
00095
00096 #endif
00097
00098