3 * Copyright 1995-2002 the LyX Team
4 * Read the file COPYING
7 * \author John Levon <moz@compsoc.man.ac.uk>
13 #pragma implementation
16 #include "BufferView.h"
17 #include "BufferView_pimpl.h"
19 #include "BufferView_pimpl.h"
21 #include "WordLangTuple.h"
23 #include "bufferlist.h"
26 #include "iterators.h"
28 #include "lyxcursor.h"
31 #include "undo_funcs.h"
33 #include "frontends/Alert.h"
34 #include "frontends/Dialogs.h"
35 #include "frontends/LyXView.h"
36 #include "frontends/WorkArea.h"
37 #include "frontends/screen.h"
39 #include "insets/insetcommand.h" // ChangeRefs
40 #include "insets/inseterror.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
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()))
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 void BufferView::beforeChange(LyXText * text)
167 pimpl_->beforeChange(text);
171 void BufferView::savePosition(unsigned int i)
173 pimpl_->savePosition(i);
177 void BufferView::restorePosition(unsigned int i)
179 pimpl_->restorePosition(i);
183 bool BufferView::isSavedPosition(unsigned int i)
185 return pimpl_->isSavedPosition(i);
189 void BufferView::update(LyXText * text, UpdateCodes f)
191 pimpl_->update(text, f);
195 void BufferView::switchKeyMap()
197 pimpl_->switchKeyMap();
201 void BufferView::insetUnlock()
203 pimpl_->insetUnlock();
207 int BufferView::workWidth() const
209 return pimpl_->workarea().workWidth();
213 void BufferView::showCursor()
215 pimpl_->showCursor();
219 void BufferView::hideCursor()
221 pimpl_->hideCursor();
225 void BufferView::toggleSelection(bool b)
227 pimpl_->toggleSelection(b);
231 void BufferView::toggleToggle()
233 pimpl_->toggleToggle();
237 void BufferView::center()
243 string const BufferView::getClipboard() const
245 return pimpl_->workarea().getClipboard();
249 void BufferView::stuffClipboard(string const & stuff) const
251 pimpl_->stuffClipboard(stuff);
255 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
256 BufferView::UpdateCodes uc2)
258 return static_cast<BufferView::UpdateCodes>
259 (static_cast<int>(uc1) | static_cast<int>(uc2));
263 bool BufferView::dispatch(FuncRequest const & ev)
265 return pimpl_->dispatch(ev);
269 void BufferView::scroll(int lines)
271 pimpl_->scroll(lines);
275 int BufferView::defaultHeight() const
277 return text->defaultHeight();
282 // Inserts a file into current document
283 bool BufferView::insertLyXFile(string const & filen)
285 // Copyright CHT Software Service GmbH
288 // Insert a LyXformat - file into current buffer
290 // Moved from lyx_cb.C (Lgb)
295 string const fname = MakeAbsPath(filen);
297 // check if file exist
298 FileInfo const fi(fname);
300 if (!fi.readable()) {
301 Alert::alert(_("Error!"),
302 _("Specified file is unreadable: "),
303 MakeDisplayPath(fname, 50));
309 ifstream ifs(fname.c_str());
311 Alert::err_alert(_("Error! Cannot open specified file:"),
312 MakeDisplayPath(fname, 50));
316 int const c = ifs.peek();
324 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
325 res = buffer()->readFile(lex, fname, text->cursor.par());
327 lyxerr[Debug::INFO] << "Will insert file without header"
329 res = buffer()->readLyXformat2(lex, text->cursor.par());
337 bool BufferView::removeAutoInsets()
339 // keep track of which pos and par the cursor was on
340 Paragraph * cursor_par = text->cursor.par();
341 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
342 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
343 pos_type cursor_pos = text->cursor.pos();
347 // Trap the deletion of the paragraph the cursor is in.
348 // Iterate until we find a paragraph that won't be immediately deleted.
349 // In reality this should mean we only execute the body of the while
350 // loop once at most. However for safety we iterate rather than just
351 // make this an if () conditional.
352 while ((cursor_par_prev || cursor_par_next)
353 && text->setCursor(this,
354 cursor_par_prev ? cursor_par_prev : cursor_par_next,
356 // We just removed cursor_par so have to fix the "cursor"
357 if (cursor_par_prev) {
361 cursor_par = cursor_par_prev;
362 cursor_pos = cursor_par->size();
366 cursor_par = cursor_par_next;
369 cursor_par_prev = cursor_par->previous();
370 cursor_par_next = cursor_par->next();
373 // Iterate through the paragraphs removing autoDelete insets as we go.
374 // If the paragraph ends up empty after all the autoDelete insets are
375 // removed that paragraph will be removed by the next setCursor() call.
376 ParIterator it = buffer()->par_iterator_begin();
377 ParIterator end = buffer()->par_iterator_end();
378 for (; it != end; ++it) {
379 Paragraph * par = *it;
380 Paragraph * par_prev = par ? par->previous() : 0;
381 bool removed = false;
383 if (text->setCursor(this, par, 0)
384 && cursor_par == par_prev) {
385 // The previous setCursor line was deleted and that
386 // was the cursor_par line. This can only happen if an
387 // error box was the sole item on cursor_par.
388 // It is possible for cursor_par_prev to be stray if
389 // the line it pointed to only had a error box on it
390 // so we have to set it to a known correct value.
391 // This is often the same value it already had.
392 cursor_par_prev = par->previous();
393 if (cursor_par_prev) {
394 // '|' = par, '.' = cursor_par, 'E' = error box
395 // First step below may occur before while{}
397 // E -> .E -> |.E -> . -> |b
400 cursor_par = cursor_par_prev;
401 cursor_pos = cursor_par_prev->size();
402 cursor_par_prev = cursor_par->previous();
403 // cursor_par_next remains the same
404 } else if (cursor_par_next) {
405 // First step below may occur before while{}
407 // E -> |.E -> |. -> . -> .|a
409 cursor_par = cursor_par_next;
411 // cursor_par_prev remains unset
412 cursor_par_next = cursor_par->next();
414 // I can't find a way to trigger this
415 // so it should be unreachable code
416 // unless the buffer is corrupted.
417 lyxerr << "BufferView::removeAutoInsets() is bad\n";
421 InsetList::iterator pit = par->insetlist.begin();
422 InsetList::iterator pend = par->insetlist.end();
424 while (pit != pend) {
425 if (pit.getInset()->autoDelete()) {
427 pos_type const pos = pit.getPos();
430 // We just invalidated par's inset iterators so
431 // we get the next valid iterator position
432 pit = par->insetlist.insetIterator(pos);
433 // and ensure we have a valid end iterator.
434 pend = par->insetlist.end();
436 if (cursor_par == par) {
437 // update the saved cursor position
438 if (cursor_pos > pos)
447 text->redoParagraph(this);
451 // It is possible that the last line is empty if it was cursor_par
452 // and/or only had an error inset on it. So we set the cursor to the
453 // start of the doc to force its removal and ensure a valid saved cursor
454 if (text->setCursor(this, text->ownerParagraph(), 0)
455 && 0 == cursor_par_next) {
456 cursor_par = cursor_par_prev;
457 cursor_pos = cursor_par->size();
458 } else if (cursor_pos > cursor_par->size()) {
459 // Some C-Enter lines were removed by the setCursor call which
460 // then invalidated cursor_pos. It could still be "wrong" because
461 // the cursor may appear to have jumped but since we collapsed
462 // some C-Enter lines this should be a reasonable compromise.
463 cursor_pos = cursor_par->size();
466 // restore the original cursor in its corrected location.
467 text->setCursorIntern(this, cursor_par, cursor_pos);
473 void BufferView::insertErrors(TeXErrors & terr)
475 // Save the cursor position
476 LyXCursor cursor = text->cursor;
478 TeXErrors::Errors::const_iterator cit = terr.begin();
479 TeXErrors::Errors::const_iterator end = terr.end();
480 for (; cit != end; ++cit) {
481 string const desctext(cit->error_desc);
482 string const errortext(cit->error_text);
483 string const msgtxt = desctext + '\n' + errortext;
484 int const errorrow = cit->error_in_line;
486 // Insert error string for row number
490 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
491 buffer()->texrow.increasePos(tmpid, tmppos);
494 Paragraph * texrowpar = 0;
497 texrowpar = text->ownerParagraph();
500 texrowpar = buffer()->getParFromID(tmpid);
507 InsetError * new_inset = new InsetError(msgtxt);
508 text->setCursorIntern(this, texrowpar, tmppos);
509 text->insertInset(this, new_inset);
510 text->fullRebreak(this);
513 // Restore the cursor position
514 text->setCursorIntern(this, cursor.par(), cursor.pos());
518 void BufferView::setCursorFromRow(int row)
523 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
525 Paragraph * texrowpar;
528 texrowpar = text->ownerParagraph();
531 texrowpar = buffer()->getParFromID(tmpid);
533 text->setCursor(this, texrowpar, tmppos);
537 bool BufferView::insertInset(Inset * inset, string const & lout)
539 return pimpl_->insertInset(inset, lout);
543 // This is also a buffer property (ale)
544 // Not so sure about that. a goto Label function can not be buffer local, just
545 // think how this will work in a multiwindow/buffer environment, all the
546 // cursors in all the views showing this buffer will move. (Lgb)
547 // OK, then no cursor action should be allowed in buffer. (ale)
548 bool BufferView::gotoLabel(string const & label)
550 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
551 it != buffer()->inset_iterator_end(); ++it) {
552 vector<string> labels = it->getLabelList();
553 if (find(labels.begin(),labels.end(),label)
556 text->setCursor(this, it.getPar(), it.getPos());
557 text->selection.cursor = text->cursor;
558 update(text, BufferView::SELECT|BufferView::FITCUR);
566 void BufferView::undo()
571 owner()->message(_("Undo"));
574 update(text, BufferView::SELECT|BufferView::FITCUR);
576 owner()->message(_("No further undo information"));
578 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
583 void BufferView::redo()
588 owner()->message(_("Redo"));
591 update(text, BufferView::SELECT|BufferView::FITCUR);
593 owner()->message(_("No further redo information"));
595 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
600 void BufferView::copyEnvironment()
603 text->copyEnvironmentType();
604 owner()->message(_("Paragraph environment type copied"));
609 void BufferView::pasteEnvironment()
612 text->pasteEnvironmentType(this);
613 owner()->message(_("Paragraph environment type set"));
614 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
619 // these functions are for the spellchecker
620 WordLangTuple const BufferView::nextWord(float & value)
624 return WordLangTuple();
627 return text->selectNextWordToSpellcheck(this, value);
631 void BufferView::selectLastWord()
636 LyXCursor cur = text->selection.cursor;
639 text->selection.cursor = cur;
640 text->selectSelectedWord(this);
641 toggleSelection(false);
642 update(text, BufferView::SELECT|BufferView::FITCUR);
646 void BufferView::endOfSpellCheck()
648 if (!available()) return;
652 text->selectSelectedWord(this);
653 text->clearSelection();
654 update(text, BufferView::SELECT|BufferView::FITCUR);
658 void BufferView::replaceWord(string const & replacestring)
663 LyXText * tt = getLyXText();
665 update(tt, BufferView::SELECT|BufferView::FITCUR);
667 // clear the selection (if there is any)
668 toggleSelection(false);
669 update(tt, BufferView::SELECT|BufferView::FITCUR);
671 // clear the selection (if there is any)
672 toggleSelection(false);
673 tt->replaceSelectionWithString(this, replacestring);
675 tt->setSelectionOverString(this, replacestring);
677 // Go back so that replacement string is also spellchecked
678 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
679 tt->cursorLeft(this);
681 update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
683 // End of spellchecker stuff
686 bool BufferView::lockInset(UpdatableInset * inset)
690 // don't relock if we're already locked
691 if (theLockingInset() == inset)
693 if (!theLockingInset()) {
694 // first check if it's the inset under the cursor we want lock
695 // should be most of the time
696 char const c = text->cursor.par()->getChar(text->cursor.pos());
697 if (c == Paragraph::META_INSET) {
698 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
700 theLockingInset(inset);
704 // Then do a deep look of the inset and lock the right one
705 int const id = inset->id();
706 ParagraphList::iterator pit = buffer()->paragraphs.begin();
707 ParagraphList::iterator pend = buffer()->paragraphs.end();
708 for (; pit != pend; ++pit) {
709 InsetList::iterator it = pit->insetlist.begin();
710 InsetList::iterator end = pit->insetlist.end();
711 for (; it != end; ++it) {
712 if (it.getInset() == inset) {
713 text->setCursorIntern(this, &*pit, it.getPos());
714 theLockingInset(inset);
717 if (it.getInset()->getInsetFromID(id)) {
718 text->setCursorIntern(this, &*pit, it.getPos());
719 it.getInset()->edit(this);
720 return theLockingInset()->lockInsetInInset(this, inset);
726 return theLockingInset()->lockInsetInInset(this, inset);
730 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
732 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
733 LyXCursor cursor = text->cursor;
734 Inset * locking_inset = theLockingInset()->getLockingInset();
736 if ((cursor.pos() - 1 >= 0) &&
737 cursor.par()->isInset(cursor.pos() - 1) &&
738 (cursor.par()->getInset(cursor.pos() - 1) ==
740 text->setCursor(this, cursor,
741 cursor.par(), cursor.pos() - 1);
742 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
743 LyXText * txt = getLyXText();
744 if (locking_inset->isTextInset() &&
745 locking_inset->lyxCode() != Inset::ERT_CODE &&
746 (txt->real_current_font.language() !=
747 buffer()->params.language
748 || txt->real_current_font.isVisibleRightToLeft()
749 != buffer()->params.language->RightToLeft()))
750 shape = (txt->real_current_font.isVisibleRightToLeft())
751 ? LyXScreen::REVERSED_L_SHAPE
752 : LyXScreen::L_SHAPE;
753 y += cursor.iy() + theLockingInset()->insetInInsetY();
754 screen().showManualCursor(text, x, y, asc, desc,
760 void BufferView::hideLockedInsetCursor()
762 if (theLockingInset() && available()) {
763 screen().hideCursor();
768 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
770 if (theLockingInset() && available()) {
771 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
772 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
781 int BufferView::unlockInset(UpdatableInset * inset)
785 if (inset && theLockingInset() == inset) {
786 inset->insetUnlock(this);
788 // make sure we update the combo !
789 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
790 // Tell the paragraph dialog that we changed paragraph
791 owner()->getDialogs().updateParagraph();
794 } else if (inset && theLockingInset() &&
795 theLockingInset()->unlockInsetInInset(this, inset)) {
796 // Tell the paragraph dialog that we changed paragraph
797 owner()->getDialogs().updateParagraph();
798 // owner inset has updated the layout combo
802 return bufferlist.unlockInset(inset);
806 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
808 if (!theLockingInset())
809 return; // shouldn't happen
810 if (kind == Undo::EDIT) // in this case insets would not be stored!
814 text->cursor.par()->next());
818 void BufferView::updateInset(Inset * inset, bool mark_dirty)
820 pimpl_->updateInset(inset, mark_dirty);
824 bool BufferView::ChangeInsets(Inset::Code code,
825 string const & from, string const & to)
827 bool need_update = false;
828 LyXCursor cursor = text->cursor;
829 LyXCursor tmpcursor = cursor;
830 cursor.par(tmpcursor.par());
831 cursor.pos(tmpcursor.pos());
833 ParIterator end = buffer()->par_iterator_end();
834 for (ParIterator it = buffer()->par_iterator_begin();
836 Paragraph * par = *it;
837 bool changed_inset = false;
838 for (InsetList::iterator it2 = par->insetlist.begin();
839 it2 != par->insetlist.end(); ++it2) {
840 if (it2.getInset()->lyxCode() == code) {
841 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
842 if (inset->getContents() == from) {
843 inset->setContents(to);
844 changed_inset = true;
853 // The test it.size()==1 was needed to prevent crashes.
854 // How to set the cursor corretly when it.size()>1 ??
855 if (it.size() == 1) {
856 text->setCursorIntern(this, par, 0);
857 text->redoParagraphs(this, text->cursor,
858 text->cursor.par()->next());
859 text->fullRebreak(this);
863 text->setCursorIntern(this, cursor.par(), cursor.pos());
868 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
870 // Check if the label 'from' appears more than once
871 vector<string> labels = buffer()->getLabelList();
873 if (lyx::count(labels.begin(), labels.end(), from) > 1)
876 return ChangeInsets(Inset::REF_CODE, from, to);
880 bool BufferView::ChangeCitationsIfUnique(string const & from,
883 typedef pair<string, string> StringPair;
885 vector<StringPair> keys = buffer()->getBibkeyList();
886 if (count_if(keys.begin(), keys.end(),
887 lyx::equal_1st_in_pair<StringPair>(from))
891 return ChangeInsets(Inset::CITE_CODE, from, to);
895 UpdatableInset * BufferView::theLockingInset() const
897 // If NULL is not allowed we should put an Assert here. (Lgb)
899 return text->the_locking_inset;
904 void BufferView::theLockingInset(UpdatableInset * inset)
906 text->the_locking_inset = inset;
910 LyXText * BufferView::getLyXText() const
912 if (theLockingInset()) {
913 LyXText * txt = theLockingInset()->getLyXText(this, true);
921 LyXText * BufferView::getParentText(Inset * inset) const
923 if (inset->owner()) {
924 LyXText * txt = inset->getLyXText(this);
925 inset = inset->owner();
926 while (inset && inset->getLyXText(this) == txt)
927 inset = inset->owner();
929 return inset->getLyXText(this);
935 Language const * BufferView::getParentLanguage(Inset * inset) const
937 LyXText * text = getParentText(inset);
938 return text->cursor.par()->getFontSettings(buffer()->params,
939 text->cursor.pos()).language();
943 Encoding const * BufferView::getEncoding() const
945 LyXText * t = getLyXText();
949 LyXCursor const & c= t->cursor;
950 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
951 return font.language()->encoding();
955 void BufferView::haveSelection(bool sel)
957 pimpl_->workarea().haveSelection(sel);
961 int BufferView::workHeight() const
963 return pimpl_->workarea().workHeight();