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 "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");
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->ownerParagraph(), 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->ownerParagraph();
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->ownerParagraph();
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 char const c = text->cursor.par()->getChar(text->cursor.pos());
717 if (c == 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();