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 "ParagraphParameters.h"
18 #include "WordLangTuple.h"
20 #include "bufferlist.h"
23 #include "iterators.h"
25 #include "lyxcursor.h"
28 #include "undo_funcs.h"
31 #include "frontends/Alert.h"
32 #include "frontends/Dialogs.h"
33 #include "frontends/LyXView.h"
34 #include "frontends/WorkArea.h"
35 #include "frontends/screen.h"
37 #include "insets/insetcommand.h" // ChangeRefs
38 #include "insets/inseterror.h"
39 #include "insets/updatableinset.h"
41 #include "support/FileInfo.h"
42 #include "support/filetools.h"
43 #include "support/lyxfunctional.h" // equal_1st_in_pair
44 #include "support/types.h"
45 #include "support/lyxalgo.h" // lyx_count
46 #include "BoostFormat.h"
51 extern BufferList bufferlist;
63 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
64 int width, int height)
65 : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
71 BufferView::~BufferView()
78 Buffer * BufferView::buffer() const
80 return pimpl_->buffer_;
84 LyXScreen & BufferView::screen() const
86 return pimpl_->screen();
90 LyXView * BufferView::owner() const
92 return pimpl_->owner_;
96 Painter & BufferView::painter() const
98 return pimpl_->painter();
102 void BufferView::buffer(Buffer * b)
108 void BufferView::reload()
110 string const fn = buffer()->fileName();
111 if (bufferlist.close(buffer(), false))
112 buffer(bufferlist.loadLyXFile(fn));
116 void BufferView::resize()
118 if (pimpl_->buffer_) {
119 pimpl_->resizeCurrentBuffer();
124 void BufferView::repaint()
130 bool BufferView::fitCursor()
132 return pimpl_->fitCursor();
136 void BufferView::update()
142 void BufferView::updateScrollbar()
144 pimpl_->updateScrollbar();
148 void BufferView::scrollDocView(int value)
150 pimpl_->scrollDocView(value);
154 void BufferView::redoCurrentBuffer()
156 pimpl_->redoCurrentBuffer();
160 bool BufferView::available() const
162 return pimpl_->available();
166 Change const BufferView::getCurrentChange()
168 return pimpl_->getCurrentChange();
172 void BufferView::beforeChange(LyXText * text)
174 pimpl_->beforeChange(text);
178 void BufferView::savePosition(unsigned int i)
180 pimpl_->savePosition(i);
184 void BufferView::restorePosition(unsigned int i)
186 pimpl_->restorePosition(i);
190 bool BufferView::isSavedPosition(unsigned int i)
192 return pimpl_->isSavedPosition(i);
196 void BufferView::update(LyXText * text, UpdateCodes f)
198 pimpl_->update(text, f);
202 void BufferView::update(UpdateCodes f)
208 void BufferView::switchKeyMap()
210 pimpl_->switchKeyMap();
214 void BufferView::insetUnlock()
216 pimpl_->insetUnlock();
220 int BufferView::workWidth() const
222 return pimpl_->workarea().workWidth();
226 void BufferView::showCursor()
228 pimpl_->showCursor();
232 void BufferView::hideCursor()
234 pimpl_->hideCursor();
238 void BufferView::toggleSelection(bool b)
240 pimpl_->toggleSelection(b);
244 void BufferView::toggleToggle()
246 pimpl_->toggleToggle();
250 void BufferView::center()
256 string const BufferView::getClipboard() const
258 return pimpl_->workarea().getClipboard();
262 void BufferView::stuffClipboard(string const & stuff) const
264 pimpl_->stuffClipboard(stuff);
268 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
269 BufferView::UpdateCodes uc2)
271 return static_cast<BufferView::UpdateCodes>
272 (static_cast<int>(uc1) | static_cast<int>(uc2));
276 bool BufferView::dispatch(FuncRequest const & ev)
278 return pimpl_->dispatch(ev);
282 void BufferView::scroll(int lines)
284 pimpl_->scroll(lines);
288 // Inserts a file into current document
289 bool BufferView::insertLyXFile(string const & filen)
291 // Copyright CHT Software Service GmbH
294 // Insert a LyXformat - file into current buffer
296 // Moved from lyx_cb.C (Lgb)
301 string const fname = MakeAbsPath(filen);
303 // check if file exist
304 FileInfo const fi(fname);
306 if (!fi.readable()) {
307 string const file = MakeDisplayPath(fname, 50);
309 boost::format fmt(_("The specified document\n%1$s\ncould not be read."));
311 string text = fmt.str();
313 string text = _("The specified document\n");
314 text += file + _(" could not be read.");
316 Alert::error(_("Could not read document"), text);
322 ifstream ifs(fname.c_str());
324 string const error = strerror(errno);
325 string const file = MakeDisplayPath(fname, 50);
327 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
330 string text = fmt.str();
332 string text = _("Could not open the specified document\n");
333 text += file + _(" due to the error: ");
336 Alert::error(_("Could not open file"), text);
340 int const c = ifs.peek();
348 // FIXME: huh ? No we won't !
349 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
350 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
352 lyxerr[Debug::INFO] << "Will insert file without header"
354 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
362 bool BufferView::removeAutoInsets()
364 // keep track of which pos and par the cursor was on
365 Paragraph * cursor_par = text->cursor.par();
366 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
367 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
368 pos_type cursor_pos = text->cursor.pos();
372 // Trap the deletion of the paragraph the cursor is in.
373 // Iterate until we find a paragraph that won't be immediately deleted.
374 // In reality this should mean we only execute the body of the while
375 // loop once at most. However for safety we iterate rather than just
376 // make this an if () conditional.
377 while ((cursor_par_prev || cursor_par_next)
379 cursor_par_prev ? cursor_par_prev : cursor_par_next,
381 // We just removed cursor_par so have to fix the "cursor"
382 if (cursor_par_prev) {
386 cursor_par = cursor_par_prev;
387 cursor_pos = cursor_par->size();
391 cursor_par = cursor_par_next;
394 cursor_par_prev = cursor_par->previous();
395 cursor_par_next = cursor_par->next();
398 // Iterate through the paragraphs removing autoDelete insets as we go.
399 // If the paragraph ends up empty after all the autoDelete insets are
400 // removed that paragraph will be removed by the next setCursor() call.
401 ParIterator it = buffer()->par_iterator_begin();
402 ParIterator end = buffer()->par_iterator_end();
403 for (; it != end; ++it) {
404 Paragraph * par = *it;
405 Paragraph * par_prev = par ? par->previous() : 0;
406 bool removed = false;
408 if (text->setCursor(par, 0)
409 && cursor_par == par_prev) {
410 // The previous setCursor line was deleted and that
411 // was the cursor_par line. This can only happen if an
412 // error box was the sole item on cursor_par.
413 // It is possible for cursor_par_prev to be stray if
414 // the line it pointed to only had a error box on it
415 // so we have to set it to a known correct value.
416 // This is often the same value it already had.
417 cursor_par_prev = par->previous();
418 if (cursor_par_prev) {
419 // '|' = par, '.' = cursor_par, 'E' = error box
420 // First step below may occur before while{}
422 // E -> .E -> |.E -> . -> |b
425 cursor_par = cursor_par_prev;
426 cursor_pos = cursor_par_prev->size();
427 cursor_par_prev = cursor_par->previous();
428 // cursor_par_next remains the same
429 } else if (cursor_par_next) {
430 // First step below may occur before while{}
432 // E -> |.E -> |. -> . -> .|a
434 cursor_par = cursor_par_next;
436 // cursor_par_prev remains unset
437 cursor_par_next = cursor_par->next();
439 // I can't find a way to trigger this
440 // so it should be unreachable code
441 // unless the buffer is corrupted.
442 lyxerr << "BufferView::removeAutoInsets() is bad\n";
446 InsetList::iterator pit = par->insetlist.begin();
447 InsetList::iterator pend = par->insetlist.end();
449 while (pit != pend) {
450 if (pit.getInset()->autoDelete()) {
452 pos_type const pos = pit.getPos();
455 // We just invalidated par's inset iterators so
456 // we get the next valid iterator position
457 pit = par->insetlist.insetIterator(pos);
458 // and ensure we have a valid end iterator.
459 pend = par->insetlist.end();
461 if (cursor_par == par) {
462 // update the saved cursor position
463 if (cursor_pos > pos)
472 text->redoParagraph();
476 // It is possible that the last line is empty if it was cursor_par
477 // and/or only had an error inset on it. So we set the cursor to the
478 // start of the doc to force its removal and ensure a valid saved cursor
479 if (text->setCursor(text->ownerParagraph(), 0)
480 && 0 == cursor_par_next) {
481 cursor_par = cursor_par_prev;
482 cursor_pos = cursor_par->size();
483 } else if (cursor_pos > cursor_par->size()) {
484 // Some C-Enter lines were removed by the setCursor call which
485 // then invalidated cursor_pos. It could still be "wrong" because
486 // the cursor may appear to have jumped but since we collapsed
487 // some C-Enter lines this should be a reasonable compromise.
488 cursor_pos = cursor_par->size();
491 // restore the original cursor in its corrected location.
492 text->setCursorIntern(cursor_par, cursor_pos);
498 void BufferView::insertErrors(TeXErrors & terr)
500 // Save the cursor position
501 LyXCursor cursor = text->cursor;
503 TeXErrors::Errors::const_iterator cit = terr.begin();
504 TeXErrors::Errors::const_iterator end = terr.end();
505 for (; cit != end; ++cit) {
506 string const desctext(cit->error_desc);
507 string const errortext(cit->error_text);
508 string const msgtxt = desctext + '\n' + errortext;
509 int const errorrow = cit->error_in_line;
511 // Insert error string for row number
515 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
516 buffer()->texrow.increasePos(tmpid, tmppos);
519 Paragraph * texrowpar = 0;
522 texrowpar = text->ownerParagraph();
525 texrowpar = buffer()->getParFromID(tmpid);
532 InsetError * new_inset = new InsetError(msgtxt);
533 text->setCursorIntern(texrowpar, tmppos);
534 text->insertInset(new_inset);
538 // Restore the cursor position
539 text->setCursorIntern(cursor.par(), cursor.pos());
543 void BufferView::setCursorFromRow(int row)
548 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
550 Paragraph * texrowpar;
553 texrowpar = text->ownerParagraph();
556 texrowpar = buffer()->getParFromID(tmpid);
558 text->setCursor(texrowpar, tmppos);
562 bool BufferView::insertInset(Inset * inset, string const & lout)
564 return pimpl_->insertInset(inset, lout);
568 void BufferView::gotoLabel(string const & label)
570 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
571 it != buffer()->inset_iterator_end(); ++it) {
572 vector<string> labels = it->getLabelList();
573 if (find(labels.begin(),labels.end(),label)
576 text->setCursor(it.getPar(), it.getPos());
577 text->selection.cursor = text->cursor;
578 update(text, BufferView::SELECT);
585 void BufferView::undo()
590 owner()->message(_("Undo"));
593 update(text, BufferView::SELECT);
595 owner()->message(_("No further undo information"));
597 update(text, BufferView::SELECT);
602 void BufferView::redo()
607 owner()->message(_("Redo"));
610 update(text, BufferView::SELECT);
612 owner()->message(_("No further redo information"));
614 update(text, BufferView::SELECT);
619 void BufferView::copyEnvironment()
622 text->copyEnvironmentType();
623 owner()->message(_("Paragraph environment type copied"));
628 void BufferView::pasteEnvironment()
631 text->pasteEnvironmentType();
632 owner()->message(_("Paragraph environment type set"));
633 update(text, BufferView::SELECT);
638 // these functions are for the spellchecker
639 WordLangTuple const BufferView::nextWord(float & value)
643 return WordLangTuple();
646 return text->selectNextWordToSpellcheck(value);
650 void BufferView::selectLastWord()
655 LyXCursor cur = text->selection.cursor;
658 text->selection.cursor = cur;
659 text->selectSelectedWord();
660 toggleSelection(false);
661 update(text, BufferView::SELECT);
665 void BufferView::endOfSpellCheck()
667 if (!available()) return;
671 text->selectSelectedWord();
672 text->clearSelection();
673 update(text, BufferView::SELECT);
677 void BufferView::replaceWord(string const & replacestring)
682 LyXText * tt = getLyXText();
684 update(tt, BufferView::SELECT);
686 // clear the selection (if there is any)
687 toggleSelection(false);
688 update(tt, BufferView::SELECT);
690 // clear the selection (if there is any)
691 toggleSelection(false);
692 tt->replaceSelectionWithString(replacestring);
694 tt->setSelectionRange(replacestring.length());
696 // Go back so that replacement string is also spellchecked
697 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
698 tt->cursorLeft(this);
700 update(tt, BufferView::SELECT);
702 // FIXME: should be done through LFUN
703 buffer()->markDirty();
706 // End of spellchecker stuff
709 bool BufferView::lockInset(UpdatableInset * inset)
713 // don't relock if we're already locked
714 if (theLockingInset() == inset)
716 if (!theLockingInset()) {
717 // first check if it's the inset under the cursor we want lock
718 // should be most of the time
719 char const c = text->cursor.par()->getChar(text->cursor.pos());
720 if (c == Paragraph::META_INSET) {
721 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
723 theLockingInset(inset);
727 // Then do a deep look of the inset and lock the right one
728 int const id = inset->id();
729 ParagraphList::iterator pit = buffer()->paragraphs.begin();
730 ParagraphList::iterator pend = buffer()->paragraphs.end();
731 for (; pit != pend; ++pit) {
732 InsetList::iterator it = pit->insetlist.begin();
733 InsetList::iterator end = pit->insetlist.end();
734 for (; it != end; ++it) {
735 if (it.getInset() == inset) {
736 text->setCursorIntern(&*pit, it.getPos());
737 theLockingInset(inset);
740 if (it.getInset()->getInsetFromID(id)) {
741 text->setCursorIntern(&*pit, it.getPos());
742 it.getInset()->edit(this);
743 return theLockingInset()->lockInsetInInset(this, inset);
749 return theLockingInset()->lockInsetInInset(this, inset);
753 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
755 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
756 LyXCursor cursor = text->cursor;
757 Inset * locking_inset = theLockingInset()->getLockingInset();
759 if ((cursor.pos() - 1 >= 0) &&
760 cursor.par()->isInset(cursor.pos() - 1) &&
761 (cursor.par()->getInset(cursor.pos() - 1) ==
763 text->setCursor(cursor,
764 cursor.par(), cursor.pos() - 1);
765 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
766 LyXText * txt = getLyXText();
767 if (locking_inset->isTextInset() &&
768 locking_inset->lyxCode() != Inset::ERT_CODE &&
769 (txt->real_current_font.language() !=
770 buffer()->params.language
771 || txt->real_current_font.isVisibleRightToLeft()
772 != buffer()->params.language->RightToLeft()))
773 shape = (txt->real_current_font.isVisibleRightToLeft())
774 ? LyXScreen::REVERSED_L_SHAPE
775 : LyXScreen::L_SHAPE;
776 y += cursor.iy() + theLockingInset()->insetInInsetY();
777 screen().showManualCursor(text, x, y, asc, desc,
783 void BufferView::hideLockedInsetCursor()
785 if (theLockingInset() && available()) {
786 screen().hideCursor();
791 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
793 if (theLockingInset() && available()) {
794 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
795 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
804 int BufferView::unlockInset(UpdatableInset * inset)
808 if (inset && theLockingInset() == inset) {
809 inset->insetUnlock(this);
811 // make sure we update the combo !
812 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
813 // Tell the paragraph dialog that we changed paragraph
814 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
817 } else if (inset && theLockingInset() &&
818 theLockingInset()->unlockInsetInInset(this, inset)) {
819 // Tell the paragraph dialog that we changed paragraph
820 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
821 // owner inset has updated the layout combo
829 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
831 if (!theLockingInset())
832 return; // shouldn't happen
833 if (kind == Undo::EDIT) // in this case insets would not be stored!
837 text->cursor.par()->next());
841 void BufferView::updateInset(Inset * inset)
843 pimpl_->updateInset(inset);
847 bool BufferView::ChangeInsets(Inset::Code code,
848 string const & from, string const & to)
850 bool need_update = false;
851 LyXCursor cursor = text->cursor;
852 LyXCursor tmpcursor = cursor;
853 cursor.par(tmpcursor.par());
854 cursor.pos(tmpcursor.pos());
856 ParIterator end = buffer()->par_iterator_end();
857 for (ParIterator it = buffer()->par_iterator_begin();
859 Paragraph * par = *it;
860 bool changed_inset = false;
861 for (InsetList::iterator it2 = par->insetlist.begin();
862 it2 != par->insetlist.end(); ++it2) {
863 if (it2.getInset()->lyxCode() == code) {
864 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
865 if (inset->getContents() == from) {
866 inset->setContents(to);
867 changed_inset = true;
876 // The test it.size()==1 was needed to prevent crashes.
877 // How to set the cursor corretly when it.size()>1 ??
878 if (it.size() == 1) {
879 text->setCursorIntern(par, 0);
880 text->redoParagraphs(text->cursor,
881 text->cursor.par()->next());
886 text->setCursorIntern(cursor.par(), cursor.pos());
891 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
893 // Check if the label 'from' appears more than once
894 vector<string> labels = buffer()->getLabelList();
896 if (lyx::count(labels.begin(), labels.end(), from) > 1)
899 return ChangeInsets(Inset::REF_CODE, from, to);
903 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
905 typedef pair<string, string> StringPair;
907 vector<StringPair> keys;
908 buffer()->fillWithBibKeys(keys);
909 if (count_if(keys.begin(), keys.end(),
910 lyx::equal_1st_in_pair<StringPair>(from))
914 return ChangeInsets(Inset::CITE_CODE, from, to);
918 UpdatableInset * BufferView::theLockingInset() const
920 // If NULL is not allowed we should put an Assert here. (Lgb)
922 return text->the_locking_inset;
927 void BufferView::theLockingInset(UpdatableInset * inset)
929 text->the_locking_inset = inset;
933 LyXText * BufferView::getLyXText() const
935 if (theLockingInset()) {
936 LyXText * txt = theLockingInset()->getLyXText(this, true);
944 LyXText * BufferView::getParentText(Inset * inset) const
946 if (inset->owner()) {
947 LyXText * txt = inset->getLyXText(this);
948 inset = inset->owner();
949 while (inset && inset->getLyXText(this) == txt)
950 inset = inset->owner();
952 return inset->getLyXText(this);
958 Language const * BufferView::getParentLanguage(Inset * inset) const
960 LyXText * text = getParentText(inset);
961 return text->cursor.par()->getFontSettings(buffer()->params,
962 text->cursor.pos()).language();
966 Encoding const * BufferView::getEncoding() const
968 LyXText * t = getLyXText();
972 LyXCursor const & c= t->cursor;
973 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
974 return font.language()->encoding();
978 void BufferView::haveSelection(bool sel)
980 pimpl_->workarea().haveSelection(sel);
984 int BufferView::workHeight() const
986 return pimpl_->workarea().workHeight();