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 Alert::alert(_("Error!"),
307 _("Specified file is unreadable: "),
308 MakeDisplayPath(fname, 50));
314 ifstream ifs(fname.c_str());
316 string const error = strerror(errno);
317 string const file = MakeDisplayPath(fname, 50);
319 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
322 string text = fmt.str();
324 string text = _("Could not open the specified document\n");
325 text += file + _(" due to the error: ");
328 Alert::error(_("Could not open file"), text);
332 int const c = ifs.peek();
340 // FIXME: huh ? No we won't !
341 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
342 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
344 lyxerr[Debug::INFO] << "Will insert file without header"
346 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
354 bool BufferView::removeAutoInsets()
356 // keep track of which pos and par the cursor was on
357 Paragraph * cursor_par = text->cursor.par();
358 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
359 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
360 pos_type cursor_pos = text->cursor.pos();
364 // Trap the deletion of the paragraph the cursor is in.
365 // Iterate until we find a paragraph that won't be immediately deleted.
366 // In reality this should mean we only execute the body of the while
367 // loop once at most. However for safety we iterate rather than just
368 // make this an if () conditional.
369 while ((cursor_par_prev || cursor_par_next)
371 cursor_par_prev ? cursor_par_prev : cursor_par_next,
373 // We just removed cursor_par so have to fix the "cursor"
374 if (cursor_par_prev) {
378 cursor_par = cursor_par_prev;
379 cursor_pos = cursor_par->size();
383 cursor_par = cursor_par_next;
386 cursor_par_prev = cursor_par->previous();
387 cursor_par_next = cursor_par->next();
390 // Iterate through the paragraphs removing autoDelete insets as we go.
391 // If the paragraph ends up empty after all the autoDelete insets are
392 // removed that paragraph will be removed by the next setCursor() call.
393 ParIterator it = buffer()->par_iterator_begin();
394 ParIterator end = buffer()->par_iterator_end();
395 for (; it != end; ++it) {
396 Paragraph * par = *it;
397 Paragraph * par_prev = par ? par->previous() : 0;
398 bool removed = false;
400 if (text->setCursor(par, 0)
401 && cursor_par == par_prev) {
402 // The previous setCursor line was deleted and that
403 // was the cursor_par line. This can only happen if an
404 // error box was the sole item on cursor_par.
405 // It is possible for cursor_par_prev to be stray if
406 // the line it pointed to only had a error box on it
407 // so we have to set it to a known correct value.
408 // This is often the same value it already had.
409 cursor_par_prev = par->previous();
410 if (cursor_par_prev) {
411 // '|' = par, '.' = cursor_par, 'E' = error box
412 // First step below may occur before while{}
414 // E -> .E -> |.E -> . -> |b
417 cursor_par = cursor_par_prev;
418 cursor_pos = cursor_par_prev->size();
419 cursor_par_prev = cursor_par->previous();
420 // cursor_par_next remains the same
421 } else if (cursor_par_next) {
422 // First step below may occur before while{}
424 // E -> |.E -> |. -> . -> .|a
426 cursor_par = cursor_par_next;
428 // cursor_par_prev remains unset
429 cursor_par_next = cursor_par->next();
431 // I can't find a way to trigger this
432 // so it should be unreachable code
433 // unless the buffer is corrupted.
434 lyxerr << "BufferView::removeAutoInsets() is bad\n";
438 InsetList::iterator pit = par->insetlist.begin();
439 InsetList::iterator pend = par->insetlist.end();
441 while (pit != pend) {
442 if (pit.getInset()->autoDelete()) {
444 pos_type const pos = pit.getPos();
447 // We just invalidated par's inset iterators so
448 // we get the next valid iterator position
449 pit = par->insetlist.insetIterator(pos);
450 // and ensure we have a valid end iterator.
451 pend = par->insetlist.end();
453 if (cursor_par == par) {
454 // update the saved cursor position
455 if (cursor_pos > pos)
464 text->redoParagraph();
468 // It is possible that the last line is empty if it was cursor_par
469 // and/or only had an error inset on it. So we set the cursor to the
470 // start of the doc to force its removal and ensure a valid saved cursor
471 if (text->setCursor(text->ownerParagraph(), 0)
472 && 0 == cursor_par_next) {
473 cursor_par = cursor_par_prev;
474 cursor_pos = cursor_par->size();
475 } else if (cursor_pos > cursor_par->size()) {
476 // Some C-Enter lines were removed by the setCursor call which
477 // then invalidated cursor_pos. It could still be "wrong" because
478 // the cursor may appear to have jumped but since we collapsed
479 // some C-Enter lines this should be a reasonable compromise.
480 cursor_pos = cursor_par->size();
483 // restore the original cursor in its corrected location.
484 text->setCursorIntern(cursor_par, cursor_pos);
490 void BufferView::insertErrors(TeXErrors & terr)
492 // Save the cursor position
493 LyXCursor cursor = text->cursor;
495 TeXErrors::Errors::const_iterator cit = terr.begin();
496 TeXErrors::Errors::const_iterator end = terr.end();
497 for (; cit != end; ++cit) {
498 string const desctext(cit->error_desc);
499 string const errortext(cit->error_text);
500 string const msgtxt = desctext + '\n' + errortext;
501 int const errorrow = cit->error_in_line;
503 // Insert error string for row number
507 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
508 buffer()->texrow.increasePos(tmpid, tmppos);
511 Paragraph * texrowpar = 0;
514 texrowpar = text->ownerParagraph();
517 texrowpar = buffer()->getParFromID(tmpid);
524 InsetError * new_inset = new InsetError(msgtxt);
525 text->setCursorIntern(texrowpar, tmppos);
526 text->insertInset(new_inset);
530 // Restore the cursor position
531 text->setCursorIntern(cursor.par(), cursor.pos());
535 void BufferView::setCursorFromRow(int row)
540 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
542 Paragraph * texrowpar;
545 texrowpar = text->ownerParagraph();
548 texrowpar = buffer()->getParFromID(tmpid);
550 text->setCursor(texrowpar, tmppos);
554 bool BufferView::insertInset(Inset * inset, string const & lout)
556 return pimpl_->insertInset(inset, lout);
560 // This is also a buffer property (ale)
561 // Not so sure about that. a goto Label function can not be buffer local, just
562 // think how this will work in a multiwindow/buffer environment, all the
563 // cursors in all the views showing this buffer will move. (Lgb)
564 // OK, then no cursor action should be allowed in buffer. (ale)
565 bool 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);
583 void BufferView::undo()
588 owner()->message(_("Undo"));
591 update(text, BufferView::SELECT);
593 owner()->message(_("No further undo information"));
595 update(text, BufferView::SELECT);
600 void BufferView::redo()
605 owner()->message(_("Redo"));
608 update(text, BufferView::SELECT);
610 owner()->message(_("No further redo information"));
612 update(text, BufferView::SELECT);
617 void BufferView::copyEnvironment()
620 text->copyEnvironmentType();
621 owner()->message(_("Paragraph environment type copied"));
626 void BufferView::pasteEnvironment()
629 text->pasteEnvironmentType();
630 owner()->message(_("Paragraph environment type set"));
631 update(text, BufferView::SELECT);
636 // these functions are for the spellchecker
637 WordLangTuple const BufferView::nextWord(float & value)
641 return WordLangTuple();
644 return text->selectNextWordToSpellcheck(value);
648 void BufferView::selectLastWord()
653 LyXCursor cur = text->selection.cursor;
656 text->selection.cursor = cur;
657 text->selectSelectedWord();
658 toggleSelection(false);
659 update(text, BufferView::SELECT);
663 void BufferView::endOfSpellCheck()
665 if (!available()) return;
669 text->selectSelectedWord();
670 text->clearSelection();
671 update(text, BufferView::SELECT);
675 void BufferView::replaceWord(string const & replacestring)
680 LyXText * tt = getLyXText();
682 update(tt, BufferView::SELECT);
684 // clear the selection (if there is any)
685 toggleSelection(false);
686 update(tt, BufferView::SELECT);
688 // clear the selection (if there is any)
689 toggleSelection(false);
690 tt->replaceSelectionWithString(replacestring);
692 tt->setSelectionRange(replacestring.length());
694 // Go back so that replacement string is also spellchecked
695 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
696 tt->cursorLeft(this);
698 update(tt, BufferView::SELECT);
700 // FIXME: should be done through LFUN
701 buffer()->markDirty();
704 // End of spellchecker stuff
707 bool BufferView::lockInset(UpdatableInset * inset)
711 // don't relock if we're already locked
712 if (theLockingInset() == inset)
714 if (!theLockingInset()) {
715 // first check if it's the inset under the cursor we want lock
716 // should be most of the time
717 char const c = text->cursor.par()->getChar(text->cursor.pos());
718 if (c == Paragraph::META_INSET) {
719 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
721 theLockingInset(inset);
725 // Then do a deep look of the inset and lock the right one
726 int const id = inset->id();
727 ParagraphList::iterator pit = buffer()->paragraphs.begin();
728 ParagraphList::iterator pend = buffer()->paragraphs.end();
729 for (; pit != pend; ++pit) {
730 InsetList::iterator it = pit->insetlist.begin();
731 InsetList::iterator end = pit->insetlist.end();
732 for (; it != end; ++it) {
733 if (it.getInset() == inset) {
734 text->setCursorIntern(&*pit, it.getPos());
735 theLockingInset(inset);
738 if (it.getInset()->getInsetFromID(id)) {
739 text->setCursorIntern(&*pit, it.getPos());
740 it.getInset()->edit(this);
741 return theLockingInset()->lockInsetInInset(this, inset);
747 return theLockingInset()->lockInsetInInset(this, inset);
751 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
753 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
754 LyXCursor cursor = text->cursor;
755 Inset * locking_inset = theLockingInset()->getLockingInset();
757 if ((cursor.pos() - 1 >= 0) &&
758 cursor.par()->isInset(cursor.pos() - 1) &&
759 (cursor.par()->getInset(cursor.pos() - 1) ==
761 text->setCursor(cursor,
762 cursor.par(), cursor.pos() - 1);
763 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
764 LyXText * txt = getLyXText();
765 if (locking_inset->isTextInset() &&
766 locking_inset->lyxCode() != Inset::ERT_CODE &&
767 (txt->real_current_font.language() !=
768 buffer()->params.language
769 || txt->real_current_font.isVisibleRightToLeft()
770 != buffer()->params.language->RightToLeft()))
771 shape = (txt->real_current_font.isVisibleRightToLeft())
772 ? LyXScreen::REVERSED_L_SHAPE
773 : LyXScreen::L_SHAPE;
774 y += cursor.iy() + theLockingInset()->insetInInsetY();
775 screen().showManualCursor(text, x, y, asc, desc,
781 void BufferView::hideLockedInsetCursor()
783 if (theLockingInset() && available()) {
784 screen().hideCursor();
789 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
791 if (theLockingInset() && available()) {
792 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
793 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
802 int BufferView::unlockInset(UpdatableInset * inset)
806 if (inset && theLockingInset() == inset) {
807 inset->insetUnlock(this);
809 // make sure we update the combo !
810 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
811 // Tell the paragraph dialog that we changed paragraph
812 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
815 } else if (inset && theLockingInset() &&
816 theLockingInset()->unlockInsetInInset(this, inset)) {
817 // Tell the paragraph dialog that we changed paragraph
818 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
819 // owner inset has updated the layout combo
827 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
829 if (!theLockingInset())
830 return; // shouldn't happen
831 if (kind == Undo::EDIT) // in this case insets would not be stored!
835 text->cursor.par()->next());
839 void BufferView::updateInset(Inset * inset)
841 pimpl_->updateInset(inset);
845 bool BufferView::ChangeInsets(Inset::Code code,
846 string const & from, string const & to)
848 bool need_update = false;
849 LyXCursor cursor = text->cursor;
850 LyXCursor tmpcursor = cursor;
851 cursor.par(tmpcursor.par());
852 cursor.pos(tmpcursor.pos());
854 ParIterator end = buffer()->par_iterator_end();
855 for (ParIterator it = buffer()->par_iterator_begin();
857 Paragraph * par = *it;
858 bool changed_inset = false;
859 for (InsetList::iterator it2 = par->insetlist.begin();
860 it2 != par->insetlist.end(); ++it2) {
861 if (it2.getInset()->lyxCode() == code) {
862 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
863 if (inset->getContents() == from) {
864 inset->setContents(to);
865 changed_inset = true;
874 // The test it.size()==1 was needed to prevent crashes.
875 // How to set the cursor corretly when it.size()>1 ??
876 if (it.size() == 1) {
877 text->setCursorIntern(par, 0);
878 text->redoParagraphs(text->cursor,
879 text->cursor.par()->next());
884 text->setCursorIntern(cursor.par(), cursor.pos());
889 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
891 // Check if the label 'from' appears more than once
892 vector<string> labels = buffer()->getLabelList();
894 if (lyx::count(labels.begin(), labels.end(), from) > 1)
897 return ChangeInsets(Inset::REF_CODE, from, to);
901 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
903 typedef pair<string, string> StringPair;
905 vector<StringPair> keys;
906 buffer()->fillWithBibKeys(keys);
907 if (count_if(keys.begin(), keys.end(),
908 lyx::equal_1st_in_pair<StringPair>(from))
912 return ChangeInsets(Inset::CITE_CODE, from, to);
916 UpdatableInset * BufferView::theLockingInset() const
918 // If NULL is not allowed we should put an Assert here. (Lgb)
920 return text->the_locking_inset;
925 void BufferView::theLockingInset(UpdatableInset * inset)
927 text->the_locking_inset = inset;
931 LyXText * BufferView::getLyXText() const
933 if (theLockingInset()) {
934 LyXText * txt = theLockingInset()->getLyXText(this, true);
942 LyXText * BufferView::getParentText(Inset * inset) const
944 if (inset->owner()) {
945 LyXText * txt = inset->getLyXText(this);
946 inset = inset->owner();
947 while (inset && inset->getLyXText(this) == txt)
948 inset = inset->owner();
950 return inset->getLyXText(this);
956 Language const * BufferView::getParentLanguage(Inset * inset) const
958 LyXText * text = getParentText(inset);
959 return text->cursor.par()->getFontSettings(buffer()->params,
960 text->cursor.pos()).language();
964 Encoding const * BufferView::getEncoding() const
966 LyXText * t = getLyXText();
970 LyXCursor const & c= t->cursor;
971 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
972 return font.language()->encoding();
976 void BufferView::haveSelection(bool sel)
978 pimpl_->workarea().haveSelection(sel);
982 int BufferView::workHeight() const
984 return pimpl_->workarea().workHeight();