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 // FIXME: huh ? No we won't !
322 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
323 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
325 lyxerr[Debug::INFO] << "Will insert file without header"
327 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
335 bool BufferView::removeAutoInsets()
337 // keep track of which pos and par the cursor was on
338 Paragraph * cursor_par = text->cursor.par();
339 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
340 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
341 pos_type cursor_pos = text->cursor.pos();
345 // Trap the deletion of the paragraph the cursor is in.
346 // Iterate until we find a paragraph that won't be immediately deleted.
347 // In reality this should mean we only execute the body of the while
348 // loop once at most. However for safety we iterate rather than just
349 // make this an if () conditional.
350 while ((cursor_par_prev || cursor_par_next)
351 && text->setCursor(this,
352 cursor_par_prev ? cursor_par_prev : cursor_par_next,
354 // We just removed cursor_par so have to fix the "cursor"
355 if (cursor_par_prev) {
359 cursor_par = cursor_par_prev;
360 cursor_pos = cursor_par->size();
364 cursor_par = cursor_par_next;
367 cursor_par_prev = cursor_par->previous();
368 cursor_par_next = cursor_par->next();
371 // Iterate through the paragraphs removing autoDelete insets as we go.
372 // If the paragraph ends up empty after all the autoDelete insets are
373 // removed that paragraph will be removed by the next setCursor() call.
374 ParIterator it = buffer()->par_iterator_begin();
375 ParIterator end = buffer()->par_iterator_end();
376 for (; it != end; ++it) {
377 Paragraph * par = *it;
378 Paragraph * par_prev = par ? par->previous() : 0;
379 bool removed = false;
381 if (text->setCursor(this, par, 0)
382 && cursor_par == par_prev) {
383 // The previous setCursor line was deleted and that
384 // was the cursor_par line. This can only happen if an
385 // error box was the sole item on cursor_par.
386 // It is possible for cursor_par_prev to be stray if
387 // the line it pointed to only had a error box on it
388 // so we have to set it to a known correct value.
389 // This is often the same value it already had.
390 cursor_par_prev = par->previous();
391 if (cursor_par_prev) {
392 // '|' = par, '.' = cursor_par, 'E' = error box
393 // First step below may occur before while{}
395 // E -> .E -> |.E -> . -> |b
398 cursor_par = cursor_par_prev;
399 cursor_pos = cursor_par_prev->size();
400 cursor_par_prev = cursor_par->previous();
401 // cursor_par_next remains the same
402 } else if (cursor_par_next) {
403 // First step below may occur before while{}
405 // E -> |.E -> |. -> . -> .|a
407 cursor_par = cursor_par_next;
409 // cursor_par_prev remains unset
410 cursor_par_next = cursor_par->next();
412 // I can't find a way to trigger this
413 // so it should be unreachable code
414 // unless the buffer is corrupted.
415 lyxerr << "BufferView::removeAutoInsets() is bad\n";
419 InsetList::iterator pit = par->insetlist.begin();
420 InsetList::iterator pend = par->insetlist.end();
422 while (pit != pend) {
423 if (pit.getInset()->autoDelete()) {
425 pos_type const pos = pit.getPos();
428 // We just invalidated par's inset iterators so
429 // we get the next valid iterator position
430 pit = par->insetlist.insetIterator(pos);
431 // and ensure we have a valid end iterator.
432 pend = par->insetlist.end();
434 if (cursor_par == par) {
435 // update the saved cursor position
436 if (cursor_pos > pos)
445 text->redoParagraph(this);
449 // It is possible that the last line is empty if it was cursor_par
450 // and/or only had an error inset on it. So we set the cursor to the
451 // start of the doc to force its removal and ensure a valid saved cursor
452 if (text->setCursor(this, text->ownerParagraph(), 0)
453 && 0 == cursor_par_next) {
454 cursor_par = cursor_par_prev;
455 cursor_pos = cursor_par->size();
456 } else if (cursor_pos > cursor_par->size()) {
457 // Some C-Enter lines were removed by the setCursor call which
458 // then invalidated cursor_pos. It could still be "wrong" because
459 // the cursor may appear to have jumped but since we collapsed
460 // some C-Enter lines this should be a reasonable compromise.
461 cursor_pos = cursor_par->size();
464 // restore the original cursor in its corrected location.
465 text->setCursorIntern(this, cursor_par, cursor_pos);
471 void BufferView::insertErrors(TeXErrors & terr)
473 // Save the cursor position
474 LyXCursor cursor = text->cursor;
476 TeXErrors::Errors::const_iterator cit = terr.begin();
477 TeXErrors::Errors::const_iterator end = terr.end();
478 for (; cit != end; ++cit) {
479 string const desctext(cit->error_desc);
480 string const errortext(cit->error_text);
481 string const msgtxt = desctext + '\n' + errortext;
482 int const errorrow = cit->error_in_line;
484 // Insert error string for row number
488 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
489 buffer()->texrow.increasePos(tmpid, tmppos);
492 Paragraph * texrowpar = 0;
495 texrowpar = text->ownerParagraph();
498 texrowpar = buffer()->getParFromID(tmpid);
505 InsetError * new_inset = new InsetError(msgtxt);
506 text->setCursorIntern(this, texrowpar, tmppos);
507 text->insertInset(this, new_inset);
508 text->fullRebreak(this);
511 // Restore the cursor position
512 text->setCursorIntern(this, cursor.par(), cursor.pos());
516 void BufferView::setCursorFromRow(int row)
521 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
523 Paragraph * texrowpar;
526 texrowpar = text->ownerParagraph();
529 texrowpar = buffer()->getParFromID(tmpid);
531 text->setCursor(this, texrowpar, tmppos);
535 bool BufferView::insertInset(Inset * inset, string const & lout)
537 return pimpl_->insertInset(inset, lout);
541 // This is also a buffer property (ale)
542 // Not so sure about that. a goto Label function can not be buffer local, just
543 // think how this will work in a multiwindow/buffer environment, all the
544 // cursors in all the views showing this buffer will move. (Lgb)
545 // OK, then no cursor action should be allowed in buffer. (ale)
546 bool BufferView::gotoLabel(string const & label)
548 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
549 it != buffer()->inset_iterator_end(); ++it) {
550 vector<string> labels = it->getLabelList();
551 if (find(labels.begin(),labels.end(),label)
554 text->setCursor(this, it.getPar(), it.getPos());
555 text->selection.cursor = text->cursor;
556 update(text, BufferView::SELECT|BufferView::FITCUR);
564 void BufferView::undo()
569 owner()->message(_("Undo"));
572 update(text, BufferView::SELECT|BufferView::FITCUR);
574 owner()->message(_("No further undo information"));
576 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
581 void BufferView::redo()
586 owner()->message(_("Redo"));
589 update(text, BufferView::SELECT|BufferView::FITCUR);
591 owner()->message(_("No further redo information"));
593 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
598 void BufferView::copyEnvironment()
601 text->copyEnvironmentType();
602 owner()->message(_("Paragraph environment type copied"));
607 void BufferView::pasteEnvironment()
610 text->pasteEnvironmentType(this);
611 owner()->message(_("Paragraph environment type set"));
612 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
617 // these functions are for the spellchecker
618 WordLangTuple const BufferView::nextWord(float & value)
622 return WordLangTuple();
625 return text->selectNextWordToSpellcheck(this, value);
629 void BufferView::selectLastWord()
634 LyXCursor cur = text->selection.cursor;
637 text->selection.cursor = cur;
638 text->selectSelectedWord(this);
639 toggleSelection(false);
640 update(text, BufferView::SELECT|BufferView::FITCUR);
644 void BufferView::endOfSpellCheck()
646 if (!available()) return;
650 text->selectSelectedWord(this);
651 text->clearSelection();
652 update(text, BufferView::SELECT|BufferView::FITCUR);
656 void BufferView::replaceWord(string const & replacestring)
661 LyXText * tt = getLyXText();
663 update(tt, BufferView::SELECT|BufferView::FITCUR);
665 // clear the selection (if there is any)
666 toggleSelection(false);
667 update(tt, BufferView::SELECT|BufferView::FITCUR);
669 // clear the selection (if there is any)
670 toggleSelection(false);
671 tt->replaceSelectionWithString(this, replacestring);
673 tt->setSelectionRange(this, replacestring.length());
675 // Go back so that replacement string is also spellchecked
676 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
677 tt->cursorLeft(this);
679 update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
681 // End of spellchecker stuff
684 bool BufferView::lockInset(UpdatableInset * inset)
688 // don't relock if we're already locked
689 if (theLockingInset() == inset)
691 if (!theLockingInset()) {
692 // first check if it's the inset under the cursor we want lock
693 // should be most of the time
694 char const c = text->cursor.par()->getChar(text->cursor.pos());
695 if (c == Paragraph::META_INSET) {
696 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
698 theLockingInset(inset);
702 // Then do a deep look of the inset and lock the right one
703 int const id = inset->id();
704 ParagraphList::iterator pit = buffer()->paragraphs.begin();
705 ParagraphList::iterator pend = buffer()->paragraphs.end();
706 for (; pit != pend; ++pit) {
707 InsetList::iterator it = pit->insetlist.begin();
708 InsetList::iterator end = pit->insetlist.end();
709 for (; it != end; ++it) {
710 if (it.getInset() == inset) {
711 text->setCursorIntern(this, &*pit, it.getPos());
712 theLockingInset(inset);
715 if (it.getInset()->getInsetFromID(id)) {
716 text->setCursorIntern(this, &*pit, it.getPos());
717 it.getInset()->edit(this);
718 return theLockingInset()->lockInsetInInset(this, inset);
724 return theLockingInset()->lockInsetInInset(this, inset);
728 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
730 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
731 LyXCursor cursor = text->cursor;
732 Inset * locking_inset = theLockingInset()->getLockingInset();
734 if ((cursor.pos() - 1 >= 0) &&
735 cursor.par()->isInset(cursor.pos() - 1) &&
736 (cursor.par()->getInset(cursor.pos() - 1) ==
738 text->setCursor(this, cursor,
739 cursor.par(), cursor.pos() - 1);
740 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
741 LyXText * txt = getLyXText();
742 if (locking_inset->isTextInset() &&
743 locking_inset->lyxCode() != Inset::ERT_CODE &&
744 (txt->real_current_font.language() !=
745 buffer()->params.language
746 || txt->real_current_font.isVisibleRightToLeft()
747 != buffer()->params.language->RightToLeft()))
748 shape = (txt->real_current_font.isVisibleRightToLeft())
749 ? LyXScreen::REVERSED_L_SHAPE
750 : LyXScreen::L_SHAPE;
751 y += cursor.iy() + theLockingInset()->insetInInsetY();
752 screen().showManualCursor(text, x, y, asc, desc,
758 void BufferView::hideLockedInsetCursor()
760 if (theLockingInset() && available()) {
761 screen().hideCursor();
766 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
768 if (theLockingInset() && available()) {
769 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
770 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
779 int BufferView::unlockInset(UpdatableInset * inset)
783 if (inset && theLockingInset() == inset) {
784 inset->insetUnlock(this);
786 // make sure we update the combo !
787 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
788 // Tell the paragraph dialog that we changed paragraph
789 owner()->getDialogs().updateParagraph();
792 } else if (inset && theLockingInset() &&
793 theLockingInset()->unlockInsetInInset(this, inset)) {
794 // Tell the paragraph dialog that we changed paragraph
795 owner()->getDialogs().updateParagraph();
796 // owner inset has updated the layout combo
804 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
806 if (!theLockingInset())
807 return; // shouldn't happen
808 if (kind == Undo::EDIT) // in this case insets would not be stored!
812 text->cursor.par()->next());
816 void BufferView::updateInset(Inset * inset, bool mark_dirty)
818 pimpl_->updateInset(inset, mark_dirty);
822 bool BufferView::ChangeInsets(Inset::Code code,
823 string const & from, string const & to)
825 bool need_update = false;
826 LyXCursor cursor = text->cursor;
827 LyXCursor tmpcursor = cursor;
828 cursor.par(tmpcursor.par());
829 cursor.pos(tmpcursor.pos());
831 ParIterator end = buffer()->par_iterator_end();
832 for (ParIterator it = buffer()->par_iterator_begin();
834 Paragraph * par = *it;
835 bool changed_inset = false;
836 for (InsetList::iterator it2 = par->insetlist.begin();
837 it2 != par->insetlist.end(); ++it2) {
838 if (it2.getInset()->lyxCode() == code) {
839 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
840 if (inset->getContents() == from) {
841 inset->setContents(to);
842 changed_inset = true;
851 // The test it.size()==1 was needed to prevent crashes.
852 // How to set the cursor corretly when it.size()>1 ??
853 if (it.size() == 1) {
854 text->setCursorIntern(this, par, 0);
855 text->redoParagraphs(this, text->cursor,
856 text->cursor.par()->next());
857 text->fullRebreak(this);
861 text->setCursorIntern(this, cursor.par(), cursor.pos());
866 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
868 // Check if the label 'from' appears more than once
869 vector<string> labels = buffer()->getLabelList();
871 if (lyx::count(labels.begin(), labels.end(), from) > 1)
874 return ChangeInsets(Inset::REF_CODE, from, to);
878 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
880 typedef pair<string, string> StringPair;
882 vector<StringPair> keys;
883 buffer()->fillWithBibKeys(keys);
884 if (count_if(keys.begin(), keys.end(),
885 lyx::equal_1st_in_pair<StringPair>(from))
889 return ChangeInsets(Inset::CITE_CODE, from, to);
893 UpdatableInset * BufferView::theLockingInset() const
895 // If NULL is not allowed we should put an Assert here. (Lgb)
897 return text->the_locking_inset;
902 void BufferView::theLockingInset(UpdatableInset * inset)
904 text->the_locking_inset = inset;
908 LyXText * BufferView::getLyXText() const
910 if (theLockingInset()) {
911 LyXText * txt = theLockingInset()->getLyXText(this, true);
919 LyXText * BufferView::getParentText(Inset * inset) const
921 if (inset->owner()) {
922 LyXText * txt = inset->getLyXText(this);
923 inset = inset->owner();
924 while (inset && inset->getLyXText(this) == txt)
925 inset = inset->owner();
927 return inset->getLyXText(this);
933 Language const * BufferView::getParentLanguage(Inset * inset) const
935 LyXText * text = getParentText(inset);
936 return text->cursor.par()->getFontSettings(buffer()->params,
937 text->cursor.pos()).language();
941 Encoding const * BufferView::getEncoding() const
943 LyXText * t = getLyXText();
947 LyXCursor const & c= t->cursor;
948 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
949 return font.language()->encoding();
953 void BufferView::haveSelection(bool sel)
955 pimpl_->workarea().haveSelection(sel);
959 int BufferView::workHeight() const
961 return pimpl_->workarea().workHeight();