3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/Clipboard.h"
64 #include "frontends/Dialogs.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/font_metrics.h"
67 #include "frontends/LyXView.h"
68 #include "frontends/Selection.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/filefilterlist.h"
74 #include "support/filetools.h"
75 #include "support/package.h"
76 #include "support/types.h"
78 #include <boost/bind.hpp>
79 #include <boost/current_function.hpp>
85 using lyx::frontend::Clipboard;
90 using lyx::support::addPath;
91 using lyx::support::bformat;
92 using lyx::support::FileFilterList;
93 using lyx::support::fileSearch;
94 using lyx::support::isDirWriteable;
95 using lyx::support::makeDisplayPath;
96 using lyx::support::makeAbsPath;
97 using lyx::support::package;
101 using std::istringstream;
103 using std::make_pair;
106 using std::mem_fun_ref;
110 extern BufferList bufferlist;
115 unsigned int const saved_positions_num = 20;
118 /// Return an inset of this class if it exists at the current cursor position
120 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
123 DocIterator it = cur;
124 if (it.nextInset() &&
125 it.nextInset()->lyxCode() == code) {
126 inset = static_cast<T*>(it.nextInset());
134 BufferView::BufferView(LyXView * owner)
135 : owner_(owner), buffer_(0), wh_(0),
137 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
140 xsel_cache_.set = false;
142 saved_positions.resize(saved_positions_num);
143 // load saved bookmarks
144 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
145 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
146 bm != bmList.end(); ++bm)
147 if (bm->get<0>() < saved_positions_num)
148 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
149 // and then clear them
152 intl_->initKeyMapper(lyxrc.use_kbmap);
156 BufferView::~BufferView()
161 Buffer * BufferView::buffer() const
167 LyXView * BufferView::owner() const
173 void BufferView::setBuffer(Buffer * b)
175 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
176 << "[ b = " << b << "]" << endl;
179 // Save the actual cursor position and anchor inside the
180 // buffer so that it can be restored in case we rechange
181 // to this buffer later on.
182 buffer_->saveCursor(cursor_.selectionBegin(),
183 cursor_.selectionEnd());
184 // current buffer is going to be switched-off, save cursor pos
185 LyX::ref().session().saveFilePosition(buffer_->fileName(),
186 boost::tie(cursor_.pit(), cursor_.pos()) );
189 // If we're quitting lyx, don't bother updating stuff
195 // If we are closing current buffer, switch to the first in
198 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
199 << " No Buffer!" << endl;
200 // We are closing the buffer, use the first buffer as current
201 buffer_ = bufferlist.first();
203 // Set current buffer
208 cursor_ = LCursor(*this);
213 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
214 << "Buffer addr: " << buffer_ << endl;
215 cursor_.push(buffer_->inset());
216 cursor_.resetAnchor();
217 buffer_->text().init(this);
218 buffer_->text().setCurrentFont(cursor_);
219 if (buffer_->getCursor().size() > 0 &&
220 buffer_->getAnchor().size() > 0)
222 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
223 cursor_.resetAnchor();
224 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
225 cursor_.setSelection();
231 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
232 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
236 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
238 // Get absolute path of file and add ".lyx"
239 // to the filename if necessary
240 string s = fileSearch(string(), filename, "lyx");
242 bool const found = !s.empty();
247 // File already open?
248 if (bufferlist.exists(s)) {
249 docstring const file = makeDisplayPath(s, 20);
250 docstring text = bformat(_("The document %1$s is already "
251 "loaded.\n\nDo you want to revert "
252 "to the saved version?"), file);
253 int const ret = Alert::prompt(_("Revert to saved document?"),
254 text, 0, 1, _("&Revert"), _("&Switch to document"));
257 setBuffer(bufferlist.getBuffer(s));
260 // FIXME: should be LFUN_REVERT
261 if (!bufferlist.close(bufferlist.getBuffer(s), false))
263 // Fall through to new load. (Asger)
269 b = bufferlist.newBuffer(s);
270 if (!::loadLyXFile(b, s)) {
271 bufferlist.release(b);
275 docstring text = bformat(_("The document %1$s does not yet "
276 "exist.\n\nDo you want to create "
277 "a new document?"), lyx::from_utf8(s));
278 int const ret = Alert::prompt(_("Create new document?"),
279 text, 0, 1, _("&Create"), _("Cancel"));
282 b = newFile(s, string(), true);
290 // Send the "errors" signal in case of parsing errors
293 // scroll to the position when the file was last closed
294 if (lyxrc.use_lastfilepos) {
297 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
298 // I am not sure how to separate the following part to a function
299 // so I will leave this to Lars.
301 // check pit since the document may be externally changed.
302 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
303 ParIterator it = b->par_iterator_begin();
304 ParIterator const end = b->par_iterator_end();
305 for (; it != end; ++it)
306 if (it.pit() == pit) {
307 // restored pos may be bigger than it->size
308 setCursor(makeDocIterator(it, min(pos, it->size())));
309 update(Update::FitCursor);
316 LyX::ref().session().addLastFile(b->fileName());
322 void BufferView::reload()
324 string const fn = buffer_->fileName();
325 if (bufferlist.close(buffer_, false))
330 void BufferView::resize()
335 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
337 buffer_->text().init(this);
343 bool BufferView::fitCursor()
345 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
346 LyXFont const font = cursor_.getFont();
347 int const asc = font_metrics::maxAscent(font);
348 int const des = font_metrics::maxDescent(font);
349 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
350 if (p.y_ - asc >= 0 && p.y_ + des < height_)
358 bool BufferView::multiParSel()
360 if (!cursor_.selection())
362 bool ret = multiparsel_cache_;
363 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
364 // Either this, or previous selection spans paragraphs
365 return ret || multiparsel_cache_;
369 bool BufferView::update(Update::flags flags)
371 // This is close to a hot-path.
372 if (lyxerr.debugging(Debug::DEBUG)) {
374 << BOOST_CURRENT_FUNCTION
375 << "[fitcursor = " << (flags & Update::FitCursor)
376 << ", forceupdate = " << (flags & Update::Force)
377 << ", singlepar = " << (flags & Update::SinglePar)
378 << "] buffer: " << buffer_ << endl;
381 // Check needed to survive LyX startup
385 // Update macro store
386 buffer_->buildMacros();
388 // First drawing step
389 updateMetrics(flags & Update::SinglePar);
391 // The second drawing step is done in WorkArea::redraw() if needed.
392 bool const need_second_step =
393 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
394 && (fitCursor() || multiParSel());
396 return need_second_step;
400 void BufferView::updateScrollbar()
403 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
404 << " no text in updateScrollbar" << endl;
405 scrollbarParameters_.reset();
409 LyXText & t = buffer_->text();
410 int const parsize = int(t.paragraphs().size() - 1);
411 if (anchor_ref_ > parsize) {
412 anchor_ref_ = parsize;
417 << BOOST_CURRENT_FUNCTION
418 << " Updating scrollbar: height: " << t.paragraphs().size()
419 << " curr par: " << cursor_.bottom().pit()
420 << " default height " << defaultRowHeight() << endl;
422 // It would be better to fix the scrollbar to understand
423 // values in [0..1] and divide everything by wh
425 // estimated average paragraph height:
428 int h = t.getPar(anchor_ref_).height();
430 // Normalize anchor/offset (MV):
431 while (offset_ref_ > h && anchor_ref_ < parsize) {
434 h = t.getPar(anchor_ref_).height();
436 // Look at paragraph heights on-screen
439 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
442 int const h2 = t.getPar(pit).height();
446 int const hav = sumh / nh;
447 // More realistic average paragraph height
451 scrollbarParameters_.height = (parsize + 1) * wh_;
452 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
453 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
457 ScrollbarParameters const & BufferView::scrollbarParameters() const
459 return scrollbarParameters_;
463 void BufferView::scrollDocView(int value)
465 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
466 << "[ value = " << value << "]" << endl;
471 LyXText & t = buffer_->text();
473 float const bar = value / float(wh_ * t.paragraphs().size());
475 anchor_ref_ = int(bar * t.paragraphs().size());
476 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
477 anchor_ref_ = int(t.paragraphs().size()) - 1;
478 t.redoParagraph(anchor_ref_);
479 int const h = t.getPar(anchor_ref_).height();
480 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
484 void BufferView::setCursorFromScrollbar()
486 LyXText & t = buffer_->text();
488 int const height = 2 * defaultRowHeight();
489 int const first = height;
490 int const last = height_ - height;
491 LCursor & cur = cursor_;
493 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
496 case bv_funcs::CUR_ABOVE:
497 t.setCursorFromCoordinates(cur, 0, first);
498 cur.clearSelection();
500 case bv_funcs::CUR_BELOW:
501 t.setCursorFromCoordinates(cur, 0, last);
502 cur.clearSelection();
504 case bv_funcs::CUR_INSIDE:
505 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
506 int const newy = min(last, max(y, first));
508 cur.reset(buffer_->inset());
509 t.setCursorFromCoordinates(cur, 0, newy);
515 Change const BufferView::getCurrentChange()
517 if (!buffer_->params().tracking_changes || !cursor_.selection())
518 return Change(Change::UNCHANGED);
520 DocIterator dit = cursor_.selectionBegin();
521 return dit.paragraph().lookupChange(dit.pos());
525 void BufferView::savePosition(unsigned int i)
527 if (i >= saved_positions_num)
529 BOOST_ASSERT(cursor_.inTexted());
530 saved_positions[i] = Position(buffer_->fileName(),
531 cursor_.paragraph().id(),
534 // emit message signal.
535 message(bformat(_("Saved bookmark %1$d"), i));
539 void BufferView::restorePosition(unsigned int i)
541 if (i >= saved_positions_num)
544 string const fname = saved_positions[i].filename;
546 cursor_.clearSelection();
548 if (fname != buffer_->fileName()) {
550 if (bufferlist.exists(fname))
551 b = bufferlist.getBuffer(fname);
553 b = bufferlist.newBuffer(fname);
554 // Don't ask, just load it
555 ::loadLyXFile(b, fname);
561 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
562 if (par == buffer_->par_iterator_end())
565 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
568 // emit message signal.
569 message(bformat(_("Moved to bookmark %1$d"), i));
573 bool BufferView::isSavedPosition(unsigned int i)
575 return i < saved_positions_num && !saved_positions[i].filename.empty();
578 void BufferView::saveSavedPositions()
580 // save bookmarks. It is better to use the pit interface
581 // but I do not know how to effectively convert between
583 for (unsigned int i=1; i < saved_positions_num; ++i) {
584 if ( isSavedPosition(i) )
585 LyX::ref().session().saveBookmark( boost::tie(
587 saved_positions[i].filename,
588 saved_positions[i].par_id,
589 saved_positions[i].par_pos) );
593 void BufferView::switchKeyMap()
595 if (!lyxrc.rtl_support)
598 if (getLyXText()->real_current_font.isRightToLeft()) {
599 if (intl_->keymap == Intl::PRIMARY)
602 if (intl_->keymap == Intl::SECONDARY)
608 int BufferView::workWidth() const
614 void BufferView::center()
616 CursorSlice & bot = cursor_.bottom();
617 lyx::pit_type const pit = bot.pit();
618 bot.text()->redoParagraph(pit);
619 Paragraph const & par = bot.text()->paragraphs()[pit];
621 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
622 + par.ascent() - height_ / 2;
626 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
630 switch (cmd.action) {
633 flag.enabled(!buffer_->undostack().empty());
636 flag.enabled(!buffer_->redostack().empty());
638 case LFUN_FILE_INSERT:
639 case LFUN_FILE_INSERT_ASCII_PARA:
640 case LFUN_FILE_INSERT_ASCII:
641 case LFUN_BOOKMARK_SAVE:
642 // FIXME: Actually, these LFUNS should be moved to LyXText
643 flag.enabled(cursor_.inTexted());
645 case LFUN_FONT_STATE:
646 case LFUN_LABEL_INSERT:
647 case LFUN_PARAGRAPH_GOTO:
648 // FIXME handle non-trivially
649 case LFUN_OUTLINE_UP:
650 case LFUN_OUTLINE_DOWN:
651 case LFUN_OUTLINE_IN:
652 case LFUN_OUTLINE_OUT:
654 case LFUN_REFERENCE_NEXT:
656 case LFUN_WORD_REPLACE:
659 case LFUN_MARK_TOGGLE:
660 case LFUN_SCREEN_RECENTER:
661 case LFUN_BIBTEX_DATABASE_ADD:
662 case LFUN_BIBTEX_DATABASE_DEL:
663 case LFUN_WORDS_COUNT:
664 case LFUN_NEXT_INSET_TOGGLE:
668 case LFUN_LABEL_GOTO: {
669 flag.enabled(!cmd.argument().empty()
670 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
674 case LFUN_BOOKMARK_GOTO:
675 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
677 case LFUN_CHANGES_TRACK:
679 flag.setOnOff(buffer_->params().tracking_changes);
682 case LFUN_CHANGES_OUTPUT: {
683 OutputParams runparams;
684 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
685 flag.enabled(buffer_ && buffer_->params().tracking_changes
686 && features.isAvailable("dvipost"));
687 flag.setOnOff(buffer_->params().output_changes);
691 case LFUN_CHANGES_MERGE:
692 case LFUN_CHANGE_ACCEPT: // what about these two
693 case LFUN_CHANGE_REJECT: // what about these two
694 case LFUN_ALL_CHANGES_ACCEPT:
695 case LFUN_ALL_CHANGES_REJECT:
696 flag.enabled(buffer_ && buffer_->params().tracking_changes);
699 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
700 flag.setOnOff(buffer_->params().compressed);
712 bool BufferView::dispatch(FuncRequest const & cmd)
714 //lyxerr << BOOST_CURRENT_FUNCTION
715 // << [ cmd = " << cmd << "]" << endl;
717 // Make sure that the cached BufferView is correct.
718 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
719 << " action[" << cmd.action << ']'
720 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
721 << " x[" << cmd.x << ']'
722 << " y[" << cmd.y << ']'
723 << " button[" << cmd.button() << ']'
726 LCursor & cur = cursor_;
728 switch (cmd.action) {
732 cur.message(_("Undo"));
733 cur.clearSelection();
734 if (!textUndo(*this))
735 cur.message(_("No further undo information"));
743 cur.message(_("Redo"));
744 cur.clearSelection();
745 if (!textRedo(*this))
746 cur.message(_("No further redo information"));
752 case LFUN_FILE_INSERT:
753 // FIXME: We don't know the encoding of filenames
754 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
757 case LFUN_FILE_INSERT_ASCII_PARA:
758 // FIXME: We don't know the encoding of filenames
759 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
762 case LFUN_FILE_INSERT_ASCII:
763 // FIXME: We don't know the encoding of filenames
764 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
767 case LFUN_FONT_STATE:
768 cur.message(lyx::from_utf8(cur.currentState()));
771 case LFUN_BOOKMARK_SAVE:
772 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
775 case LFUN_BOOKMARK_GOTO:
776 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
779 case LFUN_LABEL_GOTO: {
780 string label = lyx::to_utf8(cmd.argument());
783 getInsetByCode<InsetRef>(cursor_,
784 InsetBase::REF_CODE);
786 label = inset->getContents();
796 case LFUN_PARAGRAPH_GOTO: {
797 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
798 ParIterator par = buffer_->getParFromID(id);
799 if (par == buffer_->par_iterator_end()) {
800 lyxerr[Debug::INFO] << "No matching paragraph found! ["
801 << id << ']' << endl;
804 lyxerr[Debug::INFO] << "Paragraph " << par->id()
805 << " found." << endl;
809 setCursor(makeDocIterator(par, 0));
816 case LFUN_OUTLINE_UP:
817 lyx::toc::outline(lyx::toc::Up, cursor_);
818 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
819 updateLabels(*buffer_);
821 case LFUN_OUTLINE_DOWN:
822 lyx::toc::outline(lyx::toc::Down, cursor_);
823 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
824 updateLabels(*buffer_);
826 case LFUN_OUTLINE_IN:
827 lyx::toc::outline(lyx::toc::In, cursor_);
828 updateLabels(*buffer_);
830 case LFUN_OUTLINE_OUT:
831 lyx::toc::outline(lyx::toc::Out, cursor_);
832 updateLabels(*buffer_);
836 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
839 case LFUN_REFERENCE_NEXT: {
840 vector<InsetBase_code> tmp;
841 tmp.push_back(InsetBase::LABEL_CODE);
842 tmp.push_back(InsetBase::REF_CODE);
843 bv_funcs::gotoInset(this, tmp, true);
847 case LFUN_CHANGES_TRACK:
851 case LFUN_CHANGES_OUTPUT: {
852 bool const state = buffer_->params().output_changes;
853 buffer_->params().output_changes = !state;
857 case LFUN_CHANGES_MERGE:
858 if (lyx::find::findNextChange(this))
859 showDialog("changes");
862 case LFUN_ALL_CHANGES_ACCEPT: {
863 cursor_.reset(buffer_->inset());
865 #warning FIXME changes
867 while (lyx::find::findNextChange(this))
868 getLyXText()->acceptChange(cursor_);
873 case LFUN_ALL_CHANGES_REJECT: {
874 cursor_.reset(buffer_->inset());
876 #warning FIXME changes
878 while (lyx::find::findNextChange(this))
879 getLyXText()->rejectChange(cursor_);
884 lyx::find::find(this, cmd);
887 case LFUN_WORD_REPLACE:
888 lyx::find::replace(this, cmd);
892 cur.clearSelection();
894 cur.message(lyx::from_utf8(N_("Mark off")));
898 cur.clearSelection();
901 cur.message(lyx::from_utf8(N_("Mark on")));
904 case LFUN_MARK_TOGGLE:
905 cur.clearSelection();
908 cur.message(lyx::from_utf8(N_("Mark removed")));
911 cur.message(lyx::from_utf8(N_("Mark set")));
916 case LFUN_SCREEN_RECENTER:
920 case LFUN_BIBTEX_DATABASE_ADD: {
921 LCursor tmpcur = cursor_;
922 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
923 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
924 InsetBase::BIBTEX_CODE);
926 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
927 buffer_->updateBibfilesCache();
932 case LFUN_BIBTEX_DATABASE_DEL: {
933 LCursor tmpcur = cursor_;
934 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
935 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
936 InsetBase::BIBTEX_CODE);
938 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
939 buffer_->updateBibfilesCache();
944 case LFUN_WORDS_COUNT: {
945 DocIterator from, to;
946 if (cur.selection()) {
947 from = cur.selectionBegin();
948 to = cur.selectionEnd();
950 from = doc_iterator_begin(buffer_->inset());
951 to = doc_iterator_end(buffer_->inset());
953 int const count = countWords(from, to);
957 message = bformat(_("%1$d words in selection."),
960 message = bformat(_("%1$d words in document."),
965 message = _("One word in selection.");
967 message = _("One word in document.");
970 Alert::information(_("Count words"), message);
974 case LFUN_BUFFER_TOGGLE_COMPRESSION:
975 // turn compression on/off
976 buffer_->params().compressed = !buffer_->params().compressed;
979 case LFUN_NEXT_INSET_TOGGLE: {
980 // this is the real function we want to invoke
981 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
982 // if there is an inset at cursor, see whether it
984 InsetBase * inset = cur.nextInset();
985 if (inset && inset->isActive()) {
986 LCursor tmpcur = cur;
987 tmpcur.pushLeft(*inset);
988 inset->dispatch(tmpcur, tmpcmd);
989 if (tmpcur.result().dispatched()) {
993 // if it did not work, try the underlying inset.
994 if (!cur.result().dispatched())
995 cur.dispatch(tmpcmd);
997 if (cur.result().dispatched())
998 cur.clearSelection();
1011 docstring const BufferView::requestSelection()
1016 LCursor & cur = cursor_;
1018 if (!cur.selection()) {
1019 xsel_cache_.set = false;
1023 if (!xsel_cache_.set ||
1024 cur.top() != xsel_cache_.cursor ||
1025 cur.anchor_.top() != xsel_cache_.anchor)
1027 xsel_cache_.cursor = cur.top();
1028 xsel_cache_.anchor = cur.anchor_.top();
1029 xsel_cache_.set = cur.selection();
1030 return cur.selectionAsString(false);
1036 void BufferView::clearSelection()
1039 cursor_.clearSelection();
1040 xsel_cache_.set = false;
1045 void BufferView::workAreaResize(int width, int height)
1047 bool const widthChange = width != width_;
1048 bool const heightChange = height != height_;
1050 // Update from work area
1054 if (buffer_ && widthChange) {
1055 // The WorkArea content needs a resize
1059 if (widthChange || heightChange)
1064 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1066 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1068 // This is only called for mouse related events including
1069 // LFUN_FILE_OPEN generated by drag-and-drop.
1070 FuncRequest cmd = cmd0;
1076 cur.push(buffer_->inset());
1077 cur.selection() = cursor_.selection();
1079 // Doesn't go through lyxfunc, so we need to update
1080 // the layout choice etc. ourselves
1082 // E.g. Qt mouse press when no buffer
1086 // Either the inset under the cursor or the
1087 // surrounding LyXText will handle this event.
1089 // Build temporary cursor.
1090 cmd.y = min(max(cmd.y, -1), height_);
1091 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1092 //lyxerr << BOOST_CURRENT_FUNCTION
1093 // << " * hit inset at tip: " << inset << endl;
1094 //lyxerr << BOOST_CURRENT_FUNCTION
1095 // << " * created temp cursor:" << cur << endl;
1097 // Put anchor at the same position.
1100 // Try to dispatch to an non-editable inset near this position
1101 // via the temp cursor. If the inset wishes to change the real
1102 // cursor it has to do so explicitly by using
1103 // cur.bv().cursor() = cur; (or similar)
1105 inset->dispatch(cur, cmd);
1107 // Now dispatch to the temporary cursor. If the real cursor should
1108 // be modified, the inset's dispatch has to do so explicitly.
1109 if (!cur.result().dispatched())
1112 if (cur.result().dispatched()) {
1113 // Redraw if requested or necessary.
1114 if (cur.result().update())
1115 update(Update::FitCursor | Update::Force);
1117 update(Update::FitCursor | Update::MultiParSel);
1124 void BufferView::scroll(int lines)
1129 // LyXText const * t = &buffer_->text();
1130 // int const line_height = defaultRowHeight();
1132 // // The new absolute coordinate
1133 // int new_top_y = top_y() + lines * line_height;
1135 // // Restrict to a valid value
1136 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1137 // new_top_y = std::max(0, new_top_y);
1139 // scrollDocView(new_top_y);
1141 // // Update the scrollbar.
1142 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1146 void BufferView::setCursorFromRow(int row)
1151 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1154 buffer_->text().setCursor(cursor_, 0, 0);
1156 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1160 void BufferView::gotoLabel(string const & label)
1162 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1163 vector<string> labels;
1164 it->getLabelList(*buffer_, labels);
1165 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1174 LyXText * BufferView::getLyXText()
1176 LyXText * text = cursor_.innerText();
1182 LyXText const * BufferView::getLyXText() const
1184 LyXText const * text = cursor_.innerText();
1190 int BufferView::workHeight() const
1196 void BufferView::setCursor(DocIterator const & dit)
1198 size_t const n = dit.depth();
1199 for (size_t i = 0; i < n; ++i)
1200 dit[i].inset().edit(cursor_, true);
1202 cursor_.setCursor(dit);
1203 cursor_.selection() = false;
1207 void BufferView::mouseSetCursor(LCursor & cur)
1209 BOOST_ASSERT(&cur.bv() == this);
1211 // Has the cursor just left the inset?
1212 bool badcursor = false;
1213 if (&cursor_.inset() != &cur.inset())
1214 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1216 // do the dEPM magic if needed
1217 // FIXME: move this to InsetText::notifyCursorLeaves?
1218 if (!badcursor && cursor_.inTexted())
1219 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1222 cursor_.clearSelection();
1223 cursor_.setTargetX();
1229 void BufferView::putSelectionAt(DocIterator const & cur,
1230 int length, bool backwards)
1232 cursor_.clearSelection();
1238 cursor_.pos() += length;
1239 cursor_.setSelection(cursor_, -length);
1241 cursor_.setSelection(cursor_, length);
1246 LCursor & BufferView::cursor()
1252 LCursor const & BufferView::cursor() const
1258 lyx::pit_type BufferView::anchor_ref() const
1264 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1266 return metrics_info_;
1270 void BufferView::updateMetrics(bool singlepar)
1272 // Remove old position cache
1274 LyXText & buftext = buffer_->text();
1275 lyx::pit_type size = int(buftext.paragraphs().size());
1277 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1278 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1282 lyx::pit_type const pit = anchor_ref_;
1285 size_t const npit = buftext.paragraphs().size();
1287 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1288 // the (main text, not inset!) paragraph containing the cursor.
1289 // (if this paragraph contains insets etc., rebreaking will
1290 // recursively descend)
1291 if (!singlepar || pit == cursor_.bottom().pit())
1292 buftext.redoParagraph(pit);
1293 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1295 // Redo paragraphs above anchor if necessary; again, in Single Par
1296 // mode, only if we encounter the (main text) one having the cursor.
1298 while (y1 > 0 && pit1 > 0) {
1299 y1 -= buftext.getPar(pit1).ascent();
1301 if (!singlepar || pit1 == cursor_.bottom().pit())
1302 buftext.redoParagraph(pit1);
1303 y1 -= buftext.getPar(pit1).descent();
1307 // Take care of ascent of first line
1308 y1 -= buftext.getPar(pit1).ascent();
1310 // Normalize anchor for next time
1314 // Grey at the beginning is ugly
1315 if (pit1 == 0 && y1 > 0) {
1321 // Redo paragraphs below the anchor if necessary. Single par mode:
1322 // only the one containing the cursor if encountered.
1324 while (y2 < height_ && pit2 < int(npit) - 1) {
1325 y2 += buftext.getPar(pit2).descent();
1327 if (!singlepar || pit2 == cursor_.bottom().pit())
1328 buftext.redoParagraph(pit2);
1329 y2 += buftext.getPar(pit2).ascent();
1332 // Take care of descent of last line
1333 y2 += buftext.getPar(pit2).descent();
1335 // The coordinates of all these paragraphs are correct, cache them
1337 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1338 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1339 Paragraph const & par = buftext.getPar(pit);
1341 parPos[pit] = Point(0, y);
1342 if (singlepar && pit == cursor_.bottom().pit()) {
1343 // In Single Paragraph mode, collect here the
1344 // y1 and y2 of the (one) paragraph the cursor is in
1345 y1 = y - par.ascent();
1346 y2 = y + par.descent();
1352 // collect cursor paragraph iter bounds
1353 pit1 = cursor_.bottom().pit();
1354 pit2 = cursor_.bottom().pit();
1357 lyxerr[Debug::DEBUG]
1358 << BOOST_CURRENT_FUNCTION
1361 << " pit1: " << pit1
1362 << " pit2: " << pit2
1363 << " npit: " << npit
1364 << " singlepar: " << singlepar
1368 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1372 void BufferView::menuInsertLyXFile(string const & filenm)
1374 BOOST_ASSERT(cursor_.inTexted());
1375 string filename = filenm;
1377 if (filename.empty()) {
1378 // Launch a file browser
1379 string initpath = lyxrc.document_path;
1382 string const trypath = buffer_->filePath();
1383 // If directory is writeable, use this as default.
1384 if (isDirWriteable(trypath))
1388 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1390 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1391 string(lyxrc.document_path)),
1392 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1393 string(addPath(package().system_support(), "examples"))));
1395 FileDialog::Result result =
1396 fileDlg.open(initpath,
1397 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1400 if (result.first == FileDialog::Later)
1403 filename = result.second;
1405 // check selected filename
1406 if (filename.empty()) {
1407 // emit message signal.
1408 message(_("Canceled."));
1413 // Get absolute path of file and add ".lyx"
1414 // to the filename if necessary
1415 filename = fileSearch(string(), filename, "lyx");
1417 docstring const disp_fn = makeDisplayPath(filename);
1418 // emit message signal.
1419 message(bformat(_("Inserting document %1$s..."), disp_fn));
1422 Buffer buf("", false);
1423 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1424 ErrorList & el = buffer_->errorList("Parse");
1425 // Copy the inserted document error list into the current buffer one.
1426 el = buf.errorList("Parse");
1427 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1428 buf.params().textclass, el);
1429 res = _("Document %1$s inserted.");
1431 res = _("Could not insert document %1$s");
1433 // emit message signal.
1434 message(bformat(res, disp_fn));
1435 buffer_->errors("Parse");
1440 void BufferView::trackChanges()
1442 bool const tracking = buffer_->params().tracking_changes;
1445 for_each(buffer_->par_iterator_begin(),
1446 buffer_->par_iterator_end(),
1447 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1448 buffer_->params().tracking_changes = true;
1450 // We cannot allow undos beyond the freeze point
1451 buffer_->undostack().clear();
1453 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1454 if (lyx::find::findNextChange(this)) {
1455 showDialog("changes");
1459 for_each(buffer_->par_iterator_begin(),
1460 buffer_->par_iterator_end(),
1461 mem_fun_ref(&Paragraph::untrackChanges));
1463 buffer_->params().tracking_changes = false;
1466 buffer_->redostack().clear();