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
49 extern BufferList bufferlist;
61 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
62 int width, int height)
63 : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
69 BufferView::~BufferView()
76 Buffer * BufferView::buffer() const
78 return pimpl_->buffer_;
82 LyXScreen & BufferView::screen() const
84 return pimpl_->screen();
88 LyXView * BufferView::owner() const
90 return pimpl_->owner_;
94 Painter & BufferView::painter() const
96 return pimpl_->painter();
100 void BufferView::buffer(Buffer * b)
106 void BufferView::reload()
108 string const fn = buffer()->fileName();
109 if (bufferlist.close(buffer(), false))
110 buffer(bufferlist.loadLyXFile(fn));
114 void BufferView::resize()
116 if (pimpl_->buffer_) {
117 pimpl_->resizeCurrentBuffer();
122 void BufferView::repaint()
128 bool BufferView::fitCursor()
130 return pimpl_->fitCursor();
134 void BufferView::update()
140 void BufferView::updateScrollbar()
142 pimpl_->updateScrollbar();
146 void BufferView::scrollDocView(int value)
148 pimpl_->scrollDocView(value);
152 void BufferView::redoCurrentBuffer()
154 pimpl_->redoCurrentBuffer();
158 bool BufferView::available() const
160 return pimpl_->available();
164 Change const BufferView::getCurrentChange()
166 return pimpl_->getCurrentChange();
170 void BufferView::beforeChange(LyXText * text)
172 pimpl_->beforeChange(text);
176 void BufferView::savePosition(unsigned int i)
178 pimpl_->savePosition(i);
182 void BufferView::restorePosition(unsigned int i)
184 pimpl_->restorePosition(i);
188 bool BufferView::isSavedPosition(unsigned int i)
190 return pimpl_->isSavedPosition(i);
194 void BufferView::update(LyXText * text, UpdateCodes f)
196 pimpl_->update(text, f);
200 void BufferView::update(UpdateCodes f)
206 void BufferView::switchKeyMap()
208 pimpl_->switchKeyMap();
212 void BufferView::insetUnlock()
214 pimpl_->insetUnlock();
218 int BufferView::workWidth() const
220 return pimpl_->workarea().workWidth();
224 void BufferView::showCursor()
226 pimpl_->showCursor();
230 void BufferView::hideCursor()
232 pimpl_->hideCursor();
236 void BufferView::toggleSelection(bool b)
238 pimpl_->toggleSelection(b);
242 void BufferView::toggleToggle()
244 pimpl_->toggleToggle();
248 void BufferView::center()
254 string const BufferView::getClipboard() const
256 return pimpl_->workarea().getClipboard();
260 void BufferView::stuffClipboard(string const & stuff) const
262 pimpl_->stuffClipboard(stuff);
266 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
267 BufferView::UpdateCodes uc2)
269 return static_cast<BufferView::UpdateCodes>
270 (static_cast<int>(uc1) | static_cast<int>(uc2));
274 bool BufferView::dispatch(FuncRequest const & ev)
276 return pimpl_->dispatch(ev);
280 void BufferView::scroll(int lines)
282 pimpl_->scroll(lines);
286 // Inserts a file into current document
287 bool BufferView::insertLyXFile(string const & filen)
289 // Copyright CHT Software Service GmbH
292 // Insert a LyXformat - file into current buffer
294 // Moved from lyx_cb.C (Lgb)
299 string const fname = MakeAbsPath(filen);
301 // check if file exist
302 FileInfo const fi(fname);
304 if (!fi.readable()) {
305 Alert::alert(_("Error!"),
306 _("Specified file is unreadable: "),
307 MakeDisplayPath(fname, 50));
313 ifstream ifs(fname.c_str());
315 Alert::err_alert(_("Error! Cannot open specified file:"),
316 MakeDisplayPath(fname, 50));
320 int const c = ifs.peek();
328 // FIXME: huh ? No we won't !
329 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
330 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
332 lyxerr[Debug::INFO] << "Will insert file without header"
334 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
342 bool BufferView::removeAutoInsets()
344 // keep track of which pos and par the cursor was on
345 Paragraph * cursor_par = text->cursor.par();
346 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
347 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
348 pos_type cursor_pos = text->cursor.pos();
352 // Trap the deletion of the paragraph the cursor is in.
353 // Iterate until we find a paragraph that won't be immediately deleted.
354 // In reality this should mean we only execute the body of the while
355 // loop once at most. However for safety we iterate rather than just
356 // make this an if () conditional.
357 while ((cursor_par_prev || cursor_par_next)
359 cursor_par_prev ? cursor_par_prev : cursor_par_next,
361 // We just removed cursor_par so have to fix the "cursor"
362 if (cursor_par_prev) {
366 cursor_par = cursor_par_prev;
367 cursor_pos = cursor_par->size();
371 cursor_par = cursor_par_next;
374 cursor_par_prev = cursor_par->previous();
375 cursor_par_next = cursor_par->next();
378 // Iterate through the paragraphs removing autoDelete insets as we go.
379 // If the paragraph ends up empty after all the autoDelete insets are
380 // removed that paragraph will be removed by the next setCursor() call.
381 ParIterator it = buffer()->par_iterator_begin();
382 ParIterator end = buffer()->par_iterator_end();
383 for (; it != end; ++it) {
384 Paragraph * par = *it;
385 Paragraph * par_prev = par ? par->previous() : 0;
386 bool removed = false;
388 if (text->setCursor(par, 0)
389 && cursor_par == par_prev) {
390 // The previous setCursor line was deleted and that
391 // was the cursor_par line. This can only happen if an
392 // error box was the sole item on cursor_par.
393 // It is possible for cursor_par_prev to be stray if
394 // the line it pointed to only had a error box on it
395 // so we have to set it to a known correct value.
396 // This is often the same value it already had.
397 cursor_par_prev = par->previous();
398 if (cursor_par_prev) {
399 // '|' = par, '.' = cursor_par, 'E' = error box
400 // First step below may occur before while{}
402 // E -> .E -> |.E -> . -> |b
405 cursor_par = cursor_par_prev;
406 cursor_pos = cursor_par_prev->size();
407 cursor_par_prev = cursor_par->previous();
408 // cursor_par_next remains the same
409 } else if (cursor_par_next) {
410 // First step below may occur before while{}
412 // E -> |.E -> |. -> . -> .|a
414 cursor_par = cursor_par_next;
416 // cursor_par_prev remains unset
417 cursor_par_next = cursor_par->next();
419 // I can't find a way to trigger this
420 // so it should be unreachable code
421 // unless the buffer is corrupted.
422 lyxerr << "BufferView::removeAutoInsets() is bad\n";
426 InsetList::iterator pit = par->insetlist.begin();
427 InsetList::iterator pend = par->insetlist.end();
429 while (pit != pend) {
430 if (pit.getInset()->autoDelete()) {
432 pos_type const pos = pit.getPos();
435 // We just invalidated par's inset iterators so
436 // we get the next valid iterator position
437 pit = par->insetlist.insetIterator(pos);
438 // and ensure we have a valid end iterator.
439 pend = par->insetlist.end();
441 if (cursor_par == par) {
442 // update the saved cursor position
443 if (cursor_pos > pos)
452 text->redoParagraph();
456 // It is possible that the last line is empty if it was cursor_par
457 // and/or only had an error inset on it. So we set the cursor to the
458 // start of the doc to force its removal and ensure a valid saved cursor
459 if (text->setCursor(text->ownerParagraph(), 0)
460 && 0 == cursor_par_next) {
461 cursor_par = cursor_par_prev;
462 cursor_pos = cursor_par->size();
463 } else if (cursor_pos > cursor_par->size()) {
464 // Some C-Enter lines were removed by the setCursor call which
465 // then invalidated cursor_pos. It could still be "wrong" because
466 // the cursor may appear to have jumped but since we collapsed
467 // some C-Enter lines this should be a reasonable compromise.
468 cursor_pos = cursor_par->size();
471 // restore the original cursor in its corrected location.
472 text->setCursorIntern(cursor_par, cursor_pos);
478 void BufferView::insertErrors(TeXErrors & terr)
480 // Save the cursor position
481 LyXCursor cursor = text->cursor;
483 TeXErrors::Errors::const_iterator cit = terr.begin();
484 TeXErrors::Errors::const_iterator end = terr.end();
485 for (; cit != end; ++cit) {
486 string const desctext(cit->error_desc);
487 string const errortext(cit->error_text);
488 string const msgtxt = desctext + '\n' + errortext;
489 int const errorrow = cit->error_in_line;
491 // Insert error string for row number
495 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
496 buffer()->texrow.increasePos(tmpid, tmppos);
499 Paragraph * texrowpar = 0;
502 texrowpar = text->ownerParagraph();
505 texrowpar = buffer()->getParFromID(tmpid);
512 InsetError * new_inset = new InsetError(msgtxt);
513 text->setCursorIntern(texrowpar, tmppos);
514 text->insertInset(new_inset);
518 // Restore the cursor position
519 text->setCursorIntern(cursor.par(), cursor.pos());
523 void BufferView::setCursorFromRow(int row)
528 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
530 Paragraph * texrowpar;
533 texrowpar = text->ownerParagraph();
536 texrowpar = buffer()->getParFromID(tmpid);
538 text->setCursor(texrowpar, tmppos);
542 bool BufferView::insertInset(Inset * inset, string const & lout)
544 return pimpl_->insertInset(inset, lout);
548 // This is also a buffer property (ale)
549 // Not so sure about that. a goto Label function can not be buffer local, just
550 // think how this will work in a multiwindow/buffer environment, all the
551 // cursors in all the views showing this buffer will move. (Lgb)
552 // OK, then no cursor action should be allowed in buffer. (ale)
553 bool BufferView::gotoLabel(string const & label)
555 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
556 it != buffer()->inset_iterator_end(); ++it) {
557 vector<string> labels = it->getLabelList();
558 if (find(labels.begin(),labels.end(),label)
561 text->setCursor(it.getPar(), it.getPos());
562 text->selection.cursor = text->cursor;
563 update(text, BufferView::SELECT);
571 void BufferView::undo()
576 owner()->message(_("Undo"));
579 update(text, BufferView::SELECT);
581 owner()->message(_("No further undo information"));
583 update(text, BufferView::SELECT);
588 void BufferView::redo()
593 owner()->message(_("Redo"));
596 update(text, BufferView::SELECT);
598 owner()->message(_("No further redo information"));
600 update(text, BufferView::SELECT);
605 void BufferView::copyEnvironment()
608 text->copyEnvironmentType();
609 owner()->message(_("Paragraph environment type copied"));
614 void BufferView::pasteEnvironment()
617 text->pasteEnvironmentType();
618 owner()->message(_("Paragraph environment type set"));
619 update(text, BufferView::SELECT);
624 // these functions are for the spellchecker
625 WordLangTuple const BufferView::nextWord(float & value)
629 return WordLangTuple();
632 return text->selectNextWordToSpellcheck(value);
636 void BufferView::selectLastWord()
641 LyXCursor cur = text->selection.cursor;
644 text->selection.cursor = cur;
645 text->selectSelectedWord();
646 toggleSelection(false);
647 update(text, BufferView::SELECT);
651 void BufferView::endOfSpellCheck()
653 if (!available()) return;
657 text->selectSelectedWord();
658 text->clearSelection();
659 update(text, BufferView::SELECT);
663 void BufferView::replaceWord(string const & replacestring)
668 LyXText * tt = getLyXText();
670 update(tt, BufferView::SELECT);
672 // clear the selection (if there is any)
673 toggleSelection(false);
674 update(tt, BufferView::SELECT);
676 // clear the selection (if there is any)
677 toggleSelection(false);
678 tt->replaceSelectionWithString(replacestring);
680 tt->setSelectionRange(replacestring.length());
682 // Go back so that replacement string is also spellchecked
683 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
684 tt->cursorLeft(this);
686 update(tt, BufferView::SELECT);
688 // FIXME: should be done through LFUN
689 buffer()->markDirty();
692 // End of spellchecker stuff
695 bool BufferView::lockInset(UpdatableInset * inset)
699 // don't relock if we're already locked
700 if (theLockingInset() == inset)
702 if (!theLockingInset()) {
703 // first check if it's the inset under the cursor we want lock
704 // should be most of the time
705 char const c = text->cursor.par()->getChar(text->cursor.pos());
706 if (c == Paragraph::META_INSET) {
707 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
709 theLockingInset(inset);
713 // Then do a deep look of the inset and lock the right one
714 int const id = inset->id();
715 ParagraphList::iterator pit = buffer()->paragraphs.begin();
716 ParagraphList::iterator pend = buffer()->paragraphs.end();
717 for (; pit != pend; ++pit) {
718 InsetList::iterator it = pit->insetlist.begin();
719 InsetList::iterator end = pit->insetlist.end();
720 for (; it != end; ++it) {
721 if (it.getInset() == inset) {
722 text->setCursorIntern(&*pit, it.getPos());
723 theLockingInset(inset);
726 if (it.getInset()->getInsetFromID(id)) {
727 text->setCursorIntern(&*pit, it.getPos());
728 it.getInset()->edit(this);
729 return theLockingInset()->lockInsetInInset(this, inset);
735 return theLockingInset()->lockInsetInInset(this, inset);
739 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
741 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
742 LyXCursor cursor = text->cursor;
743 Inset * locking_inset = theLockingInset()->getLockingInset();
745 if ((cursor.pos() - 1 >= 0) &&
746 cursor.par()->isInset(cursor.pos() - 1) &&
747 (cursor.par()->getInset(cursor.pos() - 1) ==
749 text->setCursor(cursor,
750 cursor.par(), cursor.pos() - 1);
751 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
752 LyXText * txt = getLyXText();
753 if (locking_inset->isTextInset() &&
754 locking_inset->lyxCode() != Inset::ERT_CODE &&
755 (txt->real_current_font.language() !=
756 buffer()->params.language
757 || txt->real_current_font.isVisibleRightToLeft()
758 != buffer()->params.language->RightToLeft()))
759 shape = (txt->real_current_font.isVisibleRightToLeft())
760 ? LyXScreen::REVERSED_L_SHAPE
761 : LyXScreen::L_SHAPE;
762 y += cursor.iy() + theLockingInset()->insetInInsetY();
763 screen().showManualCursor(text, x, y, asc, desc,
769 void BufferView::hideLockedInsetCursor()
771 if (theLockingInset() && available()) {
772 screen().hideCursor();
777 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
779 if (theLockingInset() && available()) {
780 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
781 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
790 int BufferView::unlockInset(UpdatableInset * inset)
794 if (inset && theLockingInset() == inset) {
795 inset->insetUnlock(this);
797 // make sure we update the combo !
798 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
799 // Tell the paragraph dialog that we changed paragraph
800 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
803 } else if (inset && theLockingInset() &&
804 theLockingInset()->unlockInsetInInset(this, inset)) {
805 // Tell the paragraph dialog that we changed paragraph
806 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
807 // owner inset has updated the layout combo
815 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
817 if (!theLockingInset())
818 return; // shouldn't happen
819 if (kind == Undo::EDIT) // in this case insets would not be stored!
823 text->cursor.par()->next());
827 void BufferView::updateInset(Inset * inset)
829 pimpl_->updateInset(inset);
833 bool BufferView::ChangeInsets(Inset::Code code,
834 string const & from, string const & to)
836 bool need_update = false;
837 LyXCursor cursor = text->cursor;
838 LyXCursor tmpcursor = cursor;
839 cursor.par(tmpcursor.par());
840 cursor.pos(tmpcursor.pos());
842 ParIterator end = buffer()->par_iterator_end();
843 for (ParIterator it = buffer()->par_iterator_begin();
845 Paragraph * par = *it;
846 bool changed_inset = false;
847 for (InsetList::iterator it2 = par->insetlist.begin();
848 it2 != par->insetlist.end(); ++it2) {
849 if (it2.getInset()->lyxCode() == code) {
850 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
851 if (inset->getContents() == from) {
852 inset->setContents(to);
853 changed_inset = true;
862 // The test it.size()==1 was needed to prevent crashes.
863 // How to set the cursor corretly when it.size()>1 ??
864 if (it.size() == 1) {
865 text->setCursorIntern(par, 0);
866 text->redoParagraphs(text->cursor,
867 text->cursor.par()->next());
872 text->setCursorIntern(cursor.par(), cursor.pos());
877 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
879 // Check if the label 'from' appears more than once
880 vector<string> labels = buffer()->getLabelList();
882 if (lyx::count(labels.begin(), labels.end(), from) > 1)
885 return ChangeInsets(Inset::REF_CODE, from, to);
889 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
891 typedef pair<string, string> StringPair;
893 vector<StringPair> keys;
894 buffer()->fillWithBibKeys(keys);
895 if (count_if(keys.begin(), keys.end(),
896 lyx::equal_1st_in_pair<StringPair>(from))
900 return ChangeInsets(Inset::CITE_CODE, from, to);
904 UpdatableInset * BufferView::theLockingInset() const
906 // If NULL is not allowed we should put an Assert here. (Lgb)
908 return text->the_locking_inset;
913 void BufferView::theLockingInset(UpdatableInset * inset)
915 text->the_locking_inset = inset;
919 LyXText * BufferView::getLyXText() const
921 if (theLockingInset()) {
922 LyXText * txt = theLockingInset()->getLyXText(this, true);
930 LyXText * BufferView::getParentText(Inset * inset) const
932 if (inset->owner()) {
933 LyXText * txt = inset->getLyXText(this);
934 inset = inset->owner();
935 while (inset && inset->getLyXText(this) == txt)
936 inset = inset->owner();
938 return inset->getLyXText(this);
944 Language const * BufferView::getParentLanguage(Inset * inset) const
946 LyXText * text = getParentText(inset);
947 return text->cursor.par()->getFontSettings(buffer()->params,
948 text->cursor.pos()).language();
952 Encoding const * BufferView::getEncoding() const
954 LyXText * t = getLyXText();
958 LyXCursor const & c= t->cursor;
959 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
960 return font.language()->encoding();
964 void BufferView::haveSelection(bool sel)
966 pimpl_->workarea().haveSelection(sel);
970 int BufferView::workHeight() const
972 return pimpl_->workarea().workHeight();