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"
30 #include "paragraph_funcs.h"
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"
38 #include "insets/insetcommand.h" // ChangeRefs
39 #include "insets/inseterror.h"
40 #include "insets/updatableinset.h"
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 #include "support/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 file = MakeDisplayPath(fname, 50);
326 boost::format fmt(_("Could not open the specified document\n%1$s."));
328 string text = fmt.str();
330 string text = _("Could not open the specified document\n");
333 Alert::error(_("Could not open file"), text);
337 int const c = ifs.peek();
345 // FIXME: huh ? No we won't !
346 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
347 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
349 lyxerr[Debug::INFO] << "Will insert file without header"
351 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
359 bool BufferView::removeAutoInsets()
361 // keep track of which pos and par the cursor was on
362 Paragraph * cursor_par = &*text->cursor.par();
363 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
364 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
365 pos_type cursor_pos = text->cursor.pos();
369 // Trap the deletion of the paragraph the cursor is in.
370 // Iterate until we find a paragraph that won't be immediately deleted.
371 // In reality this should mean we only execute the body of the while
372 // loop once at most. However for safety we iterate rather than just
373 // make this an if () conditional.
374 while ((cursor_par_prev || cursor_par_next)
376 cursor_par_prev ? cursor_par_prev : cursor_par_next,
378 // We just removed cursor_par so have to fix the "cursor"
379 if (cursor_par_prev) {
383 cursor_par = cursor_par_prev;
384 cursor_pos = cursor_par->size();
388 cursor_par = cursor_par_next;
391 cursor_par_prev = cursor_par->previous();
392 cursor_par_next = cursor_par->next();
395 // Iterate through the paragraphs removing autoDelete insets as we go.
396 // If the paragraph ends up empty after all the autoDelete insets are
397 // removed that paragraph will be removed by the next setCursor() call.
398 ParIterator it = buffer()->par_iterator_begin();
399 ParIterator end = buffer()->par_iterator_end();
400 for (; it != end; ++it) {
401 Paragraph * par = *it;
402 Paragraph * par_prev = par ? par->previous() : 0;
403 bool removed = false;
405 if (text->setCursor(par, 0)
406 && cursor_par == par_prev) {
407 // The previous setCursor line was deleted and that
408 // was the cursor_par line. This can only happen if an
409 // error box was the sole item on cursor_par.
410 // It is possible for cursor_par_prev to be stray if
411 // the line it pointed to only had a error box on it
412 // so we have to set it to a known correct value.
413 // This is often the same value it already had.
414 cursor_par_prev = par->previous();
415 if (cursor_par_prev) {
416 // '|' = par, '.' = cursor_par, 'E' = error box
417 // First step below may occur before while{}
419 // E -> .E -> |.E -> . -> |b
422 cursor_par = cursor_par_prev;
423 cursor_pos = cursor_par_prev->size();
424 cursor_par_prev = cursor_par->previous();
425 // cursor_par_next remains the same
426 } else if (cursor_par_next) {
427 // First step below may occur before while{}
429 // E -> |.E -> |. -> . -> .|a
431 cursor_par = cursor_par_next;
433 // cursor_par_prev remains unset
434 cursor_par_next = cursor_par->next();
436 // I can't find a way to trigger this
437 // so it should be unreachable code
438 // unless the buffer is corrupted.
439 lyxerr << "BufferView::removeAutoInsets() is bad\n";
443 InsetList::iterator pit = par->insetlist.begin();
444 InsetList::iterator pend = par->insetlist.end();
446 while (pit != pend) {
447 if (pit.getInset()->autoDelete()) {
449 pos_type const pos = pit.getPos();
452 // We just invalidated par's inset iterators so
453 // we get the next valid iterator position
454 pit = par->insetlist.insetIterator(pos);
455 // and ensure we have a valid end iterator.
456 pend = par->insetlist.end();
458 if (cursor_par == par) {
459 // update the saved cursor position
460 if (cursor_pos > pos)
469 text->redoParagraph();
473 // It is possible that the last line is empty if it was cursor_par
474 // and/or only had an error inset on it. So we set the cursor to the
475 // start of the doc to force its removal and ensure a valid saved cursor
476 if (text->setCursor(&*text->ownerParagraphs().begin(), 0)
477 && 0 == cursor_par_next) {
478 cursor_par = cursor_par_prev;
479 cursor_pos = cursor_par->size();
480 } else if (cursor_pos > cursor_par->size()) {
481 // Some C-Enter lines were removed by the setCursor call which
482 // then invalidated cursor_pos. It could still be "wrong" because
483 // the cursor may appear to have jumped but since we collapsed
484 // some C-Enter lines this should be a reasonable compromise.
485 cursor_pos = cursor_par->size();
488 // restore the original cursor in its corrected location.
489 text->setCursorIntern(cursor_par, cursor_pos);
495 void BufferView::insertErrors(TeXErrors & terr)
497 // Save the cursor position
498 LyXCursor cursor = text->cursor;
500 TeXErrors::Errors::const_iterator cit = terr.begin();
501 TeXErrors::Errors::const_iterator end = terr.end();
502 for (; cit != end; ++cit) {
503 string const desctext(cit->error_desc);
504 string const errortext(cit->error_text);
505 string const msgtxt = desctext + '\n' + errortext;
506 int const errorrow = cit->error_in_line;
508 // Insert error string for row number
512 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
513 buffer()->texrow.increasePos(tmpid, tmppos);
516 Paragraph * texrowpar = 0;
519 texrowpar = &*text->ownerParagraphs().begin();
522 texrowpar = buffer()->getParFromID(tmpid);
529 InsetError * new_inset = new InsetError(msgtxt);
530 text->setCursorIntern(texrowpar, tmppos);
531 text->insertInset(new_inset);
535 // Restore the cursor position
536 text->setCursorIntern(cursor.par(), cursor.pos());
540 void BufferView::setCursorFromRow(int row)
545 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
547 Paragraph * texrowpar;
550 texrowpar = &*text->ownerParagraphs().begin();
553 texrowpar = buffer()->getParFromID(tmpid);
555 text->setCursor(texrowpar, tmppos);
559 bool BufferView::insertInset(Inset * inset, string const & lout)
561 return pimpl_->insertInset(inset, lout);
565 void BufferView::gotoLabel(string const & label)
567 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
568 it != buffer()->inset_iterator_end(); ++it) {
569 vector<string> labels = it->getLabelList();
570 if (find(labels.begin(),labels.end(),label)
573 text->setCursor(it.getPar(), it.getPos());
574 text->selection.cursor = text->cursor;
575 update(text, BufferView::SELECT);
582 void BufferView::undo()
587 owner()->message(_("Undo"));
590 update(text, BufferView::SELECT);
592 owner()->message(_("No further undo information"));
594 update(text, BufferView::SELECT);
599 void BufferView::redo()
604 owner()->message(_("Redo"));
607 update(text, BufferView::SELECT);
609 owner()->message(_("No further redo information"));
611 update(text, BufferView::SELECT);
616 void BufferView::copyEnvironment()
619 text->copyEnvironmentType();
620 owner()->message(_("Paragraph environment type copied"));
625 void BufferView::pasteEnvironment()
628 text->pasteEnvironmentType();
629 owner()->message(_("Paragraph environment type set"));
630 update(text, BufferView::SELECT);
635 // these functions are for the spellchecker
636 WordLangTuple const BufferView::nextWord(float & value)
640 return WordLangTuple();
643 return text->selectNextWordToSpellcheck(value);
647 void BufferView::selectLastWord()
652 LyXCursor cur = text->selection.cursor;
655 text->selection.cursor = cur;
656 text->selectSelectedWord();
657 toggleSelection(false);
658 update(text, BufferView::SELECT);
662 void BufferView::endOfSpellCheck()
664 if (!available()) return;
668 text->selectSelectedWord();
669 text->clearSelection();
670 update(text, BufferView::SELECT);
674 void BufferView::replaceWord(string const & replacestring)
679 LyXText * tt = getLyXText();
681 update(tt, BufferView::SELECT);
683 // clear the selection (if there is any)
684 toggleSelection(false);
685 update(tt, BufferView::SELECT);
687 // clear the selection (if there is any)
688 toggleSelection(false);
689 tt->replaceSelectionWithString(replacestring);
691 tt->setSelectionRange(replacestring.length());
693 // Go back so that replacement string is also spellchecked
694 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
695 tt->cursorLeft(this);
697 update(tt, BufferView::SELECT);
699 // FIXME: should be done through LFUN
700 buffer()->markDirty();
703 // End of spellchecker stuff
706 bool BufferView::lockInset(UpdatableInset * inset)
710 // don't relock if we're already locked
711 if (theLockingInset() == inset)
713 if (!theLockingInset()) {
714 // first check if it's the inset under the cursor we want lock
715 // should be most of the time
716 if (text->cursor.pos() < text->cursor.par()->size()
717 && text->cursor.par()->getChar(text->cursor.pos()) ==
718 Paragraph::META_INSET) {
719 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
721 theLockingInset(inset);
725 // Then do a deep look of the inset and lock the right one
726 int const id = inset->id();
727 ParagraphList::iterator pit = buffer()->paragraphs.begin();
728 ParagraphList::iterator pend = buffer()->paragraphs.end();
729 for (; pit != pend; ++pit) {
730 InsetList::iterator it = pit->insetlist.begin();
731 InsetList::iterator end = pit->insetlist.end();
732 for (; it != end; ++it) {
733 if (it.getInset() == inset) {
734 text->setCursorIntern(&*pit, it.getPos());
735 theLockingInset(inset);
738 if (it.getInset()->getInsetFromID(id)) {
739 text->setCursorIntern(&*pit, it.getPos());
740 it.getInset()->edit(this);
741 return theLockingInset()->lockInsetInInset(this, inset);
747 return theLockingInset()->lockInsetInInset(this, inset);
751 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
753 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
754 LyXCursor cursor = text->cursor;
755 Inset * locking_inset = theLockingInset()->getLockingInset();
757 if ((cursor.pos() - 1 >= 0) &&
758 cursor.par()->isInset(cursor.pos() - 1) &&
759 (cursor.par()->getInset(cursor.pos() - 1) ==
761 text->setCursor(cursor,
762 cursor.par(), cursor.pos() - 1);
763 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
764 LyXText * txt = getLyXText();
765 if (locking_inset->isTextInset() &&
766 locking_inset->lyxCode() != Inset::ERT_CODE &&
767 (txt->real_current_font.language() !=
768 buffer()->params.language
769 || txt->real_current_font.isVisibleRightToLeft()
770 != buffer()->params.language->RightToLeft()))
771 shape = (txt->real_current_font.isVisibleRightToLeft())
772 ? LyXScreen::REVERSED_L_SHAPE
773 : LyXScreen::L_SHAPE;
774 y += cursor.iy() + theLockingInset()->insetInInsetY();
775 screen().showManualCursor(text, x, y, asc, desc,
781 void BufferView::hideLockedInsetCursor()
783 if (theLockingInset() && available()) {
784 screen().hideCursor();
789 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
791 if (theLockingInset() && available()) {
792 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
793 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
802 int BufferView::unlockInset(UpdatableInset * inset)
806 if (inset && theLockingInset() == inset) {
807 inset->insetUnlock(this);
809 // make sure we update the combo !
810 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
811 // Tell the paragraph dialog that we changed paragraph
812 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
815 } else if (inset && theLockingInset() &&
816 theLockingInset()->unlockInsetInInset(this, inset)) {
817 // Tell the paragraph dialog that we changed paragraph
818 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
819 // owner inset has updated the layout combo
827 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
829 if (!theLockingInset())
830 return; // shouldn't happen
831 if (kind == Undo::EDIT) // in this case insets would not be stored!
834 &*text->cursor.par(),
835 text->cursor.par()->next());
839 void BufferView::updateInset(Inset * inset)
841 pimpl_->updateInset(inset);
845 bool BufferView::ChangeInsets(Inset::Code code,
846 string const & from, string const & to)
848 bool need_update = false;
849 LyXCursor cursor = text->cursor;
850 LyXCursor tmpcursor = cursor;
851 cursor.par(tmpcursor.par());
852 cursor.pos(tmpcursor.pos());
854 ParIterator end = buffer()->par_iterator_end();
855 for (ParIterator it = buffer()->par_iterator_begin();
857 Paragraph * par = *it;
858 bool changed_inset = false;
859 for (InsetList::iterator it2 = par->insetlist.begin();
860 it2 != par->insetlist.end(); ++it2) {
861 if (it2.getInset()->lyxCode() == code) {
862 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
863 if (inset->getContents() == from) {
864 inset->setContents(to);
865 changed_inset = true;
874 // The test it.size()==1 was needed to prevent crashes.
875 // How to set the cursor corretly when it.size()>1 ??
876 if (it.size() == 1) {
877 text->setCursorIntern(par, 0);
878 text->redoParagraphs(text->cursor,
879 text->cursor.par()->next());
884 text->setCursorIntern(cursor.par(), cursor.pos());
889 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
891 // Check if the label 'from' appears more than once
892 vector<string> labels = buffer()->getLabelList();
894 if (lyx::count(labels.begin(), labels.end(), from) > 1)
897 return ChangeInsets(Inset::REF_CODE, from, to);
901 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
903 typedef pair<string, string> StringPair;
905 vector<StringPair> keys;
906 buffer()->fillWithBibKeys(keys);
907 if (count_if(keys.begin(), keys.end(),
908 lyx::equal_1st_in_pair<StringPair>(from))
912 return ChangeInsets(Inset::CITE_CODE, from, to);
916 UpdatableInset * BufferView::theLockingInset() const
918 // If NULL is not allowed we should put an Assert here. (Lgb)
920 return text->the_locking_inset;
925 void BufferView::theLockingInset(UpdatableInset * inset)
927 text->the_locking_inset = inset;
931 LyXText * BufferView::getLyXText() const
933 if (theLockingInset()) {
934 LyXText * txt = theLockingInset()->getLyXText(this, true);
942 LyXText * BufferView::getParentText(Inset * inset) const
944 if (inset->owner()) {
945 LyXText * txt = inset->getLyXText(this);
946 inset = inset->owner();
947 while (inset && inset->getLyXText(this) == txt)
948 inset = inset->owner();
950 return inset->getLyXText(this);
956 Language const * BufferView::getParentLanguage(Inset * inset) const
958 LyXText * text = getParentText(inset);
959 return text->cursor.par()->getFontSettings(buffer()->params,
960 text->cursor.pos()).language();
964 Encoding const * BufferView::getEncoding() const
966 LyXText * t = getLyXText();
970 LyXCursor const & c = t->cursor;
971 LyXFont const font = c.par()->getFont(buffer()->params, c.pos(),
972 outerFont(c.par(), t->ownerParagraphs()));
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();