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"
50 extern BufferList bufferlist;
62 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
63 int width, int height)
64 : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
70 BufferView::~BufferView()
77 Buffer * BufferView::buffer() const
79 return pimpl_->buffer_;
83 LyXScreen & BufferView::screen() const
85 return pimpl_->screen();
89 LyXView * BufferView::owner() const
91 return pimpl_->owner_;
95 Painter & BufferView::painter() const
97 return pimpl_->painter();
101 void BufferView::buffer(Buffer * b)
107 void BufferView::reload()
109 string const fn = buffer()->fileName();
110 if (bufferlist.close(buffer(), false))
111 buffer(bufferlist.loadLyXFile(fn));
115 void BufferView::resize()
117 if (pimpl_->buffer_) {
118 pimpl_->resizeCurrentBuffer();
123 void BufferView::repaint()
129 bool BufferView::fitCursor()
131 return pimpl_->fitCursor();
135 void BufferView::update()
141 void BufferView::updateScrollbar()
143 pimpl_->updateScrollbar();
147 void BufferView::scrollDocView(int value)
149 pimpl_->scrollDocView(value);
153 void BufferView::redoCurrentBuffer()
155 pimpl_->redoCurrentBuffer();
159 bool BufferView::available() const
161 return pimpl_->available();
165 Change const BufferView::getCurrentChange()
167 return pimpl_->getCurrentChange();
171 void BufferView::beforeChange(LyXText * text)
173 pimpl_->beforeChange(text);
177 void BufferView::savePosition(unsigned int i)
179 pimpl_->savePosition(i);
183 void BufferView::restorePosition(unsigned int i)
185 pimpl_->restorePosition(i);
189 bool BufferView::isSavedPosition(unsigned int i)
191 return pimpl_->isSavedPosition(i);
195 void BufferView::update(LyXText * text, UpdateCodes f)
197 pimpl_->update(text, f);
201 void BufferView::update(UpdateCodes f)
207 void BufferView::switchKeyMap()
209 pimpl_->switchKeyMap();
213 void BufferView::insetUnlock()
215 pimpl_->insetUnlock();
219 int BufferView::workWidth() const
221 return pimpl_->workarea().workWidth();
225 void BufferView::showCursor()
227 pimpl_->showCursor();
231 void BufferView::hideCursor()
233 pimpl_->hideCursor();
237 void BufferView::toggleSelection(bool b)
239 pimpl_->toggleSelection(b);
243 void BufferView::toggleToggle()
245 pimpl_->toggleToggle();
249 void BufferView::center()
255 string const BufferView::getClipboard() const
257 return pimpl_->workarea().getClipboard();
261 void BufferView::stuffClipboard(string const & stuff) const
263 pimpl_->stuffClipboard(stuff);
267 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
268 BufferView::UpdateCodes uc2)
270 return static_cast<BufferView::UpdateCodes>
271 (static_cast<int>(uc1) | static_cast<int>(uc2));
275 bool BufferView::dispatch(FuncRequest const & ev)
277 return pimpl_->dispatch(ev);
281 void BufferView::scroll(int lines)
283 pimpl_->scroll(lines);
287 // Inserts a file into current document
288 bool BufferView::insertLyXFile(string const & filen)
290 // Copyright CHT Software Service GmbH
293 // Insert a LyXformat - file into current buffer
295 // Moved from lyx_cb.C (Lgb)
300 string const fname = MakeAbsPath(filen);
302 // check if file exist
303 FileInfo const fi(fname);
305 if (!fi.readable()) {
306 string const file = MakeDisplayPath(fname, 50);
308 boost::format fmt(_("The specified document\n%1$s\ncould not be read."));
310 string text = fmt.str();
312 string text = _("The specified document\n");
313 text += file + _(" could not be read.");
315 Alert::error(_("Could not read document"), text);
321 ifstream ifs(fname.c_str());
323 string const error = strerror(errno);
324 string const file = MakeDisplayPath(fname, 50);
326 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
329 string text = fmt.str();
331 string text = _("Could not open the specified document\n");
332 text += file + _(" due to the error: ");
335 Alert::error(_("Could not open file"), text);
339 int const c = ifs.peek();
347 // FIXME: huh ? No we won't !
348 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
349 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
351 lyxerr[Debug::INFO] << "Will insert file without header"
353 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
361 bool BufferView::removeAutoInsets()
363 // keep track of which pos and par the cursor was on
364 Paragraph * cursor_par = text->cursor.par();
365 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
366 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
367 pos_type cursor_pos = text->cursor.pos();
371 // Trap the deletion of the paragraph the cursor is in.
372 // Iterate until we find a paragraph that won't be immediately deleted.
373 // In reality this should mean we only execute the body of the while
374 // loop once at most. However for safety we iterate rather than just
375 // make this an if () conditional.
376 while ((cursor_par_prev || cursor_par_next)
378 cursor_par_prev ? cursor_par_prev : cursor_par_next,
380 // We just removed cursor_par so have to fix the "cursor"
381 if (cursor_par_prev) {
385 cursor_par = cursor_par_prev;
386 cursor_pos = cursor_par->size();
390 cursor_par = cursor_par_next;
393 cursor_par_prev = cursor_par->previous();
394 cursor_par_next = cursor_par->next();
397 // Iterate through the paragraphs removing autoDelete insets as we go.
398 // If the paragraph ends up empty after all the autoDelete insets are
399 // removed that paragraph will be removed by the next setCursor() call.
400 ParIterator it = buffer()->par_iterator_begin();
401 ParIterator end = buffer()->par_iterator_end();
402 for (; it != end; ++it) {
403 Paragraph * par = *it;
404 Paragraph * par_prev = par ? par->previous() : 0;
405 bool removed = false;
407 if (text->setCursor(par, 0)
408 && cursor_par == par_prev) {
409 // The previous setCursor line was deleted and that
410 // was the cursor_par line. This can only happen if an
411 // error box was the sole item on cursor_par.
412 // It is possible for cursor_par_prev to be stray if
413 // the line it pointed to only had a error box on it
414 // so we have to set it to a known correct value.
415 // This is often the same value it already had.
416 cursor_par_prev = par->previous();
417 if (cursor_par_prev) {
418 // '|' = par, '.' = cursor_par, 'E' = error box
419 // First step below may occur before while{}
421 // E -> .E -> |.E -> . -> |b
424 cursor_par = cursor_par_prev;
425 cursor_pos = cursor_par_prev->size();
426 cursor_par_prev = cursor_par->previous();
427 // cursor_par_next remains the same
428 } else if (cursor_par_next) {
429 // First step below may occur before while{}
431 // E -> |.E -> |. -> . -> .|a
433 cursor_par = cursor_par_next;
435 // cursor_par_prev remains unset
436 cursor_par_next = cursor_par->next();
438 // I can't find a way to trigger this
439 // so it should be unreachable code
440 // unless the buffer is corrupted.
441 lyxerr << "BufferView::removeAutoInsets() is bad\n";
445 InsetList::iterator pit = par->insetlist.begin();
446 InsetList::iterator pend = par->insetlist.end();
448 while (pit != pend) {
449 if (pit.getInset()->autoDelete()) {
451 pos_type const pos = pit.getPos();
454 // We just invalidated par's inset iterators so
455 // we get the next valid iterator position
456 pit = par->insetlist.insetIterator(pos);
457 // and ensure we have a valid end iterator.
458 pend = par->insetlist.end();
460 if (cursor_par == par) {
461 // update the saved cursor position
462 if (cursor_pos > pos)
471 text->redoParagraph();
475 // It is possible that the last line is empty if it was cursor_par
476 // and/or only had an error inset on it. So we set the cursor to the
477 // start of the doc to force its removal and ensure a valid saved cursor
478 if (text->setCursor(text->ownerParagraph(), 0)
479 && 0 == cursor_par_next) {
480 cursor_par = cursor_par_prev;
481 cursor_pos = cursor_par->size();
482 } else if (cursor_pos > cursor_par->size()) {
483 // Some C-Enter lines were removed by the setCursor call which
484 // then invalidated cursor_pos. It could still be "wrong" because
485 // the cursor may appear to have jumped but since we collapsed
486 // some C-Enter lines this should be a reasonable compromise.
487 cursor_pos = cursor_par->size();
490 // restore the original cursor in its corrected location.
491 text->setCursorIntern(cursor_par, cursor_pos);
497 void BufferView::insertErrors(TeXErrors & terr)
499 // Save the cursor position
500 LyXCursor cursor = text->cursor;
502 TeXErrors::Errors::const_iterator cit = terr.begin();
503 TeXErrors::Errors::const_iterator end = terr.end();
504 for (; cit != end; ++cit) {
505 string const desctext(cit->error_desc);
506 string const errortext(cit->error_text);
507 string const msgtxt = desctext + '\n' + errortext;
508 int const errorrow = cit->error_in_line;
510 // Insert error string for row number
514 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
515 buffer()->texrow.increasePos(tmpid, tmppos);
518 Paragraph * texrowpar = 0;
521 texrowpar = text->ownerParagraph();
524 texrowpar = buffer()->getParFromID(tmpid);
531 InsetError * new_inset = new InsetError(msgtxt);
532 text->setCursorIntern(texrowpar, tmppos);
533 text->insertInset(new_inset);
537 // Restore the cursor position
538 text->setCursorIntern(cursor.par(), cursor.pos());
542 void BufferView::setCursorFromRow(int row)
547 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
549 Paragraph * texrowpar;
552 texrowpar = text->ownerParagraph();
555 texrowpar = buffer()->getParFromID(tmpid);
557 text->setCursor(texrowpar, tmppos);
561 bool BufferView::insertInset(Inset * inset, string const & lout)
563 return pimpl_->insertInset(inset, lout);
567 void BufferView::gotoLabel(string const & label)
569 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
570 it != buffer()->inset_iterator_end(); ++it) {
571 vector<string> labels = it->getLabelList();
572 if (find(labels.begin(),labels.end(),label)
575 text->setCursor(it.getPar(), it.getPos());
576 text->selection.cursor = text->cursor;
577 update(text, BufferView::SELECT);
584 void BufferView::undo()
589 owner()->message(_("Undo"));
592 update(text, BufferView::SELECT);
594 owner()->message(_("No further undo information"));
596 update(text, BufferView::SELECT);
601 void BufferView::redo()
606 owner()->message(_("Redo"));
609 update(text, BufferView::SELECT);
611 owner()->message(_("No further redo information"));
613 update(text, BufferView::SELECT);
618 void BufferView::copyEnvironment()
621 text->copyEnvironmentType();
622 owner()->message(_("Paragraph environment type copied"));
627 void BufferView::pasteEnvironment()
630 text->pasteEnvironmentType();
631 owner()->message(_("Paragraph environment type set"));
632 update(text, BufferView::SELECT);
637 // these functions are for the spellchecker
638 WordLangTuple const BufferView::nextWord(float & value)
642 return WordLangTuple();
645 return text->selectNextWordToSpellcheck(value);
649 void BufferView::selectLastWord()
654 LyXCursor cur = text->selection.cursor;
657 text->selection.cursor = cur;
658 text->selectSelectedWord();
659 toggleSelection(false);
660 update(text, BufferView::SELECT);
664 void BufferView::endOfSpellCheck()
666 if (!available()) return;
670 text->selectSelectedWord();
671 text->clearSelection();
672 update(text, BufferView::SELECT);
676 void BufferView::replaceWord(string const & replacestring)
681 LyXText * tt = getLyXText();
683 update(tt, BufferView::SELECT);
685 // clear the selection (if there is any)
686 toggleSelection(false);
687 update(tt, BufferView::SELECT);
689 // clear the selection (if there is any)
690 toggleSelection(false);
691 tt->replaceSelectionWithString(replacestring);
693 tt->setSelectionRange(replacestring.length());
695 // Go back so that replacement string is also spellchecked
696 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
697 tt->cursorLeft(this);
699 update(tt, BufferView::SELECT);
701 // FIXME: should be done through LFUN
702 buffer()->markDirty();
705 // End of spellchecker stuff
708 bool BufferView::lockInset(UpdatableInset * inset)
712 // don't relock if we're already locked
713 if (theLockingInset() == inset)
715 if (!theLockingInset()) {
716 // first check if it's the inset under the cursor we want lock
717 // should be most of the time
718 char const c = text->cursor.par()->getChar(text->cursor.pos());
719 if (c == Paragraph::META_INSET) {
720 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
722 theLockingInset(inset);
726 // Then do a deep look of the inset and lock the right one
727 int const id = inset->id();
728 ParagraphList::iterator pit = buffer()->paragraphs.begin();
729 ParagraphList::iterator pend = buffer()->paragraphs.end();
730 for (; pit != pend; ++pit) {
731 InsetList::iterator it = pit->insetlist.begin();
732 InsetList::iterator end = pit->insetlist.end();
733 for (; it != end; ++it) {
734 if (it.getInset() == inset) {
735 text->setCursorIntern(&*pit, it.getPos());
736 theLockingInset(inset);
739 if (it.getInset()->getInsetFromID(id)) {
740 text->setCursorIntern(&*pit, it.getPos());
741 it.getInset()->edit(this);
742 return theLockingInset()->lockInsetInInset(this, inset);
748 return theLockingInset()->lockInsetInInset(this, inset);
752 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
754 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
755 LyXCursor cursor = text->cursor;
756 Inset * locking_inset = theLockingInset()->getLockingInset();
758 if ((cursor.pos() - 1 >= 0) &&
759 cursor.par()->isInset(cursor.pos() - 1) &&
760 (cursor.par()->getInset(cursor.pos() - 1) ==
762 text->setCursor(cursor,
763 cursor.par(), cursor.pos() - 1);
764 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
765 LyXText * txt = getLyXText();
766 if (locking_inset->isTextInset() &&
767 locking_inset->lyxCode() != Inset::ERT_CODE &&
768 (txt->real_current_font.language() !=
769 buffer()->params.language
770 || txt->real_current_font.isVisibleRightToLeft()
771 != buffer()->params.language->RightToLeft()))
772 shape = (txt->real_current_font.isVisibleRightToLeft())
773 ? LyXScreen::REVERSED_L_SHAPE
774 : LyXScreen::L_SHAPE;
775 y += cursor.iy() + theLockingInset()->insetInInsetY();
776 screen().showManualCursor(text, x, y, asc, desc,
782 void BufferView::hideLockedInsetCursor()
784 if (theLockingInset() && available()) {
785 screen().hideCursor();
790 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
792 if (theLockingInset() && available()) {
793 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
794 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
803 int BufferView::unlockInset(UpdatableInset * inset)
807 if (inset && theLockingInset() == inset) {
808 inset->insetUnlock(this);
810 // make sure we update the combo !
811 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
812 // Tell the paragraph dialog that we changed paragraph
813 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
816 } else if (inset && theLockingInset() &&
817 theLockingInset()->unlockInsetInInset(this, inset)) {
818 // Tell the paragraph dialog that we changed paragraph
819 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
820 // owner inset has updated the layout combo
828 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
830 if (!theLockingInset())
831 return; // shouldn't happen
832 if (kind == Undo::EDIT) // in this case insets would not be stored!
836 text->cursor.par()->next());
840 void BufferView::updateInset(Inset * inset)
842 pimpl_->updateInset(inset);
846 bool BufferView::ChangeInsets(Inset::Code code,
847 string const & from, string const & to)
849 bool need_update = false;
850 LyXCursor cursor = text->cursor;
851 LyXCursor tmpcursor = cursor;
852 cursor.par(tmpcursor.par());
853 cursor.pos(tmpcursor.pos());
855 ParIterator end = buffer()->par_iterator_end();
856 for (ParIterator it = buffer()->par_iterator_begin();
858 Paragraph * par = *it;
859 bool changed_inset = false;
860 for (InsetList::iterator it2 = par->insetlist.begin();
861 it2 != par->insetlist.end(); ++it2) {
862 if (it2.getInset()->lyxCode() == code) {
863 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
864 if (inset->getContents() == from) {
865 inset->setContents(to);
866 changed_inset = true;
875 // The test it.size()==1 was needed to prevent crashes.
876 // How to set the cursor corretly when it.size()>1 ??
877 if (it.size() == 1) {
878 text->setCursorIntern(par, 0);
879 text->redoParagraphs(text->cursor,
880 text->cursor.par()->next());
885 text->setCursorIntern(cursor.par(), cursor.pos());
890 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
892 // Check if the label 'from' appears more than once
893 vector<string> labels = buffer()->getLabelList();
895 if (lyx::count(labels.begin(), labels.end(), from) > 1)
898 return ChangeInsets(Inset::REF_CODE, from, to);
902 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
904 typedef pair<string, string> StringPair;
906 vector<StringPair> keys;
907 buffer()->fillWithBibKeys(keys);
908 if (count_if(keys.begin(), keys.end(),
909 lyx::equal_1st_in_pair<StringPair>(from))
913 return ChangeInsets(Inset::CITE_CODE, from, to);
917 UpdatableInset * BufferView::theLockingInset() const
919 // If NULL is not allowed we should put an Assert here. (Lgb)
921 return text->the_locking_inset;
926 void BufferView::theLockingInset(UpdatableInset * inset)
928 text->the_locking_inset = inset;
932 LyXText * BufferView::getLyXText() const
934 if (theLockingInset()) {
935 LyXText * txt = theLockingInset()->getLyXText(this, true);
943 LyXText * BufferView::getParentText(Inset * inset) const
945 if (inset->owner()) {
946 LyXText * txt = inset->getLyXText(this);
947 inset = inset->owner();
948 while (inset && inset->getLyXText(this) == txt)
949 inset = inset->owner();
951 return inset->getLyXText(this);
957 Language const * BufferView::getParentLanguage(Inset * inset) const
959 LyXText * text = getParentText(inset);
960 return text->cursor.par()->getFontSettings(buffer()->params,
961 text->cursor.pos()).language();
965 Encoding const * BufferView::getEncoding() const
967 LyXText * t = getLyXText();
971 LyXCursor const & c= t->cursor;
972 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
973 return font.language()->encoding();
977 void BufferView::haveSelection(bool sel)
979 pimpl_->workarea().haveSelection(sel);
983 int BufferView::workHeight() const
985 return pimpl_->workarea().workHeight();