]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
the errorlist change
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * Copyright 1995-2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author unknown
7  * \author John Levon <moz@compsoc.man.ac.uk>
8  */
9
10 #include <config.h>
11
12 #include "BufferView.h"
13 #include "BufferView_pimpl.h"
14
15 #include "BufferView_pimpl.h"
16 #include "LaTeX.h"
17 #include "ParagraphParameters.h"
18 #include "WordLangTuple.h"
19 #include "buffer.h"
20 #include "bufferlist.h"
21 #include "debug.h"
22 #include "gettext.h"
23 #include "iterators.h"
24 #include "language.h"
25 #include "lyxcursor.h"
26 #include "lyxlex.h"
27 #include "lyxtext.h"
28 #include "undo_funcs.h"
29 #include "changes.h"
30 #include "paragraph_funcs.h"
31
32 #include "frontends/Alert.h"
33 #include "frontends/Dialogs.h"
34 #include "frontends/LyXView.h"
35 #include "frontends/WorkArea.h"
36 #include "frontends/screen.h"
37
38 #include "insets/insetcommand.h" // ChangeRefs
39 #include "insets/inseterror.h"
40 #include "insets/updatableinset.h"
41
42 #include "support/FileInfo.h"
43 #include "support/filetools.h"
44 #include "support/lyxfunctional.h" // equal_1st_in_pair
45 #include "support/types.h"
46 #include "support/lyxalgo.h" // lyx_count
47
48 #include <fstream>
49
50 extern BufferList bufferlist;
51
52 using lyx::pos_type;
53
54 using std::pair;
55 using std::endl;
56 using std::ifstream;
57 using std::vector;
58 using std::find;
59 using std::count_if;
60
61
62 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
63                        int width, int height)
64         : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
65 {
66         text = 0;
67 }
68
69
70 BufferView::~BufferView()
71 {
72         delete text;
73         delete pimpl_;
74 }
75
76
77 Buffer * BufferView::buffer() const
78 {
79         return pimpl_->buffer_;
80 }
81
82
83 LyXScreen & BufferView::screen() const
84 {
85         return pimpl_->screen();
86 }
87
88
89 LyXView * BufferView::owner() const
90 {
91         return pimpl_->owner_;
92 }
93
94
95 Painter & BufferView::painter() const
96 {
97         return pimpl_->painter();
98 }
99
100
101 void BufferView::buffer(Buffer * b)
102 {
103         pimpl_->buffer(b);
104 }
105
106
107 void BufferView::reload()
108 {
109         string const fn = buffer()->fileName();
110         if (bufferlist.close(buffer(), false))
111                 buffer(bufferlist.loadLyXFile(fn));
112 }
113
114
115 void BufferView::resize()
116 {
117         if (pimpl_->buffer_) {
118                 pimpl_->resizeCurrentBuffer();
119         }
120 }
121
122
123 void BufferView::repaint()
124 {
125         pimpl_->repaint();
126 }
127
128
129 bool BufferView::fitCursor()
130 {
131         return pimpl_->fitCursor();
132 }
133
134
135 void BufferView::update()
136 {
137         pimpl_->update();
138 }
139
140
141 void BufferView::updateScrollbar()
142 {
143         pimpl_->updateScrollbar();
144 }
145
146
147 void BufferView::scrollDocView(int value)
148 {
149         pimpl_->scrollDocView(value);
150 }
151
152
153 void BufferView::redoCurrentBuffer()
154 {
155         pimpl_->redoCurrentBuffer();
156 }
157
158
159 bool BufferView::available() const
160 {
161         return pimpl_->available();
162 }
163
164
165 Change const BufferView::getCurrentChange()
166 {
167         return pimpl_->getCurrentChange();
168 }
169
170
171 void BufferView::beforeChange(LyXText * text)
172 {
173         pimpl_->beforeChange(text);
174 }
175
176
177 void BufferView::savePosition(unsigned int i)
178 {
179         pimpl_->savePosition(i);
180 }
181
182
183 void BufferView::restorePosition(unsigned int i)
184 {
185         pimpl_->restorePosition(i);
186 }
187
188
189 bool BufferView::isSavedPosition(unsigned int i)
190 {
191         return pimpl_->isSavedPosition(i);
192 }
193
194
195 void BufferView::update(LyXText * text, UpdateCodes f)
196 {
197         pimpl_->update(text, f);
198 }
199
200
201 void BufferView::update(UpdateCodes f)
202 {
203         pimpl_->update(f);
204 }
205
206
207 void BufferView::switchKeyMap()
208 {
209         pimpl_->switchKeyMap();
210 }
211
212
213 void BufferView::insetUnlock()
214 {
215         pimpl_->insetUnlock();
216 }
217
218
219 int BufferView::workWidth() const
220 {
221         return pimpl_->workarea().workWidth();
222 }
223
224
225 void BufferView::toggleSelection(bool b)
226 {
227         pimpl_->toggleSelection(b);
228 }
229
230
231 void BufferView::toggleToggle()
232 {
233         pimpl_->toggleToggle();
234 }
235
236
237 void BufferView::center()
238 {
239         pimpl_->center();
240 }
241
242
243 string const BufferView::getClipboard() const
244 {
245         return pimpl_->workarea().getClipboard();
246 }
247
248
249 void BufferView::stuffClipboard(string const & stuff) const
250 {
251         pimpl_->stuffClipboard(stuff);
252 }
253
254
255 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
256                                   BufferView::UpdateCodes uc2)
257 {
258         return static_cast<BufferView::UpdateCodes>
259                 (static_cast<int>(uc1) | static_cast<int>(uc2));
260 }
261
262
263 bool BufferView::dispatch(FuncRequest const & ev)
264 {
265         return pimpl_->dispatch(ev);
266 }
267
268
269 void BufferView::scroll(int lines)
270 {
271         pimpl_->scroll(lines);
272 }
273
274
275 // Inserts a file into current document
276 bool BufferView::insertLyXFile(string const & filen)
277         //
278         // Copyright CHT Software Service GmbH
279         // Uwe C. Schroeder
280         //
281         // Insert a LyXformat - file into current buffer
282         //
283         // Moved from lyx_cb.C (Lgb)
284 {
285         if (filen.empty())
286                 return false;
287
288         string const fname = MakeAbsPath(filen);
289
290         // check if file exist
291         FileInfo const fi(fname);
292
293         if (!fi.readable()) {
294                 string const file = MakeDisplayPath(fname, 50);
295                 string const text =
296                         bformat(_("The specified document\n%1$s\ncould not be read."), file);
297                 Alert::error(_("Could not read document"), text);
298                 return false;
299         }
300
301         beforeChange(text);
302
303         ifstream ifs(fname.c_str());
304         if (!ifs) {
305                 string const file = MakeDisplayPath(fname, 50);
306                 string const text =
307                         bformat(_("Could not open the specified document\n"), file);
308                 Alert::error(_("Could not open file"), text);
309                 return false;
310         }
311
312         int const c = ifs.peek();
313
314         LyXLex lex(0, 0);
315         lex.setStream(ifs);
316
317         bool res = true;
318
319         if (c == '#') {
320                 // FIXME: huh ? No we won't !
321                 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
322                 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
323         } else {
324                 lyxerr[Debug::INFO] << "Will insert file without header"
325                                     << endl;
326                 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
327         }
328
329         resize();
330         return res;
331 }
332
333
334 bool BufferView::removeAutoInsets()
335 {
336         // keep track of which pos and par the cursor was on
337         Paragraph * cursor_par = &*text->cursor.par();
338         Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
339         Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
340         pos_type cursor_pos = text->cursor.pos();
341
342         bool found = false;
343
344         // Trap the deletion of the paragraph the cursor is in.
345         // Iterate until we find a paragraph that won't be immediately deleted.
346         // In reality this should mean we only execute the body of the while
347         // loop once at most.  However for safety we iterate rather than just
348         // make this an if () conditional.
349         while ((cursor_par_prev || cursor_par_next)
350                && text->setCursor(
351                                   cursor_par_prev ? cursor_par_prev : cursor_par_next,
352                                   0)) {
353                 // We just removed cursor_par so have to fix the "cursor"
354                 if (cursor_par_prev) {
355                         // '.' = cursor_par
356                         //  a -> a.
357                         // .
358                         cursor_par = cursor_par_prev;
359                         cursor_pos = cursor_par->size();
360                 } else {
361                         // .  -> .a
362                         //  a
363                         cursor_par = cursor_par_next;
364                         cursor_pos = 0;
365                 }
366                 cursor_par_prev = cursor_par->previous();
367                 cursor_par_next = cursor_par->next();
368         }
369
370         // Iterate through the paragraphs removing autoDelete insets as we go.
371         // If the paragraph ends up empty after all the autoDelete insets are
372         // removed that paragraph will be removed by the next setCursor() call.
373         ParIterator it = buffer()->par_iterator_begin();
374         ParIterator end = buffer()->par_iterator_end();
375         for (; it != end; ++it) {
376                 Paragraph * par = *it;
377                 Paragraph * par_prev = par ? par->previous() : 0;
378                 bool removed = false;
379
380                 if (text->setCursor(par, 0)
381                     && cursor_par == par_prev) {
382                         // The previous setCursor line was deleted and that
383                         // was the cursor_par line.  This can only happen if an
384                         // error box was the sole item on cursor_par.
385                         // It is possible for cursor_par_prev to be stray if
386                         // the line it pointed to only had a error box on it
387                         // so we have to set it to a known correct value.
388                         // This is often the same value it already had.
389                         cursor_par_prev = par->previous();
390                         if (cursor_par_prev) {
391                                 // '|' = par, '.' = cursor_par, 'E' = error box
392                                 // First step below may occur before while{}
393                                 //  a    |a      a     a     a.
394                                 //  E -> .E -> |.E -> .  -> |b
395                                 // .      b      b    |b
396                                 //  b
397                                 cursor_par = cursor_par_prev;
398                                 cursor_pos = cursor_par_prev->size();
399                                 cursor_par_prev = cursor_par->previous();
400                                 // cursor_par_next remains the same
401                         } else if (cursor_par_next) {
402                                 // First step below may occur before while{}
403                                 // .
404                                 //  E -> |.E -> |.  -> . -> .|a
405                                 //  a      a      a    |a
406                                 cursor_par = cursor_par_next;
407                                 cursor_pos = 0;
408                                 // cursor_par_prev remains unset
409                                 cursor_par_next = cursor_par->next();
410                         } else {
411                                 // I can't find a way to trigger this
412                                 // so it should be unreachable code
413                                 // unless the buffer is corrupted.
414                                 lyxerr << "BufferView::removeAutoInsets() is bad\n";
415                         }
416                 }
417
418                 InsetList::iterator pit = par->insetlist.begin();
419                 InsetList::iterator pend = par->insetlist.end();
420
421                 while (pit != pend) {
422                         if (pit.getInset()->autoDelete()) {
423                                 removed = true;
424                                 pos_type const pos = pit.getPos();
425
426                                 par->erase(pos);
427                                 // We just invalidated par's inset iterators so
428                                 // we get the next valid iterator position
429                                 pit = par->insetlist.insetIterator(pos);
430                                 // and ensure we have a valid end iterator.
431                                 pend = par->insetlist.end();
432
433                                 if (cursor_par == par) {
434                                         // update the saved cursor position
435                                         if (cursor_pos > pos)
436                                                 --cursor_pos;
437                                 }
438                         } else {
439                                 ++pit;
440                         }
441                 }
442                 if (removed) {
443                         found = true;
444                         text->redoParagraph();
445                 }
446         }
447
448         // It is possible that the last line is empty if it was cursor_par
449         // and/or only had an error inset on it.  So we set the cursor to the
450         // start of the doc to force its removal and ensure a valid saved cursor
451         if (text->setCursor(&*text->ownerParagraphs().begin(), 0)
452             && 0 == cursor_par_next) {
453                 cursor_par = cursor_par_prev;
454                 cursor_pos = cursor_par->size();
455         } else if (cursor_pos > cursor_par->size()) {
456                 // Some C-Enter lines were removed by the setCursor call which
457                 // then invalidated cursor_pos. It could still be "wrong" because
458                 // the cursor may appear to have jumped but since we collapsed
459                 // some C-Enter lines this should be a reasonable compromise.
460                 cursor_pos = cursor_par->size();
461         }
462
463         // restore the original cursor in its corrected location.
464         text->setCursorIntern(cursor_par, cursor_pos);
465
466         return found;
467 }
468
469
470 void BufferView::showErrorList()
471 {
472         owner()->getDialogs().show("errorlist");
473 }
474
475
476 void BufferView::setCursorFromRow(int row)
477 {
478         int tmpid = -1;
479         int tmppos = -1;
480
481         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
482
483         Paragraph * texrowpar;
484
485         if (tmpid == -1) {
486                 texrowpar = &*text->ownerParagraphs().begin();
487                 tmppos = 0;
488         } else {
489                 texrowpar = &*buffer()->getParFromID(tmpid);
490         }
491         text->setCursor(texrowpar, tmppos);
492 }
493
494
495 bool BufferView::insertInset(Inset * inset, string const & lout)
496 {
497         return pimpl_->insertInset(inset, lout);
498 }
499
500
501 void BufferView::gotoLabel(string const & label)
502 {
503         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
504              it != buffer()->inset_iterator_end(); ++it) {
505                 vector<string> labels = it->getLabelList();
506                 if (find(labels.begin(),labels.end(),label)
507                      != labels.end()) {
508                         beforeChange(text);
509                         text->setCursor(it.getPar(), it.getPos());
510                         text->selection.cursor = text->cursor;
511                         update(text, BufferView::SELECT);
512                         return;
513                 }
514         }
515 }
516
517
518 void BufferView::undo()
519 {
520         if (!available())
521                 return;
522
523         owner()->message(_("Undo"));
524         beforeChange(text);
525         update(text, BufferView::SELECT);
526         if (!textUndo(this))
527                 owner()->message(_("No further undo information"));
528         else
529                 update(text, BufferView::SELECT);
530         switchKeyMap();
531 }
532
533
534 void BufferView::redo()
535 {
536         if (!available())
537                 return;
538
539         owner()->message(_("Redo"));
540         beforeChange(text);
541         update(text, BufferView::SELECT);
542         if (!textRedo(this))
543                 owner()->message(_("No further redo information"));
544         else
545                 update(text, BufferView::SELECT);
546         switchKeyMap();
547 }
548
549
550 // these functions are for the spellchecker
551 WordLangTuple const BufferView::nextWord(float & value)
552 {
553         if (!available()) {
554                 value = 1;
555                 return WordLangTuple();
556         }
557
558         return text->selectNextWordToSpellcheck(value);
559 }
560
561
562 void BufferView::selectLastWord()
563 {
564         if (!available())
565                 return;
566
567         LyXCursor cur = text->selection.cursor;
568         beforeChange(text);
569         text->selection.cursor = cur;
570         text->selectSelectedWord();
571         toggleSelection(false);
572         update(text, BufferView::SELECT);
573 }
574
575
576 void BufferView::endOfSpellCheck()
577 {
578         if (!available()) return;
579
580         beforeChange(text);
581         text->selectSelectedWord();
582         text->clearSelection();
583         update(text, BufferView::SELECT);
584 }
585
586
587 void BufferView::replaceWord(string const & replacestring)
588 {
589         if (!available())
590                 return;
591
592         LyXText * tt = getLyXText();
593         update(tt, BufferView::SELECT);
594
595         // clear the selection (if there is any)
596         toggleSelection(false);
597         update(tt, BufferView::SELECT);
598
599         // clear the selection (if there is any)
600         toggleSelection(false);
601         tt->replaceSelectionWithString(replacestring);
602
603         tt->setSelectionRange(replacestring.length());
604
605         // Go back so that replacement string is also spellchecked
606         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
607                 tt->cursorLeft(this);
608         }
609         update(tt, BufferView::SELECT);
610
611         // FIXME: should be done through LFUN
612         buffer()->markDirty();
613         fitCursor();
614 }
615 // End of spellchecker stuff
616
617
618 bool BufferView::lockInset(UpdatableInset * inset)
619 {
620         if (!inset)
621                 return false;
622         // don't relock if we're already locked
623         if (theLockingInset() == inset)
624                 return true;
625         if (!theLockingInset()) {
626                 // first check if it's the inset under the cursor we want lock
627                 // should be most of the time
628                 if (text->cursor.pos() < text->cursor.par()->size()
629                     && text->cursor.par()->getChar(text->cursor.pos()) ==
630                     Paragraph::META_INSET) {
631                         Inset * in = text->cursor.par()->getInset(text->cursor.pos());
632                         if (inset == in) {
633                                 theLockingInset(inset);
634                                 return true;
635                         }
636                 }
637                 // Then do a deep look of the inset and lock the right one
638                 int const id = inset->id();
639                 ParagraphList::iterator pit = buffer()->paragraphs.begin();
640                 ParagraphList::iterator pend = buffer()->paragraphs.end();
641                 for (; pit != pend; ++pit) {
642                         InsetList::iterator it = pit->insetlist.begin();
643                         InsetList::iterator end = pit->insetlist.end();
644                         for (; it != end; ++it) {
645                                 if (it.getInset() == inset) {
646                                         text->setCursorIntern(pit, it.getPos());
647                                         theLockingInset(inset);
648                                         return true;
649                                 }
650                                 if (it.getInset()->getInsetFromID(id)) {
651                                         text->setCursorIntern(pit, it.getPos());
652                                         it.getInset()->edit(this);
653                                         return theLockingInset()->lockInsetInInset(this, inset);
654                                 }
655                         }
656                 }
657                 return false;
658         }
659         return theLockingInset()->lockInsetInInset(this, inset);
660 }
661
662
663 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
664 {
665         if (theLockingInset() && available()) {
666                 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
667                 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
668                         updateScrollbar();
669                         return true;
670                 }
671         }
672         return false;
673 }
674
675
676 void BufferView::hideCursor()
677 {
678         screen().hideCursor();
679 }
680
681
682 int BufferView::unlockInset(UpdatableInset * inset)
683 {
684         if (!inset)
685                 return 0;
686         if (inset && theLockingInset() == inset) {
687                 inset->insetUnlock(this);
688                 theLockingInset(0);
689                 // make sure we update the combo !
690                 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
691                 // Tell the paragraph dialog that we changed paragraph
692                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
693                 finishUndo();
694                 return 0;
695         } else if (inset && theLockingInset() &&
696                    theLockingInset()->unlockInsetInInset(this, inset)) {
697                 // Tell the paragraph dialog that we changed paragraph
698                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
699                 // owner inset has updated the layout combo
700                 finishUndo();
701                 return 0;
702         }
703         return 1;
704 }
705
706
707 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
708 {
709         if (!theLockingInset())
710                 return; // shouldn't happen
711         if (kind == Undo::EDIT) // in this case insets would not be stored!
712                 kind = Undo::FINISH;
713         setUndo(this, kind,
714                 text->cursor.par(),
715                 boost::next(text->cursor.par()));
716 }
717
718
719 void BufferView::updateInset(Inset * inset)
720 {
721         pimpl_->updateInset(inset);
722 }
723
724
725 bool BufferView::ChangeInsets(Inset::Code code,
726                               string const & from, string const & to)
727 {
728         bool need_update = false;
729         LyXCursor cursor = text->cursor;
730         LyXCursor tmpcursor = cursor;
731         cursor.par(tmpcursor.par());
732         cursor.pos(tmpcursor.pos());
733
734         ParIterator end = buffer()->par_iterator_end();
735         for (ParIterator it = buffer()->par_iterator_begin();
736              it != end; ++it) {
737                 Paragraph * par = *it;
738                 bool changed_inset = false;
739                 for (InsetList::iterator it2 = par->insetlist.begin();
740                      it2 != par->insetlist.end(); ++it2) {
741                         if (it2.getInset()->lyxCode() == code) {
742                                 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
743                                 if (inset->getContents() == from) {
744                                         inset->setContents(to);
745                                         changed_inset = true;
746                                 }
747                         }
748                 }
749                 if (changed_inset) {
750                         need_update = true;
751
752                         // FIXME
753
754                         // The test it.size()==1 was needed to prevent crashes.
755                         // How to set the cursor corretly when it.size()>1 ??
756                         if (it.size() == 1) {
757                                 text->setCursorIntern(par, 0);
758                                 text->redoParagraphs(text->cursor,
759                                                      boost::next(text->cursor.par()));
760                                 text->fullRebreak();
761                         }
762                 }
763         }
764         text->setCursorIntern(cursor.par(), cursor.pos());
765         return need_update;
766 }
767
768
769 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
770 {
771         // Check if the label 'from' appears more than once
772         vector<string> labels = buffer()->getLabelList();
773
774         if (lyx::count(labels.begin(), labels.end(), from) > 1)
775                 return false;
776
777         return ChangeInsets(Inset::REF_CODE, from, to);
778 }
779
780
781 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
782 {
783         typedef pair<string, string> StringPair;
784
785         vector<StringPair> keys;
786         buffer()->fillWithBibKeys(keys);
787         if (count_if(keys.begin(), keys.end(),
788                      lyx::equal_1st_in_pair<StringPair>(from))
789             > 1)
790                 return false;
791
792         return ChangeInsets(Inset::CITE_CODE, from, to);
793 }
794
795
796 UpdatableInset * BufferView::theLockingInset() const
797 {
798         // If NULL is not allowed we should put an Assert here. (Lgb)
799         if (text)
800                 return text->the_locking_inset;
801         return 0;
802 }
803
804
805 void BufferView::theLockingInset(UpdatableInset * inset)
806 {
807         text->the_locking_inset = inset;
808 }
809
810
811 LyXText * BufferView::getLyXText() const
812 {
813         if (theLockingInset()) {
814                 LyXText * txt = theLockingInset()->getLyXText(this, true);
815                 if (txt)
816                         return txt;
817         }
818         return text;
819 }
820
821
822 LyXText * BufferView::getParentText(Inset * inset) const
823 {
824         if (inset->owner()) {
825                 LyXText * txt = inset->getLyXText(this);
826                 inset = inset->owner();
827                 while (inset && inset->getLyXText(this) == txt)
828                         inset = inset->owner();
829                 if (inset)
830                         return inset->getLyXText(this);
831         }
832         return text;
833 }
834
835
836 Language const * BufferView::getParentLanguage(Inset * inset) const
837 {
838         LyXText * text = getParentText(inset);
839         return text->cursor.par()->getFontSettings(buffer()->params,
840                                                    text->cursor.pos()).language();
841 }
842
843
844 Encoding const * BufferView::getEncoding() const
845 {
846         LyXText * t = getLyXText();
847         if (!t)
848                 return 0;
849
850         LyXCursor const & c = t->cursor;
851         LyXFont const font = c.par()->getFont(buffer()->params, c.pos(),
852                                               outerFont(c.par(), t->ownerParagraphs()));
853         return font.language()->encoding();
854 }
855
856
857 void BufferView::haveSelection(bool sel)
858 {
859         pimpl_->workarea().haveSelection(sel);
860 }
861
862
863 int BufferView::workHeight() const
864 {
865         return pimpl_->workarea().workHeight();
866 }