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"
30 #include "paragraph_funcs.h"
32 #include "frontends/Alert.h"
33 #include "frontends/Dialogs.h"
34 #include "frontends/LyXView.h"
35 #include "frontends/WorkArea.h"
36 #include "frontends/screen.h"
38 #include "insets/insetcommand.h" // ChangeRefs
39 #include "insets/inseterror.h"
40 #include "insets/updatableinset.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
47 #include "support/BoostFormat.h"
51 extern BufferList bufferlist;
63 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
64 int width, int height)
65 : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
71 BufferView::~BufferView()
78 Buffer * BufferView::buffer() const
80 return pimpl_->buffer_;
84 LyXScreen & BufferView::screen() const
86 return pimpl_->screen();
90 LyXView * BufferView::owner() const
92 return pimpl_->owner_;
96 Painter & BufferView::painter() const
98 return pimpl_->painter();
102 void BufferView::buffer(Buffer * b)
108 void BufferView::reload()
110 string const fn = buffer()->fileName();
111 if (bufferlist.close(buffer(), false))
112 buffer(bufferlist.loadLyXFile(fn));
116 void BufferView::resize()
118 if (pimpl_->buffer_) {
119 pimpl_->resizeCurrentBuffer();
124 void BufferView::repaint()
130 bool BufferView::fitCursor()
132 return pimpl_->fitCursor();
136 void BufferView::update()
142 void BufferView::updateScrollbar()
144 pimpl_->updateScrollbar();
148 void BufferView::scrollDocView(int value)
150 pimpl_->scrollDocView(value);
154 void BufferView::redoCurrentBuffer()
156 pimpl_->redoCurrentBuffer();
160 bool BufferView::available() const
162 return pimpl_->available();
166 Change const BufferView::getCurrentChange()
168 return pimpl_->getCurrentChange();
172 void BufferView::beforeChange(LyXText * text)
174 pimpl_->beforeChange(text);
178 void BufferView::savePosition(unsigned int i)
180 pimpl_->savePosition(i);
184 void BufferView::restorePosition(unsigned int i)
186 pimpl_->restorePosition(i);
190 bool BufferView::isSavedPosition(unsigned int i)
192 return pimpl_->isSavedPosition(i);
196 void BufferView::update(LyXText * text, UpdateCodes f)
198 pimpl_->update(text, f);
202 void BufferView::update(UpdateCodes f)
208 void BufferView::switchKeyMap()
210 pimpl_->switchKeyMap();
214 void BufferView::insetUnlock()
216 pimpl_->insetUnlock();
220 int BufferView::workWidth() const
222 return pimpl_->workarea().workWidth();
226 void BufferView::toggleSelection(bool b)
228 pimpl_->toggleSelection(b);
232 void BufferView::toggleToggle()
234 pimpl_->toggleToggle();
238 void BufferView::center()
244 string const BufferView::getClipboard() const
246 return pimpl_->workarea().getClipboard();
250 void BufferView::stuffClipboard(string const & stuff) const
252 pimpl_->stuffClipboard(stuff);
256 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
257 BufferView::UpdateCodes uc2)
259 return static_cast<BufferView::UpdateCodes>
260 (static_cast<int>(uc1) | static_cast<int>(uc2));
264 bool BufferView::dispatch(FuncRequest const & ev)
266 return pimpl_->dispatch(ev);
270 void BufferView::scroll(int lines)
272 pimpl_->scroll(lines);
276 // Inserts a file into current document
277 bool BufferView::insertLyXFile(string const & filen)
279 // Copyright CHT Software Service GmbH
282 // Insert a LyXformat - file into current buffer
284 // Moved from lyx_cb.C (Lgb)
289 string const fname = MakeAbsPath(filen);
291 // check if file exist
292 FileInfo const fi(fname);
294 if (!fi.readable()) {
295 string const file = MakeDisplayPath(fname, 50);
297 boost::format fmt(_("The specified document\n%1$s\ncould not be read."));
299 string text = fmt.str();
301 string text = _("The specified document\n");
302 text += file + _(" could not be read.");
304 Alert::error(_("Could not read document"), text);
310 ifstream ifs(fname.c_str());
312 string const file = MakeDisplayPath(fname, 50);
314 boost::format fmt(_("Could not open the specified document\n%1$s."));
316 string text = fmt.str();
318 string text = _("Could not open the specified document\n");
321 Alert::error(_("Could not open file"), text);
325 int const c = ifs.peek();
333 // FIXME: huh ? No we won't !
334 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
335 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
337 lyxerr[Debug::INFO] << "Will insert file without header"
339 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
347 bool BufferView::removeAutoInsets()
349 // keep track of which pos and par the cursor was on
350 Paragraph * cursor_par = &*text->cursor.par();
351 Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
352 Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
353 pos_type cursor_pos = text->cursor.pos();
357 // Trap the deletion of the paragraph the cursor is in.
358 // Iterate until we find a paragraph that won't be immediately deleted.
359 // In reality this should mean we only execute the body of the while
360 // loop once at most. However for safety we iterate rather than just
361 // make this an if () conditional.
362 while ((cursor_par_prev || cursor_par_next)
364 cursor_par_prev ? cursor_par_prev : cursor_par_next,
366 // We just removed cursor_par so have to fix the "cursor"
367 if (cursor_par_prev) {
371 cursor_par = cursor_par_prev;
372 cursor_pos = cursor_par->size();
376 cursor_par = cursor_par_next;
379 cursor_par_prev = cursor_par->previous();
380 cursor_par_next = cursor_par->next();
383 // Iterate through the paragraphs removing autoDelete insets as we go.
384 // If the paragraph ends up empty after all the autoDelete insets are
385 // removed that paragraph will be removed by the next setCursor() call.
386 ParIterator it = buffer()->par_iterator_begin();
387 ParIterator end = buffer()->par_iterator_end();
388 for (; it != end; ++it) {
389 Paragraph * par = *it;
390 Paragraph * par_prev = par ? par->previous() : 0;
391 bool removed = false;
393 if (text->setCursor(par, 0)
394 && cursor_par == par_prev) {
395 // The previous setCursor line was deleted and that
396 // was the cursor_par line. This can only happen if an
397 // error box was the sole item on cursor_par.
398 // It is possible for cursor_par_prev to be stray if
399 // the line it pointed to only had a error box on it
400 // so we have to set it to a known correct value.
401 // This is often the same value it already had.
402 cursor_par_prev = par->previous();
403 if (cursor_par_prev) {
404 // '|' = par, '.' = cursor_par, 'E' = error box
405 // First step below may occur before while{}
407 // E -> .E -> |.E -> . -> |b
410 cursor_par = cursor_par_prev;
411 cursor_pos = cursor_par_prev->size();
412 cursor_par_prev = cursor_par->previous();
413 // cursor_par_next remains the same
414 } else if (cursor_par_next) {
415 // First step below may occur before while{}
417 // E -> |.E -> |. -> . -> .|a
419 cursor_par = cursor_par_next;
421 // cursor_par_prev remains unset
422 cursor_par_next = cursor_par->next();
424 // I can't find a way to trigger this
425 // so it should be unreachable code
426 // unless the buffer is corrupted.
427 lyxerr << "BufferView::removeAutoInsets() is bad\n";
431 InsetList::iterator pit = par->insetlist.begin();
432 InsetList::iterator pend = par->insetlist.end();
434 while (pit != pend) {
435 if (pit.getInset()->autoDelete()) {
437 pos_type const pos = pit.getPos();
440 // We just invalidated par's inset iterators so
441 // we get the next valid iterator position
442 pit = par->insetlist.insetIterator(pos);
443 // and ensure we have a valid end iterator.
444 pend = par->insetlist.end();
446 if (cursor_par == par) {
447 // update the saved cursor position
448 if (cursor_pos > pos)
457 text->redoParagraph();
461 // It is possible that the last line is empty if it was cursor_par
462 // and/or only had an error inset on it. So we set the cursor to the
463 // start of the doc to force its removal and ensure a valid saved cursor
464 if (text->setCursor(&*text->ownerParagraphs().begin(), 0)
465 && 0 == cursor_par_next) {
466 cursor_par = cursor_par_prev;
467 cursor_pos = cursor_par->size();
468 } else if (cursor_pos > cursor_par->size()) {
469 // Some C-Enter lines were removed by the setCursor call which
470 // then invalidated cursor_pos. It could still be "wrong" because
471 // the cursor may appear to have jumped but since we collapsed
472 // some C-Enter lines this should be a reasonable compromise.
473 cursor_pos = cursor_par->size();
476 // restore the original cursor in its corrected location.
477 text->setCursorIntern(cursor_par, cursor_pos);
483 void BufferView::insertErrors(TeXErrors & terr)
485 // Save the cursor position
486 LyXCursor cursor = text->cursor;
488 TeXErrors::Errors::const_iterator cit = terr.begin();
489 TeXErrors::Errors::const_iterator end = terr.end();
490 for (; cit != end; ++cit) {
491 string const desctext(cit->error_desc);
492 string const errortext(cit->error_text);
493 string const msgtxt = desctext + '\n' + errortext;
494 int const errorrow = cit->error_in_line;
496 // Insert error string for row number
500 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
501 buffer()->texrow.increasePos(tmpid, tmppos);
504 Paragraph * texrowpar = 0;
507 texrowpar = &*text->ownerParagraphs().begin();
510 texrowpar = &*buffer()->getParFromID(tmpid);
517 InsetError * new_inset = new InsetError(msgtxt);
518 text->setCursorIntern(texrowpar, tmppos);
519 text->insertInset(new_inset);
523 // Restore the cursor position
524 text->setCursorIntern(cursor.par(), cursor.pos());
528 void BufferView::setCursorFromRow(int row)
533 buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
535 Paragraph * texrowpar;
538 texrowpar = &*text->ownerParagraphs().begin();
541 texrowpar = &*buffer()->getParFromID(tmpid);
543 text->setCursor(texrowpar, tmppos);
547 bool BufferView::insertInset(Inset * inset, string const & lout)
549 return pimpl_->insertInset(inset, lout);
553 void BufferView::gotoLabel(string const & label)
555 for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
556 it != buffer()->inset_iterator_end(); ++it) {
557 vector<string> labels = it->getLabelList();
558 if (find(labels.begin(),labels.end(),label)
561 text->setCursor(it.getPar(), it.getPos());
562 text->selection.cursor = text->cursor;
563 update(text, BufferView::SELECT);
570 void BufferView::undo()
575 owner()->message(_("Undo"));
577 update(text, BufferView::SELECT);
579 owner()->message(_("No further undo information"));
581 update(text, BufferView::SELECT);
586 void BufferView::redo()
591 owner()->message(_("Redo"));
593 update(text, BufferView::SELECT);
595 owner()->message(_("No further redo information"));
597 update(text, BufferView::SELECT);
602 // these functions are for the spellchecker
603 WordLangTuple const BufferView::nextWord(float & value)
607 return WordLangTuple();
610 return text->selectNextWordToSpellcheck(value);
614 void BufferView::selectLastWord()
619 LyXCursor cur = text->selection.cursor;
621 text->selection.cursor = cur;
622 text->selectSelectedWord();
623 toggleSelection(false);
624 update(text, BufferView::SELECT);
628 void BufferView::endOfSpellCheck()
630 if (!available()) return;
633 text->selectSelectedWord();
634 text->clearSelection();
635 update(text, BufferView::SELECT);
639 void BufferView::replaceWord(string const & replacestring)
644 LyXText * tt = getLyXText();
645 update(tt, BufferView::SELECT);
647 // clear the selection (if there is any)
648 toggleSelection(false);
649 update(tt, BufferView::SELECT);
651 // clear the selection (if there is any)
652 toggleSelection(false);
653 tt->replaceSelectionWithString(replacestring);
655 tt->setSelectionRange(replacestring.length());
657 // Go back so that replacement string is also spellchecked
658 for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
659 tt->cursorLeft(this);
661 update(tt, BufferView::SELECT);
663 // FIXME: should be done through LFUN
664 buffer()->markDirty();
667 // End of spellchecker stuff
670 bool BufferView::lockInset(UpdatableInset * inset)
674 // don't relock if we're already locked
675 if (theLockingInset() == inset)
677 if (!theLockingInset()) {
678 // first check if it's the inset under the cursor we want lock
679 // should be most of the time
680 if (text->cursor.pos() < text->cursor.par()->size()
681 && text->cursor.par()->getChar(text->cursor.pos()) ==
682 Paragraph::META_INSET) {
683 Inset * in = text->cursor.par()->getInset(text->cursor.pos());
685 theLockingInset(inset);
689 // Then do a deep look of the inset and lock the right one
690 int const id = inset->id();
691 ParagraphList::iterator pit = buffer()->paragraphs.begin();
692 ParagraphList::iterator pend = buffer()->paragraphs.end();
693 for (; pit != pend; ++pit) {
694 InsetList::iterator it = pit->insetlist.begin();
695 InsetList::iterator end = pit->insetlist.end();
696 for (; it != end; ++it) {
697 if (it.getInset() == inset) {
698 text->setCursorIntern(pit, it.getPos());
699 theLockingInset(inset);
702 if (it.getInset()->getInsetFromID(id)) {
703 text->setCursorIntern(pit, it.getPos());
704 it.getInset()->edit(this);
705 return theLockingInset()->lockInsetInInset(this, inset);
711 return theLockingInset()->lockInsetInInset(this, inset);
715 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
717 if (theLockingInset() && available()) {
718 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
719 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
728 void BufferView::hideCursor()
730 screen().hideCursor();
734 int BufferView::unlockInset(UpdatableInset * inset)
738 if (inset && theLockingInset() == inset) {
739 inset->insetUnlock(this);
741 // make sure we update the combo !
742 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
743 // Tell the paragraph dialog that we changed paragraph
744 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
747 } else if (inset && theLockingInset() &&
748 theLockingInset()->unlockInsetInInset(this, inset)) {
749 // Tell the paragraph dialog that we changed paragraph
750 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
751 // owner inset has updated the layout combo
759 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
761 if (!theLockingInset())
762 return; // shouldn't happen
763 if (kind == Undo::EDIT) // in this case insets would not be stored!
767 boost::next(text->cursor.par()));
771 void BufferView::updateInset(Inset * inset)
773 pimpl_->updateInset(inset);
777 bool BufferView::ChangeInsets(Inset::Code code,
778 string const & from, string const & to)
780 bool need_update = false;
781 LyXCursor cursor = text->cursor;
782 LyXCursor tmpcursor = cursor;
783 cursor.par(tmpcursor.par());
784 cursor.pos(tmpcursor.pos());
786 ParIterator end = buffer()->par_iterator_end();
787 for (ParIterator it = buffer()->par_iterator_begin();
789 Paragraph * par = *it;
790 bool changed_inset = false;
791 for (InsetList::iterator it2 = par->insetlist.begin();
792 it2 != par->insetlist.end(); ++it2) {
793 if (it2.getInset()->lyxCode() == code) {
794 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
795 if (inset->getContents() == from) {
796 inset->setContents(to);
797 changed_inset = true;
806 // The test it.size()==1 was needed to prevent crashes.
807 // How to set the cursor corretly when it.size()>1 ??
808 if (it.size() == 1) {
809 text->setCursorIntern(par, 0);
810 text->redoParagraphs(text->cursor,
811 boost::next(text->cursor.par()));
816 text->setCursorIntern(cursor.par(), cursor.pos());
821 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
823 // Check if the label 'from' appears more than once
824 vector<string> labels = buffer()->getLabelList();
826 if (lyx::count(labels.begin(), labels.end(), from) > 1)
829 return ChangeInsets(Inset::REF_CODE, from, to);
833 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
835 typedef pair<string, string> StringPair;
837 vector<StringPair> keys;
838 buffer()->fillWithBibKeys(keys);
839 if (count_if(keys.begin(), keys.end(),
840 lyx::equal_1st_in_pair<StringPair>(from))
844 return ChangeInsets(Inset::CITE_CODE, from, to);
848 UpdatableInset * BufferView::theLockingInset() const
850 // If NULL is not allowed we should put an Assert here. (Lgb)
852 return text->the_locking_inset;
857 void BufferView::theLockingInset(UpdatableInset * inset)
859 text->the_locking_inset = inset;
863 LyXText * BufferView::getLyXText() const
865 if (theLockingInset()) {
866 LyXText * txt = theLockingInset()->getLyXText(this, true);
874 LyXText * BufferView::getParentText(Inset * inset) const
876 if (inset->owner()) {
877 LyXText * txt = inset->getLyXText(this);
878 inset = inset->owner();
879 while (inset && inset->getLyXText(this) == txt)
880 inset = inset->owner();
882 return inset->getLyXText(this);
888 Language const * BufferView::getParentLanguage(Inset * inset) const
890 LyXText * text = getParentText(inset);
891 return text->cursor.par()->getFontSettings(buffer()->params,
892 text->cursor.pos()).language();
896 Encoding const * BufferView::getEncoding() const
898 LyXText * t = getLyXText();
902 LyXCursor const & c = t->cursor;
903 LyXFont const font = c.par()->getFont(buffer()->params, c.pos(),
904 outerFont(c.par(), t->ownerParagraphs()));
905 return font.language()->encoding();
909 void BufferView::haveSelection(bool sel)
911 pimpl_->workarea().haveSelection(sel);
915 int BufferView::workHeight() const
917 return pimpl_->workarea().workHeight();