]> git.lyx.org Git - lyx.git/blob - src/BufferView2.C
Better handling of unknown tokens
[lyx.git] / src / BufferView2.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *        
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <fstream>
12 #include <algorithm>
13
14 #include <config.h>
15
16 #include "BufferView.h"
17 #include "buffer.h"
18 #include "lyxcursor.h"
19 #include "lyxtext.h"
20 #include "insets/inseterror.h"
21 #include "LyXView.h"
22 #include "bufferlist.h"
23 #include "support/FileInfo.h"
24 #include "lyxscreen.h"
25 #include "support/filetools.h"
26 #include "lyx_gui_misc.h"
27 #include "LaTeX.h"
28 #include "BufferView_pimpl.h"
29 #include "insets/insetcommand.h" //ChangeRefs
30 #include "support/lyxfunctional.h" //equal_1st_in_pair
31 #include "language.h"
32 #include "gettext.h"
33 #include "undo_funcs.h"
34 #include "debug.h"
35 #include "iterators.h"
36
37 extern BufferList bufferlist;
38
39 using std::pair;
40 using std::endl;
41 using std::ifstream;
42 using std::vector;
43 using std::find;
44 using std::count;
45 using std::count_if;
46
47
48 // Inserts a file into current document
49 bool BufferView::insertLyXFile(string const & filen)
50         //
51         // Copyright CHT Software Service GmbH
52         // Uwe C. Schroeder
53         //
54         // Insert a Lyxformat - file into current buffer
55         //
56         // Moved from lyx_cb.C (Lgb)
57 {
58         if (filen.empty()) return false;
59
60         string const fname = MakeAbsPath(filen);
61
62         // check if file exist
63         FileInfo const fi(fname);
64
65         if (!fi.readable()) {
66                 WriteAlert(_("Error!"),
67                            _("Specified file is unreadable: "),
68                            MakeDisplayPath(fname, 50));
69                 return false;
70         }
71         
72         beforeChange(text);
73
74         ifstream ifs(fname.c_str());
75         if (!ifs) {
76                 WriteAlert(_("Error!"),
77                            _("Cannot open specified file: "),
78                            MakeDisplayPath(fname, 50));
79                 return false;
80         }
81         
82         int const c = ifs.peek();
83        
84         LyXLex lex(0, 0);
85         lex.setStream(ifs);
86
87         bool res = true;
88
89         if (c == '#') {
90                 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
91                 res = buffer()->readFile(lex, text->cursor.par());
92         } else {
93                 lyxerr[Debug::INFO] << "Will insert file without header" 
94                                     << endl;
95                 res = buffer()->readLyXformat2(lex, text->cursor.par());
96         }
97
98         resize();
99         return res;
100 }
101
102
103 bool BufferView::removeAutoInsets()
104 {
105         Paragraph * par = buffer()->paragraph;
106
107         LyXCursor tmpcursor = text->cursor;
108         LyXCursor cursor;
109
110         bool a = false;
111
112         while (par) {
113                 // this has to be done before the delete
114                 text->setCursor(this, cursor, par, 0);
115                 if (par->autoDeleteInsets()){
116                         a = true;
117                         text->redoParagraphs(this, cursor,
118                                              cursor.par()->next());
119                         text->fullRebreak(this);
120                 }
121                 par = par->next();
122         }
123
124         // avoid forbidden cursor positions caused by error removing
125         if (tmpcursor.pos() > tmpcursor.par()->size())
126                 tmpcursor.pos(tmpcursor.par()->size());
127
128         text->setCursorIntern(this, tmpcursor.par(), tmpcursor.pos());
129
130         return a;
131 }
132
133
134 void BufferView::insertErrors(TeXErrors & terr)
135 {
136         // Save the cursor position
137         LyXCursor cursor = text->cursor;
138
139         for (TeXErrors::Errors::const_iterator cit = terr.begin();
140              cit != terr.end();
141              ++cit) {
142                 string const desctext(cit->error_desc);
143                 string const errortext(cit->error_text);
144                 string const msgtxt = desctext + '\n' + errortext;
145                 int const errorrow = cit->error_in_line;
146
147                 // Insert error string for row number
148                 int tmpid = -1; 
149                 int tmppos = -1;
150
151                 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
152                         buffer()->texrow.increasePos(tmpid, tmppos);
153                 }
154                 
155                 Paragraph * texrowpar = 0;
156
157                 if (tmpid == -1) {
158                         texrowpar = text->firstParagraph();
159                         tmppos = 0;
160                 } else {
161                         texrowpar = buffer()->getParFromID(tmpid);
162                 }
163
164                 if (texrowpar == 0)
165                         continue;
166
167                 InsetError * new_inset = new InsetError(msgtxt);
168                 text->setCursorIntern(this, texrowpar, tmppos);
169                 text->insertInset(this, new_inset);
170                 text->fullRebreak(this);
171         }
172         // Restore the cursor position
173         text->setCursorIntern(this, cursor.par(), cursor.pos());
174 }
175
176
177 void BufferView::setCursorFromRow(int row)
178 {
179         int tmpid = -1; 
180         int tmppos = -1;
181
182         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
183
184         Paragraph * texrowpar;
185
186         if (tmpid == -1) {
187                 texrowpar = text->firstParagraph();
188                 tmppos = 0;
189         } else {
190                 texrowpar = buffer()->getParFromID(tmpid);
191         }
192         text->setCursor(this, texrowpar, tmppos);
193 }
194
195
196 bool BufferView::insertInset(Inset * inset, string const & lout)
197 {
198         return pimpl_->insertInset(inset, lout);
199 }
200
201
202 /* This is also a buffer property (ale) */
203 // Not so sure about that. a goto Label function can not be buffer local, just
204 // think how this will work in a multiwindo/buffer environment, all the
205 // cursors in all the views showing this buffer will move. (Lgb)
206 // OK, then no cursor action should be allowed in buffer. (ale)
207 bool BufferView::gotoLabel(string const & label)
208
209 {
210         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
211              it != buffer()->inset_iterator_end(); ++it) {
212                 vector<string> labels = (*it)->getLabelList();
213                 if (find(labels.begin(),labels.end(),label)
214                      != labels.end()) {
215                         beforeChange(text);
216                         text->setCursor(this, it.getPar(), it.getPos());
217                         text->selection.cursor = text->cursor;
218                         update(text, BufferView::SELECT|BufferView::FITCUR);
219                         return true;
220                 }
221         }
222         return false;
223 }
224
225
226 void BufferView::menuUndo()
227 {
228         if (available()) {
229                 owner()->message(_("Undo"));
230                 hideCursor();
231                 beforeChange(text);
232                 update(text, BufferView::SELECT|BufferView::FITCUR);
233                 if (!textUndo(this))
234                         owner()->message(_("No further undo information"));
235                 else
236                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
237                 setState();
238         }
239 }
240
241
242 void BufferView::menuRedo()
243 {
244         if (theLockingInset()) {
245                 owner()->message(_("Redo not yet supported in math mode"));
246                 return;
247         }    
248    
249         if (available()) {
250                 owner()->message(_("Redo"));
251                 hideCursor();
252                 beforeChange(text);
253                 update(text, BufferView::SELECT|BufferView::FITCUR);
254                 if (!textRedo(this))
255                         owner()->message(_("No further redo information"));
256                 else
257                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
258                 setState();
259         }
260 }
261
262
263 void BufferView::copyEnvironment()
264 {
265         if (available()) {
266                 text->copyEnvironmentType();
267                 // clear the selection, even if mark_set
268                 toggleSelection();
269                 text->clearSelection();
270                 update(text, BufferView::SELECT|BufferView::FITCUR);
271                 owner()->message(_("Paragraph environment type copied"));
272         }
273 }
274
275
276 void BufferView::pasteEnvironment()
277 {
278         if (available()) {
279                 text->pasteEnvironmentType(this);
280                 owner()->message(_("Paragraph environment type set"));
281                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
282         }
283 }
284
285
286 void BufferView::copy()
287 {
288         if (available()) {
289                 text->copySelection(this);
290 #if 0
291                 // clear the selection, even if mark_set
292                 toggleSelection();
293                 text->clearSelection();
294                 update(text, BufferView::SELECT|BufferView::FITCUR);
295 #endif
296                 owner()->message(_("Copy"));
297         }
298 }
299
300
301 void BufferView::cut(bool realcut)
302 {
303         if (available()) {
304                 hideCursor();
305                 update(text, BufferView::SELECT|BufferView::FITCUR);
306                 text->cutSelection(this, true, realcut);
307                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
308                 owner()->message(_("Cut"));
309         }
310 }
311
312
313 void BufferView::paste()
314 {
315         if (!available()) return;
316
317         owner()->message(_("Paste"));
318
319         hideCursor();
320         // clear the selection
321         toggleSelection();
322         text->clearSelection();
323         update(text, BufferView::SELECT|BufferView::FITCUR);
324         
325         // paste
326         text->pasteSelection(this);
327         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
328         
329         // clear the selection 
330         toggleSelection();
331         text->clearSelection();
332         update(text, BufferView::SELECT|BufferView::FITCUR);
333 }
334
335
336 /* these functions are for the spellchecker */ 
337 string const BufferView::nextWord(float & value)
338 {
339         if (!available()) {
340                 value = 1;
341                 return string();
342         }
343
344         return text->selectNextWordToSpellcheck(this, value);
345 }
346
347   
348 void BufferView::selectLastWord()
349 {
350         if (!available()) return;
351    
352         LyXCursor cur = text->selection.cursor;
353         hideCursor();
354         beforeChange(text);
355         text->selection.cursor = cur;
356         text->selectSelectedWord(this);
357         toggleSelection(false);
358         update(text, BufferView::SELECT|BufferView::FITCUR);
359 }
360
361
362 void BufferView::endOfSpellCheck()
363 {
364         if (!available()) return;
365    
366         hideCursor();
367         beforeChange(text);
368         text->selectSelectedWord(this);
369         text->clearSelection();
370         update(text, BufferView::SELECT|BufferView::FITCUR);
371 }
372
373
374 void BufferView::replaceWord(string const & replacestring)
375 {
376         if (!available()) return;
377
378         LyXText * tt = getLyXText();
379         hideCursor();
380         update(tt, BufferView::SELECT|BufferView::FITCUR);
381    
382         /* clear the selection (if there is any) */ 
383         toggleSelection(false);
384         update(tt, BufferView::SELECT|BufferView::FITCUR);
385    
386         /* clear the selection (if there is any) */ 
387         toggleSelection(false);
388         tt->replaceSelectionWithString(this, replacestring);
389    
390         tt->setSelectionOverString(this, replacestring);
391
392         // Go back so that replacement string is also spellchecked
393         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
394                 tt->cursorLeft(this);
395         }
396         update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
397 }
398 // End of spellchecker stuff
399
400
401 bool BufferView::lockInset(UpdatableInset * inset)
402 {
403         if (!theLockingInset() && inset) {
404                 theLockingInset(inset);
405                 return true;
406         } else if (inset) {
407             return theLockingInset()->lockInsetInInset(this, inset);
408         }
409         return false;
410 }
411
412
413 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
414 {
415         if (available() && theLockingInset()) {
416                 LyXCursor cursor = text->cursor;
417                 Inset * locking_inset = theLockingInset()->getLockingInset();
418
419                 if ((cursor.pos() - 1 >= 0) &&
420                     cursor.par()->isInset(cursor.pos() - 1) &&
421                     (cursor.par()->getInset(cursor.pos() - 1) ==
422                      locking_inset))
423                         text->setCursor(this, cursor,
424                                         cursor.par(), cursor.pos() - 1);
425                 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
426                 LyXText * txt = getLyXText();
427                 if (locking_inset->isTextInset() &&
428                     locking_inset->lyxCode() != Inset::ERT_CODE &&
429                     (txt->real_current_font.language() !=
430                      buffer()->params.language
431                      || txt->real_current_font.isVisibleRightToLeft()
432                      != buffer()->params.language->RightToLeft()))
433                         shape = (txt->real_current_font.isVisibleRightToLeft())
434                                 ? LyXScreen::REVERSED_L_SHAPE
435                                 : LyXScreen::L_SHAPE;
436                 y += cursor.y() + theLockingInset()->insetInInsetY();
437                 pimpl_->screen_->showManualCursor(text, x, y, asc, desc,
438                                                   shape);
439         }
440 }
441
442
443 void BufferView::hideLockedInsetCursor()
444 {
445         if (theLockingInset() && available()) {
446                 pimpl_->screen_->hideCursor();
447         }
448 }
449
450
451 void BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
452 {
453         if (theLockingInset() && available()) {
454                 y += text->cursor.y() + theLockingInset()->insetInInsetY();
455                 if (pimpl_->screen_->fitManualCursor(text, this, x, y, asc, desc))
456                         updateScrollbar();
457         }
458 }
459
460
461 int BufferView::unlockInset(UpdatableInset * inset)
462 {
463         if (inset && theLockingInset() == inset) {
464                 inset->insetUnlock(this);
465                 theLockingInset(0);
466                 finishUndo();
467                 return 0;
468         } else if (inset && theLockingInset() &&
469                    theLockingInset()->unlockInsetInInset(this, inset)) {
470                 finishUndo();
471                 return 0;
472         }
473         return bufferlist.unlockInset(inset);
474 }
475
476
477 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
478 {
479         if (!theLockingInset())
480                 return; // shouldn't happen
481         if (kind == Undo::EDIT) // in this case insets would not be stored!
482                 kind = Undo::FINISH;
483         setUndo(this, kind,
484                 text->cursor.par(),
485                 text->cursor.par()->next());
486 }
487
488
489 void BufferView::updateInset(Inset * inset, bool mark_dirty)
490 {
491         pimpl_->updateInset(inset, mark_dirty);
492 }
493
494
495 bool BufferView::ChangeInsets(Inset::Code code,
496                               string const & from, string const & to)
497 {
498         bool flag = false;
499         LyXCursor cursor = text->cursor;
500         LyXCursor tmpcursor = cursor;
501         cursor.par(tmpcursor.par());
502         cursor.pos(tmpcursor.pos());
503
504         ParIterator end = buffer()->par_iterator_end();
505         for (ParIterator it = buffer()->par_iterator_begin();
506              it != end; ++it) {
507                 Paragraph * par = *it;
508                 bool flag2 = false;
509                 for (Paragraph::inset_iterator it2 = par->inset_iterator_begin();
510                      it2 != par->inset_iterator_end(); ++it2) {
511                         if ((*it2)->lyxCode() == code) {
512                                 InsetCommand * inset = static_cast<InsetCommand *>(*it2);
513                                 if (inset->getContents() == from) {
514                                         inset->setContents(to);
515                                         flag2 = true;
516                                 }
517                         }
518                 }
519                 if (flag2) {
520                         flag = true;
521 #warning Fix me
522                         // The test it.size()==1 was needed to prevent crashes.
523                         // How to set the cursor corretly when it.size()>1 ??
524                         if (it.size() == 1) {
525                                 text->setCursorIntern(this, par, 0);
526                                 text->redoParagraphs(this, text->cursor,
527                                                      text->cursor.par()->next());
528                                 text->fullRebreak(this);
529                         }
530                 }
531         }
532         text->setCursorIntern(this, cursor.par(), cursor.pos());
533         return flag;
534 }
535
536
537 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
538 {
539         // Check if the label 'from' appears more than once
540         vector<string> labels = buffer()->getLabelList();
541         if (count(labels.begin(), labels.end(), from) > 1)
542                 return false;
543
544         return ChangeInsets(Inset::REF_CODE, from, to);
545 }
546
547
548 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
549 {
550
551         vector<pair<string,string> > keys = buffer()->getBibkeyList();  
552         if (count_if(keys.begin(), keys.end(), 
553                      lyx::equal_1st_in_pair<string,string>(from)) 
554             > 1)
555                 return false;
556
557         return ChangeInsets(Inset::CITE_CODE, from, to);
558 }
559
560
561 UpdatableInset * BufferView::theLockingInset() const
562 {
563         // If NULL is not allowed we should put an Assert here. (Lgb)
564         if (text)
565                 return text->the_locking_inset;
566         return 0;
567 }
568
569
570 void BufferView::theLockingInset(UpdatableInset * inset)
571 {
572         text->the_locking_inset = inset;
573 }
574
575
576 LyXText * BufferView::getLyXText() const
577 {
578         if (theLockingInset()) {
579                 LyXText * txt = theLockingInset()->getLyXText(this, true);
580                 if (txt)
581                         return txt;
582         }
583         return text;
584 }
585
586
587 LyXText * BufferView::getParentText(Inset * inset) const
588 {
589         if (inset->owner()) {
590                 LyXText * txt = inset->getLyXText(this);
591                 inset = inset->owner();
592                 while (inset && inset->getLyXText(this) == txt)
593                         inset = inset->owner();
594                 if (inset)
595                         return inset->getLyXText(this);
596         }
597         return text;
598 }
599
600
601 Language const * BufferView::getParentLanguage(Inset * inset) const
602 {
603         LyXText * text = getParentText(inset);
604         return text->cursor.par()->getFontSettings(buffer()->params,
605                                                    text->cursor.pos()).language();
606 }