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 error = strerror(errno);
324 string const file = MakeDisplayPath(fname, 50);
326 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
329 string text = fmt.str();
331 string text = _("Could not open the specified document\n");
332 text += file + _(" due to the error: ");
335 Alert::error(_("Could not open file"), text);
339 int const c = ifs.peek();
347 // FIXME: huh ? No we won't !
348 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
349 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
351 lyxerr[Debug::INFO] << "Will insert file without header"
353 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
361 bool BufferView::removeAutoInsets()
363 // keep track of which pos and par the cursor was on
364 Paragraph * cursor_par = text->cursor.par();
365 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
366 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
367 pos_type cursor_pos = text->cursor.pos();
371 // Trap the deletion of the paragraph the cursor is in.
372 // Iterate until we find a paragraph that won't be immediately deleted.
373 // In reality this should mean we only execute the body of the while
374 // loop once at most. However for safety we iterate rather than just
375 // make this an if () conditional.
376 while ((cursor_par_prev || cursor_par_next)
378 cursor_par_prev ? cursor_par_prev : cursor_par_next,
380 // We just removed cursor_par so have to fix the "cursor"
381 if (cursor_par_prev) {
385 cursor_par = cursor_par_prev;
386 cursor_pos = cursor_par->size();
390 cursor_par = cursor_par_next;
393 cursor_par_prev = cursor_par->previous();
394 cursor_par_next = cursor_par->next();
397 // Iterate through the paragraphs removing autoDelete insets as we go.
398 // If the paragraph ends up empty after all the autoDelete insets are
399 // removed that paragraph will be removed by the next setCursor() call.
400 ParIterator it = buffer()->par_iterator_begin();
401 ParIterator end = buffer()->par_iterator_end();
402 for (; it != end; ++it) {
403 Paragraph * par = *it;
404 Paragraph * par_prev = par ? par->previous() : 0;
405 bool removed = false;
407 if (text->setCursor(par, 0)
408 && cursor_par == par_prev) {
409 // The previous setCursor line was deleted and that
410 // was the cursor_par line. This can only happen if an
411 // error box was the sole item on cursor_par.
412 // It is possible for cursor_par_prev to be stray if
413 // the line it pointed to only had a error box on it
414 // so we have to set it to a known correct value.
415 // This is often the same value it already had.
416 cursor_par_prev = par->previous();
417 if (cursor_par_prev) {
418 // '|' = par, '.' = cursor_par, 'E' = error box
419 // First step below may occur before while{}
421 // E -> .E -> |.E -> . -> |b
424 cursor_par = cursor_par_prev;
425 cursor_pos = cursor_par_prev->size();
426 cursor_par_prev = cursor_par->previous();
427 // cursor_par_next remains the same
428 } else if (cursor_par_next) {
429 // First step below may occur before while{}
431 // E -> |.E -> |. -> . -> .|a
433 cursor_par = cursor_par_next;
435 // cursor_par_prev remains unset
436 cursor_par_next = cursor_par->next();
438 // I can't find a way to trigger this
439 // so it should be unreachable code
440 // unless the buffer is corrupted.
441 lyxerr << "BufferView::removeAutoInsets() is bad\n";
445 InsetList::iterator pit = par->insetlist.begin();
446 InsetList::iterator pend = par->insetlist.end();
448 while (pit != pend) {
449 if (pit.getInset()->autoDelete()) {
451 pos_type const pos = pit.getPos();
454 // We just invalidated par's inset iterators so
455 // we get the next valid iterator position
456 pit = par->insetlist.insetIterator(pos);
457 // and ensure we have a valid end iterator.
458 pend = par->insetlist.end();
460 if (cursor_par == par) {
461 // update the saved cursor position
462 if (cursor_pos > pos)
471 text->redoParagraph();
475 // It is possible that the last line is empty if it was cursor_par
476 // and/or only had an error inset on it. So we set the cursor to the
477 // start of the doc to force its removal and ensure a valid saved cursor
478 if (text->setCursor(text->ownerParagraph(), 0)
479 && 0 == cursor_par_next) {
480 cursor_par = cursor_par_prev;
481 cursor_pos = cursor_par->size();
482 } else if (cursor_pos > cursor_par->size()) {
483 // Some C-Enter lines were removed by the setCursor call which
484 // then invalidated cursor_pos. It could still be "wrong" because
485 // the cursor may appear to have jumped but since we collapsed
486 // some C-Enter lines this should be a reasonable compromise.
487 cursor_pos = cursor_par->size();
490 // restore the original cursor in its corrected location.
491 text->setCursorIntern(cursor_par, cursor_pos);
497 void BufferView::insertErrors(TeXErrors & terr)
499 // Save the cursor position
500 LyXCursor cursor = text->cursor;
502 TeXErrors::Errors::const_iterator cit = terr.begin();
503 TeXErrors::Errors::const_iterator end = terr.end();
504 for (; cit != end; ++cit) {
505 string const desctext(cit->error_desc);
506 string const errortext(cit->error_text);
507 string const msgtxt = desctext + '\n' + errortext;
508 int const errorrow = cit->error_in_line;
510 // Insert error string for row number
514 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
515 buffer()->texrow.increasePos(tmpid, tmppos);
518 Paragraph * texrowpar = 0;
521 texrowpar = text->ownerParagraph();
524 texrowpar = buffer()->getParFromID(tmpid);
531 InsetError * new_inset = new InsetError(msgtxt);
532 text->setCursorIntern(texrowpar, tmppos);
533 text->insertInset(new_inset);
537 // Restore the cursor position
538 text->setCursorIntern(cursor.par(), cursor.pos());
542 void BufferView::setCursorFromRow(int row)
547 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
549 Paragraph * texrowpar;
552 texrowpar = text->ownerParagraph();
555 texrowpar = buffer()->getParFromID(tmpid);
557 text->setCursor(texrowpar, tmppos);
561 bool BufferView::insertInset(Inset * inset, string const & lout)
563 return pimpl_->insertInset(inset, lout);
567 // This is also a buffer property (ale)
568 // Not so sure about that. a goto Label function can not be buffer local, just
569 // think how this will work in a multiwindow/buffer environment, all the
570 // cursors in all the views showing this buffer will move. (Lgb)
571 // OK, then no cursor action should be allowed in buffer. (ale)
572 bool BufferView::gotoLabel(string const & label)
574 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
575 it != buffer()->inset_iterator_end(); ++it) {
576 vector<string> labels = it->getLabelList();
577 if (find(labels.begin(),labels.end(),label)
580 text->setCursor(it.getPar(), it.getPos());
581 text->selection.cursor = text->cursor;
582 update(text, BufferView::SELECT);
590 void BufferView::undo()
595 owner()->message(_("Undo"));
598 update(text, BufferView::SELECT);
600 owner()->message(_("No further undo information"));
602 update(text, BufferView::SELECT);
607 void BufferView::redo()
612 owner()->message(_("Redo"));
615 update(text, BufferView::SELECT);
617 owner()->message(_("No further redo information"));
619 update(text, BufferView::SELECT);
624 void BufferView::copyEnvironment()
627 text->copyEnvironmentType();
628 owner()->message(_("Paragraph environment type copied"));
633 void BufferView::pasteEnvironment()
636 text->pasteEnvironmentType();
637 owner()->message(_("Paragraph environment type set"));
638 update(text, BufferView::SELECT);
643 // these functions are for the spellchecker
644 WordLangTuple const BufferView::nextWord(float & value)
648 return WordLangTuple();
651 return text->selectNextWordToSpellcheck(value);
655 void BufferView::selectLastWord()
660 LyXCursor cur = text->selection.cursor;
663 text->selection.cursor = cur;
664 text->selectSelectedWord();
665 toggleSelection(false);
666 update(text, BufferView::SELECT);
670 void BufferView::endOfSpellCheck()
672 if (!available()) return;
676 text->selectSelectedWord();
677 text->clearSelection();
678 update(text, BufferView::SELECT);
682 void BufferView::replaceWord(string const & replacestring)
687 LyXText * tt = getLyXText();
689 update(tt, BufferView::SELECT);
691 // clear the selection (if there is any)
692 toggleSelection(false);
693 update(tt, BufferView::SELECT);
695 // clear the selection (if there is any)
696 toggleSelection(false);
697 tt->replaceSelectionWithString(replacestring);
699 tt->setSelectionRange(replacestring.length());
701 // Go back so that replacement string is also spellchecked
702 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
703 tt->cursorLeft(this);
705 update(tt, BufferView::SELECT);
707 // FIXME: should be done through LFUN
708 buffer()->markDirty();
711 // End of spellchecker stuff
714 bool BufferView::lockInset(UpdatableInset * inset)
718 // don't relock if we're already locked
719 if (theLockingInset() == inset)
721 if (!theLockingInset()) {
722 // first check if it's the inset under the cursor we want lock
723 // should be most of the time
724 char const c = text->cursor.par()->getChar(text->cursor.pos());
725 if (c == Paragraph::META_INSET) {
726 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
728 theLockingInset(inset);
732 // Then do a deep look of the inset and lock the right one
733 int const id = inset->id();
734 ParagraphList::iterator pit = buffer()->paragraphs.begin();
735 ParagraphList::iterator pend = buffer()->paragraphs.end();
736 for (; pit != pend; ++pit) {
737 InsetList::iterator it = pit->insetlist.begin();
738 InsetList::iterator end = pit->insetlist.end();
739 for (; it != end; ++it) {
740 if (it.getInset() == inset) {
741 text->setCursorIntern(&*pit, it.getPos());
742 theLockingInset(inset);
745 if (it.getInset()->getInsetFromID(id)) {
746 text->setCursorIntern(&*pit, it.getPos());
747 it.getInset()->edit(this);
748 return theLockingInset()->lockInsetInInset(this, inset);
754 return theLockingInset()->lockInsetInInset(this, inset);
758 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
760 if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
761 LyXCursor cursor = text->cursor;
762 Inset * locking_inset = theLockingInset()->getLockingInset();
764 if ((cursor.pos() - 1 >= 0) &&
765 cursor.par()->isInset(cursor.pos() - 1) &&
766 (cursor.par()->getInset(cursor.pos() - 1) ==
768 text->setCursor(cursor,
769 cursor.par(), cursor.pos() - 1);
770 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
771 LyXText * txt = getLyXText();
772 if (locking_inset->isTextInset() &&
773 locking_inset->lyxCode() != Inset::ERT_CODE &&
774 (txt->real_current_font.language() !=
775 buffer()->params.language
776 || txt->real_current_font.isVisibleRightToLeft()
777 != buffer()->params.language->RightToLeft()))
778 shape = (txt->real_current_font.isVisibleRightToLeft())
779 ? LyXScreen::REVERSED_L_SHAPE
780 : LyXScreen::L_SHAPE;
781 y += cursor.iy() + theLockingInset()->insetInInsetY();
782 screen().showManualCursor(text, x, y, asc, desc,
788 void BufferView::hideLockedInsetCursor()
790 if (theLockingInset() && available()) {
791 screen().hideCursor();
796 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
798 if (theLockingInset() && available()) {
799 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
800 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
809 int BufferView::unlockInset(UpdatableInset * inset)
813 if (inset && theLockingInset() == inset) {
814 inset->insetUnlock(this);
816 // make sure we update the combo !
817 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
818 // Tell the paragraph dialog that we changed paragraph
819 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
822 } else if (inset && theLockingInset() &&
823 theLockingInset()->unlockInsetInInset(this, inset)) {
824 // Tell the paragraph dialog that we changed paragraph
825 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
826 // owner inset has updated the layout combo
834 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
836 if (!theLockingInset())
837 return; // shouldn't happen
838 if (kind == Undo::EDIT) // in this case insets would not be stored!
842 text->cursor.par()->next());
846 void BufferView::updateInset(Inset * inset)
848 pimpl_->updateInset(inset);
852 bool BufferView::ChangeInsets(Inset::Code code,
853 string const & from, string const & to)
855 bool need_update = false;
856 LyXCursor cursor = text->cursor;
857 LyXCursor tmpcursor = cursor;
858 cursor.par(tmpcursor.par());
859 cursor.pos(tmpcursor.pos());
861 ParIterator end = buffer()->par_iterator_end();
862 for (ParIterator it = buffer()->par_iterator_begin();
864 Paragraph * par = *it;
865 bool changed_inset = false;
866 for (InsetList::iterator it2 = par->insetlist.begin();
867 it2 != par->insetlist.end(); ++it2) {
868 if (it2.getInset()->lyxCode() == code) {
869 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
870 if (inset->getContents() == from) {
871 inset->setContents(to);
872 changed_inset = true;
881 // The test it.size()==1 was needed to prevent crashes.
882 // How to set the cursor corretly when it.size()>1 ??
883 if (it.size() == 1) {
884 text->setCursorIntern(par, 0);
885 text->redoParagraphs(text->cursor,
886 text->cursor.par()->next());
891 text->setCursorIntern(cursor.par(), cursor.pos());
896 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
898 // Check if the label 'from' appears more than once
899 vector<string> labels = buffer()->getLabelList();
901 if (lyx::count(labels.begin(), labels.end(), from) > 1)
904 return ChangeInsets(Inset::REF_CODE, from, to);
908 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
910 typedef pair<string, string> StringPair;
912 vector<StringPair> keys;
913 buffer()->fillWithBibKeys(keys);
914 if (count_if(keys.begin(), keys.end(),
915 lyx::equal_1st_in_pair<StringPair>(from))
919 return ChangeInsets(Inset::CITE_CODE, from, to);
923 UpdatableInset * BufferView::theLockingInset() const
925 // If NULL is not allowed we should put an Assert here. (Lgb)
927 return text->the_locking_inset;
932 void BufferView::theLockingInset(UpdatableInset * inset)
934 text->the_locking_inset = inset;
938 LyXText * BufferView::getLyXText() const
940 if (theLockingInset()) {
941 LyXText * txt = theLockingInset()->getLyXText(this, true);
949 LyXText * BufferView::getParentText(Inset * inset) const
951 if (inset->owner()) {
952 LyXText * txt = inset->getLyXText(this);
953 inset = inset->owner();
954 while (inset && inset->getLyXText(this) == txt)
955 inset = inset->owner();
957 return inset->getLyXText(this);
963 Language const * BufferView::getParentLanguage(Inset * inset) const
965 LyXText * text = getParentText(inset);
966 return text->cursor.par()->getFontSettings(buffer()->params,
967 text->cursor.pos()).language();
971 Encoding const * BufferView::getEncoding() const
973 LyXText * t = getLyXText();
977 LyXCursor const & c= t->cursor;
978 LyXFont const font = c.par()->getFont(buffer()->params, c.pos());
979 return font.language()->encoding();
983 void BufferView::haveSelection(bool sel)
985 pimpl_->workarea().haveSelection(sel);
989 int BufferView::workHeight() const
991 return pimpl_->workarea().workHeight();