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 char const c = text->cursor.par()->getChar(text->cursor.pos());
716 if (c == Paragraph::META_INSET) {
717 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
719 theLockingInset(inset);
723 // Then do a deep look of the inset and lock the right one
724 int const id = inset->id();
725 ParagraphList::iterator pit = buffer()->paragraphs.begin();
726 ParagraphList::iterator pend = buffer()->paragraphs.end();
727 for (; pit != pend; ++pit) {
728 InsetList::iterator it = pit->insetlist.begin();
729 InsetList::iterator end = pit->insetlist.end();
730 for (; it != end; ++it) {
731 if (it.getInset() == inset) {
732 text->setCursorIntern(&*pit, it.getPos());
733 theLockingInset(inset);
736 if (it.getInset()->getInsetFromID(id)) {
737 text->setCursorIntern(&*pit, it.getPos());
738 it.getInset()->edit(this);
739 return theLockingInset()->lockInsetInInset(this, inset);
745 return theLockingInset()->lockInsetInInset(this, inset);
749 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
751 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
752 LyXCursor cursor = text->cursor;
753 Inset * locking_inset = theLockingInset()->getLockingInset();
755 if ((cursor.pos() - 1 >= 0) &&
756 cursor.par()->isInset(cursor.pos() - 1) &&
757 (cursor.par()->getInset(cursor.pos() - 1) ==
759 text->setCursor(cursor,
760 cursor.par(), cursor.pos() - 1);
761 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
762 LyXText * txt = getLyXText();
763 if (locking_inset->isTextInset() &&
764 locking_inset->lyxCode() != Inset::ERT_CODE &&
765 (txt->real_current_font.language() !=
766 buffer()->params.language
767 || txt->real_current_font.isVisibleRightToLeft()
768 != buffer()->params.language->RightToLeft()))
769 shape = (txt->real_current_font.isVisibleRightToLeft())
770 ? LyXScreen::REVERSED_L_SHAPE
771 : LyXScreen::L_SHAPE;
772 y += cursor.iy() + theLockingInset()->insetInInsetY();
773 screen().showManualCursor(text, x, y, asc, desc,
779 void BufferView::hideLockedInsetCursor()
781 if (theLockingInset() && available()) {
782 screen().hideCursor();
787 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
789 if (theLockingInset() && available()) {
790 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
791 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
800 int BufferView::unlockInset(UpdatableInset * inset)
804 if (inset && theLockingInset() == inset) {
805 inset->insetUnlock(this);
807 // make sure we update the combo !
808 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
809 // Tell the paragraph dialog that we changed paragraph
810 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
813 } else if (inset && theLockingInset() &&
814 theLockingInset()->unlockInsetInInset(this, inset)) {
815 // Tell the paragraph dialog that we changed paragraph
816 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
817 // owner inset has updated the layout combo
825 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
827 if (!theLockingInset())
828 return; // shouldn't happen
829 if (kind == Undo::EDIT) // in this case insets would not be stored!
833 text->cursor.par()->next());
837 void BufferView::updateInset(Inset * inset)
839 pimpl_->updateInset(inset);
843 bool BufferView::ChangeInsets(Inset::Code code,
844 string const & from, string const & to)
846 bool need_update = false;
847 LyXCursor cursor = text->cursor;
848 LyXCursor tmpcursor = cursor;
849 cursor.par(tmpcursor.par());
850 cursor.pos(tmpcursor.pos());
852 ParIterator end = buffer()->par_iterator_end();
853 for (ParIterator it = buffer()->par_iterator_begin();
855 Paragraph * par = *it;
856 bool changed_inset = false;
857 for (InsetList::iterator it2 = par->insetlist.begin();
858 it2 != par->insetlist.end(); ++it2) {
859 if (it2.getInset()->lyxCode() == code) {
860 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
861 if (inset->getContents() == from) {
862 inset->setContents(to);
863 changed_inset = true;
872 // The test it.size()==1 was needed to prevent crashes.
873 // How to set the cursor corretly when it.size()>1 ??
874 if (it.size() == 1) {
875 text->setCursorIntern(par, 0);
876 text->redoParagraphs(text->cursor,
877 text->cursor.par()->next());
882 text->setCursorIntern(cursor.par(), cursor.pos());
887 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
889 // Check if the label 'from' appears more than once
890 vector<string> labels = buffer()->getLabelList();
892 if (lyx::count(labels.begin(), labels.end(), from) > 1)
895 return ChangeInsets(Inset::REF_CODE, from, to);
899 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
901 typedef pair<string, string> StringPair;
903 vector<StringPair> keys;
904 buffer()->fillWithBibKeys(keys);
905 if (count_if(keys.begin(), keys.end(),
906 lyx::equal_1st_in_pair<StringPair>(from))
910 return ChangeInsets(Inset::CITE_CODE, from, to);
914 UpdatableInset * BufferView::theLockingInset() const
916 // If NULL is not allowed we should put an Assert here. (Lgb)
918 return text->the_locking_inset;
923 void BufferView::theLockingInset(UpdatableInset * inset)
925 text->the_locking_inset = inset;
929 LyXText * BufferView::getLyXText() const
931 if (theLockingInset()) {
932 LyXText * txt = theLockingInset()->getLyXText(this, true);
940 LyXText * BufferView::getParentText(Inset * inset) const
942 if (inset->owner()) {
943 LyXText * txt = inset->getLyXText(this);
944 inset = inset->owner();
945 while (inset && inset->getLyXText(this) == txt)
946 inset = inset->owner();
948 return inset->getLyXText(this);
954 Language const * BufferView::getParentLanguage(Inset * inset) const
956 LyXText * text = getParentText(inset);
957 return text->cursor.par()->getFontSettings(buffer()->params,
958 text->cursor.pos()).language();
962 Encoding const * BufferView::getEncoding() const
964 LyXText * t = getLyXText();
968 LyXCursor const & c= t->cursor;
969 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
970 return font.language()->encoding();
974 void BufferView::haveSelection(bool sel)
976 pimpl_->workarea().haveSelection(sel);
980 int BufferView::workHeight() const
982 return pimpl_->workarea().workHeight();