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/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
84 using lyx::support::addPath;
85 using lyx::support::bformat;
86 using lyx::support::FileFilterList;
87 using lyx::support::fileSearch;
88 using lyx::support::isDirWriteable;
89 using lyx::support::makeDisplayPath;
90 using lyx::support::makeAbsPath;
91 using lyx::support::package;
95 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = lyx::frontend::Alert;
108 unsigned int const saved_positions_num = 20;
111 /// Return an inset of this class if it exists at the current cursor position
113 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
116 DocIterator it = cur;
117 if (it.nextInset() &&
118 it.nextInset()->lyxCode() == code) {
119 inset = static_cast<T*>(it.nextInset());
127 BufferView::BufferView()
128 : buffer_(0), wh_(0),
130 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
133 xsel_cache_.set = false;
135 saved_positions.resize(saved_positions_num);
136 // load saved bookmarks
137 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
138 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
139 bm != bmList.end(); ++bm)
140 if (bm->get<0>() < saved_positions_num)
141 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
142 // and then clear them
145 intl_->initKeyMapper(lyxrc.use_kbmap);
149 BufferView::~BufferView()
154 Buffer * BufferView::buffer() const
160 void BufferView::setBuffer(Buffer * b)
162 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
163 << "[ b = " << b << "]" << endl;
166 // Save the actual cursor position and anchor inside the
167 // buffer so that it can be restored in case we rechange
168 // to this buffer later on.
169 buffer_->saveCursor(cursor_.selectionBegin(),
170 cursor_.selectionEnd());
171 // current buffer is going to be switched-off, save cursor pos
172 LyX::ref().session().saveFilePosition(buffer_->fileName(),
173 boost::tie(cursor_.pit(), cursor_.pos()) );
176 // If we're quitting lyx, don't bother updating stuff
182 // If we are closing current buffer, switch to the first in
185 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
186 << " No Buffer!" << endl;
187 // We are closing the buffer, use the first buffer as current
188 buffer_ = theBufferList().first();
190 // Set current buffer
195 cursor_ = LCursor(*this);
200 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
201 << "Buffer addr: " << buffer_ << endl;
202 cursor_.push(buffer_->inset());
203 cursor_.resetAnchor();
204 buffer_->text().init(this);
205 buffer_->text().setCurrentFont(cursor_);
206 if (buffer_->getCursor().size() > 0 &&
207 buffer_->getAnchor().size() > 0)
209 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
210 cursor_.resetAnchor();
211 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
212 cursor_.setSelection();
218 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
219 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
223 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
225 // Get absolute path of file and add ".lyx"
226 // to the filename if necessary
227 string s = fileSearch(string(), filename, "lyx");
229 bool const found = !s.empty();
234 // File already open?
235 if (theBufferList().exists(s)) {
236 docstring const file = makeDisplayPath(s, 20);
237 docstring text = bformat(_("The document %1$s is already "
238 "loaded.\n\nDo you want to revert "
239 "to the saved version?"), file);
240 int const ret = Alert::prompt(_("Revert to saved document?"),
241 text, 0, 1, _("&Revert"), _("&Switch to document"));
244 setBuffer(theBufferList().getBuffer(s));
247 // FIXME: should be LFUN_REVERT
248 if (!theBufferList().close(theBufferList().getBuffer(s), false))
250 // Fall through to new load. (Asger)
256 b = theBufferList().newBuffer(s);
257 if (!::loadLyXFile(b, s)) {
258 theBufferList().release(b);
262 docstring text = bformat(_("The document %1$s does not yet "
263 "exist.\n\nDo you want to create "
264 "a new document?"), lyx::from_utf8(s));
265 int const ret = Alert::prompt(_("Create new document?"),
266 text, 0, 1, _("&Create"), _("Cancel"));
269 b = newFile(s, string(), true);
277 // Send the "errors" signal in case of parsing errors
280 // scroll to the position when the file was last closed
281 if (lyxrc.use_lastfilepos) {
284 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
285 // I am not sure how to separate the following part to a function
286 // so I will leave this to Lars.
288 // check pit since the document may be externally changed.
289 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
290 ParIterator it = b->par_iterator_begin();
291 ParIterator const end = b->par_iterator_end();
292 for (; it != end; ++it)
293 if (it.pit() == pit) {
294 // restored pos may be bigger than it->size
295 setCursor(makeDocIterator(it, min(pos, it->size())));
296 update(Update::FitCursor);
303 LyX::ref().session().addLastFile(b->fileName());
309 void BufferView::reload()
311 string const fn = buffer_->fileName();
312 if (theBufferList().close(buffer_, false))
317 void BufferView::resize()
322 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
324 buffer_->text().init(this);
330 bool BufferView::fitCursor()
332 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
333 lyx::frontend::FontMetrics const & fm =
334 theFontMetrics(cursor_.getFont());
335 int const asc = fm.maxAscent();
336 int const des = fm.maxDescent();
337 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
338 if (p.y_ - asc >= 0 && p.y_ + des < height_)
346 bool BufferView::multiParSel()
348 if (!cursor_.selection())
350 bool ret = multiparsel_cache_;
351 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
352 // Either this, or previous selection spans paragraphs
353 return ret || multiparsel_cache_;
357 bool BufferView::update(Update::flags flags)
359 // This is close to a hot-path.
360 if (lyxerr.debugging(Debug::DEBUG)) {
362 << BOOST_CURRENT_FUNCTION
363 << "[fitcursor = " << (flags & Update::FitCursor)
364 << ", forceupdate = " << (flags & Update::Force)
365 << ", singlepar = " << (flags & Update::SinglePar)
366 << "] buffer: " << buffer_ << endl;
369 // Check needed to survive LyX startup
373 // Update macro store
374 buffer_->buildMacros();
376 // First drawing step
377 updateMetrics(flags & Update::SinglePar);
379 // The second drawing step is done in WorkArea::redraw() if needed.
380 bool const need_second_step =
381 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
382 && (fitCursor() || multiParSel());
384 return need_second_step;
388 void BufferView::updateScrollbar()
391 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
392 << " no text in updateScrollbar" << endl;
393 scrollbarParameters_.reset();
397 LyXText & t = buffer_->text();
398 int const parsize = int(t.paragraphs().size() - 1);
399 if (anchor_ref_ > parsize) {
400 anchor_ref_ = parsize;
405 << BOOST_CURRENT_FUNCTION
406 << " Updating scrollbar: height: " << t.paragraphs().size()
407 << " curr par: " << cursor_.bottom().pit()
408 << " default height " << defaultRowHeight() << endl;
410 // It would be better to fix the scrollbar to understand
411 // values in [0..1] and divide everything by wh
413 // estimated average paragraph height:
416 int h = t.getPar(anchor_ref_).height();
418 // Normalize anchor/offset (MV):
419 while (offset_ref_ > h && anchor_ref_ < parsize) {
422 h = t.getPar(anchor_ref_).height();
424 // Look at paragraph heights on-screen
427 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
430 int const h2 = t.getPar(pit).height();
434 int const hav = sumh / nh;
435 // More realistic average paragraph height
439 scrollbarParameters_.height = (parsize + 1) * wh_;
440 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
441 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
445 ScrollbarParameters const & BufferView::scrollbarParameters() const
447 return scrollbarParameters_;
451 void BufferView::scrollDocView(int value)
453 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
454 << "[ value = " << value << "]" << endl;
459 LyXText & t = buffer_->text();
461 float const bar = value / float(wh_ * t.paragraphs().size());
463 anchor_ref_ = int(bar * t.paragraphs().size());
464 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
465 anchor_ref_ = int(t.paragraphs().size()) - 1;
466 t.redoParagraph(anchor_ref_);
467 int const h = t.getPar(anchor_ref_).height();
468 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
472 void BufferView::setCursorFromScrollbar()
474 LyXText & t = buffer_->text();
476 int const height = 2 * defaultRowHeight();
477 int const first = height;
478 int const last = height_ - height;
479 LCursor & cur = cursor_;
481 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
484 case bv_funcs::CUR_ABOVE:
485 t.setCursorFromCoordinates(cur, 0, first);
486 cur.clearSelection();
488 case bv_funcs::CUR_BELOW:
489 t.setCursorFromCoordinates(cur, 0, last);
490 cur.clearSelection();
492 case bv_funcs::CUR_INSIDE:
493 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
494 int const newy = min(last, max(y, first));
496 cur.reset(buffer_->inset());
497 t.setCursorFromCoordinates(cur, 0, newy);
503 Change const BufferView::getCurrentChange() const
505 if (!cursor_.selection())
506 return Change(Change::UNCHANGED);
508 DocIterator dit = cursor_.selectionBegin();
509 return dit.paragraph().lookupChange(dit.pos());
513 void BufferView::savePosition(unsigned int i)
515 if (i >= saved_positions_num)
517 BOOST_ASSERT(cursor_.inTexted());
518 saved_positions[i] = Position(buffer_->fileName(),
519 cursor_.paragraph().id(),
522 // emit message signal.
523 message(bformat(_("Saved bookmark %1$d"), i));
527 void BufferView::restorePosition(unsigned int i)
529 if (i >= saved_positions_num)
532 string const fname = saved_positions[i].filename;
534 cursor_.clearSelection();
536 if (fname != buffer_->fileName()) {
538 if (theBufferList().exists(fname))
539 b = theBufferList().getBuffer(fname);
541 b = theBufferList().newBuffer(fname);
542 // Don't ask, just load it
543 ::loadLyXFile(b, fname);
549 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
550 if (par == buffer_->par_iterator_end())
553 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
556 // emit message signal.
557 message(bformat(_("Moved to bookmark %1$d"), i));
561 bool BufferView::isSavedPosition(unsigned int i)
563 return i < saved_positions_num && !saved_positions[i].filename.empty();
566 void BufferView::saveSavedPositions()
568 // save bookmarks. It is better to use the pit interface
569 // but I do not know how to effectively convert between
571 for (unsigned int i=1; i < saved_positions_num; ++i) {
572 if ( isSavedPosition(i) )
573 LyX::ref().session().saveBookmark( boost::tie(
575 saved_positions[i].filename,
576 saved_positions[i].par_id,
577 saved_positions[i].par_pos) );
581 void BufferView::switchKeyMap()
583 if (!lyxrc.rtl_support)
586 if (getLyXText()->real_current_font.isRightToLeft()) {
587 if (intl_->keymap == Intl::PRIMARY)
590 if (intl_->keymap == Intl::SECONDARY)
596 int BufferView::workWidth() const
602 void BufferView::center()
604 CursorSlice & bot = cursor_.bottom();
605 lyx::pit_type const pit = bot.pit();
606 bot.text()->redoParagraph(pit);
607 Paragraph const & par = bot.text()->paragraphs()[pit];
609 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
610 + par.ascent() - height_ / 2;
614 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
618 switch (cmd.action) {
621 flag.enabled(!buffer_->undostack().empty());
624 flag.enabled(!buffer_->redostack().empty());
626 case LFUN_FILE_INSERT:
627 case LFUN_FILE_INSERT_ASCII_PARA:
628 case LFUN_FILE_INSERT_ASCII:
629 case LFUN_BOOKMARK_SAVE:
630 // FIXME: Actually, these LFUNS should be moved to LyXText
631 flag.enabled(cursor_.inTexted());
633 case LFUN_FONT_STATE:
634 case LFUN_LABEL_INSERT:
635 case LFUN_PARAGRAPH_GOTO:
636 // FIXME handle non-trivially
637 case LFUN_OUTLINE_UP:
638 case LFUN_OUTLINE_DOWN:
639 case LFUN_OUTLINE_IN:
640 case LFUN_OUTLINE_OUT:
642 case LFUN_REFERENCE_NEXT:
644 case LFUN_WORD_REPLACE:
647 case LFUN_MARK_TOGGLE:
648 case LFUN_SCREEN_RECENTER:
649 case LFUN_BIBTEX_DATABASE_ADD:
650 case LFUN_BIBTEX_DATABASE_DEL:
651 case LFUN_WORDS_COUNT:
652 case LFUN_NEXT_INSET_TOGGLE:
656 case LFUN_LABEL_GOTO: {
657 flag.enabled(!cmd.argument().empty()
658 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
662 case LFUN_BOOKMARK_GOTO:
663 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
666 case LFUN_CHANGES_TRACK:
668 flag.setOnOff(buffer_->params().trackChanges);
671 case LFUN_CHANGES_OUTPUT: {
672 OutputParams runparams;
673 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
674 flag.enabled(buffer_ && features.isAvailable("dvipost"));
675 flag.setOnOff(buffer_->params().outputChanges);
679 case LFUN_CHANGES_MERGE:
680 case LFUN_CHANGE_NEXT:
681 case LFUN_ALL_CHANGES_ACCEPT:
682 case LFUN_ALL_CHANGES_REJECT:
683 flag.enabled(buffer_); // FIXME: Change tracking (MG)
686 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
687 flag.setOnOff(buffer_->params().compressed);
699 bool BufferView::dispatch(FuncRequest const & cmd)
701 //lyxerr << BOOST_CURRENT_FUNCTION
702 // << [ cmd = " << cmd << "]" << endl;
704 // Make sure that the cached BufferView is correct.
705 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
706 << " action[" << cmd.action << ']'
707 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
708 << " x[" << cmd.x << ']'
709 << " y[" << cmd.y << ']'
710 << " button[" << cmd.button() << ']'
713 LCursor & cur = cursor_;
715 switch (cmd.action) {
719 cur.message(_("Undo"));
720 cur.clearSelection();
721 if (!textUndo(*this))
722 cur.message(_("No further undo information"));
730 cur.message(_("Redo"));
731 cur.clearSelection();
732 if (!textRedo(*this))
733 cur.message(_("No further redo information"));
739 case LFUN_FILE_INSERT:
740 // FIXME: We don't know the encoding of filenames
741 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
744 case LFUN_FILE_INSERT_ASCII_PARA:
745 // FIXME: We don't know the encoding of filenames
746 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
749 case LFUN_FILE_INSERT_ASCII:
750 // FIXME: We don't know the encoding of filenames
751 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
754 case LFUN_FONT_STATE:
755 cur.message(lyx::from_utf8(cur.currentState()));
758 case LFUN_BOOKMARK_SAVE:
759 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
762 case LFUN_BOOKMARK_GOTO:
763 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
766 case LFUN_LABEL_GOTO: {
767 docstring label = cmd.argument();
770 getInsetByCode<InsetRef>(cursor_,
771 InsetBase::REF_CODE);
773 label = lyx::from_utf8(inset->getContents());
783 case LFUN_PARAGRAPH_GOTO: {
784 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
785 ParIterator par = buffer_->getParFromID(id);
786 if (par == buffer_->par_iterator_end()) {
787 lyxerr[Debug::INFO] << "No matching paragraph found! ["
788 << id << ']' << endl;
791 lyxerr[Debug::INFO] << "Paragraph " << par->id()
792 << " found." << endl;
796 setCursor(makeDocIterator(par, 0));
803 case LFUN_OUTLINE_UP:
804 lyx::toc::outline(lyx::toc::Up, cursor_);
805 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
806 updateLabels(*buffer_);
808 case LFUN_OUTLINE_DOWN:
809 lyx::toc::outline(lyx::toc::Down, cursor_);
810 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
811 updateLabels(*buffer_);
813 case LFUN_OUTLINE_IN:
814 lyx::toc::outline(lyx::toc::In, cursor_);
815 updateLabels(*buffer_);
817 case LFUN_OUTLINE_OUT:
818 lyx::toc::outline(lyx::toc::Out, cursor_);
819 updateLabels(*buffer_);
823 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
826 case LFUN_REFERENCE_NEXT: {
827 vector<InsetBase_code> tmp;
828 tmp.push_back(InsetBase::LABEL_CODE);
829 tmp.push_back(InsetBase::REF_CODE);
830 bv_funcs::gotoInset(this, tmp, true);
834 case LFUN_CHANGES_TRACK:
835 buffer_->params().trackChanges = !buffer_->params().trackChanges;
838 case LFUN_CHANGES_OUTPUT: {
839 buffer_->params().outputChanges = !buffer_->params().outputChanges;
843 case LFUN_CHANGE_NEXT:
844 lyx::find::findNextChange(this);
847 case LFUN_CHANGES_MERGE:
848 if (lyx::find::findNextChange(this))
849 showDialog("changes");
852 case LFUN_ALL_CHANGES_ACCEPT: {
853 cursor_.reset(buffer_->inset());
855 #warning FIXME changes
857 while (lyx::find::findNextChange(this))
858 getLyXText()->acceptChange(cursor_);
863 case LFUN_ALL_CHANGES_REJECT: {
864 cursor_.reset(buffer_->inset());
866 #warning FIXME changes
868 while (lyx::find::findNextChange(this))
869 getLyXText()->rejectChange(cursor_);
874 lyx::find::find(this, cmd);
877 case LFUN_WORD_REPLACE:
878 lyx::find::replace(this, cmd);
882 cur.clearSelection();
884 cur.message(lyx::from_utf8(N_("Mark off")));
888 cur.clearSelection();
891 cur.message(lyx::from_utf8(N_("Mark on")));
894 case LFUN_MARK_TOGGLE:
895 cur.clearSelection();
898 cur.message(lyx::from_utf8(N_("Mark removed")));
901 cur.message(lyx::from_utf8(N_("Mark set")));
906 case LFUN_SCREEN_RECENTER:
910 case LFUN_BIBTEX_DATABASE_ADD: {
911 LCursor tmpcur = cursor_;
912 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
913 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
914 InsetBase::BIBTEX_CODE);
916 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
917 buffer_->updateBibfilesCache();
922 case LFUN_BIBTEX_DATABASE_DEL: {
923 LCursor tmpcur = cursor_;
924 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
925 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
926 InsetBase::BIBTEX_CODE);
928 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
929 buffer_->updateBibfilesCache();
934 case LFUN_WORDS_COUNT: {
935 DocIterator from, to;
936 if (cur.selection()) {
937 from = cur.selectionBegin();
938 to = cur.selectionEnd();
940 from = doc_iterator_begin(buffer_->inset());
941 to = doc_iterator_end(buffer_->inset());
943 int const count = countWords(from, to);
947 message = bformat(_("%1$d words in selection."),
950 message = bformat(_("%1$d words in document."),
955 message = _("One word in selection.");
957 message = _("One word in document.");
960 Alert::information(_("Count words"), message);
964 case LFUN_BUFFER_TOGGLE_COMPRESSION:
965 // turn compression on/off
966 buffer_->params().compressed = !buffer_->params().compressed;
969 case LFUN_NEXT_INSET_TOGGLE: {
970 // this is the real function we want to invoke
971 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
972 // if there is an inset at cursor, see whether it
974 InsetBase * inset = cur.nextInset();
975 if (inset && inset->isActive()) {
976 LCursor tmpcur = cur;
977 tmpcur.pushLeft(*inset);
978 inset->dispatch(tmpcur, tmpcmd);
979 if (tmpcur.result().dispatched()) {
983 // if it did not work, try the underlying inset.
984 if (!cur.result().dispatched())
985 cur.dispatch(tmpcmd);
987 if (cur.result().dispatched())
988 cur.clearSelection();
1001 docstring const BufferView::requestSelection()
1006 LCursor & cur = cursor_;
1008 if (!cur.selection()) {
1009 xsel_cache_.set = false;
1013 if (!xsel_cache_.set ||
1014 cur.top() != xsel_cache_.cursor ||
1015 cur.anchor_.top() != xsel_cache_.anchor)
1017 xsel_cache_.cursor = cur.top();
1018 xsel_cache_.anchor = cur.anchor_.top();
1019 xsel_cache_.set = cur.selection();
1020 return cur.selectionAsString(false);
1026 void BufferView::clearSelection()
1029 cursor_.clearSelection();
1030 xsel_cache_.set = false;
1035 void BufferView::workAreaResize(int width, int height)
1037 bool const widthChange = width != width_;
1038 bool const heightChange = height != height_;
1040 // Update from work area
1044 if (buffer_ && widthChange) {
1045 // The WorkArea content needs a resize
1049 if (widthChange || heightChange)
1054 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1056 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1058 // This is only called for mouse related events including
1059 // LFUN_FILE_OPEN generated by drag-and-drop.
1060 FuncRequest cmd = cmd0;
1066 cur.push(buffer_->inset());
1067 cur.selection() = cursor_.selection();
1069 // Doesn't go through lyxfunc, so we need to update
1070 // the layout choice etc. ourselves
1072 // E.g. Qt mouse press when no buffer
1076 // Either the inset under the cursor or the
1077 // surrounding LyXText will handle this event.
1079 // Build temporary cursor.
1080 cmd.y = min(max(cmd.y, -1), height_);
1081 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1082 //lyxerr << BOOST_CURRENT_FUNCTION
1083 // << " * hit inset at tip: " << inset << endl;
1084 //lyxerr << BOOST_CURRENT_FUNCTION
1085 // << " * created temp cursor:" << cur << endl;
1087 // Put anchor at the same position.
1090 // Try to dispatch to an non-editable inset near this position
1091 // via the temp cursor. If the inset wishes to change the real
1092 // cursor it has to do so explicitly by using
1093 // cur.bv().cursor() = cur; (or similar)
1095 inset->dispatch(cur, cmd);
1097 // Now dispatch to the temporary cursor. If the real cursor should
1098 // be modified, the inset's dispatch has to do so explicitly.
1099 if (!cur.result().dispatched())
1102 if (cur.result().dispatched()) {
1103 // Redraw if requested or necessary.
1104 if (cur.result().update())
1105 update(Update::FitCursor | Update::Force);
1107 update(Update::FitCursor | Update::MultiParSel);
1114 void BufferView::scroll(int lines)
1119 // LyXText const * t = &buffer_->text();
1120 // int const line_height = defaultRowHeight();
1122 // // The new absolute coordinate
1123 // int new_top_y = top_y() + lines * line_height;
1125 // // Restrict to a valid value
1126 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1127 // new_top_y = std::max(0, new_top_y);
1129 // scrollDocView(new_top_y);
1131 // // Update the scrollbar.
1132 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1136 void BufferView::setCursorFromRow(int row)
1141 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1144 buffer_->text().setCursor(cursor_, 0, 0);
1146 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1150 void BufferView::gotoLabel(docstring const & label)
1152 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1153 vector<docstring> labels;
1154 it->getLabelList(*buffer_, labels);
1155 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1164 LyXText * BufferView::getLyXText()
1166 LyXText * text = cursor_.innerText();
1172 LyXText const * BufferView::getLyXText() const
1174 LyXText const * text = cursor_.innerText();
1180 int BufferView::workHeight() const
1186 void BufferView::setCursor(DocIterator const & dit)
1188 size_t const n = dit.depth();
1189 for (size_t i = 0; i < n; ++i)
1190 dit[i].inset().edit(cursor_, true);
1192 cursor_.setCursor(dit);
1193 cursor_.selection() = false;
1197 void BufferView::mouseSetCursor(LCursor & cur)
1199 BOOST_ASSERT(&cur.bv() == this);
1201 // Has the cursor just left the inset?
1202 bool badcursor = false;
1203 if (&cursor_.inset() != &cur.inset())
1204 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1206 // do the dEPM magic if needed
1207 // FIXME: move this to InsetText::notifyCursorLeaves?
1208 if (!badcursor && cursor_.inTexted())
1209 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1212 cursor_.clearSelection();
1213 cursor_.setTargetX();
1219 void BufferView::putSelectionAt(DocIterator const & cur,
1220 int length, bool backwards)
1222 cursor_.clearSelection();
1228 cursor_.pos() += length;
1229 cursor_.setSelection(cursor_, -length);
1231 cursor_.setSelection(cursor_, length);
1236 LCursor & BufferView::cursor()
1242 LCursor const & BufferView::cursor() const
1248 lyx::pit_type BufferView::anchor_ref() const
1254 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1256 return metrics_info_;
1260 void BufferView::updateMetrics(bool singlepar)
1262 // Remove old position cache
1263 coord_cache_.clear();
1264 LyXText & buftext = buffer_->text();
1265 lyx::pit_type size = int(buftext.paragraphs().size());
1267 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1268 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1272 lyx::pit_type const pit = anchor_ref_;
1275 size_t const npit = buftext.paragraphs().size();
1277 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1278 // the (main text, not inset!) paragraph containing the cursor.
1279 // (if this paragraph contains insets etc., rebreaking will
1280 // recursively descend)
1281 if (!singlepar || pit == cursor_.bottom().pit())
1282 buftext.redoParagraph(pit);
1283 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1285 // Redo paragraphs above anchor if necessary; again, in Single Par
1286 // mode, only if we encounter the (main text) one having the cursor.
1288 while (y1 > 0 && pit1 > 0) {
1289 y1 -= buftext.getPar(pit1).ascent();
1291 if (!singlepar || pit1 == cursor_.bottom().pit())
1292 buftext.redoParagraph(pit1);
1293 y1 -= buftext.getPar(pit1).descent();
1297 // Take care of ascent of first line
1298 y1 -= buftext.getPar(pit1).ascent();
1300 // Normalize anchor for next time
1304 // Grey at the beginning is ugly
1305 if (pit1 == 0 && y1 > 0) {
1311 // Redo paragraphs below the anchor if necessary. Single par mode:
1312 // only the one containing the cursor if encountered.
1314 while (y2 < height_ && pit2 < int(npit) - 1) {
1315 y2 += buftext.getPar(pit2).descent();
1317 if (!singlepar || pit2 == cursor_.bottom().pit())
1318 buftext.redoParagraph(pit2);
1319 y2 += buftext.getPar(pit2).ascent();
1322 // Take care of descent of last line
1323 y2 += buftext.getPar(pit2).descent();
1325 // The coordinates of all these paragraphs are correct, cache them
1327 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1328 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1329 Paragraph const & par = buftext.getPar(pit);
1331 parPos[pit] = Point(0, y);
1332 if (singlepar && pit == cursor_.bottom().pit()) {
1333 // In Single Paragraph mode, collect here the
1334 // y1 and y2 of the (one) paragraph the cursor is in
1335 y1 = y - par.ascent();
1336 y2 = y + par.descent();
1342 // collect cursor paragraph iter bounds
1343 pit1 = cursor_.bottom().pit();
1344 pit2 = cursor_.bottom().pit();
1347 lyxerr[Debug::DEBUG]
1348 << BOOST_CURRENT_FUNCTION
1351 << " pit1: " << pit1
1352 << " pit2: " << pit2
1353 << " npit: " << npit
1354 << " singlepar: " << singlepar
1358 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1362 void BufferView::menuInsertLyXFile(string const & filenm)
1364 BOOST_ASSERT(cursor_.inTexted());
1365 string filename = filenm;
1367 if (filename.empty()) {
1368 // Launch a file browser
1370 string initpath = lyxrc.document_path;
1373 string const trypath = buffer_->filePath();
1374 // If directory is writeable, use this as default.
1375 if (isDirWriteable(trypath))
1380 FileDialog fileDlg(_("Select LyX document to insert"),
1382 make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
1383 make_pair(_("Examples|#E#e"), lyx::from_utf8(addPath(package().system_support(), "examples"))));
1385 FileDialog::Result result =
1386 fileDlg.open(lyx::from_utf8(initpath),
1387 FileFilterList(_("LyX Documents (*.lyx)")),
1390 if (result.first == FileDialog::Later)
1394 filename = lyx::to_utf8(result.second);
1396 // check selected filename
1397 if (filename.empty()) {
1398 // emit message signal.
1399 message(_("Canceled."));
1404 // Get absolute path of file and add ".lyx"
1405 // to the filename if necessary
1406 filename = fileSearch(string(), filename, "lyx");
1408 docstring const disp_fn = makeDisplayPath(filename);
1409 // emit message signal.
1410 message(bformat(_("Inserting document %1$s..."), disp_fn));
1413 Buffer buf("", false);
1414 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1415 ErrorList & el = buffer_->errorList("Parse");
1416 // Copy the inserted document error list into the current buffer one.
1417 el = buf.errorList("Parse");
1418 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1419 buf.params().textclass, el);
1420 res = _("Document %1$s inserted.");
1422 res = _("Could not insert document %1$s");
1424 // emit message signal.
1425 message(bformat(res, disp_fn));
1426 buffer_->errors("Parse");