]> git.lyx.org Git - lyx.git/blob - src/BufferView2.C
redraw fix 1.
[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 "frontends/LyXView.h"
18 #include "bufferlist.h"
19 #include "frontends/screen.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 #include "frontends/Dialogs.h"
30
31 #include "insets/insetcommand.h" //ChangeRefs
32 #include "insets/inseterror.h"
33
34 #include "support/FileInfo.h"
35 #include "support/filetools.h"
36 #include "support/lyxfunctional.h" //equal_1st_in_pair
37 #include "support/types.h"
38 #include "support/lyxalgo.h" // lyx_count
39
40 #include <fstream>
41
42 extern BufferList bufferlist;
43
44 using lyx::pos_type;
45
46 using std::pair;
47 using std::endl;
48 using std::ifstream;
49 using std::vector;
50 using std::find;
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         // keep track of which pos and par the cursor was on
112         Paragraph * cursor_par = text->cursor.par();
113         Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
114         Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
115         pos_type cursor_pos = text->cursor.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 ((cursor_par_prev || cursor_par_next)
125                && text->setCursor(this,
126                                   cursor_par_prev ? cursor_par_prev : cursor_par_next,
127                                   0)) {
128                 // We just removed cursor_par so have to fix the "cursor"
129                 if (cursor_par_prev) {
130                         // '.' = cursor_par
131                         //  a -> a.
132                         // .
133                         cursor_par = cursor_par_prev;
134                         cursor_pos = cursor_par->size();
135                 } else {
136                         // .  -> .a
137                         //  a
138                         cursor_par = cursor_par_next;
139                         cursor_pos = 0;
140                 }
141                 cursor_par_prev = cursor_par->previous();
142                 cursor_par_next = cursor_par->next();
143         }
144
145         // Iterate through the paragraphs removing autoDelete insets as we go.
146         // If the paragraph ends up empty after all the autoDelete insets are
147         // removed that paragraph will be removed by the next setCursor() call.
148         ParIterator it = buffer()->par_iterator_begin();
149         ParIterator end = buffer()->par_iterator_end();
150         for (; it != end; ++it) {
151                 Paragraph * par = *it;
152                 Paragraph * par_prev = par ? par->previous() : 0;
153                 bool removed = false;
154
155                 if (text->setCursor(this, par, 0)
156                     && cursor_par == par_prev) {
157                         // The previous setCursor line was deleted and that
158                         // was the cursor_par line.  This can only happen if an
159                         // error box was the sole item on cursor_par.
160                         // It is possible for cursor_par_prev to be stray if
161                         // the line it pointed to only had a error box on it
162                         // so we have to set it to a known correct value.
163                         // This is often the same value it already had.
164                         cursor_par_prev = par->previous();
165                         if (cursor_par_prev) {
166                                 // '|' = par, '.' = cursor_par, 'E' = error box
167                                 // First step below may occur before while{}
168                                 //  a    |a      a     a     a.
169                                 //  E -> .E -> |.E -> .  -> |b
170                                 // .      b      b    |b
171                                 //  b
172                                 cursor_par = cursor_par_prev;
173                                 cursor_pos = cursor_par_prev->size();
174                                 cursor_par_prev = cursor_par->previous();
175                                 // cursor_par_next remains the same
176                         } else if (cursor_par_next) {
177                                 // First step below may occur before while{}
178                                 // .
179                                 //  E -> |.E -> |.  -> . -> .|a
180                                 //  a      a      a    |a
181                                 cursor_par = cursor_par_next;
182                                 cursor_pos = 0;
183                                 // cursor_par_prev remains unset
184                                 cursor_par_next = cursor_par->next();
185                         } else {
186                                 // I can't find a way to trigger this
187                                 // so it should be unreachable code
188                                 // unless the buffer is corrupted.
189                                 lyxerr << "BufferView::removeAutoInsets() is bad\n";
190                         }
191                 }
192
193                 Paragraph::inset_iterator pit = par->inset_iterator_begin();
194                 Paragraph::inset_iterator pend = par->inset_iterator_end();
195                 while (pit != pend) {
196                         if (pit->autoDelete()) {
197                                 removed = true;
198                                 pos_type const pos = pit.getPos();
199
200                                 par->erase(pos);
201                                 // We just invalidated par's inset iterators so
202                                 // we get the next valid iterator position
203                                 pit = par->InsetIterator(pos);
204                                 // and ensure we have a valid end iterator.
205                                 pend = par->inset_iterator_end();
206
207                                 if (cursor_par == par) {
208                                         // update the saved cursor position
209                                         if (cursor_pos > pos)
210                                                 --cursor_pos;
211                                 }
212                         } else {
213                                 ++pit;
214                         }
215                 }
216                 if (removed) {
217                         found = true;
218                         text->redoParagraph(this);
219                 }
220         }
221
222         // It is possible that the last line is empty if it was cursor_par
223         // and/or only had an error inset on it.  So we set the cursor to the
224         // start of the doc to force its removal and ensure a valid saved cursor
225         if (text->setCursor(this, text->ownerParagraph(), 0)
226             && 0 == cursor_par_next) {
227                 cursor_par = cursor_par_prev;
228                 cursor_pos = cursor_par->size();
229         } else if (cursor_pos > cursor_par->size()) {
230                 // Some C-Enter lines were removed by the setCursor call which
231                 // then invalidated cursor_pos. It could still be "wrong" because
232                 // the cursor may appear to have jumped but since we collapsed
233                 // some C-Enter lines this should be a reasonable compromise.
234                 cursor_pos = cursor_par->size();
235         }
236
237         // restore the original cursor in its corrected location.
238         text->setCursorIntern(this, cursor_par, cursor_pos);
239
240         return found;
241 }
242
243
244 void BufferView::insertErrors(TeXErrors & terr)
245 {
246         // Save the cursor position
247         LyXCursor cursor = text->cursor;
248
249         TeXErrors::Errors::const_iterator cit = terr.begin();
250         TeXErrors::Errors::const_iterator end = terr.end();
251         for (; cit != end; ++cit) {
252                 string const desctext(cit->error_desc);
253                 string const errortext(cit->error_text);
254                 string const msgtxt = desctext + '\n' + errortext;
255                 int const errorrow = cit->error_in_line;
256
257                 // Insert error string for row number
258                 int tmpid = -1;
259                 int tmppos = -1;
260
261                 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
262                         buffer()->texrow.increasePos(tmpid, tmppos);
263                 }
264
265                 Paragraph * texrowpar = 0;
266
267                 if (tmpid == -1) {
268                         texrowpar = text->ownerParagraph();
269                         tmppos = 0;
270                 } else {
271                         texrowpar = buffer()->getParFromID(tmpid);
272                 }
273
274                 if (texrowpar == 0)
275                         continue;
276
277                 InsetError * new_inset = new InsetError(msgtxt);
278                 text->setCursorIntern(this, texrowpar, tmppos);
279                 text->insertInset(this, new_inset);
280                 text->fullRebreak(this);
281         }
282         // Restore the cursor position
283         text->setCursorIntern(this, cursor.par(), cursor.pos());
284 }
285
286
287 void BufferView::setCursorFromRow(int row)
288 {
289         int tmpid = -1;
290         int tmppos = -1;
291
292         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
293
294         Paragraph * texrowpar;
295
296         if (tmpid == -1) {
297                 texrowpar = text->ownerParagraph();
298                 tmppos = 0;
299         } else {
300                 texrowpar = buffer()->getParFromID(tmpid);
301         }
302         text->setCursor(this, texrowpar, tmppos);
303 }
304
305
306 bool BufferView::insertInset(Inset * inset, string const & lout)
307 {
308         return pimpl_->insertInset(inset, lout);
309 }
310
311
312 /* This is also a buffer property (ale) */
313 // Not so sure about that. a goto Label function can not be buffer local, just
314 // think how this will work in a multiwindo/buffer environment, all the
315 // cursors in all the views showing this buffer will move. (Lgb)
316 // OK, then no cursor action should be allowed in buffer. (ale)
317 bool BufferView::gotoLabel(string const & label)
318
319 {
320         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
321              it != buffer()->inset_iterator_end(); ++it) {
322                 vector<string> labels = (*it)->getLabelList();
323                 if (find(labels.begin(),labels.end(),label)
324                      != labels.end()) {
325                         beforeChange(text);
326                         text->setCursor(this, it.getPar(), it.getPos());
327                         text->selection.cursor = text->cursor;
328                         update(text, BufferView::SELECT|BufferView::FITCUR);
329                         return true;
330                 }
331         }
332         return false;
333 }
334
335
336 void BufferView::menuUndo()
337 {
338         if (available()) {
339                 owner()->message(_("Undo"));
340                 hideCursor();
341                 beforeChange(text);
342                 update(text, BufferView::SELECT|BufferView::FITCUR);
343                 if (!textUndo(this))
344                         owner()->message(_("No further undo information"));
345                 else
346                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
347                 setState();
348         }
349 }
350
351
352 void BufferView::menuRedo()
353 {
354 #if 0 // this should not be here (Jug 20011206)
355         if (theLockingInset()) {
356                 owner()->message(_("Redo not yet supported in math mode"));
357                 return;
358         }
359 #endif
360
361         if (available()) {
362                 owner()->message(_("Redo"));
363                 hideCursor();
364                 beforeChange(text);
365                 update(text, BufferView::SELECT|BufferView::FITCUR);
366                 if (!textRedo(this))
367                         owner()->message(_("No further redo information"));
368                 else
369                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
370                 setState();
371         }
372 }
373
374
375 void BufferView::copyEnvironment()
376 {
377         if (available()) {
378                 text->copyEnvironmentType();
379                 owner()->message(_("Paragraph environment type copied"));
380         }
381 }
382
383
384 void BufferView::pasteEnvironment()
385 {
386         if (available()) {
387                 text->pasteEnvironmentType(this);
388                 owner()->message(_("Paragraph environment type set"));
389                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
390         }
391 }
392
393
394 void BufferView::copy()
395 {
396         if (available()) {
397                 getLyXText()->copySelection(this);
398                 owner()->message(_("Copy"));
399         }
400 }
401
402
403 void BufferView::cut(bool realcut)
404 {
405         if (available()) {
406                 hideCursor();
407                 update(text, BufferView::SELECT|BufferView::FITCUR);
408                 text->cutSelection(this, true, realcut);
409                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
410                 owner()->message(_("Cut"));
411         }
412 }
413
414
415 void BufferView::paste()
416 {
417         if (!available())
418                 return;
419
420         owner()->message(_("Paste"));
421
422         hideCursor();
423         // clear the selection
424         toggleSelection();
425         text->clearSelection();
426         update(text, BufferView::SELECT|BufferView::FITCUR);
427
428         // paste
429         text->pasteSelection(this);
430         // bug 393
431         text->clearSelection();
432         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
433 // why fake a selection only I think it should be a real one and not only
434 // a painted one (Jug 20020318).
435 #if 0
436         // clear the selection
437         toggleSelection();
438         text->clearSelection();
439         update(text, BufferView::SELECT|BufferView::FITCUR);
440 #endif
441 }
442
443
444 /* these functions are for the spellchecker */
445 string const BufferView::nextWord(float & value)
446 {
447         if (!available()) {
448                 value = 1;
449                 return string();
450         }
451
452         return text->selectNextWordToSpellcheck(this, value);
453 }
454
455
456 void BufferView::selectLastWord()
457 {
458         if (!available()) return;
459
460         LyXCursor cur = text->selection.cursor;
461         hideCursor();
462         beforeChange(text);
463         text->selection.cursor = cur;
464         text->selectSelectedWord(this);
465         toggleSelection(false);
466         update(text, BufferView::SELECT|BufferView::FITCUR);
467 }
468
469
470 void BufferView::endOfSpellCheck()
471 {
472         if (!available()) return;
473
474         hideCursor();
475         beforeChange(text);
476         text->selectSelectedWord(this);
477         text->clearSelection();
478         update(text, BufferView::SELECT|BufferView::FITCUR);
479 }
480
481
482 void BufferView::replaceWord(string const & replacestring)
483 {
484         if (!available()) return;
485
486         LyXText * tt = getLyXText();
487         hideCursor();
488         update(tt, BufferView::SELECT|BufferView::FITCUR);
489
490         /* clear the selection (if there is any) */
491         toggleSelection(false);
492         update(tt, BufferView::SELECT|BufferView::FITCUR);
493
494         /* clear the selection (if there is any) */
495         toggleSelection(false);
496         tt->replaceSelectionWithString(this, replacestring);
497
498         tt->setSelectionOverString(this, replacestring);
499
500         // Go back so that replacement string is also spellchecked
501         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
502                 tt->cursorLeft(this);
503         }
504         update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
505 }
506 // End of spellchecker stuff
507
508
509 bool BufferView::lockInset(UpdatableInset * inset)
510 {
511         if (!inset)
512                 return false;
513         // don't relock if we're already locked
514         if (theLockingInset() == inset)
515                 return true;
516         if (!theLockingInset()) {
517                 // first check if it's the inset under the cursor we want lock
518                 // should be most of the time
519                 char const c = text->cursor.par()->getChar(text->cursor.pos());
520                 if (c == Paragraph::META_INSET) {
521                         Inset * in = text->cursor.par()->getInset(text->cursor.pos());
522                         if (inset == in) {
523                                 theLockingInset(inset);
524                                 return true;
525                         }
526                 }
527                 // Then do a deep look of the inset and lock the right one
528                 Paragraph * par = buffer()->paragraph;
529                 int const id = inset->id();
530                 while(par) {
531                         Paragraph::inset_iterator it =
532                                 par->inset_iterator_begin();
533                         Paragraph::inset_iterator const end =
534                                 par->inset_iterator_end();
535                         for (; it != end; ++it) {
536                                 if ((*it) == inset) {
537                                         text->setCursorIntern(this, par, it.getPos());
538                                         theLockingInset(inset);
539                                         return true;
540                                 }
541                                 if ((*it)->getInsetFromID(id)) {
542                                         text->setCursorIntern(this, par, it.getPos());
543                                         (*it)->edit(this);
544                                         return theLockingInset()->lockInsetInInset(this, inset);
545                                 }
546                         }
547                         par = par->next();
548                 }
549                 return false;
550         }
551         return theLockingInset()->lockInsetInInset(this, inset);
552 }
553
554
555 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
556 {
557         if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
558                 LyXCursor cursor = text->cursor;
559                 Inset * locking_inset = theLockingInset()->getLockingInset();
560
561                 if ((cursor.pos() - 1 >= 0) &&
562                     cursor.par()->isInset(cursor.pos() - 1) &&
563                     (cursor.par()->getInset(cursor.pos() - 1) ==
564                      locking_inset))
565                         text->setCursor(this, cursor,
566                                         cursor.par(), cursor.pos() - 1);
567                 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
568                 LyXText * txt = getLyXText();
569                 if (locking_inset->isTextInset() &&
570                     locking_inset->lyxCode() != Inset::ERT_CODE &&
571                     (txt->real_current_font.language() !=
572                      buffer()->params.language
573                      || txt->real_current_font.isVisibleRightToLeft()
574                      != buffer()->params.language->RightToLeft()))
575                         shape = (txt->real_current_font.isVisibleRightToLeft())
576                                 ? LyXScreen::REVERSED_L_SHAPE
577                                 : LyXScreen::L_SHAPE;
578                 y += cursor.iy() + theLockingInset()->insetInInsetY();
579                 screen().showManualCursor(text, x, y, asc, desc,
580                                                   shape);
581         }
582 }
583
584
585 void BufferView::hideLockedInsetCursor()
586 {
587         if (theLockingInset() && available()) {
588                 screen().hideCursor();
589         }
590 }
591
592
593 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
594 {
595         if (theLockingInset() && available()) {
596                 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
597                 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
598                         updateScrollbar();
599                         return true;
600                 }
601         }
602         return false;
603 }
604
605
606 int BufferView::unlockInset(UpdatableInset * inset)
607 {
608         if (!inset)
609                 return 0;
610         if (inset && theLockingInset() == inset) {
611                 inset->insetUnlock(this);
612                 theLockingInset(0);
613                 // make sure we update the combo !
614                 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
615                 // Tell the paragraph dialog that we changed paragraph
616                 owner()->getDialogs()->updateParagraph();
617                 finishUndo();
618                 return 0;
619         } else if (inset && theLockingInset() &&
620                    theLockingInset()->unlockInsetInInset(this, inset)) {
621                 // Tell the paragraph dialog that we changed paragraph
622                 owner()->getDialogs()->updateParagraph();
623                 // owner inset has updated the layout combo
624                 finishUndo();
625                 return 0;
626         }
627         return bufferlist.unlockInset(inset);
628 }
629
630
631 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
632 {
633         if (!theLockingInset())
634                 return; // shouldn't happen
635         if (kind == Undo::EDIT) // in this case insets would not be stored!
636                 kind = Undo::FINISH;
637         setUndo(this, kind,
638                 text->cursor.par(),
639                 text->cursor.par()->next());
640 }
641
642
643 void BufferView::updateInset(Inset * inset, bool mark_dirty)
644 {
645         pimpl_->updateInset(inset, mark_dirty);
646 }
647
648
649 bool BufferView::ChangeInsets(Inset::Code code,
650                               string const & from, string const & to)
651 {
652         bool need_update = false;
653         LyXCursor cursor = text->cursor;
654         LyXCursor tmpcursor = cursor;
655         cursor.par(tmpcursor.par());
656         cursor.pos(tmpcursor.pos());
657
658         ParIterator end = buffer()->par_iterator_end();
659         for (ParIterator it = buffer()->par_iterator_begin();
660              it != end; ++it) {
661                 Paragraph * par = *it;
662                 bool changed_inset = false;
663                 for (Paragraph::inset_iterator it2 = par->inset_iterator_begin();
664                      it2 != par->inset_iterator_end(); ++it2) {
665                         if ((*it2)->lyxCode() == code) {
666                                 InsetCommand * inset = static_cast<InsetCommand *>(*it2);
667                                 if (inset->getContents() == from) {
668                                         inset->setContents(to);
669                                         changed_inset = true;
670                                 }
671                         }
672                 }
673                 if (changed_inset) {
674                         need_update = true;
675
676                         // FIXME
677
678                         // The test it.size()==1 was needed to prevent crashes.
679                         // How to set the cursor corretly when it.size()>1 ??
680                         if (it.size() == 1) {
681                                 text->setCursorIntern(this, par, 0);
682                                 text->redoParagraphs(this, text->cursor,
683                                                      text->cursor.par()->next());
684                                 text->fullRebreak(this);
685                         }
686                 }
687         }
688         text->setCursorIntern(this, cursor.par(), cursor.pos());
689         return need_update;
690 }
691
692
693 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
694 {
695         // Check if the label 'from' appears more than once
696         vector<string> labels = buffer()->getLabelList();
697
698         if (lyx::count(labels.begin(), labels.end(), from) > 1)
699                 return false;
700
701         return ChangeInsets(Inset::REF_CODE, from, to);
702 }
703
704
705 bool BufferView::ChangeCitationsIfUnique(string const & from,
706                                          string const & to)
707 {
708         typedef pair<string, string> StringPair;
709
710         vector<StringPair> keys = buffer()->getBibkeyList();
711         if (count_if(keys.begin(), keys.end(),
712                      lyx::equal_1st_in_pair<StringPair>(from))
713             > 1)
714                 return false;
715
716         return ChangeInsets(Inset::CITE_CODE, from, to);
717 }
718
719
720 UpdatableInset * BufferView::theLockingInset() const
721 {
722         // If NULL is not allowed we should put an Assert here. (Lgb)
723         if (text)
724                 return text->the_locking_inset;
725         return 0;
726 }
727
728
729 void BufferView::theLockingInset(UpdatableInset * inset)
730 {
731         text->the_locking_inset = inset;
732 }
733
734
735 LyXText * BufferView::getLyXText() const
736 {
737         if (theLockingInset()) {
738                 LyXText * txt = theLockingInset()->getLyXText(this, true);
739                 if (txt)
740                         return txt;
741         }
742         return text;
743 }
744
745
746 LyXText * BufferView::getParentText(Inset * inset) const
747 {
748         if (inset->owner()) {
749                 LyXText * txt = inset->getLyXText(this);
750                 inset = inset->owner();
751                 while (inset && inset->getLyXText(this) == txt)
752                         inset = inset->owner();
753                 if (inset)
754                         return inset->getLyXText(this);
755         }
756         return text;
757 }
758
759
760 Language const * BufferView::getParentLanguage(Inset * inset) const
761 {
762         LyXText * text = getParentText(inset);
763         return text->cursor.par()->getFontSettings(buffer()->params,
764                                                    text->cursor.pos()).language();
765 }