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 "support/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 file = MakeDisplayPath(fname, 50);
325 boost::format fmt(_("Could not open the specified document\n%1$s."));
327 string text = fmt.str();
329 string text = _("Could not open the specified document\n");
332 Alert::error(_("Could not open file"), text);
336 int const c = ifs.peek();
344 // FIXME: huh ? No we won't !
345 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
346 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
348 lyxerr[Debug::INFO] << "Will insert file without header"
350 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
358 bool BufferView::removeAutoInsets()
360 // keep track of which pos and par the cursor was on
361 Paragraph * cursor_par = text->cursor.par();
362 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
363 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
364 pos_type cursor_pos = text->cursor.pos();
368 // Trap the deletion of the paragraph the cursor is in.
369 // Iterate until we find a paragraph that won't be immediately deleted.
370 // In reality this should mean we only execute the body of the while
371 // loop once at most. However for safety we iterate rather than just
372 // make this an if () conditional.
373 while ((cursor_par_prev || cursor_par_next)
375 cursor_par_prev ? cursor_par_prev : cursor_par_next,
377 // We just removed cursor_par so have to fix the "cursor"
378 if (cursor_par_prev) {
382 cursor_par = cursor_par_prev;
383 cursor_pos = cursor_par->size();
387 cursor_par = cursor_par_next;
390 cursor_par_prev = cursor_par->previous();
391 cursor_par_next = cursor_par->next();
394 // Iterate through the paragraphs removing autoDelete insets as we go.
395 // If the paragraph ends up empty after all the autoDelete insets are
396 // removed that paragraph will be removed by the next setCursor() call.
397 ParIterator it = buffer()->par_iterator_begin();
398 ParIterator end = buffer()->par_iterator_end();
399 for (; it != end; ++it) {
400 Paragraph * par = *it;
401 Paragraph * par_prev = par ? par->previous() : 0;
402 bool removed = false;
404 if (text->setCursor(par, 0)
405 && cursor_par == par_prev) {
406 // The previous setCursor line was deleted and that
407 // was the cursor_par line. This can only happen if an
408 // error box was the sole item on cursor_par.
409 // It is possible for cursor_par_prev to be stray if
410 // the line it pointed to only had a error box on it
411 // so we have to set it to a known correct value.
412 // This is often the same value it already had.
413 cursor_par_prev = par->previous();
414 if (cursor_par_prev) {
415 // '|' = par, '.' = cursor_par, 'E' = error box
416 // First step below may occur before while{}
418 // E -> .E -> |.E -> . -> |b
421 cursor_par = cursor_par_prev;
422 cursor_pos = cursor_par_prev->size();
423 cursor_par_prev = cursor_par->previous();
424 // cursor_par_next remains the same
425 } else if (cursor_par_next) {
426 // First step below may occur before while{}
428 // E -> |.E -> |. -> . -> .|a
430 cursor_par = cursor_par_next;
432 // cursor_par_prev remains unset
433 cursor_par_next = cursor_par->next();
435 // I can't find a way to trigger this
436 // so it should be unreachable code
437 // unless the buffer is corrupted.
438 lyxerr << "BufferView::removeAutoInsets() is bad\n";
442 InsetList::iterator pit = par->insetlist.begin();
443 InsetList::iterator pend = par->insetlist.end();
445 while (pit != pend) {
446 if (pit.getInset()->autoDelete()) {
448 pos_type const pos = pit.getPos();
451 // We just invalidated par's inset iterators so
452 // we get the next valid iterator position
453 pit = par->insetlist.insetIterator(pos);
454 // and ensure we have a valid end iterator.
455 pend = par->insetlist.end();
457 if (cursor_par == par) {
458 // update the saved cursor position
459 if (cursor_pos > pos)
468 text->redoParagraph();
472 // It is possible that the last line is empty if it was cursor_par
473 // and/or only had an error inset on it. So we set the cursor to the
474 // start of the doc to force its removal and ensure a valid saved cursor
475 if (text->setCursor(&*text->ownerParagraphs().begin(), 0)
476 && 0 == cursor_par_next) {
477 cursor_par = cursor_par_prev;
478 cursor_pos = cursor_par->size();
479 } else if (cursor_pos > cursor_par->size()) {
480 // Some C-Enter lines were removed by the setCursor call which
481 // then invalidated cursor_pos. It could still be "wrong" because
482 // the cursor may appear to have jumped but since we collapsed
483 // some C-Enter lines this should be a reasonable compromise.
484 cursor_pos = cursor_par->size();
487 // restore the original cursor in its corrected location.
488 text->setCursorIntern(cursor_par, cursor_pos);
494 void BufferView::insertErrors(TeXErrors & terr)
496 // Save the cursor position
497 LyXCursor cursor = text->cursor;
499 TeXErrors::Errors::const_iterator cit = terr.begin();
500 TeXErrors::Errors::const_iterator end = terr.end();
501 for (; cit != end; ++cit) {
502 string const desctext(cit->error_desc);
503 string const errortext(cit->error_text);
504 string const msgtxt = desctext + '\n' + errortext;
505 int const errorrow = cit->error_in_line;
507 // Insert error string for row number
511 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
512 buffer()->texrow.increasePos(tmpid, tmppos);
515 Paragraph * texrowpar = 0;
518 texrowpar = &*text->ownerParagraphs().begin();
521 texrowpar = buffer()->getParFromID(tmpid);
528 InsetError * new_inset = new InsetError(msgtxt);
529 text->setCursorIntern(texrowpar, tmppos);
530 text->insertInset(new_inset);
534 // Restore the cursor position
535 text->setCursorIntern(cursor.par(), cursor.pos());
539 void BufferView::setCursorFromRow(int row)
544 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
546 Paragraph * texrowpar;
549 texrowpar = &*text->ownerParagraphs().begin();
552 texrowpar = buffer()->getParFromID(tmpid);
554 text->setCursor(texrowpar, tmppos);
558 bool BufferView::insertInset(Inset * inset, string const & lout)
560 return pimpl_->insertInset(inset, lout);
564 void BufferView::gotoLabel(string const & label)
566 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
567 it != buffer()->inset_iterator_end(); ++it) {
568 vector<string> labels = it->getLabelList();
569 if (find(labels.begin(),labels.end(),label)
572 text->setCursor(it.getPar(), it.getPos());
573 text->selection.cursor = text->cursor;
574 update(text, BufferView::SELECT);
581 void BufferView::undo()
586 owner()->message(_("Undo"));
589 update(text, BufferView::SELECT);
591 owner()->message(_("No further undo information"));
593 update(text, BufferView::SELECT);
598 void BufferView::redo()
603 owner()->message(_("Redo"));
606 update(text, BufferView::SELECT);
608 owner()->message(_("No further redo information"));
610 update(text, BufferView::SELECT);
615 void BufferView::copyEnvironment()
618 text->copyEnvironmentType();
619 owner()->message(_("Paragraph environment type copied"));
624 void BufferView::pasteEnvironment()
627 text->pasteEnvironmentType();
628 owner()->message(_("Paragraph environment type set"));
629 update(text, BufferView::SELECT);
634 // these functions are for the spellchecker
635 WordLangTuple const BufferView::nextWord(float & value)
639 return WordLangTuple();
642 return text->selectNextWordToSpellcheck(value);
646 void BufferView::selectLastWord()
651 LyXCursor cur = text->selection.cursor;
654 text->selection.cursor = cur;
655 text->selectSelectedWord();
656 toggleSelection(false);
657 update(text, BufferView::SELECT);
661 void BufferView::endOfSpellCheck()
663 if (!available()) return;
667 text->selectSelectedWord();
668 text->clearSelection();
669 update(text, BufferView::SELECT);
673 void BufferView::replaceWord(string const & replacestring)
678 LyXText * tt = getLyXText();
680 update(tt, BufferView::SELECT);
682 // clear the selection (if there is any)
683 toggleSelection(false);
684 update(tt, BufferView::SELECT);
686 // clear the selection (if there is any)
687 toggleSelection(false);
688 tt->replaceSelectionWithString(replacestring);
690 tt->setSelectionRange(replacestring.length());
692 // Go back so that replacement string is also spellchecked
693 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
694 tt->cursorLeft(this);
696 update(tt, BufferView::SELECT);
698 // FIXME: should be done through LFUN
699 buffer()->markDirty();
702 // End of spellchecker stuff
705 bool BufferView::lockInset(UpdatableInset * inset)
709 // don't relock if we're already locked
710 if (theLockingInset() == inset)
712 if (!theLockingInset()) {
713 // first check if it's the inset under the cursor we want lock
714 // should be most of the time
715 if (text->cursor.pos() < text->cursor.par()->size()
716 && text->cursor.par()->getChar(text->cursor.pos()) ==
717 Paragraph::META_INSET) {
718 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
720 theLockingInset(inset);
724 // Then do a deep look of the inset and lock the right one
725 int const id = inset->id();
726 ParagraphList::iterator pit = buffer()->paragraphs.begin();
727 ParagraphList::iterator pend = buffer()->paragraphs.end();
728 for (; pit != pend; ++pit) {
729 InsetList::iterator it = pit->insetlist.begin();
730 InsetList::iterator end = pit->insetlist.end();
731 for (; it != end; ++it) {
732 if (it.getInset() == inset) {
733 text->setCursorIntern(&*pit, it.getPos());
734 theLockingInset(inset);
737 if (it.getInset()->getInsetFromID(id)) {
738 text->setCursorIntern(&*pit, it.getPos());
739 it.getInset()->edit(this);
740 return theLockingInset()->lockInsetInInset(this, inset);
746 return theLockingInset()->lockInsetInInset(this, inset);
750 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
752 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
753 LyXCursor cursor = text->cursor;
754 Inset * locking_inset = theLockingInset()->getLockingInset();
756 if ((cursor.pos() - 1 >= 0) &&
757 cursor.par()->isInset(cursor.pos() - 1) &&
758 (cursor.par()->getInset(cursor.pos() - 1) ==
760 text->setCursor(cursor,
761 cursor.par(), cursor.pos() - 1);
762 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
763 LyXText * txt = getLyXText();
764 if (locking_inset->isTextInset() &&
765 locking_inset->lyxCode() != Inset::ERT_CODE &&
766 (txt->real_current_font.language() !=
767 buffer()->params.language
768 || txt->real_current_font.isVisibleRightToLeft()
769 != buffer()->params.language->RightToLeft()))
770 shape = (txt->real_current_font.isVisibleRightToLeft())
771 ? LyXScreen::REVERSED_L_SHAPE
772 : LyXScreen::L_SHAPE;
773 y += cursor.iy() + theLockingInset()->insetInInsetY();
774 screen().showManualCursor(text, x, y, asc, desc,
780 void BufferView::hideLockedInsetCursor()
782 if (theLockingInset() && available()) {
783 screen().hideCursor();
788 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
790 if (theLockingInset() && available()) {
791 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
792 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
801 int BufferView::unlockInset(UpdatableInset * inset)
805 if (inset && theLockingInset() == inset) {
806 inset->insetUnlock(this);
808 // make sure we update the combo !
809 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
810 // Tell the paragraph dialog that we changed paragraph
811 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
814 } else if (inset && theLockingInset() &&
815 theLockingInset()->unlockInsetInInset(this, inset)) {
816 // Tell the paragraph dialog that we changed paragraph
817 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
818 // owner inset has updated the layout combo
826 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
828 if (!theLockingInset())
829 return; // shouldn't happen
830 if (kind == Undo::EDIT) // in this case insets would not be stored!
834 text->cursor.par()->next());
838 void BufferView::updateInset(Inset * inset)
840 pimpl_->updateInset(inset);
844 bool BufferView::ChangeInsets(Inset::Code code,
845 string const & from, string const & to)
847 bool need_update = false;
848 LyXCursor cursor = text->cursor;
849 LyXCursor tmpcursor = cursor;
850 cursor.par(tmpcursor.par());
851 cursor.pos(tmpcursor.pos());
853 ParIterator end = buffer()->par_iterator_end();
854 for (ParIterator it = buffer()->par_iterator_begin();
856 Paragraph * par = *it;
857 bool changed_inset = false;
858 for (InsetList::iterator it2 = par->insetlist.begin();
859 it2 != par->insetlist.end(); ++it2) {
860 if (it2.getInset()->lyxCode() == code) {
861 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
862 if (inset->getContents() == from) {
863 inset->setContents(to);
864 changed_inset = true;
873 // The test it.size()==1 was needed to prevent crashes.
874 // How to set the cursor corretly when it.size()>1 ??
875 if (it.size() == 1) {
876 text->setCursorIntern(par, 0);
877 text->redoParagraphs(text->cursor,
878 text->cursor.par()->next());
883 text->setCursorIntern(cursor.par(), cursor.pos());
888 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
890 // Check if the label 'from' appears more than once
891 vector<string> labels = buffer()->getLabelList();
893 if (lyx::count(labels.begin(), labels.end(), from) > 1)
896 return ChangeInsets(Inset::REF_CODE, from, to);
900 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
902 typedef pair<string, string> StringPair;
904 vector<StringPair> keys;
905 buffer()->fillWithBibKeys(keys);
906 if (count_if(keys.begin(), keys.end(),
907 lyx::equal_1st_in_pair<StringPair>(from))
911 return ChangeInsets(Inset::CITE_CODE, from, to);
915 UpdatableInset * BufferView::theLockingInset() const
917 // If NULL is not allowed we should put an Assert here. (Lgb)
919 return text->the_locking_inset;
924 void BufferView::theLockingInset(UpdatableInset * inset)
926 text->the_locking_inset = inset;
930 LyXText * BufferView::getLyXText() const
932 if (theLockingInset()) {
933 LyXText * txt = theLockingInset()->getLyXText(this, true);
941 LyXText * BufferView::getParentText(Inset * inset) const
943 if (inset->owner()) {
944 LyXText * txt = inset->getLyXText(this);
945 inset = inset->owner();
946 while (inset && inset->getLyXText(this) == txt)
947 inset = inset->owner();
949 return inset->getLyXText(this);
955 Language const * BufferView::getParentLanguage(Inset * inset) const
957 LyXText * text = getParentText(inset);
958 return text->cursor.par()->getFontSettings(buffer()->params,
959 text->cursor.pos()).language();
963 Encoding const * BufferView::getEncoding() const
965 LyXText * t = getLyXText();
969 LyXCursor const & c= t->cursor;
970 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
971 return font.language()->encoding();
975 void BufferView::haveSelection(bool sel)
977 pimpl_->workarea().haveSelection(sel);
981 int BufferView::workHeight() const
983 return pimpl_->workarea().workHeight();