1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
|
#include "codesnippet.h"
#include "qeditor.h"
#include "qdocumentcursor.h"
#include "qdocumentline.h"
#include "filechooser.h"
#include "latexdocument.h"
#include "smallUsefulFunctions.h"
int CodeSnippetPlaceHolder::offsetEnd(){
return offset + length;
}
inline void translatePlaceholder(const QString& content, QString& curLine, CodeSnippetPlaceHolder& ph){
for (int i=0;i<content.length();i++)
if (!content[i].toAscii()){ //don't translate non ascii placeholders
curLine+=content;
ph.length+=content.length();
return;
}
QString trans = QApplication::translate("CodeSnippet_PlaceHolder", content.toAscii().constData());
curLine += trans;
ph.length = trans.length();
return;
}
void parseSnippetPlaceHolder(const QString& snippet, int& i, QString& curLine, CodeSnippetPlaceHolder& ph){
QString tmpPlaceHolderContent;
ph.offset = curLine.length();
ph.length = 0;
ph.id = -1;
ph.flags = 0;
for (;i<snippet.length(); i++){
if (snippet.at(i) == '%' && i+1<snippet.length()) {
i++;
switch (snippet.at(i).toAscii()){
case'|': ph.flags |= CodeSnippetPlaceHolder::AutoSelect; break;
case '>': translatePlaceholder(tmpPlaceHolderContent, curLine, ph); return;
case '%': tmpPlaceHolderContent+='%'; ph.length++; break;
case ':': goto secondLevelBreak;
default: tmpPlaceHolderContent+="%"; tmpPlaceHolderContent+=snippet.at(i); ph.length++;
}
} else tmpPlaceHolderContent += snippet.at(i);
}
secondLevelBreak:
translatePlaceholder(tmpPlaceHolderContent, curLine, ph);
if (i>=snippet.length()) return;
if (snippet.at(i)!=':') return;
int snippetEnd = snippet.indexOf("%>", i);
if (snippetEnd == -1) return;
QString options = snippet.mid(i+1, snippetEnd-i-1);
i = snippetEnd+1;
foreach (const QString& s, options.split(",")) {
QString t = s.trimmed();
if (t == "mirror") ph.flags|=CodeSnippetPlaceHolder::Mirror;
else if (t == "multiline") ph.flags|=CodeSnippetPlaceHolder::PreferredMultilineAutoSelect;
else if (t.startsWith("id:")) ph.id = t.remove(0,3).toInt();
else if (t.startsWith("select")) ph.flags|=CodeSnippetPlaceHolder::AutoSelect;
}
}
bool CodeSnippet::autoReplaceCommands=true;
CodeSnippet::CodeSnippet(const QString &newWord) {
QString realNewWord=newWord;
// \begin magic
if (newWord == "%<%:TEXMAKERX-GENERIC-ENVIRONMENT-TEMPLATE%>" ||
newWord == "%<%:TEXSTUDIO-GENERIC-ENVIRONMENT-TEMPLATE%>"){
realNewWord = "\\begin{%<"+QObject::tr("*environment-name*")+"%:select,id:2%>}\n"
"%<"+QObject::tr("content...")+"%:select,multiline%>\n"
"\\end{%<"+QObject::tr("*environment-name*")+"%:mirror,id:2%>}";
} else if (realNewWord.startsWith("\\begin{")&&
!realNewWord.contains("\n")&&!realNewWord.contains("%n") //only a single line
&& realNewWord.lastIndexOf("\\") == 0) //only one latex command in the line
{
int p=newWord.indexOf("{");
QString environmentName=realNewWord.mid(p,newWord.indexOf("}")-p+1); //contains the {}
QString content="%<"+QObject::tr("content...")+"%:multiline%>";
realNewWord+="\n"+content+"\n\\end"+environmentName;
}
cursorLine=-1;
cursorOffset=-1;
anchorOffset=-1;
usageCount=0;
index=0;
snippetLength=0;
QString curLine;
curLine.reserve(realNewWord.length());
word.reserve(realNewWord.length());
bool escape=false;
bool hasPlaceHolder=false, hasMirrors = false, hasAutoSelectPlaceHolder = false;
placeHolders.append(QList<CodeSnippetPlaceHolder>()); //during the creation this contains a line more than lines
CodeSnippetPlaceHolder tempPlaceholder;
bool firstLine=true;
for (int i=0; i<realNewWord.length(); i++){
QChar currentChar=realNewWord.at(i);
if (!escape) {
if (currentChar==QChar('\n')) {
lines.append(curLine);
placeHolders.append(QList<CodeSnippetPlaceHolder>());
curLine.clear();
firstLine=false;
} else if (currentChar==QChar('%')) escape=true;
else {
curLine+=currentChar;
word.append(currentChar);
if(firstLine){
switch (currentChar.toAscii()) {
case '{':
case '}':
sortWord.append('!');
break;
case '[':
sortWord.append('\\');
break;
case '*':
sortWord.append('#');
break;
default:
sortWord.append(currentChar);
}
}
}
} else {
escape=false;
switch (currentChar.toAscii()) {
case '%':
word+='%';
curLine+='%';
if(firstLine)
sortWord.append(currentChar);
break;
case '|':
cursorLine=lines.count(); //first line is 0
anchorOffset=cursorOffset;
cursorOffset=curLine.length();
break;
case '<':
i++;
parseSnippetPlaceHolder(realNewWord, i, curLine, tempPlaceholder);
hasPlaceHolder = true;
if (tempPlaceholder.flags & CodeSnippetPlaceHolder::AutoSelect) hasAutoSelectPlaceHolder = true;
if (tempPlaceholder.flags & CodeSnippetPlaceHolder::Mirror) hasMirrors = true;
placeHolders.last().append(tempPlaceholder);
// foundDescription = true;
break;
case 'n':
lines.append(curLine);
placeHolders.append(QList<CodeSnippetPlaceHolder>());
curLine.clear();
//curLine+="\n";
break;
default: // escape was not an escape character ...
curLine+='%';
curLine+=currentChar;
word.append('%');
word.append(currentChar);
if(firstLine)
sortWord.append(currentChar);
}
}
}
lines.append(curLine);
if (cursorLine == -1 && hasPlaceHolder && !hasAutoSelectPlaceHolder) //use first placeholder at new selection if nothing else is set
for (int i=0;i<placeHolders.count();i++)
if (placeHolders[i].count()>0)
placeHolders[i].first().flags |= CodeSnippetPlaceHolder::AutoSelect;
if (hasMirrors){
for (int l=0;l<placeHolders.count();l++)
for (int i=0;i<placeHolders[l].size();i++)
if (placeHolders[l][i].flags & CodeSnippetPlaceHolder::Mirror) {
for (int lm=0;lm<placeHolders.count();lm++)
for (int im=0;im<placeHolders[lm].size();im++)
if ((placeHolders[l][i].id == placeHolders[lm][im].id) &&
!(placeHolders[lm][im].flags & CodeSnippetPlaceHolder::Mirrored)){
placeHolders[lm][im].flags |= CodeSnippetPlaceHolder::Mirrored;
goto secondLevelBreak;
}
secondLevelBreak:;
}
}
if (anchorOffset==-1) anchorOffset=cursorOffset;
/*
sortWord=lines.first().toLower(); //only sort by first line which is visible in completer (otherwise \begin{frame} comes after \begin{frame}[xy])
sortWord.replace("{","!");//js: still using dirty hack, however order should be ' '{[* abcde...
sortWord.replace("}","!");// needs to be replaced as well for sorting \bgein{abc*} after \bgein{abc}
sortWord.replace("[","\"");//(first is a space->) !"# follow directly in the ascii table
sortWord.replace("*","#");
*/
}
bool CodeSnippet::operator< (const CodeSnippet &cw) const {
return cw.sortWord > sortWord;
}
bool CodeSnippet::operator== (const CodeSnippet &cw) const {
return cw.word == word;
}
void CodeSnippet::insert(QEditor* editor){
if (!editor) return;
QDocumentCursor c=editor->cursor();
insertAt(editor,&c);
}
void CodeSnippet::insertAt(QEditor* editor, QDocumentCursor* cursor, bool usePlaceholders, bool byCompleter) const{
if (lines.empty()||!editor||!cursor) return;
//find filechooser escape %( %)
QString line=lines.join("\n");
QRegExp rx("%\\((.+)%\\)");
int pos=rx.indexIn(line,0);
if(pos>-1){
FileChooser sfDlg(0,QApplication::tr("Select a File"));
sfDlg.setFilter(rx.cap(1));
LatexDocument *doc=qobject_cast<LatexDocument*>(cursor->document());
QString path=doc->parent->getCompileFileName();
path=getPathfromFilename(path);
QString directory;
if(path.isEmpty()) directory=QDir::homePath();
else directory=path;
sfDlg.setDir(directory);
if (sfDlg.exec()) {
QString fn=sfDlg.fileName();
line.replace(rx,getRelativeBaseNameToPath(fn,path));
} else return;
}
QString savedSelection;
bool alwaysSelect = false;
bool editBlockOpened = false;
if (cursor->hasSelection()) {
savedSelection=cursor->selectedText();
editBlockOpened = true;
cursor->beginEditBlock();
cursor->removeSelectedText();
}else if(!editor->cutBuffer.isEmpty()){
savedSelection=editor->cutBuffer;
editor->cutBuffer.clear();
alwaysSelect = true;
}
bool multiLineSavedSelection = savedSelection.contains("\n");
QDocumentCursor selector=*cursor;
QDocumentLine curLine=cursor->line();
// on multi line commands, replace environments only
if(autoReplaceCommands && lines.size()>1 && line.contains("\\begin{")){
QString curLine=cursor->line().text();
int wordBreak=curLine.indexOf(QRegExp("\\W"),cursor->columnNumber());
int closeCurl=curLine.indexOf("}",cursor->columnNumber());
int openCurl=curLine.indexOf("{",cursor->columnNumber());
int openBracket=curLine.indexOf("[",cursor->columnNumber());
if(closeCurl>0){
if(openBracket<0) openBracket=1e9;
if(openCurl<0) openCurl=1e9;
if(wordBreak<0) wordBreak=1e9;
if(closeCurl<openBracket && (closeCurl<=wordBreak || openCurl<=wordBreak)){
QString oldEnv;
if(closeCurl<openCurl)
oldEnv=curLine.mid(cursor->columnNumber(),closeCurl-cursor->columnNumber());
else
oldEnv=curLine.mid(openCurl+1,closeCurl-openCurl-1);
QRegExp rx("\\\\begin\\{(.+)\\}");
rx.setMinimal(true);
rx.indexIn(line);
QString newEnv=rx.cap(1);
// remove curly brakets as well
QDocument* doc=cursor->document();
QString searchWord="\\end{"+oldEnv+"}";
QString inhibitor="\\begin{"+oldEnv+"}";
bool backward=false;
int step=1;
int startLine=cursor->lineNumber();
//int startCol=cursor.columnNumber();
int endLine=doc->findLineContaining(searchWord,startLine+step,Qt::CaseSensitive,backward);
int inhibitLine=doc->findLineContaining(inhibitor,startLine+step,Qt::CaseSensitive,backward); // not perfect (same line end/start ...)
while (inhibitLine>0 && endLine>0 && inhibitLine*step<endLine*step) {
endLine=doc->findLineContaining(searchWord,endLine+step,Qt::CaseSensitive,backward); // not perfect (same line end/start ...)
inhibitLine=doc->findLineContaining(inhibitor,inhibitLine+step,Qt::CaseSensitive,backward);
}
QString endText=doc->line(endLine).text();
int start=endText.indexOf(searchWord);
int offset=searchWord.indexOf("{");
int length=searchWord.length()-offset-1;
selector.moveTo(endLine,start+1+offset);
selector.movePosition(length-1,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
selector.replaceSelectedText(newEnv);
cursor->movePosition(closeCurl-cursor->columnNumber()+1,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
QString first=lines.first();
int pos=first.indexOf('{');
pos=first.indexOf('{',pos+1); //pos of second {
if(pos>-1)
first.remove(pos,first.length()-pos);
editor->insertText(*cursor,first);
if (editBlockOpened) cursor->endEditBlock();
return;
}
}
}
int baseLine=cursor->lineNumber();
int baseLineIndent = cursor->columnNumber(); //text before inserted word moves placeholders to the right
int lastLineRemainingLength = curLine.text().length()-baseLineIndent; //last line will has length: indentation + codesnippet + lastLineRemainingLength
editor->insertText(*cursor,line); //don't use cursor->insertText to keep autoindentation working
if (editBlockOpened) cursor->endEditBlock();
// on single line commands only: replace command
if(byCompleter && autoReplaceCommands && lines.size()==1 && line.startsWith('\\')){
if(cursor->nextChar().isLetterOrNumber()||cursor->nextChar()==QChar('{')){
QString curLine=cursor->line().text();
int wordBreak=curLine.indexOf(QRegExp("\\W"),cursor->columnNumber());
int closeCurl=curLine.indexOf("}",cursor->columnNumber());
int openCurl=curLine.indexOf("{",cursor->columnNumber());
int openBracket=curLine.indexOf("[",cursor->columnNumber());
if(!line.contains("{")){
if(openBracket<0) openBracket=1e9;
if(closeCurl<0) closeCurl=1e9;
if(openCurl<0) openCurl=1e9;
if(wordBreak<openBracket && wordBreak<closeCurl &&wordBreak<openCurl){
if(wordBreak<0)
cursor->movePosition(wordBreak-cursor->columnNumber(),QDocumentCursor::EndOfLine,QDocumentCursor::KeepAnchor);
else
cursor->movePosition(wordBreak-cursor->columnNumber(),QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
cursor->removeSelectedText();
return;
}
}else{
if(openCurl>-1){
if(openBracket<0) openBracket=1e9;
if(closeCurl<0) closeCurl=1e9;
if(openCurl<openBracket && openCurl<closeCurl &&openCurl<=wordBreak){
cursor->movePosition(openCurl-cursor->columnNumber(),QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
cursor->removeSelectedText();
int curl=line.length()-line.indexOf("{");
cursor->movePosition(curl,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
cursor->removeSelectedText();
return;
}
}
}
}
}
Q_ASSERT(placeHolders.size()==lines.count());
if (usePlaceholders) {
//check if there actually are placeholders to insert
usePlaceholders=false;
for (int l=0;l< lines.count();l++)
usePlaceholders|=placeHolders[l].size();
}
int autoSelectPlaceholder = -1;
if (usePlaceholders) {
if (editor->currentPlaceHolder()!=-1 &&
editor->getPlaceHolder(editor->currentPlaceHolder()).cursor.isWithinSelection(*cursor))
editor->removePlaceHolder(editor->currentPlaceHolder()); //remove currentplaceholder to prevent nesting
for (int l=0;l< lines.count();l++){
//if (l<mLines.count()-1) cursor->insertLine();
for (int i=0; i<placeHolders[l].size(); i++) {
if (placeHolders[l][i].flags & CodeSnippetPlaceHolder::Mirror) continue;
PlaceHolder ph;
ph.length=placeHolders[l][i].length;
ph.cursor = getCursor(editor, placeHolders[l][i], l, baseLine, baseLineIndent, lastLineRemainingLength);
if (!ph.cursor.isValid()) continue;
editor->addPlaceHolder(ph);
if (placeHolders[l][i].flags & CodeSnippetPlaceHolder::Mirrored) {
int phId = editor->placeHolderCount()-1;
for (int lm=0; lm<placeHolders.size(); lm++)
for (int im=0; im < placeHolders[lm].size(); im++)
if (placeHolders[lm][im].flags & CodeSnippetPlaceHolder::Mirror &&
placeHolders[lm][im].id == placeHolders[l][i].id)
editor->addPlaceHolderMirror(phId, getCursor(editor, placeHolders[lm][im], lm, baseLine, baseLineIndent, lastLineRemainingLength));
}
if ((placeHolders[l][i].flags & CodeSnippetPlaceHolder::AutoSelect) &&
((autoSelectPlaceholder == -1) ||
(multiLineSavedSelection && (placeHolders[l][i].flags & CodeSnippetPlaceHolder::PreferredMultilineAutoSelect))))
autoSelectPlaceholder = editor->placeHolderCount()-1;
}
}
}
//place cursor/add \end
if (cursorOffset!=-1) {
int realAnchorOffset=anchorOffset; //will be moved to the right if text is already inserted on this line
if (cursorLine>0) {
if (cursorLine>=lines.size()) return;
if (!selector.movePosition(cursorLine,QDocumentCursor::Down,QDocumentCursor::MoveAnchor))
return;
//if (editor->flag(QEditor::AutoIndent))
realAnchorOffset += selector.line().length()-lines[cursorLine].length();
if (cursorLine + 1 == lines.size())
realAnchorOffset-=lastLineRemainingLength;
} else realAnchorOffset += baseLineIndent;
selector.setColumnNumber(realAnchorOffset);
bool ok=true;
if (cursorOffset>anchorOffset)
ok=selector.movePosition(cursorOffset-anchorOffset,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
else if (cursorOffset<anchorOffset)
ok=selector.movePosition(anchorOffset-cursorOffset,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
if (!ok) return;
editor->setCursor(selector);
} else if (autoSelectPlaceholder!=-1) editor->setPlaceHolder(autoSelectPlaceholder, true); //this moves the cursor to that placeholder
else {
editor->setCursor(*cursor); //place after insertion
return;
}
if (!savedSelection.isEmpty()) {
QDocumentCursor oldCursor = editor->cursor();
editor->cursor().insertText(savedSelection,true);
if (!editor->cursor().hasSelection() && alwaysSelect) {
oldCursor.movePosition(savedSelection.length(), QDocumentCursor::Right, QDocumentCursor::KeepAnchor);
editor->setCursor(oldCursor);
}
if (autoSelectPlaceholder!=-1) editor->setPlaceHolder(autoSelectPlaceholder, true); //this synchronizes the placeholder mirrors with the current placeholder text
}
}
void CodeSnippet::setName(const QString& newName){
name=newName;
}
QString CodeSnippet::getName(){
return name;
}
QDocumentCursor CodeSnippet::getCursor(QEditor * editor, const CodeSnippetPlaceHolder &ph, int snippetLine, int baseLine, int baseLineIndent, int lastLineRemainingLength) const{
QDocumentCursor cursor=editor->document()->cursor(baseLine+snippetLine, ph.offset);
if (snippetLine==0) cursor.movePosition(baseLineIndent,QDocumentCursor::NextCharacter);
else {
cursor.movePosition(cursor.line().length()-lines[snippetLine].length(),QDocumentCursor::NextCharacter);
if (snippetLine+1==lines.size())
cursor.movePosition(lastLineRemainingLength,QDocumentCursor::PreviousCharacter);
}
return cursor;
}
|