2 * \file BufferView_pimpl.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Alfredo Braunstein
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
15 * \author Abdelrazak Younes
17 * Full author contact details are available in file CREDITS.
22 #include "BufferView_pimpl.h"
24 #include "buffer_funcs.h"
25 #include "bufferlist.h"
26 #include "bufferparams.h"
27 #include "coordcache.h"
29 #include "CutAndPaste.h"
31 #include "dispatchresult.h"
32 #include "errorlist.h"
34 #include "FloatList.h"
35 #include "funcrequest.h"
36 #include "FuncStatus.h"
39 #include "insetiterator.h"
40 #include "LaTeXFeatures.h"
41 #include "lyx_cb.h" // added for Dispatch functions
48 #include "metricsinfo.h"
49 #include "paragraph.h"
50 #include "paragraph_funcs.h"
51 #include "ParagraphParameters.h"
52 #include "pariterator.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetref.h"
59 #include "insets/insettext.h"
61 #include "frontends/Alert.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Selection.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/filefilterlist.h"
73 #include "support/filetools.h"
74 #include "support/package.h"
75 #include "support/types.h"
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
83 using lyx::frontend::Clipboard;
84 using lyx::frontend::Gui;
88 using lyx::support::addPath;
89 using lyx::support::bformat;
90 using lyx::support::FileFilterList;
91 using lyx::support::fileSearch;
92 using lyx::support::isDirWriteable;
93 using lyx::support::makeDisplayPath;
94 using lyx::support::makeAbsPath;
95 using lyx::support::package;
98 using std::istringstream;
103 using std::mem_fun_ref;
106 extern BufferList bufferlist;
111 unsigned int const saved_positions_num = 20;
114 /// Return an inset of this class if it exists at the current cursor position
116 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
119 DocIterator it = cur;
120 if (it.nextInset() &&
121 it.nextInset()->lyxCode() == code) {
122 inset = static_cast<T*>(it.nextInset());
130 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
131 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
133 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
135 xsel_cache_.set = false;
137 saved_positions.resize(saved_positions_num);
138 // load saved bookmarks
139 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
140 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
141 bm != bmList.end(); ++bm)
142 if (bm->get<0>() < saved_positions_num)
143 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
144 // and then clear them
149 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
151 // Get absolute path of file and add ".lyx"
152 // to the filename if necessary
153 string s = fileSearch(string(), filename, "lyx");
155 bool const found = !s.empty();
160 // File already open?
161 if (bufferlist.exists(s)) {
162 string const file = makeDisplayPath(s, 20);
163 string text = bformat(_("The document %1$s is already "
164 "loaded.\n\nDo you want to revert "
165 "to the saved version?"), file);
166 int const ret = Alert::prompt(_("Revert to saved document?"),
167 text, 0, 1, _("&Revert"), _("&Switch to document"));
170 setBuffer(bufferlist.getBuffer(s));
173 // FIXME: should be LFUN_REVERT
174 if (!bufferlist.close(bufferlist.getBuffer(s), false))
176 // Fall through to new load. (Asger)
182 b = bufferlist.newBuffer(s);
183 if (!::loadLyXFile(b, s)) {
184 bufferlist.release(b);
188 string text = bformat(_("The document %1$s does not yet "
189 "exist.\n\nDo you want to create "
190 "a new document?"), s);
191 int const ret = Alert::prompt(_("Create new document?"),
192 text, 0, 1, _("&Create"), _("Cancel"));
195 b = newFile(s, string(), true);
203 // Send the "errors" signal in case of parsing errors
206 // scroll to the position when the file was last closed
207 if (lyxrc.use_lastfilepos) {
210 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
211 // I am not sure how to separate the following part to a function
212 // so I will leave this to Lars.
214 // check pit since the document may be externally changed.
215 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
216 ParIterator it = b->par_iterator_begin();
217 ParIterator const end = b->par_iterator_end();
218 for (; it != end; ++it)
219 if (it.pit() == pit) {
220 // restored pos may be bigger than it->size
221 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
222 bv_->update(Update::FitCursor);
229 LyX::ref().session().addLastFile(b->fileName());
235 int BufferView::Pimpl::width() const
241 int BufferView::Pimpl::height() const
247 void BufferView::Pimpl::setBuffer(Buffer * b)
249 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
250 << "[ b = " << b << "]" << endl;
253 // Save the actual cursor position and anchor inside the
254 // buffer so that it can be restored in case we rechange
255 // to this buffer later on.
256 buffer_->saveCursor(cursor_.selectionBegin(),
257 cursor_.selectionEnd());
258 // current buffer is going to be switched-off, save cursor pos
259 LyX::ref().session().saveFilePosition(buffer_->fileName(),
260 boost::tie(cursor_.pit(), cursor_.pos()) );
263 // If we're quitting lyx, don't bother updating stuff
269 // If we are closing current buffer, switch to the first in
272 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
273 << " No Buffer!" << endl;
274 // We are closing the buffer, use the first buffer as current
275 buffer_ = bufferlist.first();
277 // Set current buffer
282 cursor_ = LCursor(*bv_);
287 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
288 << "Buffer addr: " << buffer_ << endl;
289 cursor_.push(buffer_->inset());
290 cursor_.resetAnchor();
291 buffer_->text().init(bv_);
292 buffer_->text().setCurrentFont(cursor_);
293 if (buffer_->getCursor().size() > 0 &&
294 buffer_->getAnchor().size() > 0)
296 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
297 cursor_.resetAnchor();
298 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
299 cursor_.setSelection();
305 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
306 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
309 string BufferView::Pimpl::firstLayout()
313 // This is done after the layout combox has been populated
315 size_t i = cursor_.depth() - 1;
316 // we know we'll eventually find a paragraph
318 CursorSlice const & slice = cursor_[i];
319 if (!slice.inset().inMathed()) {
320 LyXLayout_ptr const layout = slice.paragraph().layout();
321 firstlayout = layout->name();
332 void BufferView::Pimpl::resizeCurrentBuffer()
334 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
336 LyXText * text = bv_->text();
346 void BufferView::Pimpl::updateScrollbar()
349 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
350 << " no text in updateScrollbar" << endl;
351 scrollbarParameters_.reset();
355 LyXText & t = *bv_->text();
356 int const parsize = int(t.paragraphs().size() - 1);
357 if (anchor_ref_ > parsize) {
358 anchor_ref_ = parsize;
363 << BOOST_CURRENT_FUNCTION
364 << " Updating scrollbar: height: " << t.paragraphs().size()
365 << " curr par: " << cursor_.bottom().pit()
366 << " default height " << defaultRowHeight() << endl;
368 // It would be better to fix the scrollbar to understand
369 // values in [0..1] and divide everything by wh
371 // estimated average paragraph height:
374 int h = t.getPar(anchor_ref_).height();
376 // Normalize anchor/offset (MV):
377 while (offset_ref_ > h && anchor_ref_ < parsize) {
380 h = t.getPar(anchor_ref_).height();
382 // Look at paragraph heights on-screen
385 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
388 int const h2 = t.getPar(pit).height();
392 int const hav = sumh / nh;
393 // More realistic average paragraph height
397 scrollbarParameters_.height = (parsize + 1) * wh_;
398 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
399 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
403 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
405 return scrollbarParameters_;
409 void BufferView::Pimpl::scrollDocView(int value)
411 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
412 << "[ value = " << value << "]" << endl;
417 LyXText & t = *bv_->text();
419 float const bar = value / float(wh_ * t.paragraphs().size());
421 anchor_ref_ = int(bar * t.paragraphs().size());
422 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
423 anchor_ref_ = int(t.paragraphs().size()) - 1;
424 t.redoParagraph(anchor_ref_);
425 int const h = t.getPar(anchor_ref_).height();
426 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
430 void BufferView::Pimpl::setCursorFromScrollbar()
432 LyXText & t = *bv_->text();
434 int const height = 2 * defaultRowHeight();
435 int const first = height;
436 int const last = height_ - height;
437 LCursor & cur = cursor_;
439 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
442 case bv_funcs::CUR_ABOVE:
443 t.setCursorFromCoordinates(cur, 0, first);
444 cur.clearSelection();
446 case bv_funcs::CUR_BELOW:
447 t.setCursorFromCoordinates(cur, 0, last);
448 cur.clearSelection();
450 case bv_funcs::CUR_INSIDE:
451 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
452 int const newy = min(last, max(y, first));
454 cur.reset(buffer_->inset());
455 t.setCursorFromCoordinates(cur, 0, newy);
461 void BufferView::Pimpl::scroll(int /*lines*/)
466 // LyXText const * t = bv_->text();
467 // int const line_height = defaultRowHeight();
469 // // The new absolute coordinate
470 // int new_top_y = top_y() + lines * line_height;
472 // // Restrict to a valid value
473 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
474 // new_top_y = std::max(0, new_top_y);
476 // scrollDocView(new_top_y);
478 // // Update the scrollbar.
479 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
483 void BufferView::Pimpl::selectionRequested()
490 LCursor & cur = cursor_;
492 if (!cur.selection()) {
493 xsel_cache_.set = false;
497 if (!xsel_cache_.set ||
498 cur.top() != xsel_cache_.cursor ||
499 cur.anchor_.top() != xsel_cache_.anchor)
501 xsel_cache_.cursor = cur.top();
502 xsel_cache_.anchor = cur.anchor_.top();
503 xsel_cache_.set = cur.selection();
504 sel = cur.selectionAsString(false);
506 owner_->gui().selection().put(sel);
511 void BufferView::Pimpl::selectionLost()
514 cursor_.clearSelection();
515 xsel_cache_.set = false;
520 void BufferView::Pimpl::workAreaResize(int width, int height)
522 bool const widthChange = width != width_;
523 bool const heightChange = height != height_;
525 // Update from work area
529 if (buffer_ && widthChange) {
530 // The WorkArea content needs a resize
531 resizeCurrentBuffer();
534 if (widthChange || heightChange)
539 bool BufferView::Pimpl::fitCursor()
541 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
542 LyXFont const font = cursor_.getFont();
543 int const asc = font_metrics::maxAscent(font);
544 int const des = font_metrics::maxDescent(font);
545 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
546 if (p.y_ - asc >= 0 && p.y_ + des < height_)
554 bool BufferView::Pimpl::multiParSel()
556 if (!cursor_.selection())
558 bool ret = multiparsel_cache_;
559 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
560 // Either this, or previous selection spans paragraphs
561 return ret || multiparsel_cache_;
565 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
567 return metrics_info_;
571 bool BufferView::Pimpl::update(Update::flags flags)
573 // This is close to a hot-path.
574 if (lyxerr.debugging(Debug::DEBUG)) {
576 << BOOST_CURRENT_FUNCTION
577 << "[fitcursor = " << (flags & Update::FitCursor)
578 << ", forceupdate = " << (flags & Update::Force)
579 << ", singlepar = " << (flags & Update::SinglePar)
580 << "] buffer: " << buffer_ << endl;
583 // Check needed to survive LyX startup
587 // Update macro store
588 buffer_->buildMacros();
590 // First drawing step
591 updateMetrics(flags & Update::SinglePar);
593 // The second drawing step is done in WorkArea::redraw() if needed.
594 bool const need_second_step =
595 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
596 && (fitCursor() || multiParSel());
598 return need_second_step;
602 bool BufferView::Pimpl::available() const
604 return buffer_ && bv_->text();
608 Change const BufferView::Pimpl::getCurrentChange()
610 if (!buffer_->params().tracking_changes)
611 return Change(Change::UNCHANGED);
613 LyXText * text = bv_->getLyXText();
614 LCursor & cur = cursor_;
616 if (!cur.selection())
617 return Change(Change::UNCHANGED);
619 return text->getPar(cur.selBegin().pit()).
620 lookupChange(cur.selBegin().pos());
624 void BufferView::Pimpl::savePosition(unsigned int i)
626 if (i >= saved_positions_num)
628 BOOST_ASSERT(cursor_.inTexted());
629 saved_positions[i] = Position(buffer_->fileName(),
630 cursor_.paragraph().id(),
633 // emit message signal.
634 buffer_->message(bformat(_("Saved bookmark %1$d"), i));
638 void BufferView::Pimpl::restorePosition(unsigned int i)
640 if (i >= saved_positions_num)
643 string const fname = saved_positions[i].filename;
645 cursor_.clearSelection();
647 if (fname != buffer_->fileName()) {
649 if (bufferlist.exists(fname))
650 b = bufferlist.getBuffer(fname);
652 b = bufferlist.newBuffer(fname);
653 // Don't ask, just load it
654 ::loadLyXFile(b, fname);
660 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
661 if (par == buffer_->par_iterator_end())
664 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
667 // emit message signal.
668 buffer_->message(bformat(_("Moved to bookmark %1$d"), i));
672 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
674 return i < saved_positions_num && !saved_positions[i].filename.empty();
678 void BufferView::Pimpl::saveSavedPositions()
680 // save bookmarks. It is better to use the pit interface
681 // but I do not know how to effectively convert between
683 for (unsigned int i=1; i < saved_positions_num; ++i) {
684 if ( isSavedPosition(i) )
685 LyX::ref().session().saveBookmark( boost::tie(
687 saved_positions[i].filename,
688 saved_positions[i].par_id,
689 saved_positions[i].par_pos) );
694 void BufferView::Pimpl::switchKeyMap()
696 if (!lyxrc.rtl_support)
699 Intl & intl = owner_->getIntl();
700 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
701 if (intl.keymap == Intl::PRIMARY)
704 if (intl.keymap == Intl::SECONDARY)
710 void BufferView::Pimpl::center()
712 CursorSlice & bot = cursor_.bottom();
713 lyx::pit_type const pit = bot.pit();
714 bot.text()->redoParagraph(pit);
715 Paragraph const & par = bot.text()->paragraphs()[pit];
717 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
718 + par.ascent() - height_ / 2;
722 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
724 BOOST_ASSERT(cursor_.inTexted());
725 string filename = filenm;
727 if (filename.empty()) {
728 // Launch a file browser
729 string initpath = lyxrc.document_path;
732 string const trypath = buffer_->filePath();
733 // If directory is writeable, use this as default.
734 if (isDirWriteable(trypath))
738 FileDialog fileDlg(_("Select LyX document to insert"),
740 make_pair(string(_("Documents|#o#O")),
741 string(lyxrc.document_path)),
742 make_pair(string(_("Examples|#E#e")),
743 string(addPath(package().system_support(), "examples"))));
745 FileDialog::Result result =
746 fileDlg.open(initpath,
747 FileFilterList(_("LyX Documents (*.lyx)")),
750 if (result.first == FileDialog::Later)
753 filename = result.second;
755 // check selected filename
756 if (filename.empty()) {
757 // emit message signal.
758 buffer_->message(_("Canceled."));
763 // Get absolute path of file and add ".lyx"
764 // to the filename if necessary
765 filename = fileSearch(string(), filename, "lyx");
767 string const disp_fn = makeDisplayPath(filename);
768 // emit message signal.
769 buffer_->message(bformat(_("Inserting document %1$s..."), disp_fn));
772 Buffer buf("", false);
773 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
774 ErrorList & el = buffer_->errorList("Parse");
775 // Copy the inserted document error list into the current buffer one.
776 el = buf.errorList("Parse");
777 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
778 buf.params().textclass, el);
779 res = _("Document %1$s inserted.");
781 res = _("Could not insert document %1$s");
783 // emit message signal.
784 buffer_->message(bformat(res, disp_fn));
785 buffer_->errors("Parse");
786 resizeCurrentBuffer();
790 void BufferView::Pimpl::trackChanges()
792 bool const tracking = buffer_->params().tracking_changes;
795 for_each(buffer_->par_iterator_begin(),
796 buffer_->par_iterator_end(),
797 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
798 buffer_->params().tracking_changes = true;
800 // We cannot allow undos beyond the freeze point
801 buffer_->undostack().clear();
803 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
804 if (lyx::find::findNextChange(bv_)) {
805 owner_->getDialogs().show("changes");
809 for_each(buffer_->par_iterator_begin(),
810 buffer_->par_iterator_end(),
811 mem_fun_ref(&Paragraph::untrackChanges));
813 buffer_->params().tracking_changes = false;
816 buffer_->redostack().clear();
820 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
822 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
824 // This is only called for mouse related events including
825 // LFUN_FILE_OPEN generated by drag-and-drop.
826 FuncRequest cmd = cmd0;
832 cur.push(buffer_->inset());
833 cur.selection() = cursor_.selection();
835 // Doesn't go through lyxfunc, so we need to update
836 // the layout choice etc. ourselves
838 // E.g. Qt mouse press when no buffer
842 // Either the inset under the cursor or the
843 // surrounding LyXText will handle this event.
845 // Build temporary cursor.
846 cmd.y = min(max(cmd.y, -1), height_);
847 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
848 //lyxerr << BOOST_CURRENT_FUNCTION
849 // << " * hit inset at tip: " << inset << endl;
850 //lyxerr << BOOST_CURRENT_FUNCTION
851 // << " * created temp cursor:" << cur << endl;
853 // Put anchor at the same position.
856 // Try to dispatch to an non-editable inset near this position
857 // via the temp cursor. If the inset wishes to change the real
858 // cursor it has to do so explicitly by using
859 // cur.bv().cursor() = cur; (or similar)
861 inset->dispatch(cur, cmd);
863 // Now dispatch to the temporary cursor. If the real cursor should
864 // be modified, the inset's dispatch has to do so explicitly.
865 if (!cur.result().dispatched())
868 if (cur.result().dispatched()) {
869 // Redraw if requested or necessary.
870 if (cur.result().update())
871 update(Update::FitCursor | Update::Force);
873 update(Update::FitCursor | Update::MultiParSel);
880 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
884 switch (cmd.action) {
887 flag.enabled(!buffer_->undostack().empty());
890 flag.enabled(!buffer_->redostack().empty());
892 case LFUN_FILE_INSERT:
893 case LFUN_FILE_INSERT_ASCII_PARA:
894 case LFUN_FILE_INSERT_ASCII:
895 case LFUN_BOOKMARK_SAVE:
896 // FIXME: Actually, these LFUNS should be moved to LyXText
897 flag.enabled(cursor_.inTexted());
899 case LFUN_FONT_STATE:
900 case LFUN_LABEL_INSERT:
901 case LFUN_PARAGRAPH_GOTO:
902 // FIXME handle non-trivially
903 case LFUN_OUTLINE_UP:
904 case LFUN_OUTLINE_DOWN:
905 case LFUN_OUTLINE_IN:
906 case LFUN_OUTLINE_OUT:
908 case LFUN_REFERENCE_NEXT:
910 case LFUN_WORD_REPLACE:
913 case LFUN_MARK_TOGGLE:
914 case LFUN_SCREEN_RECENTER:
915 case LFUN_BIBTEX_DATABASE_ADD:
916 case LFUN_BIBTEX_DATABASE_DEL:
917 case LFUN_WORDS_COUNT:
918 case LFUN_NEXT_INSET_TOGGLE:
922 case LFUN_LABEL_GOTO: {
923 flag.enabled(!cmd.argument.empty()
924 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
928 case LFUN_BOOKMARK_GOTO:
929 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
931 case LFUN_CHANGES_TRACK:
933 flag.setOnOff(buffer_->params().tracking_changes);
936 case LFUN_CHANGES_OUTPUT: {
937 OutputParams runparams;
938 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
939 flag.enabled(buffer_ && buffer_->params().tracking_changes
940 && features.isAvailable("dvipost"));
941 flag.setOnOff(buffer_->params().output_changes);
945 case LFUN_CHANGES_MERGE:
946 case LFUN_CHANGE_ACCEPT: // what about these two
947 case LFUN_CHANGE_REJECT: // what about these two
948 case LFUN_ALL_CHANGES_ACCEPT:
949 case LFUN_ALL_CHANGES_REJECT:
950 flag.enabled(buffer_ && buffer_->params().tracking_changes);
953 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
954 flag.setOnOff(buffer_->params().compressed);
967 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
969 //lyxerr << BOOST_CURRENT_FUNCTION
970 // << [ cmd = " << cmd << "]" << endl;
972 // Make sure that the cached BufferView is correct.
973 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
974 << " action[" << cmd.action << ']'
975 << " arg[" << cmd.argument << ']'
976 << " x[" << cmd.x << ']'
977 << " y[" << cmd.y << ']'
978 << " button[" << cmd.button() << ']'
981 LCursor & cur = cursor_;
983 switch (cmd.action) {
987 cur.message(_("Undo"));
988 cur.clearSelection();
990 cur.message(_("No further undo information"));
998 cur.message(_("Redo"));
999 cur.clearSelection();
1000 if (!textRedo(*bv_))
1001 cur.message(_("No further redo information"));
1007 case LFUN_FILE_INSERT:
1008 menuInsertLyXFile(cmd.argument);
1011 case LFUN_FILE_INSERT_ASCII_PARA:
1012 insertAsciiFile(bv_, cmd.argument, true);
1015 case LFUN_FILE_INSERT_ASCII:
1016 insertAsciiFile(bv_, cmd.argument, false);
1019 case LFUN_FONT_STATE:
1020 cur.message(cur.currentState());
1023 case LFUN_BOOKMARK_SAVE:
1024 savePosition(convert<unsigned int>(cmd.argument));
1027 case LFUN_BOOKMARK_GOTO:
1028 restorePosition(convert<unsigned int>(cmd.argument));
1031 case LFUN_LABEL_GOTO: {
1032 string label = cmd.argument;
1033 if (label.empty()) {
1035 getInsetByCode<InsetRef>(cursor_,
1036 InsetBase::REF_CODE);
1038 label = inset->getContents();
1044 bv_->gotoLabel(label);
1048 case LFUN_PARAGRAPH_GOTO: {
1049 int const id = convert<int>(cmd.argument);
1050 ParIterator par = buffer_->getParFromID(id);
1051 if (par == buffer_->par_iterator_end()) {
1052 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1053 << id << ']' << endl;
1056 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1057 << " found." << endl;
1061 bv_->setCursor(makeDocIterator(par, 0));
1068 case LFUN_OUTLINE_UP:
1069 lyx::toc::outline(lyx::toc::Up, cursor_);
1070 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1071 updateLabels(*buffer_);
1073 case LFUN_OUTLINE_DOWN:
1074 lyx::toc::outline(lyx::toc::Down, cursor_);
1075 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1076 updateLabels(*buffer_);
1078 case LFUN_OUTLINE_IN:
1079 lyx::toc::outline(lyx::toc::In, cursor_);
1080 updateLabels(*buffer_);
1082 case LFUN_OUTLINE_OUT:
1083 lyx::toc::outline(lyx::toc::Out, cursor_);
1084 updateLabels(*buffer_);
1087 case LFUN_NOTE_NEXT:
1088 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1091 case LFUN_REFERENCE_NEXT: {
1092 vector<InsetBase_code> tmp;
1093 tmp.push_back(InsetBase::LABEL_CODE);
1094 tmp.push_back(InsetBase::REF_CODE);
1095 bv_funcs::gotoInset(bv_, tmp, true);
1099 case LFUN_CHANGES_TRACK:
1103 case LFUN_CHANGES_OUTPUT: {
1104 bool const state = buffer_->params().output_changes;
1105 buffer_->params().output_changes = !state;
1109 case LFUN_CHANGES_MERGE:
1110 if (lyx::find::findNextChange(bv_))
1111 owner_->getDialogs().show("changes");
1114 case LFUN_ALL_CHANGES_ACCEPT: {
1115 cursor_.reset(buffer_->inset());
1116 #ifdef WITH_WARNINGS
1117 #warning FIXME changes
1119 while (lyx::find::findNextChange(bv_))
1120 bv_->getLyXText()->acceptChange(cursor_);
1125 case LFUN_ALL_CHANGES_REJECT: {
1126 cursor_.reset(buffer_->inset());
1127 #ifdef WITH_WARNINGS
1128 #warning FIXME changes
1130 while (lyx::find::findNextChange(bv_))
1131 bv_->getLyXText()->rejectChange(cursor_);
1135 case LFUN_WORD_FIND:
1136 lyx::find::find(bv_, cmd);
1139 case LFUN_WORD_REPLACE:
1140 lyx::find::replace(bv_, cmd);
1144 cur.clearSelection();
1146 cur.message(N_("Mark off"));
1150 cur.clearSelection();
1153 cur.message(N_("Mark on"));
1156 case LFUN_MARK_TOGGLE:
1157 cur.clearSelection();
1160 cur.message(N_("Mark removed"));
1163 cur.message(N_("Mark set"));
1168 case LFUN_SCREEN_RECENTER:
1172 case LFUN_BIBTEX_DATABASE_ADD: {
1173 LCursor tmpcur = cursor_;
1174 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1175 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1176 InsetBase::BIBTEX_CODE);
1178 if (inset->addDatabase(cmd.argument))
1179 buffer_->updateBibfilesCache();
1184 case LFUN_BIBTEX_DATABASE_DEL: {
1185 LCursor tmpcur = cursor_;
1186 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1187 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1188 InsetBase::BIBTEX_CODE);
1190 if (inset->delDatabase(cmd.argument))
1191 buffer_->updateBibfilesCache();
1196 case LFUN_WORDS_COUNT: {
1197 DocIterator from, to;
1198 if (cur.selection()) {
1199 from = cur.selectionBegin();
1200 to = cur.selectionEnd();
1202 from = doc_iterator_begin(buffer_->inset());
1203 to = doc_iterator_end(buffer_->inset());
1205 int const count = countWords(from, to);
1208 if (cur.selection())
1209 message = bformat(_("%1$d words in selection."),
1212 message = bformat(_("%1$d words in document."),
1216 if (cur.selection())
1217 message = _("One word in selection.");
1219 message = _("One word in document.");
1222 Alert::information(_("Count words"), message);
1226 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1227 // turn compression on/off
1228 buffer_->params().compressed = !buffer_->params().compressed;
1231 case LFUN_NEXT_INSET_TOGGLE: {
1232 // this is the real function we want to invoke
1233 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1234 // if there is an inset at cursor, see whether it
1236 InsetBase * inset = cur.nextInset();
1237 if (inset && inset->isActive()) {
1238 LCursor tmpcur = cur;
1239 tmpcur.pushLeft(*inset);
1240 inset->dispatch(tmpcur, tmpcmd);
1241 if (tmpcur.result().dispatched()) {
1245 // if it did not work, try the underlying inset.
1246 if (!cur.result().dispatched())
1247 cur.dispatch(tmpcmd);
1249 if (cur.result().dispatched())
1250 cur.clearSelection();
1263 void BufferView::Pimpl::updateMetrics(bool singlepar)
1265 // Remove old position cache
1267 BufferView & bv = *bv_;
1268 LyXText * const text = bv.text();
1269 lyx::pit_type size = int(text->paragraphs().size());
1271 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1272 anchor_ref_ = int(text->paragraphs().size() - 1);
1276 lyx::pit_type const pit = anchor_ref_;
1279 size_t const npit = text->paragraphs().size();
1281 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1282 // the (main text, not inset!) paragraph containing the cursor.
1283 // (if this paragraph contains insets etc., rebreaking will
1284 // recursively descend)
1285 if (!singlepar || pit == cursor_.bottom().pit())
1286 text->redoParagraph(pit);
1287 int y0 = text->getPar(pit).ascent() - offset_ref_;
1289 // Redo paragraphs above anchor if necessary; again, in Single Par
1290 // mode, only if we encounter the (main text) one having the cursor.
1292 while (y1 > 0 && pit1 > 0) {
1293 y1 -= text->getPar(pit1).ascent();
1295 if (!singlepar || pit1 == cursor_.bottom().pit())
1296 text->redoParagraph(pit1);
1297 y1 -= text->getPar(pit1).descent();
1301 // Take care of ascent of first line
1302 y1 -= text->getPar(pit1).ascent();
1304 // Normalize anchor for next time
1308 // Grey at the beginning is ugly
1309 if (pit1 == 0 && y1 > 0) {
1315 // Redo paragraphs below the anchor if necessary. Single par mode:
1316 // only the one containing the cursor if encountered.
1318 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1319 y2 += text->getPar(pit2).descent();
1321 if (!singlepar || pit2 == cursor_.bottom().pit())
1322 text->redoParagraph(pit2);
1323 y2 += text->getPar(pit2).ascent();
1326 // Take care of descent of last line
1327 y2 += text->getPar(pit2).descent();
1329 // The coordinates of all these paragraphs are correct, cache them
1331 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1332 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1333 Paragraph const & par = text->getPar(pit);
1335 parPos[pit] = Point(0, y);
1336 if (singlepar && pit == cursor_.bottom().pit()) {
1337 // In Single Paragraph mode, collect here the
1338 // y1 and y2 of the (one) paragraph the cursor is in
1339 y1 = y - par.ascent();
1340 y2 = y + par.descent();
1346 // collect cursor paragraph iter bounds
1347 pit1 = cursor_.bottom().pit();
1348 pit2 = cursor_.bottom().pit();
1351 lyxerr[Debug::DEBUG]
1352 << BOOST_CURRENT_FUNCTION
1355 << " pit1: " << pit1
1356 << " pit2: " << pit2
1357 << " npit: " << npit
1358 << " singlepar: " << singlepar
1362 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);