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;
89 using lyx::support::addPath;
90 using lyx::support::bformat;
91 using lyx::support::FileFilterList;
92 using lyx::support::fileSearch;
93 using lyx::support::isDirWriteable;
94 using lyx::support::makeDisplayPath;
95 using lyx::support::makeAbsPath;
96 using lyx::support::package;
99 using std::istringstream;
100 using std::make_pair;
104 using std::mem_fun_ref;
107 extern BufferList bufferlist;
112 unsigned int const saved_positions_num = 20;
115 /// Return an inset of this class if it exists at the current cursor position
117 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
120 DocIterator it = cur;
121 if (it.nextInset() &&
122 it.nextInset()->lyxCode() == code) {
123 inset = static_cast<T*>(it.nextInset());
131 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
132 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
134 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
136 xsel_cache_.set = false;
138 saved_positions.resize(saved_positions_num);
139 // load saved bookmarks
140 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
141 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
142 bm != bmList.end(); ++bm)
143 if (bm->get<0>() < saved_positions_num)
144 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
145 // and then clear them
150 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
152 // Get absolute path of file and add ".lyx"
153 // to the filename if necessary
154 string s = fileSearch(string(), filename, "lyx");
156 bool const found = !s.empty();
161 // File already open?
162 if (bufferlist.exists(s)) {
163 string const file = makeDisplayPath(s, 20);
164 string text = bformat(_("The document %1$s is already "
165 "loaded.\n\nDo you want to revert "
166 "to the saved version?"), file);
167 int const ret = Alert::prompt(_("Revert to saved document?"),
168 text, 0, 1, _("&Revert"), _("&Switch to document"));
171 setBuffer(bufferlist.getBuffer(s));
174 // FIXME: should be LFUN_REVERT
175 if (!bufferlist.close(bufferlist.getBuffer(s), false))
177 // Fall through to new load. (Asger)
183 b = bufferlist.newBuffer(s);
184 if (!::loadLyXFile(b, s)) {
185 bufferlist.release(b);
189 string text = bformat(_("The document %1$s does not yet "
190 "exist.\n\nDo you want to create "
191 "a new document?"), s);
192 int const ret = Alert::prompt(_("Create new document?"),
193 text, 0, 1, _("&Create"), _("Cancel"));
196 b = newFile(s, string(), true);
204 // Send the "errors" signal in case of parsing errors
207 // scroll to the position when the file was last closed
208 if (lyxrc.use_lastfilepos) {
211 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
212 // I am not sure how to separate the following part to a function
213 // so I will leave this to Lars.
215 // check pit since the document may be externally changed.
216 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
217 ParIterator it = b->par_iterator_begin();
218 ParIterator const end = b->par_iterator_end();
219 for (; it != end; ++it)
220 if (it.pit() == pit) {
221 // restored pos may be bigger than it->size
222 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
223 bv_->update(Update::FitCursor);
230 LyX::ref().session().addLastFile(b->fileName());
236 int BufferView::Pimpl::width() const
242 int BufferView::Pimpl::height() const
248 void BufferView::Pimpl::setBuffer(Buffer * b)
250 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
251 << "[ b = " << b << "]" << endl;
254 // Save the actual cursor position and anchor inside the
255 // buffer so that it can be restored in case we rechange
256 // to this buffer later on.
257 buffer_->saveCursor(cursor_.selectionBegin(),
258 cursor_.selectionEnd());
259 // current buffer is going to be switched-off, save cursor pos
260 LyX::ref().session().saveFilePosition(buffer_->fileName(),
261 boost::tie(cursor_.pit(), cursor_.pos()) );
264 // If we're quitting lyx, don't bother updating stuff
270 // If we are closing current buffer, switch to the first in
273 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
274 << " No Buffer!" << endl;
275 // We are closing the buffer, use the first buffer as current
276 buffer_ = bufferlist.first();
278 // Set current buffer
283 cursor_ = LCursor(*bv_);
288 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
289 << "Buffer addr: " << buffer_ << endl;
290 cursor_.push(buffer_->inset());
291 cursor_.resetAnchor();
292 buffer_->text().init(bv_);
293 buffer_->text().setCurrentFont(cursor_);
294 if (buffer_->getCursor().size() > 0 &&
295 buffer_->getAnchor().size() > 0)
297 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
298 cursor_.resetAnchor();
299 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
300 cursor_.setSelection();
306 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
307 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
311 void BufferView::Pimpl::resizeCurrentBuffer()
313 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
315 LyXText * text = bv_->text();
325 void BufferView::Pimpl::updateScrollbar()
328 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
329 << " no text in updateScrollbar" << endl;
330 scrollbarParameters_.reset();
334 LyXText & t = *bv_->text();
335 int const parsize = int(t.paragraphs().size() - 1);
336 if (anchor_ref_ > parsize) {
337 anchor_ref_ = parsize;
342 << BOOST_CURRENT_FUNCTION
343 << " Updating scrollbar: height: " << t.paragraphs().size()
344 << " curr par: " << cursor_.bottom().pit()
345 << " default height " << defaultRowHeight() << endl;
347 // It would be better to fix the scrollbar to understand
348 // values in [0..1] and divide everything by wh
350 // estimated average paragraph height:
353 int h = t.getPar(anchor_ref_).height();
355 // Normalize anchor/offset (MV):
356 while (offset_ref_ > h && anchor_ref_ < parsize) {
359 h = t.getPar(anchor_ref_).height();
361 // Look at paragraph heights on-screen
364 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
367 int const h2 = t.getPar(pit).height();
371 int const hav = sumh / nh;
372 // More realistic average paragraph height
376 scrollbarParameters_.height = (parsize + 1) * wh_;
377 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
378 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
382 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
384 return scrollbarParameters_;
388 void BufferView::Pimpl::scrollDocView(int value)
390 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
391 << "[ value = " << value << "]" << endl;
396 LyXText & t = *bv_->text();
398 float const bar = value / float(wh_ * t.paragraphs().size());
400 anchor_ref_ = int(bar * t.paragraphs().size());
401 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
402 anchor_ref_ = int(t.paragraphs().size()) - 1;
403 t.redoParagraph(anchor_ref_);
404 int const h = t.getPar(anchor_ref_).height();
405 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
409 void BufferView::Pimpl::setCursorFromScrollbar()
411 LyXText & t = *bv_->text();
413 int const height = 2 * defaultRowHeight();
414 int const first = height;
415 int const last = height_ - height;
416 LCursor & cur = cursor_;
418 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
421 case bv_funcs::CUR_ABOVE:
422 t.setCursorFromCoordinates(cur, 0, first);
423 cur.clearSelection();
425 case bv_funcs::CUR_BELOW:
426 t.setCursorFromCoordinates(cur, 0, last);
427 cur.clearSelection();
429 case bv_funcs::CUR_INSIDE:
430 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
431 int const newy = min(last, max(y, first));
433 cur.reset(buffer_->inset());
434 t.setCursorFromCoordinates(cur, 0, newy);
440 void BufferView::Pimpl::scroll(int /*lines*/)
445 // LyXText const * t = bv_->text();
446 // int const line_height = defaultRowHeight();
448 // // The new absolute coordinate
449 // int new_top_y = top_y() + lines * line_height;
451 // // Restrict to a valid value
452 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
453 // new_top_y = std::max(0, new_top_y);
455 // scrollDocView(new_top_y);
457 // // Update the scrollbar.
458 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
462 void BufferView::Pimpl::selectionRequested()
464 static docstring sel;
469 LCursor & cur = cursor_;
471 if (!cur.selection()) {
472 xsel_cache_.set = false;
476 if (!xsel_cache_.set ||
477 cur.top() != xsel_cache_.cursor ||
478 cur.anchor_.top() != xsel_cache_.anchor)
480 xsel_cache_.cursor = cur.top();
481 xsel_cache_.anchor = cur.anchor_.top();
482 xsel_cache_.set = cur.selection();
483 sel = cur.selectionAsString(false);
485 owner_->gui().selection().put(sel);
490 void BufferView::Pimpl::selectionLost()
493 cursor_.clearSelection();
494 xsel_cache_.set = false;
499 void BufferView::Pimpl::workAreaResize(int width, int height)
501 bool const widthChange = width != width_;
502 bool const heightChange = height != height_;
504 // Update from work area
508 if (buffer_ && widthChange) {
509 // The WorkArea content needs a resize
510 resizeCurrentBuffer();
513 if (widthChange || heightChange)
518 bool BufferView::Pimpl::fitCursor()
520 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
521 LyXFont const font = cursor_.getFont();
522 int const asc = font_metrics::maxAscent(font);
523 int const des = font_metrics::maxDescent(font);
524 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
525 if (p.y_ - asc >= 0 && p.y_ + des < height_)
533 bool BufferView::Pimpl::multiParSel()
535 if (!cursor_.selection())
537 bool ret = multiparsel_cache_;
538 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
539 // Either this, or previous selection spans paragraphs
540 return ret || multiparsel_cache_;
544 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
546 return metrics_info_;
550 bool BufferView::Pimpl::update(Update::flags flags)
552 // This is close to a hot-path.
553 if (lyxerr.debugging(Debug::DEBUG)) {
555 << BOOST_CURRENT_FUNCTION
556 << "[fitcursor = " << (flags & Update::FitCursor)
557 << ", forceupdate = " << (flags & Update::Force)
558 << ", singlepar = " << (flags & Update::SinglePar)
559 << "] buffer: " << buffer_ << endl;
562 // Check needed to survive LyX startup
566 // Update macro store
567 buffer_->buildMacros();
569 // First drawing step
570 updateMetrics(flags & Update::SinglePar);
572 // The second drawing step is done in WorkArea::redraw() if needed.
573 bool const need_second_step =
574 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
575 && (fitCursor() || multiParSel());
577 return need_second_step;
581 bool BufferView::Pimpl::available() const
583 return buffer_ && bv_->text();
587 Change const BufferView::Pimpl::getCurrentChange()
589 if (!buffer_->params().tracking_changes)
590 return Change(Change::UNCHANGED);
592 LyXText * text = bv_->getLyXText();
593 LCursor & cur = cursor_;
595 if (!cur.selection())
596 return Change(Change::UNCHANGED);
598 return text->getPar(cur.selBegin().pit()).
599 lookupChange(cur.selBegin().pos());
603 void BufferView::Pimpl::savePosition(unsigned int i)
605 if (i >= saved_positions_num)
607 BOOST_ASSERT(cursor_.inTexted());
608 saved_positions[i] = Position(buffer_->fileName(),
609 cursor_.paragraph().id(),
612 // emit message signal.
613 bv_->message(bformat(_("Saved bookmark %1$d"), i));
617 void BufferView::Pimpl::restorePosition(unsigned int i)
619 if (i >= saved_positions_num)
622 string const fname = saved_positions[i].filename;
624 cursor_.clearSelection();
626 if (fname != buffer_->fileName()) {
628 if (bufferlist.exists(fname))
629 b = bufferlist.getBuffer(fname);
631 b = bufferlist.newBuffer(fname);
632 // Don't ask, just load it
633 ::loadLyXFile(b, fname);
639 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
640 if (par == buffer_->par_iterator_end())
643 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
646 // emit message signal.
647 bv_->message(bformat(_("Moved to bookmark %1$d"), i));
651 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
653 return i < saved_positions_num && !saved_positions[i].filename.empty();
657 void BufferView::Pimpl::saveSavedPositions()
659 // save bookmarks. It is better to use the pit interface
660 // but I do not know how to effectively convert between
662 for (unsigned int i=1; i < saved_positions_num; ++i) {
663 if ( isSavedPosition(i) )
664 LyX::ref().session().saveBookmark( boost::tie(
666 saved_positions[i].filename,
667 saved_positions[i].par_id,
668 saved_positions[i].par_pos) );
673 void BufferView::Pimpl::switchKeyMap()
675 if (!lyxrc.rtl_support)
678 Intl & intl = owner_->getIntl();
679 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
680 if (intl.keymap == Intl::PRIMARY)
683 if (intl.keymap == Intl::SECONDARY)
689 void BufferView::Pimpl::center()
691 CursorSlice & bot = cursor_.bottom();
692 lyx::pit_type const pit = bot.pit();
693 bot.text()->redoParagraph(pit);
694 Paragraph const & par = bot.text()->paragraphs()[pit];
696 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
697 + par.ascent() - height_ / 2;
701 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
703 BOOST_ASSERT(cursor_.inTexted());
704 string filename = filenm;
706 if (filename.empty()) {
707 // Launch a file browser
708 string initpath = lyxrc.document_path;
711 string const trypath = buffer_->filePath();
712 // If directory is writeable, use this as default.
713 if (isDirWriteable(trypath))
717 FileDialog fileDlg(_("Select LyX document to insert"),
719 make_pair(string(_("Documents|#o#O")),
720 string(lyxrc.document_path)),
721 make_pair(string(_("Examples|#E#e")),
722 string(addPath(package().system_support(), "examples"))));
724 FileDialog::Result result =
725 fileDlg.open(initpath,
726 FileFilterList(_("LyX Documents (*.lyx)")),
729 if (result.first == FileDialog::Later)
732 filename = result.second;
734 // check selected filename
735 if (filename.empty()) {
736 // emit message signal.
737 bv_->message(_("Canceled."));
742 // Get absolute path of file and add ".lyx"
743 // to the filename if necessary
744 filename = fileSearch(string(), filename, "lyx");
746 string const disp_fn = makeDisplayPath(filename);
747 // emit message signal.
748 bv_->message(bformat(_("Inserting document %1$s..."), disp_fn));
751 Buffer buf("", false);
752 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
753 ErrorList & el = buffer_->errorList("Parse");
754 // Copy the inserted document error list into the current buffer one.
755 el = buf.errorList("Parse");
756 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
757 buf.params().textclass, el);
758 res = _("Document %1$s inserted.");
760 res = _("Could not insert document %1$s");
762 // emit message signal.
763 bv_->message(bformat(res, disp_fn));
764 buffer_->errors("Parse");
765 resizeCurrentBuffer();
769 void BufferView::Pimpl::trackChanges()
771 bool const tracking = buffer_->params().tracking_changes;
774 for_each(buffer_->par_iterator_begin(),
775 buffer_->par_iterator_end(),
776 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
777 buffer_->params().tracking_changes = true;
779 // We cannot allow undos beyond the freeze point
780 buffer_->undostack().clear();
782 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
783 if (lyx::find::findNextChange(bv_)) {
784 owner_->getDialogs().show("changes");
788 for_each(buffer_->par_iterator_begin(),
789 buffer_->par_iterator_end(),
790 mem_fun_ref(&Paragraph::untrackChanges));
792 buffer_->params().tracking_changes = false;
795 buffer_->redostack().clear();
799 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
801 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
803 // This is only called for mouse related events including
804 // LFUN_FILE_OPEN generated by drag-and-drop.
805 FuncRequest cmd = cmd0;
811 cur.push(buffer_->inset());
812 cur.selection() = cursor_.selection();
814 // Doesn't go through lyxfunc, so we need to update
815 // the layout choice etc. ourselves
817 // E.g. Qt mouse press when no buffer
821 // Either the inset under the cursor or the
822 // surrounding LyXText will handle this event.
824 // Build temporary cursor.
825 cmd.y = min(max(cmd.y, -1), height_);
826 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
827 //lyxerr << BOOST_CURRENT_FUNCTION
828 // << " * hit inset at tip: " << inset << endl;
829 //lyxerr << BOOST_CURRENT_FUNCTION
830 // << " * created temp cursor:" << cur << endl;
832 // Put anchor at the same position.
835 // Try to dispatch to an non-editable inset near this position
836 // via the temp cursor. If the inset wishes to change the real
837 // cursor it has to do so explicitly by using
838 // cur.bv().cursor() = cur; (or similar)
840 inset->dispatch(cur, cmd);
842 // Now dispatch to the temporary cursor. If the real cursor should
843 // be modified, the inset's dispatch has to do so explicitly.
844 if (!cur.result().dispatched())
847 if (cur.result().dispatched()) {
848 // Redraw if requested or necessary.
849 if (cur.result().update())
850 update(Update::FitCursor | Update::Force);
852 update(Update::FitCursor | Update::MultiParSel);
859 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
863 switch (cmd.action) {
866 flag.enabled(!buffer_->undostack().empty());
869 flag.enabled(!buffer_->redostack().empty());
871 case LFUN_FILE_INSERT:
872 case LFUN_FILE_INSERT_ASCII_PARA:
873 case LFUN_FILE_INSERT_ASCII:
874 case LFUN_BOOKMARK_SAVE:
875 // FIXME: Actually, these LFUNS should be moved to LyXText
876 flag.enabled(cursor_.inTexted());
878 case LFUN_FONT_STATE:
879 case LFUN_LABEL_INSERT:
880 case LFUN_PARAGRAPH_GOTO:
881 // FIXME handle non-trivially
882 case LFUN_OUTLINE_UP:
883 case LFUN_OUTLINE_DOWN:
884 case LFUN_OUTLINE_IN:
885 case LFUN_OUTLINE_OUT:
887 case LFUN_REFERENCE_NEXT:
889 case LFUN_WORD_REPLACE:
892 case LFUN_MARK_TOGGLE:
893 case LFUN_SCREEN_RECENTER:
894 case LFUN_BIBTEX_DATABASE_ADD:
895 case LFUN_BIBTEX_DATABASE_DEL:
896 case LFUN_WORDS_COUNT:
897 case LFUN_NEXT_INSET_TOGGLE:
901 case LFUN_LABEL_GOTO: {
902 flag.enabled(!cmd.argument().empty()
903 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
907 case LFUN_BOOKMARK_GOTO:
908 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
910 case LFUN_CHANGES_TRACK:
912 flag.setOnOff(buffer_->params().tracking_changes);
915 case LFUN_CHANGES_OUTPUT: {
916 OutputParams runparams;
917 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
918 flag.enabled(buffer_ && buffer_->params().tracking_changes
919 && features.isAvailable("dvipost"));
920 flag.setOnOff(buffer_->params().output_changes);
924 case LFUN_CHANGES_MERGE:
925 case LFUN_CHANGE_ACCEPT: // what about these two
926 case LFUN_CHANGE_REJECT: // what about these two
927 case LFUN_ALL_CHANGES_ACCEPT:
928 case LFUN_ALL_CHANGES_REJECT:
929 flag.enabled(buffer_ && buffer_->params().tracking_changes);
932 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
933 flag.setOnOff(buffer_->params().compressed);
946 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
948 //lyxerr << BOOST_CURRENT_FUNCTION
949 // << [ cmd = " << cmd << "]" << endl;
951 // Make sure that the cached BufferView is correct.
952 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
953 << " action[" << cmd.action << ']'
954 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
955 << " x[" << cmd.x << ']'
956 << " y[" << cmd.y << ']'
957 << " button[" << cmd.button() << ']'
960 LCursor & cur = cursor_;
962 switch (cmd.action) {
966 cur.message(_("Undo"));
967 cur.clearSelection();
969 cur.message(_("No further undo information"));
977 cur.message(_("Redo"));
978 cur.clearSelection();
980 cur.message(_("No further redo information"));
986 case LFUN_FILE_INSERT:
987 // FIXME: We don't know the encoding of filenames
988 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
991 case LFUN_FILE_INSERT_ASCII_PARA:
992 // FIXME: We don't know the encoding of filenames
993 insertAsciiFile(bv_, lyx::to_utf8(cmd.argument()), true);
996 case LFUN_FILE_INSERT_ASCII:
997 // FIXME: We don't know the encoding of filenames
998 insertAsciiFile(bv_, lyx::to_utf8(cmd.argument()), false);
1001 case LFUN_FONT_STATE:
1002 cur.message(cur.currentState());
1005 case LFUN_BOOKMARK_SAVE:
1006 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
1009 case LFUN_BOOKMARK_GOTO:
1010 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
1013 case LFUN_LABEL_GOTO: {
1014 string label = lyx::to_utf8(cmd.argument());
1015 if (label.empty()) {
1017 getInsetByCode<InsetRef>(cursor_,
1018 InsetBase::REF_CODE);
1020 label = inset->getContents();
1026 bv_->gotoLabel(label);
1030 case LFUN_PARAGRAPH_GOTO: {
1031 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
1032 ParIterator par = buffer_->getParFromID(id);
1033 if (par == buffer_->par_iterator_end()) {
1034 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1035 << id << ']' << endl;
1038 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1039 << " found." << endl;
1043 bv_->setCursor(makeDocIterator(par, 0));
1050 case LFUN_OUTLINE_UP:
1051 lyx::toc::outline(lyx::toc::Up, cursor_);
1052 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1053 updateLabels(*buffer_);
1055 case LFUN_OUTLINE_DOWN:
1056 lyx::toc::outline(lyx::toc::Down, cursor_);
1057 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1058 updateLabels(*buffer_);
1060 case LFUN_OUTLINE_IN:
1061 lyx::toc::outline(lyx::toc::In, cursor_);
1062 updateLabels(*buffer_);
1064 case LFUN_OUTLINE_OUT:
1065 lyx::toc::outline(lyx::toc::Out, cursor_);
1066 updateLabels(*buffer_);
1069 case LFUN_NOTE_NEXT:
1070 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1073 case LFUN_REFERENCE_NEXT: {
1074 vector<InsetBase_code> tmp;
1075 tmp.push_back(InsetBase::LABEL_CODE);
1076 tmp.push_back(InsetBase::REF_CODE);
1077 bv_funcs::gotoInset(bv_, tmp, true);
1081 case LFUN_CHANGES_TRACK:
1085 case LFUN_CHANGES_OUTPUT: {
1086 bool const state = buffer_->params().output_changes;
1087 buffer_->params().output_changes = !state;
1091 case LFUN_CHANGES_MERGE:
1092 if (lyx::find::findNextChange(bv_))
1093 owner_->getDialogs().show("changes");
1096 case LFUN_ALL_CHANGES_ACCEPT: {
1097 cursor_.reset(buffer_->inset());
1098 #ifdef WITH_WARNINGS
1099 #warning FIXME changes
1101 while (lyx::find::findNextChange(bv_))
1102 bv_->getLyXText()->acceptChange(cursor_);
1107 case LFUN_ALL_CHANGES_REJECT: {
1108 cursor_.reset(buffer_->inset());
1109 #ifdef WITH_WARNINGS
1110 #warning FIXME changes
1112 while (lyx::find::findNextChange(bv_))
1113 bv_->getLyXText()->rejectChange(cursor_);
1117 case LFUN_WORD_FIND:
1118 lyx::find::find(bv_, cmd);
1121 case LFUN_WORD_REPLACE:
1122 lyx::find::replace(bv_, cmd);
1126 cur.clearSelection();
1128 cur.message(N_("Mark off"));
1132 cur.clearSelection();
1135 cur.message(N_("Mark on"));
1138 case LFUN_MARK_TOGGLE:
1139 cur.clearSelection();
1142 cur.message(N_("Mark removed"));
1145 cur.message(N_("Mark set"));
1150 case LFUN_SCREEN_RECENTER:
1154 case LFUN_BIBTEX_DATABASE_ADD: {
1155 LCursor tmpcur = cursor_;
1156 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1157 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1158 InsetBase::BIBTEX_CODE);
1160 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
1161 buffer_->updateBibfilesCache();
1166 case LFUN_BIBTEX_DATABASE_DEL: {
1167 LCursor tmpcur = cursor_;
1168 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1169 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1170 InsetBase::BIBTEX_CODE);
1172 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
1173 buffer_->updateBibfilesCache();
1178 case LFUN_WORDS_COUNT: {
1179 DocIterator from, to;
1180 if (cur.selection()) {
1181 from = cur.selectionBegin();
1182 to = cur.selectionEnd();
1184 from = doc_iterator_begin(buffer_->inset());
1185 to = doc_iterator_end(buffer_->inset());
1187 int const count = countWords(from, to);
1190 if (cur.selection())
1191 message = bformat(_("%1$d words in selection."),
1194 message = bformat(_("%1$d words in document."),
1198 if (cur.selection())
1199 message = _("One word in selection.");
1201 message = _("One word in document.");
1204 Alert::information(_("Count words"), message);
1208 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1209 // turn compression on/off
1210 buffer_->params().compressed = !buffer_->params().compressed;
1213 case LFUN_NEXT_INSET_TOGGLE: {
1214 // this is the real function we want to invoke
1215 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1216 // if there is an inset at cursor, see whether it
1218 InsetBase * inset = cur.nextInset();
1219 if (inset && inset->isActive()) {
1220 LCursor tmpcur = cur;
1221 tmpcur.pushLeft(*inset);
1222 inset->dispatch(tmpcur, tmpcmd);
1223 if (tmpcur.result().dispatched()) {
1227 // if it did not work, try the underlying inset.
1228 if (!cur.result().dispatched())
1229 cur.dispatch(tmpcmd);
1231 if (cur.result().dispatched())
1232 cur.clearSelection();
1245 void BufferView::Pimpl::updateMetrics(bool singlepar)
1247 // Remove old position cache
1249 BufferView & bv = *bv_;
1250 LyXText * const text = bv.text();
1251 lyx::pit_type size = int(text->paragraphs().size());
1253 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1254 anchor_ref_ = int(text->paragraphs().size() - 1);
1258 lyx::pit_type const pit = anchor_ref_;
1261 size_t const npit = text->paragraphs().size();
1263 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1264 // the (main text, not inset!) paragraph containing the cursor.
1265 // (if this paragraph contains insets etc., rebreaking will
1266 // recursively descend)
1267 if (!singlepar || pit == cursor_.bottom().pit())
1268 text->redoParagraph(pit);
1269 int y0 = text->getPar(pit).ascent() - offset_ref_;
1271 // Redo paragraphs above anchor if necessary; again, in Single Par
1272 // mode, only if we encounter the (main text) one having the cursor.
1274 while (y1 > 0 && pit1 > 0) {
1275 y1 -= text->getPar(pit1).ascent();
1277 if (!singlepar || pit1 == cursor_.bottom().pit())
1278 text->redoParagraph(pit1);
1279 y1 -= text->getPar(pit1).descent();
1283 // Take care of ascent of first line
1284 y1 -= text->getPar(pit1).ascent();
1286 // Normalize anchor for next time
1290 // Grey at the beginning is ugly
1291 if (pit1 == 0 && y1 > 0) {
1297 // Redo paragraphs below the anchor if necessary. Single par mode:
1298 // only the one containing the cursor if encountered.
1300 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1301 y2 += text->getPar(pit2).descent();
1303 if (!singlepar || pit2 == cursor_.bottom().pit())
1304 text->redoParagraph(pit2);
1305 y2 += text->getPar(pit2).ascent();
1308 // Take care of descent of last line
1309 y2 += text->getPar(pit2).descent();
1311 // The coordinates of all these paragraphs are correct, cache them
1313 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1314 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1315 Paragraph const & par = text->getPar(pit);
1317 parPos[pit] = Point(0, y);
1318 if (singlepar && pit == cursor_.bottom().pit()) {
1319 // In Single Paragraph mode, collect here the
1320 // y1 and y2 of the (one) paragraph the cursor is in
1321 y1 = y - par.ascent();
1322 y2 = y + par.descent();
1328 // collect cursor paragraph iter bounds
1329 pit1 = cursor_.bottom().pit();
1330 pit2 = cursor_.bottom().pit();
1333 lyxerr[Debug::DEBUG]
1334 << BOOST_CURRENT_FUNCTION
1337 << " pit1: " << pit1
1338 << " pit2: " << pit2
1339 << " npit: " << npit
1340 << " singlepar: " << singlepar
1344 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);