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/Gui.h"
68 #include "frontends/LyXView.h"
69 #include "frontends/Selection.h"
71 #include "graphics/Previews.h"
73 #include "support/convert.h"
74 #include "support/filefilterlist.h"
75 #include "support/filetools.h"
76 #include "support/package.h"
77 #include "support/types.h"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
92 using lyx::support::addPath;
93 using lyx::support::bformat;
94 using lyx::support::FileFilterList;
95 using lyx::support::fileSearch;
96 using lyx::support::isDirWriteable;
97 using lyx::support::makeDisplayPath;
98 using lyx::support::makeAbsPath;
99 using lyx::support::package;
103 using std::istringstream;
105 using std::make_pair;
108 using std::mem_fun_ref;
112 extern BufferList bufferlist;
117 unsigned int const saved_positions_num = 20;
120 /// Return an inset of this class if it exists at the current cursor position
122 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
125 DocIterator it = cur;
126 if (it.nextInset() &&
127 it.nextInset()->lyxCode() == code) {
128 inset = static_cast<T*>(it.nextInset());
136 BufferView::BufferView(LyXView * owner)
137 : owner_(owner), buffer_(0), wh_(0),
139 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
141 xsel_cache_.set = false;
143 saved_positions.resize(saved_positions_num);
144 // load saved bookmarks
145 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
146 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
147 bm != bmList.end(); ++bm)
148 if (bm->get<0>() < saved_positions_num)
149 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
150 // and then clear them
155 BufferView::~BufferView()
160 Buffer * BufferView::buffer() const
166 LyXView * BufferView::owner() const
172 void BufferView::setBuffer(Buffer * b)
174 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
175 << "[ b = " << b << "]" << endl;
178 // Save the actual cursor position and anchor inside the
179 // buffer so that it can be restored in case we rechange
180 // to this buffer later on.
181 buffer_->saveCursor(cursor_.selectionBegin(),
182 cursor_.selectionEnd());
183 // current buffer is going to be switched-off, save cursor pos
184 LyX::ref().session().saveFilePosition(buffer_->fileName(),
185 boost::tie(cursor_.pit(), cursor_.pos()) );
188 // If we're quitting lyx, don't bother updating stuff
194 // If we are closing current buffer, switch to the first in
197 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
198 << " No Buffer!" << endl;
199 // We are closing the buffer, use the first buffer as current
200 buffer_ = bufferlist.first();
202 // Set current buffer
207 cursor_ = LCursor(*this);
212 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().init(this);
217 buffer_->text().setCurrentFont(cursor_);
218 if (buffer_->getCursor().size() > 0 &&
219 buffer_->getAnchor().size() > 0)
221 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
222 cursor_.resetAnchor();
223 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
224 cursor_.setSelection();
230 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
231 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
235 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
237 // Get absolute path of file and add ".lyx"
238 // to the filename if necessary
239 string s = fileSearch(string(), filename, "lyx");
241 bool const found = !s.empty();
246 // File already open?
247 if (bufferlist.exists(s)) {
248 docstring const file = makeDisplayPath(s, 20);
249 docstring text = bformat(_("The document %1$s is already "
250 "loaded.\n\nDo you want to revert "
251 "to the saved version?"), file);
252 int const ret = Alert::prompt(_("Revert to saved document?"),
253 text, 0, 1, _("&Revert"), _("&Switch to document"));
256 setBuffer(bufferlist.getBuffer(s));
259 // FIXME: should be LFUN_REVERT
260 if (!bufferlist.close(bufferlist.getBuffer(s), false))
262 // Fall through to new load. (Asger)
268 b = bufferlist.newBuffer(s);
269 if (!::loadLyXFile(b, s)) {
270 bufferlist.release(b);
274 docstring text = bformat(_("The document %1$s does not yet "
275 "exist.\n\nDo you want to create "
276 "a new document?"), lyx::from_utf8(s));
277 int const ret = Alert::prompt(_("Create new document?"),
278 text, 0, 1, _("&Create"), _("Cancel"));
281 b = newFile(s, string(), true);
289 // Send the "errors" signal in case of parsing errors
292 // scroll to the position when the file was last closed
293 if (lyxrc.use_lastfilepos) {
296 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
297 // I am not sure how to separate the following part to a function
298 // so I will leave this to Lars.
300 // check pit since the document may be externally changed.
301 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
302 ParIterator it = b->par_iterator_begin();
303 ParIterator const end = b->par_iterator_end();
304 for (; it != end; ++it)
305 if (it.pit() == pit) {
306 // restored pos may be bigger than it->size
307 setCursor(makeDocIterator(it, min(pos, it->size())));
308 update(Update::FitCursor);
315 LyX::ref().session().addLastFile(b->fileName());
321 void BufferView::reload()
323 string const fn = buffer_->fileName();
324 if (bufferlist.close(buffer_, false))
329 void BufferView::resize()
334 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
336 buffer_->text().init(this);
342 bool BufferView::fitCursor()
344 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
345 LyXFont const font = cursor_.getFont();
346 int const asc = font_metrics::maxAscent(font);
347 int const des = font_metrics::maxDescent(font);
348 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
349 if (p.y_ - asc >= 0 && p.y_ + des < height_)
357 bool BufferView::multiParSel()
359 if (!cursor_.selection())
361 bool ret = multiparsel_cache_;
362 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
363 // Either this, or previous selection spans paragraphs
364 return ret || multiparsel_cache_;
368 bool BufferView::update(Update::flags flags)
370 // This is close to a hot-path.
371 if (lyxerr.debugging(Debug::DEBUG)) {
373 << BOOST_CURRENT_FUNCTION
374 << "[fitcursor = " << (flags & Update::FitCursor)
375 << ", forceupdate = " << (flags & Update::Force)
376 << ", singlepar = " << (flags & Update::SinglePar)
377 << "] buffer: " << buffer_ << endl;
380 // Check needed to survive LyX startup
384 // Update macro store
385 buffer_->buildMacros();
387 // First drawing step
388 updateMetrics(flags & Update::SinglePar);
390 // The second drawing step is done in WorkArea::redraw() if needed.
391 bool const need_second_step =
392 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
393 && (fitCursor() || multiParSel());
395 return need_second_step;
399 void BufferView::updateScrollbar()
402 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
403 << " no text in updateScrollbar" << endl;
404 scrollbarParameters_.reset();
408 LyXText & t = buffer_->text();
409 int const parsize = int(t.paragraphs().size() - 1);
410 if (anchor_ref_ > parsize) {
411 anchor_ref_ = parsize;
416 << BOOST_CURRENT_FUNCTION
417 << " Updating scrollbar: height: " << t.paragraphs().size()
418 << " curr par: " << cursor_.bottom().pit()
419 << " default height " << defaultRowHeight() << endl;
421 // It would be better to fix the scrollbar to understand
422 // values in [0..1] and divide everything by wh
424 // estimated average paragraph height:
427 int h = t.getPar(anchor_ref_).height();
429 // Normalize anchor/offset (MV):
430 while (offset_ref_ > h && anchor_ref_ < parsize) {
433 h = t.getPar(anchor_ref_).height();
435 // Look at paragraph heights on-screen
438 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
441 int const h2 = t.getPar(pit).height();
445 int const hav = sumh / nh;
446 // More realistic average paragraph height
450 scrollbarParameters_.height = (parsize + 1) * wh_;
451 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
452 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
456 ScrollbarParameters const & BufferView::scrollbarParameters() const
458 return scrollbarParameters_;
462 void BufferView::scrollDocView(int value)
464 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
465 << "[ value = " << value << "]" << endl;
470 LyXText & t = buffer_->text();
472 float const bar = value / float(wh_ * t.paragraphs().size());
474 anchor_ref_ = int(bar * t.paragraphs().size());
475 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
476 anchor_ref_ = int(t.paragraphs().size()) - 1;
477 t.redoParagraph(anchor_ref_);
478 int const h = t.getPar(anchor_ref_).height();
479 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
483 void BufferView::setCursorFromScrollbar()
485 LyXText & t = buffer_->text();
487 int const height = 2 * defaultRowHeight();
488 int const first = height;
489 int const last = height_ - height;
490 LCursor & cur = cursor_;
492 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
495 case bv_funcs::CUR_ABOVE:
496 t.setCursorFromCoordinates(cur, 0, first);
497 cur.clearSelection();
499 case bv_funcs::CUR_BELOW:
500 t.setCursorFromCoordinates(cur, 0, last);
501 cur.clearSelection();
503 case bv_funcs::CUR_INSIDE:
504 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
505 int const newy = min(last, max(y, first));
507 cur.reset(buffer_->inset());
508 t.setCursorFromCoordinates(cur, 0, newy);
514 Change const BufferView::getCurrentChange()
516 if (!buffer_->params().tracking_changes || !cursor_.selection())
517 return Change(Change::UNCHANGED);
519 DocIterator dit = cursor_.selectionBegin();
520 return dit.paragraph().lookupChange(dit.pos());
524 void BufferView::savePosition(unsigned int i)
526 if (i >= saved_positions_num)
528 BOOST_ASSERT(cursor_.inTexted());
529 saved_positions[i] = Position(buffer_->fileName(),
530 cursor_.paragraph().id(),
533 // emit message signal.
534 message(bformat(_("Saved bookmark %1$d"), i));
538 void BufferView::restorePosition(unsigned int i)
540 if (i >= saved_positions_num)
543 string const fname = saved_positions[i].filename;
545 cursor_.clearSelection();
547 if (fname != buffer_->fileName()) {
549 if (bufferlist.exists(fname))
550 b = bufferlist.getBuffer(fname);
552 b = bufferlist.newBuffer(fname);
553 // Don't ask, just load it
554 ::loadLyXFile(b, fname);
560 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
561 if (par == buffer_->par_iterator_end())
564 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
567 // emit message signal.
568 message(bformat(_("Moved to bookmark %1$d"), i));
572 bool BufferView::isSavedPosition(unsigned int i)
574 return i < saved_positions_num && !saved_positions[i].filename.empty();
577 void BufferView::saveSavedPositions()
579 // save bookmarks. It is better to use the pit interface
580 // but I do not know how to effectively convert between
582 for (unsigned int i=1; i < saved_positions_num; ++i) {
583 if ( isSavedPosition(i) )
584 LyX::ref().session().saveBookmark( boost::tie(
586 saved_positions[i].filename,
587 saved_positions[i].par_id,
588 saved_positions[i].par_pos) );
592 void BufferView::switchKeyMap()
594 if (!lyxrc.rtl_support)
597 Intl & intl = owner_->getIntl();
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 owner_->getDialogs().show("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 int BufferView::offset_ref() const
1270 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1272 return metrics_info_;
1276 void BufferView::updateMetrics(bool singlepar)
1278 // Remove old position cache
1280 LyXText & buftext = buffer_->text();
1281 lyx::pit_type size = int(buftext.paragraphs().size());
1283 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1284 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1288 lyx::pit_type const pit = anchor_ref_;
1291 size_t const npit = buftext.paragraphs().size();
1293 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1294 // the (main text, not inset!) paragraph containing the cursor.
1295 // (if this paragraph contains insets etc., rebreaking will
1296 // recursively descend)
1297 if (!singlepar || pit == cursor_.bottom().pit())
1298 buftext.redoParagraph(pit);
1299 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1301 // Redo paragraphs above anchor if necessary; again, in Single Par
1302 // mode, only if we encounter the (main text) one having the cursor.
1304 while (y1 > 0 && pit1 > 0) {
1305 y1 -= buftext.getPar(pit1).ascent();
1307 if (!singlepar || pit1 == cursor_.bottom().pit())
1308 buftext.redoParagraph(pit1);
1309 y1 -= buftext.getPar(pit1).descent();
1313 // Take care of ascent of first line
1314 y1 -= buftext.getPar(pit1).ascent();
1316 // Normalize anchor for next time
1320 // Grey at the beginning is ugly
1321 if (pit1 == 0 && y1 > 0) {
1327 // Redo paragraphs below the anchor if necessary. Single par mode:
1328 // only the one containing the cursor if encountered.
1330 while (y2 < height_ && pit2 < int(npit) - 1) {
1331 y2 += buftext.getPar(pit2).descent();
1333 if (!singlepar || pit2 == cursor_.bottom().pit())
1334 buftext.redoParagraph(pit2);
1335 y2 += buftext.getPar(pit2).ascent();
1338 // Take care of descent of last line
1339 y2 += buftext.getPar(pit2).descent();
1341 // The coordinates of all these paragraphs are correct, cache them
1343 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1344 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1345 Paragraph const & par = buftext.getPar(pit);
1347 parPos[pit] = Point(0, y);
1348 if (singlepar && pit == cursor_.bottom().pit()) {
1349 // In Single Paragraph mode, collect here the
1350 // y1 and y2 of the (one) paragraph the cursor is in
1351 y1 = y - par.ascent();
1352 y2 = y + par.descent();
1358 // collect cursor paragraph iter bounds
1359 pit1 = cursor_.bottom().pit();
1360 pit2 = cursor_.bottom().pit();
1363 lyxerr[Debug::DEBUG]
1364 << BOOST_CURRENT_FUNCTION
1367 << " pit1: " << pit1
1368 << " pit2: " << pit2
1369 << " npit: " << npit
1370 << " singlepar: " << singlepar
1374 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1378 void BufferView::menuInsertLyXFile(string const & filenm)
1380 BOOST_ASSERT(cursor_.inTexted());
1381 string filename = filenm;
1383 if (filename.empty()) {
1384 // Launch a file browser
1385 string initpath = lyxrc.document_path;
1388 string const trypath = buffer_->filePath();
1389 // If directory is writeable, use this as default.
1390 if (isDirWriteable(trypath))
1394 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1396 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1397 string(lyxrc.document_path)),
1398 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1399 string(addPath(package().system_support(), "examples"))));
1401 FileDialog::Result result =
1402 fileDlg.open(initpath,
1403 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1406 if (result.first == FileDialog::Later)
1409 filename = result.second;
1411 // check selected filename
1412 if (filename.empty()) {
1413 // emit message signal.
1414 message(_("Canceled."));
1419 // Get absolute path of file and add ".lyx"
1420 // to the filename if necessary
1421 filename = fileSearch(string(), filename, "lyx");
1423 docstring const disp_fn = makeDisplayPath(filename);
1424 // emit message signal.
1425 message(bformat(_("Inserting document %1$s..."), disp_fn));
1428 Buffer buf("", false);
1429 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1430 ErrorList & el = buffer_->errorList("Parse");
1431 // Copy the inserted document error list into the current buffer one.
1432 el = buf.errorList("Parse");
1433 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1434 buf.params().textclass, el);
1435 res = _("Document %1$s inserted.");
1437 res = _("Could not insert document %1$s");
1439 // emit message signal.
1440 message(bformat(res, disp_fn));
1441 buffer_->errors("Parse");
1446 void BufferView::trackChanges()
1448 bool const tracking = buffer_->params().tracking_changes;
1451 for_each(buffer_->par_iterator_begin(),
1452 buffer_->par_iterator_end(),
1453 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1454 buffer_->params().tracking_changes = true;
1456 // We cannot allow undos beyond the freeze point
1457 buffer_->undostack().clear();
1459 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1460 if (lyx::find::findNextChange(this)) {
1461 owner_->getDialogs().show("changes");
1465 for_each(buffer_->par_iterator_begin(),
1466 buffer_->par_iterator_end(),
1467 mem_fun_ref(&Paragraph::untrackChanges));
1469 buffer_->params().tracking_changes = false;
1472 buffer_->redostack().clear();