]> git.lyx.org Git - lyx.git/blob - src/BufferView2.C
bug 183
[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 <config.h>
12
13 #include "BufferView.h"
14 #include "buffer.h"
15 #include "lyxcursor.h"
16 #include "lyxtext.h"
17 #include "LyXView.h"
18 #include "bufferlist.h"
19 #include "lyxscreen.h"
20 #include "LaTeX.h"
21 #include "BufferView_pimpl.h"
22 #include "language.h"
23 #include "gettext.h"
24 #include "undo_funcs.h"
25 #include "debug.h"
26 #include "iterators.h"
27
28 #include "frontends/Alert.h"
29
30 #include "insets/insetcommand.h" //ChangeRefs
31 #include "insets/inseterror.h"
32
33 #include "support/FileInfo.h"
34 #include "support/filetools.h"
35 #include "support/lyxfunctional.h" //equal_1st_in_pair
36 #include "support/types.h"
37
38 #include <fstream>
39 #include <algorithm>
40
41 extern BufferList bufferlist;
42
43 using lyx::pos_type;
44
45 using std::pair;
46 using std::endl;
47 using std::ifstream;
48 using std::vector;
49 using std::find;
50 using std::count;
51 using std::count_if;
52
53
54 // Inserts a file into current document
55 bool BufferView::insertLyXFile(string const & filen)
56         //
57         // Copyright CHT Software Service GmbH
58         // Uwe C. Schroeder
59         //
60         // Insert a Lyxformat - file into current buffer
61         //
62         // Moved from lyx_cb.C (Lgb)
63 {
64         if (filen.empty()) return false;
65
66         string const fname = MakeAbsPath(filen);
67
68         // check if file exist
69         FileInfo const fi(fname);
70
71         if (!fi.readable()) {
72                 Alert::alert(_("Error!"),
73                            _("Specified file is unreadable: "),
74                            MakeDisplayPath(fname, 50));
75                 return false;
76         }
77         
78         beforeChange(text);
79
80         ifstream ifs(fname.c_str());
81         if (!ifs) {
82                 Alert::alert(_("Error!"),
83                            _("Cannot open specified file: "),
84                            MakeDisplayPath(fname, 50));
85                 return false;
86         }
87         
88         int const c = ifs.peek();
89        
90         LyXLex lex(0, 0);
91         lex.setStream(ifs);
92
93         bool res = true;
94
95         if (c == '#') {
96                 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
97                 res = buffer()->readFile(lex, text->cursor.par());
98         } else {
99                 lyxerr[Debug::INFO] << "Will insert file without header" 
100                                     << endl;
101                 res = buffer()->readLyXformat2(lex, text->cursor.par());
102         }
103
104         resize();
105         return res;
106 }
107
108
109 bool BufferView::removeAutoInsets()
110 {
111         LyXCursor tmpcursor = text->cursor;
112         Paragraph * cur_par = tmpcursor.par();
113         Paragraph * cur_par_prev = cur_par ? cur_par->previous() : 0;
114         Paragraph * cur_par_next = cur_par ? cur_par->next() : 0;
115         pos_type cur_pos = tmpcursor.pos();
116
117         bool found = false;
118
119         // Trap the deletion of the paragraph the cursor is in.
120         // Iterate until we find a paragraph that won't be immediately deleted.
121         // In reality this should mean we only execute the body of the while
122         // loop once at most.  However for safety we iterate rather than just
123         // make this an if() conditional.
124         while ((cur_par_prev || cur_par_next)
125                && text->setCursor(this,
126                                   cur_par_prev ? cur_par_prev : cur_par_next,
127                                   0)) {
128                 // We just removed cur_par so have to fix the "cursor"
129                 if (cur_par_prev) {
130                         // '.' = cur_par
131                         //  a -> a.
132                         // .
133                         cur_par = cur_par_prev;
134                         cur_pos = cur_par->size();
135                 } else {
136                         // .  -> .a
137                         //  a
138                         cur_par = cur_par_next;
139                         cur_pos = 0;
140                 }
141                 cur_par_prev = cur_par->previous();
142                 cur_par_next = cur_par->next();
143         }
144
145         ParIterator it = buffer()->par_iterator_begin();
146         ParIterator end = buffer()->par_iterator_end();
147         for (; it != end; ++it) {
148                 Paragraph * par = *it;
149                 Paragraph * par_prev = par ? par->previous() : 0;
150                 bool removed = false;
151
152                 if (text->setCursor(this, par, 0)
153                     && cur_par == par_prev) {
154                         // The previous setCursor line was deleted and that
155                         // was the cur_par line.  This can only happen if an
156                         // error box was the sole item on cur_par.
157                         if (cur_par_prev) {
158                                 // '|' = par, '.' = cur_par, 'E' = error box
159                                 // First step below may occur before while{}
160                                 //  a    |a      a     a     a.
161                                 //  E -> .E -> |.E -> .  -> |b
162                                 // .      b      b    |b
163                                 //  b
164                                 cur_par = cur_par_prev;
165                                 cur_pos = cur_par_prev->size();
166                                 cur_par_prev = cur_par->previous();
167                                 // cur_par_next remains the same 
168                         } else if (cur_par_next) {
169                                 // First step below may occur before while{}
170                                 // .
171                                 //  E -> |.E -> |.  -> . -> .|a
172                                 //  a      a      a    |a
173                                 cur_par = cur_par_next;
174                                 cur_pos = 0;
175                                 // cur_par_prev remains unset
176                                 cur_par_next = cur_par->next();
177                         } else {
178                                 // I can't find a way to trigger this
179                                 // so it should be unreachable code
180                                 // unless the buffer is corrupted.
181                                 lyxerr << "BufferView::removeAutoInsets() is bad\n";
182                         }
183                 }
184
185                 Paragraph::inset_iterator pit = par->inset_iterator_begin();
186                 Paragraph::inset_iterator pend = par->inset_iterator_end();
187                 while (pit != pend) {
188                         if (pit->autoDelete()) {
189                                 removed = true;
190                                 pos_type const pos = pit.getPos();
191                                 
192                                 par->erase(pos);
193                                 if (cur_par == par) {
194                                         if (cur_pos > pos)
195                                                 --cur_pos;
196                                 }
197                         } else {
198                                 ++pit;
199                         }
200                 }
201                 if (removed) {
202                         found = true;
203                         text->redoParagraph(this);
204                 }
205         }
206
207         text->setCursorIntern(this, cur_par, cur_pos);
208
209         return found;
210 }
211
212
213 void BufferView::insertErrors(TeXErrors & terr)
214 {
215         // Save the cursor position
216         LyXCursor cursor = text->cursor;
217
218         TeXErrors::Errors::const_iterator cit = terr.begin();
219         TeXErrors::Errors::const_iterator end = terr.end();
220         for (; cit != end; ++cit) {
221                 string const desctext(cit->error_desc);
222                 string const errortext(cit->error_text);
223                 string const msgtxt = desctext + '\n' + errortext;
224                 int const errorrow = cit->error_in_line;
225
226                 // Insert error string for row number
227                 int tmpid = -1; 
228                 int tmppos = -1;
229
230                 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
231                         buffer()->texrow.increasePos(tmpid, tmppos);
232                 }
233                 
234                 Paragraph * texrowpar = 0;
235
236                 if (tmpid == -1) {
237                         texrowpar = text->ownerParagraph();
238                         tmppos = 0;
239                 } else {
240                         texrowpar = buffer()->getParFromID(tmpid);
241                 }
242
243                 if (texrowpar == 0)
244                         continue;
245
246                 InsetError * new_inset = new InsetError(msgtxt);
247                 text->setCursorIntern(this, texrowpar, tmppos);
248                 text->insertInset(this, new_inset);
249                 text->fullRebreak(this);
250         }
251         // Restore the cursor position
252         text->setCursorIntern(this, cursor.par(), cursor.pos());
253 }
254
255
256 void BufferView::setCursorFromRow(int row)
257 {
258         int tmpid = -1; 
259         int tmppos = -1;
260
261         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
262
263         Paragraph * texrowpar;
264
265         if (tmpid == -1) {
266                 texrowpar = text->ownerParagraph();
267                 tmppos = 0;
268         } else {
269                 texrowpar = buffer()->getParFromID(tmpid);
270         }
271         text->setCursor(this, texrowpar, tmppos);
272 }
273
274
275 bool BufferView::insertInset(Inset * inset, string const & lout)
276 {
277         return pimpl_->insertInset(inset, lout);
278 }
279
280
281 /* This is also a buffer property (ale) */
282 // Not so sure about that. a goto Label function can not be buffer local, just
283 // think how this will work in a multiwindo/buffer environment, all the
284 // cursors in all the views showing this buffer will move. (Lgb)
285 // OK, then no cursor action should be allowed in buffer. (ale)
286 bool BufferView::gotoLabel(string const & label)
287
288 {
289         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
290              it != buffer()->inset_iterator_end(); ++it) {
291                 vector<string> labels = (*it)->getLabelList();
292                 if (find(labels.begin(),labels.end(),label)
293                      != labels.end()) {
294                         beforeChange(text);
295                         text->setCursor(this, it.getPar(), it.getPos());
296                         text->selection.cursor = text->cursor;
297                         update(text, BufferView::SELECT|BufferView::FITCUR);
298                         return true;
299                 }
300         }
301         return false;
302 }
303
304
305 void BufferView::menuUndo()
306 {
307         if (available()) {
308                 owner()->message(_("Undo"));
309                 hideCursor();
310                 beforeChange(text);
311                 update(text, BufferView::SELECT|BufferView::FITCUR);
312                 if (!textUndo(this))
313                         owner()->message(_("No further undo information"));
314                 else
315                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
316                 setState();
317         }
318 }
319
320
321 void BufferView::menuRedo()
322 {
323 #if 0 // this should not be here (Jug 20011206)
324         if (theLockingInset()) {
325                 owner()->message(_("Redo not yet supported in math mode"));
326                 return;
327         }
328 #endif
329    
330         if (available()) {
331                 owner()->message(_("Redo"));
332                 hideCursor();
333                 beforeChange(text);
334                 update(text, BufferView::SELECT|BufferView::FITCUR);
335                 if (!textRedo(this))
336                         owner()->message(_("No further redo information"));
337                 else
338                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
339                 setState();
340         }
341 }
342
343
344 void BufferView::copyEnvironment()
345 {
346         if (available()) {
347                 text->copyEnvironmentType();
348                 owner()->message(_("Paragraph environment type copied"));
349         }
350 }
351
352
353 void BufferView::pasteEnvironment()
354 {
355         if (available()) {
356                 text->pasteEnvironmentType(this);
357                 owner()->message(_("Paragraph environment type set"));
358                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
359         }
360 }
361
362
363 void BufferView::copy()
364 {
365         if (available()) {
366                 text->copySelection(this);
367                 owner()->message(_("Copy"));
368         }
369 }
370
371
372 void BufferView::cut(bool realcut)
373 {
374         if (available()) {
375                 hideCursor();
376                 update(text, BufferView::SELECT|BufferView::FITCUR);
377                 text->cutSelection(this, true, realcut);
378                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
379                 owner()->message(_("Cut"));
380         }
381 }
382
383
384 void BufferView::paste()
385 {
386         if (!available()) return;
387
388         owner()->message(_("Paste"));
389
390         hideCursor();
391         // clear the selection
392         toggleSelection();
393         text->clearSelection();
394         update(text, BufferView::SELECT|BufferView::FITCUR);
395         
396         // paste
397         text->pasteSelection(this);
398         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
399         
400         // clear the selection 
401         toggleSelection();
402         text->clearSelection();
403         update(text, BufferView::SELECT|BufferView::FITCUR);
404 }
405
406
407 /* these functions are for the spellchecker */ 
408 string const BufferView::nextWord(float & value)
409 {
410         if (!available()) {
411                 value = 1;
412                 return string();
413         }
414
415         return text->selectNextWordToSpellcheck(this, value);
416 }
417
418   
419 void BufferView::selectLastWord()
420 {
421         if (!available()) return;
422    
423         LyXCursor cur = text->selection.cursor;
424         hideCursor();
425         beforeChange(text);
426         text->selection.cursor = cur;
427         text->selectSelectedWord(this);
428         toggleSelection(false);
429         update(text, BufferView::SELECT|BufferView::FITCUR);
430 }
431
432
433 void BufferView::endOfSpellCheck()
434 {
435         if (!available()) return;
436    
437         hideCursor();
438         beforeChange(text);
439         text->selectSelectedWord(this);
440         text->clearSelection();
441         update(text, BufferView::SELECT|BufferView::FITCUR);
442 }
443
444
445 void BufferView::replaceWord(string const & replacestring)
446 {
447         if (!available()) return;
448
449         LyXText * tt = getLyXText();
450         hideCursor();
451         update(tt, BufferView::SELECT|BufferView::FITCUR);
452    
453         /* clear the selection (if there is any) */ 
454         toggleSelection(false);
455         update(tt, BufferView::SELECT|BufferView::FITCUR);
456    
457         /* clear the selection (if there is any) */ 
458         toggleSelection(false);
459         tt->replaceSelectionWithString(this, replacestring);
460    
461         tt->setSelectionOverString(this, replacestring);
462
463         // Go back so that replacement string is also spellchecked
464         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
465                 tt->cursorLeft(this);
466         }
467         update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
468 }
469 // End of spellchecker stuff
470
471
472 bool BufferView::lockInset(UpdatableInset * inset)
473 {
474         if (!inset)
475                 return false;
476         // don't relock if we're already locked
477         if (theLockingInset() == inset)
478                 return true;
479         if (!theLockingInset()) {
480                 // first check if it's the inset under the cursor we want lock
481                 // should be most of the time
482                 char const c = text->cursor.par()->getChar(text->cursor.pos());
483                 if (c == Paragraph::META_INSET) {
484                         Inset * in = text->cursor.par()->getInset(text->cursor.pos());
485                         if (inset == in) {
486                                 theLockingInset(inset);
487                                 return true;
488                         }
489                 }
490                 // Then do a deep look of the inset and lock the right one
491                 Paragraph * par = buffer()->paragraph;
492                 int const id = inset->id();
493                 while(par) {
494                         Paragraph::inset_iterator it =
495                                 par->inset_iterator_begin();
496                         Paragraph::inset_iterator const end =
497                                 par->inset_iterator_end();
498                         for (; it != end; ++it) {
499                                 if ((*it) == inset) {
500                                         text->setCursorIntern(this, par, it.getPos());
501                                         theLockingInset(inset);
502                                         return true;
503                                 }
504                                 if ((*it)->getInsetFromID(id)) {
505                                         text->setCursorIntern(this, par, it.getPos());
506                                         theLockingInset(static_cast<UpdatableInset *>(*it));
507                                         return theLockingInset()->lockInsetInInset(this, inset);
508                                 }
509                         }
510                         par = par->next();
511                 }
512                 return false;
513         }
514         return theLockingInset()->lockInsetInInset(this, inset);
515 }
516
517
518 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
519 {
520         if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
521                 LyXCursor cursor = text->cursor;
522                 Inset * locking_inset = theLockingInset()->getLockingInset();
523
524                 if ((cursor.pos() - 1 >= 0) &&
525                     cursor.par()->isInset(cursor.pos() - 1) &&
526                     (cursor.par()->getInset(cursor.pos() - 1) ==
527                      locking_inset))
528                         text->setCursor(this, cursor,
529                                         cursor.par(), cursor.pos() - 1);
530                 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
531                 LyXText * txt = getLyXText();
532                 if (locking_inset->isTextInset() &&
533                     locking_inset->lyxCode() != Inset::ERT_CODE &&
534                     (txt->real_current_font.language() !=
535                      buffer()->params.language
536                      || txt->real_current_font.isVisibleRightToLeft()
537                      != buffer()->params.language->RightToLeft()))
538                         shape = (txt->real_current_font.isVisibleRightToLeft())
539                                 ? LyXScreen::REVERSED_L_SHAPE
540                                 : LyXScreen::L_SHAPE;
541                 y += cursor.y() + theLockingInset()->insetInInsetY();
542                 pimpl_->screen_->showManualCursor(text, x, y, asc, desc,
543                                                   shape);
544         }
545 }
546
547
548 void BufferView::hideLockedInsetCursor()
549 {
550         if (theLockingInset() && available()) {
551                 pimpl_->screen_->hideCursor();
552         }
553 }
554
555
556 void BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
557 {
558         if (theLockingInset() && available()) {
559                 y += text->cursor.y() + theLockingInset()->insetInInsetY();
560                 if (pimpl_->screen_->fitManualCursor(text, this, x, y, asc, desc))
561                         updateScrollbar();
562         }
563 }
564
565
566 int BufferView::unlockInset(UpdatableInset * inset)
567 {
568         if (!inset)
569                 return 0;
570         if (inset && theLockingInset() == inset) {
571                 inset->insetUnlock(this);
572                 theLockingInset(0);
573                 // make sure we update the combo !
574                 owner()->setLayout(getLyXText()->cursor.par()->getLayout());
575                 finishUndo();
576                 return 0;
577         } else if (inset && theLockingInset() &&
578                    theLockingInset()->unlockInsetInInset(this, inset)) {
579                 // owner inset has updated the layout combo 
580                 finishUndo();
581                 return 0;
582         }
583         return bufferlist.unlockInset(inset);
584 }
585
586
587 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
588 {
589         if (!theLockingInset())
590                 return; // shouldn't happen
591         if (kind == Undo::EDIT) // in this case insets would not be stored!
592                 kind = Undo::FINISH;
593         setUndo(this, kind,
594                 text->cursor.par(),
595                 text->cursor.par()->next());
596 }
597
598
599 void BufferView::updateInset(Inset * inset, bool mark_dirty)
600 {
601         pimpl_->updateInset(inset, mark_dirty);
602 }
603
604
605 bool BufferView::ChangeInsets(Inset::Code code,
606                               string const & from, string const & to)
607 {
608         bool need_update = false;
609         LyXCursor cursor = text->cursor;
610         LyXCursor tmpcursor = cursor;
611         cursor.par(tmpcursor.par());
612         cursor.pos(tmpcursor.pos());
613
614         ParIterator end = buffer()->par_iterator_end();
615         for (ParIterator it = buffer()->par_iterator_begin();
616              it != end; ++it) {
617                 Paragraph * par = *it;
618                 bool changed_inset = false;
619                 for (Paragraph::inset_iterator it2 = par->inset_iterator_begin();
620                      it2 != par->inset_iterator_end(); ++it2) {
621                         if ((*it2)->lyxCode() == code) {
622                                 InsetCommand * inset = static_cast<InsetCommand *>(*it2);
623                                 if (inset->getContents() == from) {
624                                         inset->setContents(to);
625                                         changed_inset = true;
626                                 }
627                         }
628                 }
629                 if (changed_inset) {
630                         need_update = true;
631 #ifdef WITH_WARNINGS
632 #warning FIXME
633 #endif
634                         // The test it.size()==1 was needed to prevent crashes.
635                         // How to set the cursor corretly when it.size()>1 ??
636                         if (it.size() == 1) {
637                                 text->setCursorIntern(this, par, 0);
638                                 text->redoParagraphs(this, text->cursor,
639                                                      text->cursor.par()->next());
640                                 text->fullRebreak(this);
641                         }
642                 }
643         }
644         text->setCursorIntern(this, cursor.par(), cursor.pos());
645         return need_update;
646 }
647
648
649 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
650 {
651         // Check if the label 'from' appears more than once
652         vector<string> labels = buffer()->getLabelList();
653         // count is broken on some systems, so use the HP version
654         int res;
655         count(labels.begin(), labels.end(), from, res);
656         if (res > 1)
657                 return false;
658
659         return ChangeInsets(Inset::REF_CODE, from, to);
660 }
661
662
663 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
664 {
665
666         vector<pair<string,string> > keys = buffer()->getBibkeyList();  
667         if (count_if(keys.begin(), keys.end(), 
668                      lyx::equal_1st_in_pair<string,string>(from)) 
669             > 1)
670                 return false;
671
672         return ChangeInsets(Inset::CITE_CODE, from, to);
673 }
674
675
676 UpdatableInset * BufferView::theLockingInset() const
677 {
678         // If NULL is not allowed we should put an Assert here. (Lgb)
679         if (text)
680                 return text->the_locking_inset;
681         return 0;
682 }
683
684
685 void BufferView::theLockingInset(UpdatableInset * inset)
686 {
687         text->the_locking_inset = inset;
688 }
689
690
691 LyXText * BufferView::getLyXText() const
692 {
693         if (theLockingInset()) {
694                 LyXText * txt = theLockingInset()->getLyXText(this, true);
695                 if (txt)
696                         return txt;
697         }
698         return text;
699 }
700
701
702 LyXText * BufferView::getParentText(Inset * inset) const
703 {
704         if (inset->owner()) {
705                 LyXText * txt = inset->getLyXText(this);
706                 inset = inset->owner();
707                 while (inset && inset->getLyXText(this) == txt)
708                         inset = inset->owner();
709                 if (inset)
710                         return inset->getLyXText(this);
711         }
712         return text;
713 }
714
715
716 Language const * BufferView::getParentLanguage(Inset * inset) const
717 {
718         LyXText * text = getParentText(inset);
719         return text->cursor.par()->getFontSettings(buffer()->params,
720                                                    text->cursor.pos()).language();
721 }