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;
109 unsigned int const saved_positions_num = 20;
112 /// Return an inset of this class if it exists at the current cursor position
114 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
117 DocIterator it = cur;
118 if (it.nextInset() &&
119 it.nextInset()->lyxCode() == code) {
120 inset = static_cast<T*>(it.nextInset());
128 BufferView::BufferView()
129 : buffer_(0), wh_(0),
131 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
134 xsel_cache_.set = false;
136 saved_positions.resize(saved_positions_num);
137 // load saved bookmarks
138 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
139 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
140 bm != bmList.end(); ++bm)
141 if (bm->get<0>() < saved_positions_num)
142 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
143 // and then clear them
146 intl_->initKeyMapper(lyxrc.use_kbmap);
150 BufferView::~BufferView()
155 Buffer * BufferView::buffer() const
161 void BufferView::setBuffer(Buffer * b)
163 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
164 << "[ b = " << b << "]" << endl;
167 // Save the actual cursor position and anchor inside the
168 // buffer so that it can be restored in case we rechange
169 // to this buffer later on.
170 buffer_->saveCursor(cursor_.selectionBegin(),
171 cursor_.selectionEnd());
172 // current buffer is going to be switched-off, save cursor pos
173 LyX::ref().session().saveFilePosition(buffer_->fileName(),
174 boost::tie(cursor_.pit(), cursor_.pos()) );
177 // If we're quitting lyx, don't bother updating stuff
183 // If we are closing current buffer, switch to the first in
186 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
187 << " No Buffer!" << endl;
188 // We are closing the buffer, use the first buffer as current
189 buffer_ = theBufferList().first();
191 // Set current buffer
196 cursor_ = LCursor(*this);
201 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
202 << "Buffer addr: " << buffer_ << endl;
203 cursor_.push(buffer_->inset());
204 cursor_.resetAnchor();
205 buffer_->text().init(this);
206 buffer_->text().setCurrentFont(cursor_);
207 if (buffer_->getCursor().size() > 0 &&
208 buffer_->getAnchor().size() > 0)
210 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
211 cursor_.resetAnchor();
212 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
213 cursor_.setSelection();
219 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
220 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
224 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
226 // Get absolute path of file and add ".lyx"
227 // to the filename if necessary
228 string s = fileSearch(string(), filename, "lyx");
230 bool const found = !s.empty();
235 // File already open?
236 if (theBufferList().exists(s)) {
237 docstring const file = makeDisplayPath(s, 20);
238 docstring text = bformat(_("The document %1$s is already "
239 "loaded.\n\nDo you want to revert "
240 "to the saved version?"), file);
241 int const ret = Alert::prompt(_("Revert to saved document?"),
242 text, 0, 1, _("&Revert"), _("&Switch to document"));
245 setBuffer(theBufferList().getBuffer(s));
248 // FIXME: should be LFUN_REVERT
249 if (!theBufferList().close(theBufferList().getBuffer(s), false))
251 // Fall through to new load. (Asger)
257 b = theBufferList().newBuffer(s);
258 if (!::loadLyXFile(b, s)) {
259 theBufferList().release(b);
263 docstring text = bformat(_("The document %1$s does not yet "
264 "exist.\n\nDo you want to create "
265 "a new document?"), lyx::from_utf8(s));
266 int const ret = Alert::prompt(_("Create new document?"),
267 text, 0, 1, _("&Create"), _("Cancel"));
270 b = newFile(s, string(), true);
278 // Send the "errors" signal in case of parsing errors
281 // scroll to the position when the file was last closed
282 if (lyxrc.use_lastfilepos) {
285 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
286 // I am not sure how to separate the following part to a function
287 // so I will leave this to Lars.
289 // check pit since the document may be externally changed.
290 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
291 ParIterator it = b->par_iterator_begin();
292 ParIterator const end = b->par_iterator_end();
293 for (; it != end; ++it)
294 if (it.pit() == pit) {
295 // restored pos may be bigger than it->size
296 setCursor(makeDocIterator(it, min(pos, it->size())));
297 update(Update::FitCursor);
304 LyX::ref().session().addLastFile(b->fileName());
310 void BufferView::reload()
312 string const fn = buffer_->fileName();
313 if (theBufferList().close(buffer_, false))
318 void BufferView::resize()
323 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
325 buffer_->text().init(this);
331 bool BufferView::fitCursor()
333 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
334 lyx::frontend::FontMetrics const & fm =
335 theFontMetrics(cursor_.getFont());
336 int const asc = fm.maxAscent();
337 int const des = fm.maxDescent();
338 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
339 if (p.y_ - asc >= 0 && p.y_ + des < height_)
347 bool BufferView::multiParSel()
349 if (!cursor_.selection())
351 bool ret = multiparsel_cache_;
352 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
353 // Either this, or previous selection spans paragraphs
354 return ret || multiparsel_cache_;
358 bool BufferView::update(Update::flags flags)
360 // This is close to a hot-path.
361 if (lyxerr.debugging(Debug::DEBUG)) {
363 << BOOST_CURRENT_FUNCTION
364 << "[fitcursor = " << (flags & Update::FitCursor)
365 << ", forceupdate = " << (flags & Update::Force)
366 << ", singlepar = " << (flags & Update::SinglePar)
367 << "] buffer: " << buffer_ << endl;
370 // Check needed to survive LyX startup
374 // Update macro store
375 buffer_->buildMacros();
377 // First drawing step
378 updateMetrics(flags & Update::SinglePar);
380 // The second drawing step is done in WorkArea::redraw() if needed.
381 bool const need_second_step =
382 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
383 && (fitCursor() || multiParSel());
385 return need_second_step;
389 void BufferView::updateScrollbar()
392 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
393 << " no text in updateScrollbar" << endl;
394 scrollbarParameters_.reset();
398 LyXText & t = buffer_->text();
399 int const parsize = int(t.paragraphs().size() - 1);
400 if (anchor_ref_ > parsize) {
401 anchor_ref_ = parsize;
406 << BOOST_CURRENT_FUNCTION
407 << " Updating scrollbar: height: " << t.paragraphs().size()
408 << " curr par: " << cursor_.bottom().pit()
409 << " default height " << defaultRowHeight() << endl;
411 // It would be better to fix the scrollbar to understand
412 // values in [0..1] and divide everything by wh
414 // estimated average paragraph height:
417 int h = t.getPar(anchor_ref_).height();
419 // Normalize anchor/offset (MV):
420 while (offset_ref_ > h && anchor_ref_ < parsize) {
423 h = t.getPar(anchor_ref_).height();
425 // Look at paragraph heights on-screen
428 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
431 int const h2 = t.getPar(pit).height();
435 int const hav = sumh / nh;
436 // More realistic average paragraph height
440 scrollbarParameters_.height = (parsize + 1) * wh_;
441 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
442 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
446 ScrollbarParameters const & BufferView::scrollbarParameters() const
448 return scrollbarParameters_;
452 void BufferView::scrollDocView(int value)
454 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
455 << "[ value = " << value << "]" << endl;
460 LyXText & t = buffer_->text();
462 float const bar = value / float(wh_ * t.paragraphs().size());
464 anchor_ref_ = int(bar * t.paragraphs().size());
465 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
466 anchor_ref_ = int(t.paragraphs().size()) - 1;
467 t.redoParagraph(anchor_ref_);
468 int const h = t.getPar(anchor_ref_).height();
469 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
473 void BufferView::setCursorFromScrollbar()
475 LyXText & t = buffer_->text();
477 int const height = 2 * defaultRowHeight();
478 int const first = height;
479 int const last = height_ - height;
480 LCursor & cur = cursor_;
482 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
485 case bv_funcs::CUR_ABOVE:
486 t.setCursorFromCoordinates(cur, 0, first);
487 cur.clearSelection();
489 case bv_funcs::CUR_BELOW:
490 t.setCursorFromCoordinates(cur, 0, last);
491 cur.clearSelection();
493 case bv_funcs::CUR_INSIDE:
494 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
495 int const newy = min(last, max(y, first));
497 cur.reset(buffer_->inset());
498 t.setCursorFromCoordinates(cur, 0, newy);
504 Change const BufferView::getCurrentChange() const
506 if (!cursor_.selection())
507 return Change(Change::UNCHANGED);
509 DocIterator dit = cursor_.selectionBegin();
510 return dit.paragraph().lookupChange(dit.pos());
514 void BufferView::savePosition(unsigned int i)
516 if (i >= saved_positions_num)
518 BOOST_ASSERT(cursor_.inTexted());
519 saved_positions[i] = Position(buffer_->fileName(),
520 cursor_.paragraph().id(),
523 // emit message signal.
524 message(bformat(_("Saved bookmark %1$d"), i));
528 void BufferView::restorePosition(unsigned int i)
530 if (i >= saved_positions_num)
533 string const fname = saved_positions[i].filename;
535 cursor_.clearSelection();
537 if (fname != buffer_->fileName()) {
539 if (theBufferList().exists(fname))
540 b = theBufferList().getBuffer(fname);
542 b = theBufferList().newBuffer(fname);
543 // Don't ask, just load it
544 ::loadLyXFile(b, fname);
550 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
551 if (par == buffer_->par_iterator_end())
554 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
557 // emit message signal.
558 message(bformat(_("Moved to bookmark %1$d"), i));
562 bool BufferView::isSavedPosition(unsigned int i)
564 return i < saved_positions_num && !saved_positions[i].filename.empty();
567 void BufferView::saveSavedPositions()
569 // save bookmarks. It is better to use the pit interface
570 // but I do not know how to effectively convert between
572 for (unsigned int i=1; i < saved_positions_num; ++i) {
573 if ( isSavedPosition(i) )
574 LyX::ref().session().saveBookmark( boost::tie(
576 saved_positions[i].filename,
577 saved_positions[i].par_id,
578 saved_positions[i].par_pos) );
582 void BufferView::switchKeyMap()
584 if (!lyxrc.rtl_support)
587 if (getLyXText()->real_current_font.isRightToLeft()) {
588 if (intl_->keymap == Intl::PRIMARY)
591 if (intl_->keymap == Intl::SECONDARY)
597 int BufferView::workWidth() const
603 void BufferView::center()
605 CursorSlice & bot = cursor_.bottom();
606 lyx::pit_type const pit = bot.pit();
607 bot.text()->redoParagraph(pit);
608 Paragraph const & par = bot.text()->paragraphs()[pit];
610 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
611 + par.ascent() - height_ / 2;
615 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
619 switch (cmd.action) {
622 flag.enabled(!buffer_->undostack().empty());
625 flag.enabled(!buffer_->redostack().empty());
627 case LFUN_FILE_INSERT:
628 case LFUN_FILE_INSERT_ASCII_PARA:
629 case LFUN_FILE_INSERT_ASCII:
630 case LFUN_BOOKMARK_SAVE:
631 // FIXME: Actually, these LFUNS should be moved to LyXText
632 flag.enabled(cursor_.inTexted());
634 case LFUN_FONT_STATE:
635 case LFUN_LABEL_INSERT:
636 case LFUN_PARAGRAPH_GOTO:
637 // FIXME handle non-trivially
638 case LFUN_OUTLINE_UP:
639 case LFUN_OUTLINE_DOWN:
640 case LFUN_OUTLINE_IN:
641 case LFUN_OUTLINE_OUT:
643 case LFUN_REFERENCE_NEXT:
645 case LFUN_WORD_REPLACE:
648 case LFUN_MARK_TOGGLE:
649 case LFUN_SCREEN_RECENTER:
650 case LFUN_BIBTEX_DATABASE_ADD:
651 case LFUN_BIBTEX_DATABASE_DEL:
652 case LFUN_WORDS_COUNT:
653 case LFUN_NEXT_INSET_TOGGLE:
657 case LFUN_LABEL_GOTO: {
658 flag.enabled(!cmd.argument().empty()
659 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
663 case LFUN_BOOKMARK_GOTO:
664 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
667 case LFUN_CHANGES_TRACK:
669 flag.setOnOff(buffer_->params().trackChanges);
672 case LFUN_CHANGES_OUTPUT: {
673 OutputParams runparams;
674 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
675 flag.enabled(buffer_ && features.isAvailable("dvipost"));
676 flag.setOnOff(buffer_->params().outputChanges);
680 case LFUN_CHANGES_MERGE:
681 case LFUN_CHANGE_NEXT:
682 case LFUN_ALL_CHANGES_ACCEPT:
683 case LFUN_ALL_CHANGES_REJECT:
684 flag.enabled(buffer_); // FIXME: Change tracking (MG)
687 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
688 flag.setOnOff(buffer_->params().compressed);
700 bool BufferView::dispatch(FuncRequest const & cmd)
702 //lyxerr << BOOST_CURRENT_FUNCTION
703 // << [ cmd = " << cmd << "]" << endl;
705 // Make sure that the cached BufferView is correct.
706 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
707 << " action[" << cmd.action << ']'
708 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
709 << " x[" << cmd.x << ']'
710 << " y[" << cmd.y << ']'
711 << " button[" << cmd.button() << ']'
714 LCursor & cur = cursor_;
716 switch (cmd.action) {
720 cur.message(_("Undo"));
721 cur.clearSelection();
722 if (!textUndo(*this))
723 cur.message(_("No further undo information"));
731 cur.message(_("Redo"));
732 cur.clearSelection();
733 if (!textRedo(*this))
734 cur.message(_("No further redo information"));
740 case LFUN_FILE_INSERT:
741 // FIXME: We don't know the encoding of filenames
742 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
745 case LFUN_FILE_INSERT_ASCII_PARA:
746 // FIXME: We don't know the encoding of filenames
747 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
750 case LFUN_FILE_INSERT_ASCII:
751 // FIXME: We don't know the encoding of filenames
752 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
755 case LFUN_FONT_STATE:
756 cur.message(lyx::from_utf8(cur.currentState()));
759 case LFUN_BOOKMARK_SAVE:
760 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
763 case LFUN_BOOKMARK_GOTO:
764 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
767 case LFUN_LABEL_GOTO: {
768 docstring label = cmd.argument();
771 getInsetByCode<InsetRef>(cursor_,
772 InsetBase::REF_CODE);
774 label = lyx::from_utf8(inset->getContents());
784 case LFUN_PARAGRAPH_GOTO: {
785 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
786 ParIterator par = buffer_->getParFromID(id);
787 if (par == buffer_->par_iterator_end()) {
788 lyxerr[Debug::INFO] << "No matching paragraph found! ["
789 << id << ']' << endl;
792 lyxerr[Debug::INFO] << "Paragraph " << par->id()
793 << " found." << endl;
797 setCursor(makeDocIterator(par, 0));
804 case LFUN_OUTLINE_UP:
805 lyx::toc::outline(lyx::toc::Up, cursor_);
806 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
807 updateLabels(*buffer_);
809 case LFUN_OUTLINE_DOWN:
810 lyx::toc::outline(lyx::toc::Down, cursor_);
811 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
812 updateLabels(*buffer_);
814 case LFUN_OUTLINE_IN:
815 lyx::toc::outline(lyx::toc::In, cursor_);
816 updateLabels(*buffer_);
818 case LFUN_OUTLINE_OUT:
819 lyx::toc::outline(lyx::toc::Out, cursor_);
820 updateLabels(*buffer_);
824 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
827 case LFUN_REFERENCE_NEXT: {
828 vector<InsetBase_code> tmp;
829 tmp.push_back(InsetBase::LABEL_CODE);
830 tmp.push_back(InsetBase::REF_CODE);
831 bv_funcs::gotoInset(this, tmp, true);
835 case LFUN_CHANGES_TRACK:
836 buffer_->params().trackChanges = !buffer_->params().trackChanges;
839 case LFUN_CHANGES_OUTPUT: {
840 buffer_->params().outputChanges = !buffer_->params().outputChanges;
844 case LFUN_CHANGE_NEXT:
845 lyx::find::findNextChange(this);
848 case LFUN_CHANGES_MERGE:
849 if (lyx::find::findNextChange(this))
850 showDialog("changes");
853 case LFUN_ALL_CHANGES_ACCEPT: {
854 cursor_.reset(buffer_->inset());
856 #warning FIXME changes
858 while (lyx::find::findNextChange(this))
859 getLyXText()->acceptChange(cursor_);
864 case LFUN_ALL_CHANGES_REJECT: {
865 cursor_.reset(buffer_->inset());
867 #warning FIXME changes
869 while (lyx::find::findNextChange(this))
870 getLyXText()->rejectChange(cursor_);
875 lyx::find::find(this, cmd);
878 case LFUN_WORD_REPLACE:
879 lyx::find::replace(this, cmd);
883 cur.clearSelection();
885 cur.message(lyx::from_utf8(N_("Mark off")));
889 cur.clearSelection();
892 cur.message(lyx::from_utf8(N_("Mark on")));
895 case LFUN_MARK_TOGGLE:
896 cur.clearSelection();
899 cur.message(lyx::from_utf8(N_("Mark removed")));
902 cur.message(lyx::from_utf8(N_("Mark set")));
907 case LFUN_SCREEN_RECENTER:
911 case LFUN_BIBTEX_DATABASE_ADD: {
912 LCursor tmpcur = cursor_;
913 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
914 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
915 InsetBase::BIBTEX_CODE);
917 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
918 buffer_->updateBibfilesCache();
923 case LFUN_BIBTEX_DATABASE_DEL: {
924 LCursor tmpcur = cursor_;
925 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
926 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
927 InsetBase::BIBTEX_CODE);
929 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
930 buffer_->updateBibfilesCache();
935 case LFUN_WORDS_COUNT: {
936 DocIterator from, to;
937 if (cur.selection()) {
938 from = cur.selectionBegin();
939 to = cur.selectionEnd();
941 from = doc_iterator_begin(buffer_->inset());
942 to = doc_iterator_end(buffer_->inset());
944 int const count = countWords(from, to);
948 message = bformat(_("%1$d words in selection."),
951 message = bformat(_("%1$d words in document."),
956 message = _("One word in selection.");
958 message = _("One word in document.");
961 Alert::information(_("Count words"), message);
965 case LFUN_BUFFER_TOGGLE_COMPRESSION:
966 // turn compression on/off
967 buffer_->params().compressed = !buffer_->params().compressed;
970 case LFUN_NEXT_INSET_TOGGLE: {
971 // this is the real function we want to invoke
972 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
973 // if there is an inset at cursor, see whether it
975 InsetBase * inset = cur.nextInset();
976 if (inset && inset->isActive()) {
977 LCursor tmpcur = cur;
978 tmpcur.pushLeft(*inset);
979 inset->dispatch(tmpcur, tmpcmd);
980 if (tmpcur.result().dispatched()) {
984 // if it did not work, try the underlying inset.
985 if (!cur.result().dispatched())
986 cur.dispatch(tmpcmd);
988 if (cur.result().dispatched())
989 cur.clearSelection();
1002 docstring const BufferView::requestSelection()
1007 LCursor & cur = cursor_;
1009 if (!cur.selection()) {
1010 xsel_cache_.set = false;
1014 if (!xsel_cache_.set ||
1015 cur.top() != xsel_cache_.cursor ||
1016 cur.anchor_.top() != xsel_cache_.anchor)
1018 xsel_cache_.cursor = cur.top();
1019 xsel_cache_.anchor = cur.anchor_.top();
1020 xsel_cache_.set = cur.selection();
1021 return cur.selectionAsString(false);
1027 void BufferView::clearSelection()
1030 cursor_.clearSelection();
1031 xsel_cache_.set = false;
1036 void BufferView::workAreaResize(int width, int height)
1038 bool const widthChange = width != width_;
1039 bool const heightChange = height != height_;
1041 // Update from work area
1045 if (buffer_ && widthChange) {
1046 // The WorkArea content needs a resize
1050 if (widthChange || heightChange)
1055 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1057 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1059 // This is only called for mouse related events including
1060 // LFUN_FILE_OPEN generated by drag-and-drop.
1061 FuncRequest cmd = cmd0;
1067 cur.push(buffer_->inset());
1068 cur.selection() = cursor_.selection();
1070 // Doesn't go through lyxfunc, so we need to update
1071 // the layout choice etc. ourselves
1073 // E.g. Qt mouse press when no buffer
1077 // Either the inset under the cursor or the
1078 // surrounding LyXText will handle this event.
1080 // Build temporary cursor.
1081 cmd.y = min(max(cmd.y, -1), height_);
1082 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1083 //lyxerr << BOOST_CURRENT_FUNCTION
1084 // << " * hit inset at tip: " << inset << endl;
1085 //lyxerr << BOOST_CURRENT_FUNCTION
1086 // << " * created temp cursor:" << cur << endl;
1088 // Put anchor at the same position.
1091 // Try to dispatch to an non-editable inset near this position
1092 // via the temp cursor. If the inset wishes to change the real
1093 // cursor it has to do so explicitly by using
1094 // cur.bv().cursor() = cur; (or similar)
1096 inset->dispatch(cur, cmd);
1098 // Now dispatch to the temporary cursor. If the real cursor should
1099 // be modified, the inset's dispatch has to do so explicitly.
1100 if (!cur.result().dispatched())
1103 if (cur.result().dispatched()) {
1104 // Redraw if requested or necessary.
1105 if (cur.result().update())
1106 update(Update::FitCursor | Update::Force);
1108 update(Update::FitCursor | Update::MultiParSel);
1115 void BufferView::scroll(int lines)
1120 // LyXText const * t = &buffer_->text();
1121 // int const line_height = defaultRowHeight();
1123 // // The new absolute coordinate
1124 // int new_top_y = top_y() + lines * line_height;
1126 // // Restrict to a valid value
1127 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1128 // new_top_y = std::max(0, new_top_y);
1130 // scrollDocView(new_top_y);
1132 // // Update the scrollbar.
1133 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1137 void BufferView::setCursorFromRow(int row)
1142 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1145 buffer_->text().setCursor(cursor_, 0, 0);
1147 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1151 void BufferView::gotoLabel(docstring const & label)
1153 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1154 vector<docstring> labels;
1155 it->getLabelList(*buffer_, labels);
1156 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1165 LyXText * BufferView::getLyXText()
1167 LyXText * text = cursor_.innerText();
1173 LyXText const * BufferView::getLyXText() const
1175 LyXText const * text = cursor_.innerText();
1181 int BufferView::workHeight() const
1187 void BufferView::setCursor(DocIterator const & dit)
1189 size_t const n = dit.depth();
1190 for (size_t i = 0; i < n; ++i)
1191 dit[i].inset().edit(cursor_, true);
1193 cursor_.setCursor(dit);
1194 cursor_.selection() = false;
1198 void BufferView::mouseSetCursor(LCursor & cur)
1200 BOOST_ASSERT(&cur.bv() == this);
1202 // Has the cursor just left the inset?
1203 bool badcursor = false;
1204 if (&cursor_.inset() != &cur.inset())
1205 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1207 // do the dEPM magic if needed
1208 // FIXME: move this to InsetText::notifyCursorLeaves?
1209 if (!badcursor && cursor_.inTexted())
1210 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1213 cursor_.clearSelection();
1214 cursor_.setTargetX();
1220 void BufferView::putSelectionAt(DocIterator const & cur,
1221 int length, bool backwards)
1223 cursor_.clearSelection();
1229 cursor_.pos() += length;
1230 cursor_.setSelection(cursor_, -length);
1232 cursor_.setSelection(cursor_, length);
1237 LCursor & BufferView::cursor()
1243 LCursor const & BufferView::cursor() const
1249 lyx::pit_type BufferView::anchor_ref() const
1255 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1257 return metrics_info_;
1261 void BufferView::updateMetrics(bool singlepar)
1263 // Remove old position cache
1265 LyXText & buftext = buffer_->text();
1266 lyx::pit_type size = int(buftext.paragraphs().size());
1268 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1269 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1273 lyx::pit_type const pit = anchor_ref_;
1276 size_t const npit = buftext.paragraphs().size();
1278 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1279 // the (main text, not inset!) paragraph containing the cursor.
1280 // (if this paragraph contains insets etc., rebreaking will
1281 // recursively descend)
1282 if (!singlepar || pit == cursor_.bottom().pit())
1283 buftext.redoParagraph(pit);
1284 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1286 // Redo paragraphs above anchor if necessary; again, in Single Par
1287 // mode, only if we encounter the (main text) one having the cursor.
1289 while (y1 > 0 && pit1 > 0) {
1290 y1 -= buftext.getPar(pit1).ascent();
1292 if (!singlepar || pit1 == cursor_.bottom().pit())
1293 buftext.redoParagraph(pit1);
1294 y1 -= buftext.getPar(pit1).descent();
1298 // Take care of ascent of first line
1299 y1 -= buftext.getPar(pit1).ascent();
1301 // Normalize anchor for next time
1305 // Grey at the beginning is ugly
1306 if (pit1 == 0 && y1 > 0) {
1312 // Redo paragraphs below the anchor if necessary. Single par mode:
1313 // only the one containing the cursor if encountered.
1315 while (y2 < height_ && pit2 < int(npit) - 1) {
1316 y2 += buftext.getPar(pit2).descent();
1318 if (!singlepar || pit2 == cursor_.bottom().pit())
1319 buftext.redoParagraph(pit2);
1320 y2 += buftext.getPar(pit2).ascent();
1323 // Take care of descent of last line
1324 y2 += buftext.getPar(pit2).descent();
1326 // The coordinates of all these paragraphs are correct, cache them
1328 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1329 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1330 Paragraph const & par = buftext.getPar(pit);
1332 parPos[pit] = Point(0, y);
1333 if (singlepar && pit == cursor_.bottom().pit()) {
1334 // In Single Paragraph mode, collect here the
1335 // y1 and y2 of the (one) paragraph the cursor is in
1336 y1 = y - par.ascent();
1337 y2 = y + par.descent();
1343 // collect cursor paragraph iter bounds
1344 pit1 = cursor_.bottom().pit();
1345 pit2 = cursor_.bottom().pit();
1348 lyxerr[Debug::DEBUG]
1349 << BOOST_CURRENT_FUNCTION
1352 << " pit1: " << pit1
1353 << " pit2: " << pit2
1354 << " npit: " << npit
1355 << " singlepar: " << singlepar
1359 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1363 void BufferView::menuInsertLyXFile(string const & filenm)
1365 BOOST_ASSERT(cursor_.inTexted());
1366 string filename = filenm;
1368 if (filename.empty()) {
1369 // Launch a file browser
1371 string initpath = lyxrc.document_path;
1374 string const trypath = buffer_->filePath();
1375 // If directory is writeable, use this as default.
1376 if (isDirWriteable(trypath))
1381 FileDialog fileDlg(_("Select LyX document to insert"),
1383 make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
1384 make_pair(_("Examples|#E#e"), lyx::from_utf8(addPath(package().system_support(), "examples"))));
1386 FileDialog::Result result =
1387 fileDlg.open(lyx::from_utf8(initpath),
1388 FileFilterList(_("LyX Documents (*.lyx)")),
1391 if (result.first == FileDialog::Later)
1395 filename = lyx::to_utf8(result.second);
1397 // check selected filename
1398 if (filename.empty()) {
1399 // emit message signal.
1400 message(_("Canceled."));
1405 // Get absolute path of file and add ".lyx"
1406 // to the filename if necessary
1407 filename = fileSearch(string(), filename, "lyx");
1409 docstring const disp_fn = makeDisplayPath(filename);
1410 // emit message signal.
1411 message(bformat(_("Inserting document %1$s..."), disp_fn));
1414 Buffer buf("", false);
1415 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1416 ErrorList & el = buffer_->errorList("Parse");
1417 // Copy the inserted document error list into the current buffer one.
1418 el = buf.errorList("Parse");
1419 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1420 buf.params().textclass, el);
1421 res = _("Document %1$s inserted.");
1423 res = _("Could not insert document %1$s");
1425 // emit message signal.
1426 message(bformat(res, disp_fn));
1427 buffer_->errors("Parse");