3 * Copyright 1995-2002 the LyX Team
4 * Read the file COPYING
7 * \author John Levon <moz@compsoc.man.ac.uk>
12 #include "BufferView.h"
13 #include "BufferView_pimpl.h"
15 #include "BufferView_pimpl.h"
17 #include "WordLangTuple.h"
19 #include "bufferlist.h"
22 #include "iterators.h"
24 #include "lyxcursor.h"
27 #include "undo_funcs.h"
30 #include "frontends/Alert.h"
31 #include "frontends/Dialogs.h"
32 #include "frontends/LyXView.h"
33 #include "frontends/WorkArea.h"
34 #include "frontends/screen.h"
36 #include "insets/insetcommand.h" // ChangeRefs
37 #include "insets/inseterror.h"
38 #include "insets/updatableinset.h"
40 #include "support/FileInfo.h"
41 #include "support/filetools.h"
42 #include "support/lyxfunctional.h" // equal_1st_in_pair
43 #include "support/types.h"
44 #include "support/lyxalgo.h" // lyx_count
48 extern BufferList bufferlist;
60 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
61 int width, int height)
62 : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
68 BufferView::~BufferView()
75 Buffer * BufferView::buffer() const
77 return pimpl_->buffer_;
81 LyXScreen & BufferView::screen() const
83 return pimpl_->screen();
87 LyXView * BufferView::owner() const
89 return pimpl_->owner_;
93 Painter & BufferView::painter() const
95 return pimpl_->painter();
99 void BufferView::buffer(Buffer * b)
105 void BufferView::reload()
107 string const fn = buffer()->fileName();
108 if (bufferlist.close(buffer()))
109 buffer(bufferlist.loadLyXFile(fn));
113 void BufferView::resize()
115 if (pimpl_->buffer_) {
116 pimpl_->resizeCurrentBuffer();
121 void BufferView::repaint()
127 bool BufferView::fitCursor()
129 return pimpl_->fitCursor();
133 void BufferView::update()
139 void BufferView::updateScrollbar()
141 pimpl_->updateScrollbar();
145 void BufferView::scrollDocView(int value)
147 pimpl_->scrollDocView(value);
151 void BufferView::redoCurrentBuffer()
153 pimpl_->redoCurrentBuffer();
157 bool BufferView::available() const
159 return pimpl_->available();
163 Change const BufferView::getCurrentChange()
165 return pimpl_->getCurrentChange();
169 void BufferView::beforeChange(LyXText * text)
171 pimpl_->beforeChange(text);
175 void BufferView::savePosition(unsigned int i)
177 pimpl_->savePosition(i);
181 void BufferView::restorePosition(unsigned int i)
183 pimpl_->restorePosition(i);
187 bool BufferView::isSavedPosition(unsigned int i)
189 return pimpl_->isSavedPosition(i);
193 void BufferView::update(LyXText * text, UpdateCodes f)
195 pimpl_->update(text, f);
199 void BufferView::switchKeyMap()
201 pimpl_->switchKeyMap();
205 void BufferView::insetUnlock()
207 pimpl_->insetUnlock();
211 int BufferView::workWidth() const
213 return pimpl_->workarea().workWidth();
217 void BufferView::showCursor()
219 pimpl_->showCursor();
223 void BufferView::hideCursor()
225 pimpl_->hideCursor();
229 void BufferView::toggleSelection(bool b)
231 pimpl_->toggleSelection(b);
235 void BufferView::toggleToggle()
237 pimpl_->toggleToggle();
241 void BufferView::center()
247 string const BufferView::getClipboard() const
249 return pimpl_->workarea().getClipboard();
253 void BufferView::stuffClipboard(string const & stuff) const
255 pimpl_->stuffClipboard(stuff);
259 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
260 BufferView::UpdateCodes uc2)
262 return static_cast<BufferView::UpdateCodes>
263 (static_cast<int>(uc1) | static_cast<int>(uc2));
267 bool BufferView::dispatch(FuncRequest const & ev)
269 return pimpl_->dispatch(ev);
273 void BufferView::scroll(int lines)
275 pimpl_->scroll(lines);
279 // Inserts a file into current document
280 bool BufferView::insertLyXFile(string const & filen)
282 // Copyright CHT Software Service GmbH
285 // Insert a LyXformat - file into current buffer
287 // Moved from lyx_cb.C (Lgb)
292 string const fname = MakeAbsPath(filen);
294 // check if file exist
295 FileInfo const fi(fname);
297 if (!fi.readable()) {
298 Alert::alert(_("Error!"),
299 _("Specified file is unreadable: "),
300 MakeDisplayPath(fname, 50));
306 ifstream ifs(fname.c_str());
308 Alert::err_alert(_("Error! Cannot open specified file:"),
309 MakeDisplayPath(fname, 50));
313 int const c = ifs.peek();
321 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
322 res = buffer()->readFile(lex, fname, text->cursor.par());
324 lyxerr[Debug::INFO] << "Will insert file without header"
326 res = buffer()->readLyXformat2(lex, text->cursor.par());
334 bool BufferView::removeAutoInsets()
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();
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(this,
351 cursor_par_prev ? cursor_par_prev : cursor_par_next,
353 // We just removed cursor_par so have to fix the "cursor"
354 if (cursor_par_prev) {
358 cursor_par = cursor_par_prev;
359 cursor_pos = cursor_par->size();
363 cursor_par = cursor_par_next;
366 cursor_par_prev = cursor_par->previous();
367 cursor_par_next = cursor_par->next();
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;
380 if (text->setCursor(this, 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{}
394 // E -> .E -> |.E -> . -> |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{}
404 // E -> |.E -> |. -> . -> .|a
406 cursor_par = cursor_par_next;
408 // cursor_par_prev remains unset
409 cursor_par_next = cursor_par->next();
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";
418 InsetList::iterator pit = par->insetlist.begin();
419 InsetList::iterator pend = par->insetlist.end();
421 while (pit != pend) {
422 if (pit.getInset()->autoDelete()) {
424 pos_type const pos = pit.getPos();
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();
433 if (cursor_par == par) {
434 // update the saved cursor position
435 if (cursor_pos > pos)
444 text->redoParagraph(this);
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(this, text->ownerParagraph(), 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();
463 // restore the original cursor in its corrected location.
464 text->setCursorIntern(this, cursor_par, cursor_pos);
470 void BufferView::insertErrors(TeXErrors & terr)
472 // Save the cursor position
473 LyXCursor cursor = text->cursor;
475 TeXErrors::Errors::const_iterator cit = terr.begin();
476 TeXErrors::Errors::const_iterator end = terr.end();
477 for (; cit != end; ++cit) {
478 string const desctext(cit->error_desc);
479 string const errortext(cit->error_text);
480 string const msgtxt = desctext + '\n' + errortext;
481 int const errorrow = cit->error_in_line;
483 // Insert error string for row number
487 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
488 buffer()->texrow.increasePos(tmpid, tmppos);
491 Paragraph * texrowpar = 0;
494 texrowpar = text->ownerParagraph();
497 texrowpar = buffer()->getParFromID(tmpid);
504 InsetError * new_inset = new InsetError(msgtxt);
505 text->setCursorIntern(this, texrowpar, tmppos);
506 text->insertInset(this, new_inset);
507 text->fullRebreak(this);
510 // Restore the cursor position
511 text->setCursorIntern(this, cursor.par(), cursor.pos());
515 void BufferView::setCursorFromRow(int row)
520 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
522 Paragraph * texrowpar;
525 texrowpar = text->ownerParagraph();
528 texrowpar = buffer()->getParFromID(tmpid);
530 text->setCursor(this, texrowpar, tmppos);
534 bool BufferView::insertInset(Inset * inset, string const & lout)
536 return pimpl_->insertInset(inset, lout);
540 // This is also a buffer property (ale)
541 // Not so sure about that. a goto Label function can not be buffer local, just
542 // think how this will work in a multiwindow/buffer environment, all the
543 // cursors in all the views showing this buffer will move. (Lgb)
544 // OK, then no cursor action should be allowed in buffer. (ale)
545 bool BufferView::gotoLabel(string const & label)
547 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
548 it != buffer()->inset_iterator_end(); ++it) {
549 vector<string> labels = it->getLabelList();
550 if (find(labels.begin(),labels.end(),label)
553 text->setCursor(this, it.getPar(), it.getPos());
554 text->selection.cursor = text->cursor;
555 update(text, BufferView::SELECT|BufferView::FITCUR);
563 void BufferView::undo()
568 owner()->message(_("Undo"));
571 update(text, BufferView::SELECT|BufferView::FITCUR);
573 owner()->message(_("No further undo information"));
575 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
580 void BufferView::redo()
585 owner()->message(_("Redo"));
588 update(text, BufferView::SELECT|BufferView::FITCUR);
590 owner()->message(_("No further redo information"));
592 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
597 void BufferView::copyEnvironment()
600 text->copyEnvironmentType();
601 owner()->message(_("Paragraph environment type copied"));
606 void BufferView::pasteEnvironment()
609 text->pasteEnvironmentType(this);
610 owner()->message(_("Paragraph environment type set"));
611 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
616 // these functions are for the spellchecker
617 WordLangTuple const BufferView::nextWord(float & value)
621 return WordLangTuple();
624 return text->selectNextWordToSpellcheck(this, value);
628 void BufferView::selectLastWord()
633 LyXCursor cur = text->selection.cursor;
636 text->selection.cursor = cur;
637 text->selectSelectedWord(this);
638 toggleSelection(false);
639 update(text, BufferView::SELECT|BufferView::FITCUR);
643 void BufferView::endOfSpellCheck()
645 if (!available()) return;
649 text->selectSelectedWord(this);
650 text->clearSelection();
651 update(text, BufferView::SELECT|BufferView::FITCUR);
655 void BufferView::replaceWord(string const & replacestring)
660 LyXText * tt = getLyXText();
662 update(tt, BufferView::SELECT|BufferView::FITCUR);
664 // clear the selection (if there is any)
665 toggleSelection(false);
666 update(tt, BufferView::SELECT|BufferView::FITCUR);
668 // clear the selection (if there is any)
669 toggleSelection(false);
670 tt->replaceSelectionWithString(this, replacestring);
672 tt->setSelectionRange(this, replacestring.length());
674 // Go back so that replacement string is also spellchecked
675 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
676 tt->cursorLeft(this);
678 update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
680 // End of spellchecker stuff
683 bool BufferView::lockInset(UpdatableInset * inset)
687 // don't relock if we're already locked
688 if (theLockingInset() == inset)
690 if (!theLockingInset()) {
691 // first check if it's the inset under the cursor we want lock
692 // should be most of the time
693 char const c = text->cursor.par()->getChar(text->cursor.pos());
694 if (c == Paragraph::META_INSET) {
695 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
697 theLockingInset(inset);
701 // Then do a deep look of the inset and lock the right one
702 int const id = inset->id();
703 ParagraphList::iterator pit = buffer()->paragraphs.begin();
704 ParagraphList::iterator pend = buffer()->paragraphs.end();
705 for (; pit != pend; ++pit) {
706 InsetList::iterator it = pit->insetlist.begin();
707 InsetList::iterator end = pit->insetlist.end();
708 for (; it != end; ++it) {
709 if (it.getInset() == inset) {
710 text->setCursorIntern(this, &*pit, it.getPos());
711 theLockingInset(inset);
714 if (it.getInset()->getInsetFromID(id)) {
715 text->setCursorIntern(this, &*pit, it.getPos());
716 it.getInset()->edit(this);
717 return theLockingInset()->lockInsetInInset(this, inset);
723 return theLockingInset()->lockInsetInInset(this, inset);
727 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
729 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
730 LyXCursor cursor = text->cursor;
731 Inset * locking_inset = theLockingInset()->getLockingInset();
733 if ((cursor.pos() - 1 >= 0) &&
734 cursor.par()->isInset(cursor.pos() - 1) &&
735 (cursor.par()->getInset(cursor.pos() - 1) ==
737 text->setCursor(this, cursor,
738 cursor.par(), cursor.pos() - 1);
739 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
740 LyXText * txt = getLyXText();
741 if (locking_inset->isTextInset() &&
742 locking_inset->lyxCode() != Inset::ERT_CODE &&
743 (txt->real_current_font.language() !=
744 buffer()->params.language
745 || txt->real_current_font.isVisibleRightToLeft()
746 != buffer()->params.language->RightToLeft()))
747 shape = (txt->real_current_font.isVisibleRightToLeft())
748 ? LyXScreen::REVERSED_L_SHAPE
749 : LyXScreen::L_SHAPE;
750 y += cursor.iy() + theLockingInset()->insetInInsetY();
751 screen().showManualCursor(text, x, y, asc, desc,
757 void BufferView::hideLockedInsetCursor()
759 if (theLockingInset() && available()) {
760 screen().hideCursor();
765 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
767 if (theLockingInset() && available()) {
768 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
769 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
778 int BufferView::unlockInset(UpdatableInset * inset)
782 if (inset && theLockingInset() == inset) {
783 inset->insetUnlock(this);
785 // make sure we update the combo !
786 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
787 // Tell the paragraph dialog that we changed paragraph
788 owner()->getDialogs().updateParagraph();
791 } else if (inset && theLockingInset() &&
792 theLockingInset()->unlockInsetInInset(this, inset)) {
793 // Tell the paragraph dialog that we changed paragraph
794 owner()->getDialogs().updateParagraph();
795 // owner inset has updated the layout combo
803 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
805 if (!theLockingInset())
806 return; // shouldn't happen
807 if (kind == Undo::EDIT) // in this case insets would not be stored!
811 text->cursor.par()->next());
815 void BufferView::updateInset(Inset * inset, bool mark_dirty)
817 pimpl_->updateInset(inset, mark_dirty);
821 bool BufferView::ChangeInsets(Inset::Code code,
822 string const & from, string const & to)
824 bool need_update = false;
825 LyXCursor cursor = text->cursor;
826 LyXCursor tmpcursor = cursor;
827 cursor.par(tmpcursor.par());
828 cursor.pos(tmpcursor.pos());
830 ParIterator end = buffer()->par_iterator_end();
831 for (ParIterator it = buffer()->par_iterator_begin();
833 Paragraph * par = *it;
834 bool changed_inset = false;
835 for (InsetList::iterator it2 = par->insetlist.begin();
836 it2 != par->insetlist.end(); ++it2) {
837 if (it2.getInset()->lyxCode() == code) {
838 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
839 if (inset->getContents() == from) {
840 inset->setContents(to);
841 changed_inset = true;
850 // The test it.size()==1 was needed to prevent crashes.
851 // How to set the cursor corretly when it.size()>1 ??
852 if (it.size() == 1) {
853 text->setCursorIntern(this, par, 0);
854 text->redoParagraphs(this, text->cursor,
855 text->cursor.par()->next());
856 text->fullRebreak(this);
860 text->setCursorIntern(this, cursor.par(), cursor.pos());
865 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
867 // Check if the label 'from' appears more than once
868 vector<string> labels = buffer()->getLabelList();
870 if (lyx::count(labels.begin(), labels.end(), from) > 1)
873 return ChangeInsets(Inset::REF_CODE, from, to);
877 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
879 typedef pair<string, string> StringPair;
881 vector<StringPair> keys;
882 buffer()->fillWithBibKeys(keys);
883 if (count_if(keys.begin(), keys.end(),
884 lyx::equal_1st_in_pair<StringPair>(from))
888 return ChangeInsets(Inset::CITE_CODE, from, to);
892 UpdatableInset * BufferView::theLockingInset() const
894 // If NULL is not allowed we should put an Assert here. (Lgb)
896 return text->the_locking_inset;
901 void BufferView::theLockingInset(UpdatableInset * inset)
903 text->the_locking_inset = inset;
907 LyXText * BufferView::getLyXText() const
909 if (theLockingInset()) {
910 LyXText * txt = theLockingInset()->getLyXText(this, true);
918 LyXText * BufferView::getParentText(Inset * inset) const
920 if (inset->owner()) {
921 LyXText * txt = inset->getLyXText(this);
922 inset = inset->owner();
923 while (inset && inset->getLyXText(this) == txt)
924 inset = inset->owner();
926 return inset->getLyXText(this);
932 Language const * BufferView::getParentLanguage(Inset * inset) const
934 LyXText * text = getParentText(inset);
935 return text->cursor.par()->getFontSettings(buffer()->params,
936 text->cursor.pos()).language();
940 Encoding const * BufferView::getEncoding() const
942 LyXText * t = getLyXText();
946 LyXCursor const & c= t->cursor;
947 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
948 return font.language()->encoding();
952 void BufferView::haveSelection(bool sel)
954 pimpl_->workarea().haveSelection(sel);
958 int BufferView::workHeight() const
960 return pimpl_->workarea().workHeight();