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 are closing current buffer, switch to the first in
266 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
267 << " No Buffer!" << endl;
268 // We are closing the buffer, use the first buffer as current
269 buffer_ = bufferlist.first();
271 // Set current buffer
276 cursor_ = LCursor(*bv_);
280 // If we're quitting lyx, don't bother updating stuff
285 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
286 << "Buffer addr: " << buffer_ << endl;
287 cursor_.push(buffer_->inset());
288 cursor_.resetAnchor();
289 buffer_->text().init(bv_);
290 buffer_->text().setCurrentFont(cursor_);
291 if (buffer_->getCursor().size() > 0 &&
292 buffer_->getAnchor().size() > 0)
294 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
295 cursor_.resetAnchor();
296 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
297 cursor_.setSelection();
303 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
304 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
307 string BufferView::Pimpl::firstLayout()
311 // This is done after the layout combox has been populated
313 size_t i = cursor_.depth() - 1;
314 // we know we'll eventually find a paragraph
316 CursorSlice const & slice = cursor_[i];
317 if (!slice.inset().inMathed()) {
318 LyXLayout_ptr const layout = slice.paragraph().layout();
319 firstlayout = layout->name();
330 void BufferView::Pimpl::resizeCurrentBuffer()
332 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
334 LyXText * text = bv_->text();
344 void BufferView::Pimpl::updateScrollbar()
347 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
348 << " no text in updateScrollbar" << endl;
349 scrollbarParameters_.reset();
353 LyXText & t = *bv_->text();
354 int const parsize = int(t.paragraphs().size() - 1);
355 if (anchor_ref_ > parsize) {
356 anchor_ref_ = parsize;
361 << BOOST_CURRENT_FUNCTION
362 << " Updating scrollbar: height: " << t.paragraphs().size()
363 << " curr par: " << cursor_.bottom().pit()
364 << " default height " << defaultRowHeight() << endl;
366 // It would be better to fix the scrollbar to understand
367 // values in [0..1] and divide everything by wh
369 // estimated average paragraph height:
372 int h = t.getPar(anchor_ref_).height();
374 // Normalize anchor/offset (MV):
375 while (offset_ref_ > h && anchor_ref_ < parsize) {
378 h = t.getPar(anchor_ref_).height();
380 // Look at paragraph heights on-screen
383 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
386 int const h2 = t.getPar(pit).height();
390 int const hav = sumh / nh;
391 // More realistic average paragraph height
395 scrollbarParameters_.height = (parsize + 1) * wh_;
396 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
397 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
401 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
403 return scrollbarParameters_;
407 void BufferView::Pimpl::scrollDocView(int value)
409 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
410 << "[ value = " << value << "]" << endl;
415 LyXText & t = *bv_->text();
417 float const bar = value / float(wh_ * t.paragraphs().size());
419 anchor_ref_ = int(bar * t.paragraphs().size());
420 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
421 anchor_ref_ = int(t.paragraphs().size()) - 1;
422 t.redoParagraph(anchor_ref_);
423 int const h = t.getPar(anchor_ref_).height();
424 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
428 void BufferView::Pimpl::setCursorFromScrollbar()
430 LyXText & t = *bv_->text();
432 int const height = 2 * defaultRowHeight();
433 int const first = height;
434 int const last = height_ - height;
435 LCursor & cur = cursor_;
437 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
440 case bv_funcs::CUR_ABOVE:
441 t.setCursorFromCoordinates(cur, 0, first);
442 cur.clearSelection();
444 case bv_funcs::CUR_BELOW:
445 t.setCursorFromCoordinates(cur, 0, last);
446 cur.clearSelection();
448 case bv_funcs::CUR_INSIDE:
449 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
450 int const newy = min(last, max(y, first));
452 cur.reset(buffer_->inset());
453 t.setCursorFromCoordinates(cur, 0, newy);
459 void BufferView::Pimpl::scroll(int /*lines*/)
464 // LyXText const * t = bv_->text();
465 // int const line_height = defaultRowHeight();
467 // // The new absolute coordinate
468 // int new_top_y = top_y() + lines * line_height;
470 // // Restrict to a valid value
471 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
472 // new_top_y = std::max(0, new_top_y);
474 // scrollDocView(new_top_y);
476 // // Update the scrollbar.
477 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
481 void BufferView::Pimpl::selectionRequested()
488 LCursor & cur = cursor_;
490 if (!cur.selection()) {
491 xsel_cache_.set = false;
495 if (!xsel_cache_.set ||
496 cur.top() != xsel_cache_.cursor ||
497 cur.anchor_.top() != xsel_cache_.anchor)
499 xsel_cache_.cursor = cur.top();
500 xsel_cache_.anchor = cur.anchor_.top();
501 xsel_cache_.set = cur.selection();
502 sel = cur.selectionAsString(false);
504 owner_->gui().selection().put(sel);
509 void BufferView::Pimpl::selectionLost()
512 cursor_.clearSelection();
513 xsel_cache_.set = false;
518 void BufferView::Pimpl::workAreaResize(int width, int height)
520 bool const widthChange = width != width_;
521 bool const heightChange = height != height_;
523 // Update from work area
527 if (buffer_ && widthChange) {
528 // The WorkArea content needs a resize
529 resizeCurrentBuffer();
532 if (widthChange || heightChange)
537 bool BufferView::Pimpl::fitCursor()
539 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
540 LyXFont const font = cursor_.getFont();
541 int const asc = font_metrics::maxAscent(font);
542 int const des = font_metrics::maxDescent(font);
543 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
544 if (p.y_ - asc >= 0 && p.y_ + des < height_)
552 bool BufferView::Pimpl::multiParSel()
554 if (!cursor_.selection())
556 bool ret = multiparsel_cache_;
557 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
558 // Either this, or previous selection spans paragraphs
559 return ret || multiparsel_cache_;
563 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
565 return metrics_info_;
569 bool BufferView::Pimpl::update(Update::flags flags)
571 // This is close to a hot-path.
572 if (lyxerr.debugging(Debug::DEBUG)) {
574 << BOOST_CURRENT_FUNCTION
575 << "[fitcursor = " << (flags & Update::FitCursor)
576 << ", forceupdate = " << (flags & Update::Force)
577 << ", singlepar = " << (flags & Update::SinglePar)
578 << "] buffer: " << buffer_ << endl;
581 // Check needed to survive LyX startup
585 // Update macro store
586 buffer_->buildMacros();
588 // First drawing step
589 updateMetrics(flags & Update::SinglePar);
591 // The second drawing step is done in WorkArea::redraw() if needed.
592 bool const need_second_step =
593 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
594 && (fitCursor() || multiParSel());
596 return need_second_step;
600 bool BufferView::Pimpl::available() const
602 return buffer_ && bv_->text();
606 Change const BufferView::Pimpl::getCurrentChange()
608 if (!buffer_->params().tracking_changes)
609 return Change(Change::UNCHANGED);
611 LyXText * text = bv_->getLyXText();
612 LCursor & cur = cursor_;
614 if (!cur.selection())
615 return Change(Change::UNCHANGED);
617 return text->getPar(cur.selBegin().pit()).
618 lookupChange(cur.selBegin().pos());
622 void BufferView::Pimpl::savePosition(unsigned int i)
624 if (i >= saved_positions_num)
626 BOOST_ASSERT(cursor_.inTexted());
627 saved_positions[i] = Position(buffer_->fileName(),
628 cursor_.paragraph().id(),
631 owner_->message(bformat(_("Saved bookmark %1$d"), i));
635 void BufferView::Pimpl::restorePosition(unsigned int i)
637 if (i >= saved_positions_num)
640 string const fname = saved_positions[i].filename;
642 cursor_.clearSelection();
644 if (fname != buffer_->fileName()) {
646 if (bufferlist.exists(fname))
647 b = bufferlist.getBuffer(fname);
649 b = bufferlist.newBuffer(fname);
650 // Don't ask, just load it
651 ::loadLyXFile(b, fname);
657 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
658 if (par == buffer_->par_iterator_end())
661 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
664 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
668 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
670 return i < saved_positions_num && !saved_positions[i].filename.empty();
674 void BufferView::Pimpl::saveSavedPositions()
676 // save bookmarks. It is better to use the pit interface
677 // but I do not know how to effectively convert between
679 for (unsigned int i=1; i < saved_positions_num; ++i) {
680 if ( isSavedPosition(i) )
681 LyX::ref().session().saveBookmark( boost::tie(
683 saved_positions[i].filename,
684 saved_positions[i].par_id,
685 saved_positions[i].par_pos) );
690 void BufferView::Pimpl::switchKeyMap()
692 if (!lyxrc.rtl_support)
695 Intl & intl = owner_->getIntl();
696 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
697 if (intl.keymap == Intl::PRIMARY)
700 if (intl.keymap == Intl::SECONDARY)
706 void BufferView::Pimpl::center()
708 CursorSlice & bot = cursor_.bottom();
709 lyx::pit_type const pit = bot.pit();
710 bot.text()->redoParagraph(pit);
711 Paragraph const & par = bot.text()->paragraphs()[pit];
713 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
714 + par.ascent() - height_ / 2;
718 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
720 BOOST_ASSERT(cursor_.inTexted());
721 string filename = filenm;
723 if (filename.empty()) {
724 // Launch a file browser
725 string initpath = lyxrc.document_path;
728 string const trypath = buffer_->filePath();
729 // If directory is writeable, use this as default.
730 if (isDirWriteable(trypath))
734 FileDialog fileDlg(_("Select LyX document to insert"),
736 make_pair(string(_("Documents|#o#O")),
737 string(lyxrc.document_path)),
738 make_pair(string(_("Examples|#E#e")),
739 string(addPath(package().system_support(), "examples"))));
741 FileDialog::Result result =
742 fileDlg.open(initpath,
743 FileFilterList(_("LyX Documents (*.lyx)")),
746 if (result.first == FileDialog::Later)
749 filename = result.second;
751 // check selected filename
752 if (filename.empty()) {
753 owner_->message(_("Canceled."));
758 // Get absolute path of file and add ".lyx"
759 // to the filename if necessary
760 filename = fileSearch(string(), filename, "lyx");
762 string const disp_fn = makeDisplayPath(filename);
763 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
766 Buffer buf("", false);
767 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
768 ErrorList & el = buffer_->errorList("Parse");
769 // Copy the inserted document error list into the current buffer one.
770 el = buf.errorList("Parse");
771 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
772 buf.params().textclass, el);
773 res = _("Document %1$s inserted.");
775 res = _("Could not insert document %1$s");
777 owner_->message(bformat(res, disp_fn));
778 buffer_->errors("Parse");
779 resizeCurrentBuffer();
783 void BufferView::Pimpl::trackChanges()
785 bool const tracking = buffer_->params().tracking_changes;
788 for_each(buffer_->par_iterator_begin(),
789 buffer_->par_iterator_end(),
790 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
791 buffer_->params().tracking_changes = true;
793 // We cannot allow undos beyond the freeze point
794 buffer_->undostack().clear();
796 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
797 if (lyx::find::findNextChange(bv_)) {
798 owner_->getDialogs().show("changes");
802 for_each(buffer_->par_iterator_begin(),
803 buffer_->par_iterator_end(),
804 mem_fun_ref(&Paragraph::untrackChanges));
806 buffer_->params().tracking_changes = false;
809 buffer_->redostack().clear();
813 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
815 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
817 // This is only called for mouse related events including
818 // LFUN_FILE_OPEN generated by drag-and-drop.
819 FuncRequest cmd = cmd0;
825 cur.push(buffer_->inset());
826 cur.selection() = cursor_.selection();
828 // Doesn't go through lyxfunc, so we need to update
829 // the layout choice etc. ourselves
831 // E.g. Qt mouse press when no buffer
835 // Either the inset under the cursor or the
836 // surrounding LyXText will handle this event.
838 // Build temporary cursor.
839 cmd.y = min(max(cmd.y, -1), height_);
840 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
841 //lyxerr << BOOST_CURRENT_FUNCTION
842 // << " * hit inset at tip: " << inset << endl;
843 //lyxerr << BOOST_CURRENT_FUNCTION
844 // << " * created temp cursor:" << cur << endl;
846 // Put anchor at the same position.
849 // Try to dispatch to an non-editable inset near this position
850 // via the temp cursor. If the inset wishes to change the real
851 // cursor it has to do so explicitly by using
852 // cur.bv().cursor() = cur; (or similar)
854 inset->dispatch(cur, cmd);
856 // Now dispatch to the temporary cursor. If the real cursor should
857 // be modified, the inset's dispatch has to do so explicitly.
858 if (!cur.result().dispatched())
861 if (cur.result().dispatched()) {
862 // Redraw if requested or necessary.
863 if (cur.result().update())
864 update(Update::FitCursor | Update::Force);
866 update(Update::FitCursor | Update::MultiParSel);
873 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
877 switch (cmd.action) {
880 flag.enabled(!buffer_->undostack().empty());
883 flag.enabled(!buffer_->redostack().empty());
885 case LFUN_FILE_INSERT:
886 case LFUN_FILE_INSERT_ASCII_PARA:
887 case LFUN_FILE_INSERT_ASCII:
888 case LFUN_BOOKMARK_SAVE:
889 // FIXME: Actually, these LFUNS should be moved to LyXText
890 flag.enabled(cursor_.inTexted());
892 case LFUN_FONT_STATE:
893 case LFUN_LABEL_INSERT:
894 case LFUN_PARAGRAPH_GOTO:
895 // FIXME handle non-trivially
896 case LFUN_OUTLINE_UP:
897 case LFUN_OUTLINE_DOWN:
898 case LFUN_OUTLINE_IN:
899 case LFUN_OUTLINE_OUT:
901 case LFUN_REFERENCE_NEXT:
903 case LFUN_WORD_REPLACE:
906 case LFUN_MARK_TOGGLE:
907 case LFUN_SCREEN_RECENTER:
908 case LFUN_BIBTEX_DATABASE_ADD:
909 case LFUN_BIBTEX_DATABASE_DEL:
910 case LFUN_WORDS_COUNT:
911 case LFUN_NEXT_INSET_TOGGLE:
915 case LFUN_LABEL_GOTO: {
916 flag.enabled(!cmd.argument.empty()
917 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
921 case LFUN_BOOKMARK_GOTO:
922 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
924 case LFUN_CHANGES_TRACK:
926 flag.setOnOff(buffer_->params().tracking_changes);
929 case LFUN_CHANGES_OUTPUT: {
930 OutputParams runparams;
931 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
932 flag.enabled(buffer_ && buffer_->params().tracking_changes
933 && features.isAvailable("dvipost"));
934 flag.setOnOff(buffer_->params().output_changes);
938 case LFUN_CHANGES_MERGE:
939 case LFUN_CHANGE_ACCEPT: // what about these two
940 case LFUN_CHANGE_REJECT: // what about these two
941 case LFUN_ALL_CHANGES_ACCEPT:
942 case LFUN_ALL_CHANGES_REJECT:
943 flag.enabled(buffer_ && buffer_->params().tracking_changes);
946 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
947 flag.setOnOff(buffer_->params().compressed);
960 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
962 //lyxerr << BOOST_CURRENT_FUNCTION
963 // << [ cmd = " << cmd << "]" << endl;
965 // Make sure that the cached BufferView is correct.
966 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
967 << " action[" << cmd.action << ']'
968 << " arg[" << cmd.argument << ']'
969 << " x[" << cmd.x << ']'
970 << " y[" << cmd.y << ']'
971 << " button[" << cmd.button() << ']'
974 LCursor & cur = cursor_;
976 switch (cmd.action) {
980 cur.message(_("Undo"));
981 cur.clearSelection();
983 cur.message(_("No further undo information"));
991 cur.message(_("Redo"));
992 cur.clearSelection();
994 cur.message(_("No further redo information"));
1000 case LFUN_FILE_INSERT:
1001 menuInsertLyXFile(cmd.argument);
1004 case LFUN_FILE_INSERT_ASCII_PARA:
1005 insertAsciiFile(bv_, cmd.argument, true);
1008 case LFUN_FILE_INSERT_ASCII:
1009 insertAsciiFile(bv_, cmd.argument, false);
1012 case LFUN_FONT_STATE:
1013 cur.message(cur.currentState());
1016 case LFUN_BOOKMARK_SAVE:
1017 savePosition(convert<unsigned int>(cmd.argument));
1020 case LFUN_BOOKMARK_GOTO:
1021 restorePosition(convert<unsigned int>(cmd.argument));
1024 case LFUN_LABEL_GOTO: {
1025 string label = cmd.argument;
1026 if (label.empty()) {
1028 getInsetByCode<InsetRef>(cursor_,
1029 InsetBase::REF_CODE);
1031 label = inset->getContents();
1037 bv_->gotoLabel(label);
1041 case LFUN_PARAGRAPH_GOTO: {
1042 int const id = convert<int>(cmd.argument);
1043 ParIterator par = buffer_->getParFromID(id);
1044 if (par == buffer_->par_iterator_end()) {
1045 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1046 << id << ']' << endl;
1049 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1050 << " found." << endl;
1054 bv_->setCursor(makeDocIterator(par, 0));
1061 case LFUN_OUTLINE_UP:
1062 lyx::toc::outline(lyx::toc::Up, cursor_);
1063 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1064 updateLabels(*buffer_);
1066 case LFUN_OUTLINE_DOWN:
1067 lyx::toc::outline(lyx::toc::Down, cursor_);
1068 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1069 updateLabels(*buffer_);
1071 case LFUN_OUTLINE_IN:
1072 lyx::toc::outline(lyx::toc::In, cursor_);
1073 updateLabels(*buffer_);
1075 case LFUN_OUTLINE_OUT:
1076 lyx::toc::outline(lyx::toc::Out, cursor_);
1077 updateLabels(*buffer_);
1080 case LFUN_NOTE_NEXT:
1081 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1084 case LFUN_REFERENCE_NEXT: {
1085 vector<InsetBase_code> tmp;
1086 tmp.push_back(InsetBase::LABEL_CODE);
1087 tmp.push_back(InsetBase::REF_CODE);
1088 bv_funcs::gotoInset(bv_, tmp, true);
1092 case LFUN_CHANGES_TRACK:
1096 case LFUN_CHANGES_OUTPUT: {
1097 bool const state = buffer_->params().output_changes;
1098 buffer_->params().output_changes = !state;
1102 case LFUN_CHANGES_MERGE:
1103 if (lyx::find::findNextChange(bv_))
1104 owner_->getDialogs().show("changes");
1107 case LFUN_ALL_CHANGES_ACCEPT: {
1108 cursor_.reset(buffer_->inset());
1109 #ifdef WITH_WARNINGS
1110 #warning FIXME changes
1112 while (lyx::find::findNextChange(bv_))
1113 bv_->getLyXText()->acceptChange(cursor_);
1118 case LFUN_ALL_CHANGES_REJECT: {
1119 cursor_.reset(buffer_->inset());
1120 #ifdef WITH_WARNINGS
1121 #warning FIXME changes
1123 while (lyx::find::findNextChange(bv_))
1124 bv_->getLyXText()->rejectChange(cursor_);
1128 case LFUN_WORD_FIND:
1129 lyx::find::find(bv_, cmd);
1132 case LFUN_WORD_REPLACE:
1133 lyx::find::replace(bv_, cmd);
1137 cur.clearSelection();
1139 cur.message(N_("Mark off"));
1143 cur.clearSelection();
1146 cur.message(N_("Mark on"));
1149 case LFUN_MARK_TOGGLE:
1150 cur.clearSelection();
1153 cur.message(N_("Mark removed"));
1156 cur.message(N_("Mark set"));
1161 case LFUN_SCREEN_RECENTER:
1165 case LFUN_BIBTEX_DATABASE_ADD: {
1166 LCursor tmpcur = cursor_;
1167 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1168 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1169 InsetBase::BIBTEX_CODE);
1171 if (inset->addDatabase(cmd.argument))
1172 buffer_->updateBibfilesCache();
1177 case LFUN_BIBTEX_DATABASE_DEL: {
1178 LCursor tmpcur = cursor_;
1179 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1180 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1181 InsetBase::BIBTEX_CODE);
1183 if (inset->delDatabase(cmd.argument))
1184 buffer_->updateBibfilesCache();
1189 case LFUN_WORDS_COUNT: {
1190 DocIterator from, to;
1191 if (cur.selection()) {
1192 from = cur.selectionBegin();
1193 to = cur.selectionEnd();
1195 from = doc_iterator_begin(buffer_->inset());
1196 to = doc_iterator_end(buffer_->inset());
1198 int const count = countWords(from, to);
1201 if (cur.selection())
1202 message = bformat(_("%1$d words in selection."),
1205 message = bformat(_("%1$d words in document."),
1209 if (cur.selection())
1210 message = _("One word in selection.");
1212 message = _("One word in document.");
1215 Alert::information(_("Count words"), message);
1219 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1220 // turn compression on/off
1221 buffer_->params().compressed = !buffer_->params().compressed;
1224 case LFUN_NEXT_INSET_TOGGLE: {
1225 // this is the real function we want to invoke
1226 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1227 // if there is an inset at cursor, see whether it
1229 InsetBase * inset = cur.nextInset();
1230 if (inset && inset->isActive()) {
1231 LCursor tmpcur = cur;
1232 tmpcur.pushLeft(*inset);
1233 inset->dispatch(tmpcur, tmpcmd);
1234 if (tmpcur.result().dispatched()) {
1238 // if it did not work, try the underlying inset.
1239 if (!cur.result().dispatched())
1240 cur.dispatch(tmpcmd);
1242 if (cur.result().dispatched())
1243 cur.clearSelection();
1256 void BufferView::Pimpl::updateMetrics(bool singlepar)
1258 // Remove old position cache
1260 BufferView & bv = *bv_;
1261 LyXText * const text = bv.text();
1262 lyx::pit_type size = int(text->paragraphs().size());
1264 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1265 anchor_ref_ = int(text->paragraphs().size() - 1);
1269 lyx::pit_type const pit = anchor_ref_;
1272 size_t const npit = text->paragraphs().size();
1274 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1275 // the (main text, not inset!) paragraph containing the cursor.
1276 // (if this paragraph contains insets etc., rebreaking will
1277 // recursively descend)
1278 if (!singlepar || pit == cursor_.bottom().pit())
1279 text->redoParagraph(pit);
1280 int y0 = text->getPar(pit).ascent() - offset_ref_;
1282 // Redo paragraphs above anchor if necessary; again, in Single Par
1283 // mode, only if we encounter the (main text) one having the cursor.
1285 while (y1 > 0 && pit1 > 0) {
1286 y1 -= text->getPar(pit1).ascent();
1288 if (!singlepar || pit1 == cursor_.bottom().pit())
1289 text->redoParagraph(pit1);
1290 y1 -= text->getPar(pit1).descent();
1294 // Take care of ascent of first line
1295 y1 -= text->getPar(pit1).ascent();
1297 // Normalize anchor for next time
1301 // Grey at the beginning is ugly
1302 if (pit1 == 0 && y1 > 0) {
1308 // Redo paragraphs below the anchor if necessary. Single par mode:
1309 // only the one containing the cursor if encountered.
1311 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1312 y2 += text->getPar(pit2).descent();
1314 if (!singlepar || pit2 == cursor_.bottom().pit())
1315 text->redoParagraph(pit2);
1316 y2 += text->getPar(pit2).ascent();
1319 // Take care of descent of last line
1320 y2 += text->getPar(pit2).descent();
1322 // The coordinates of all these paragraphs are correct, cache them
1324 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1325 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1326 Paragraph const & par = text->getPar(pit);
1328 parPos[pit] = Point(0, y);
1329 if (singlepar && pit == cursor_.bottom().pit()) {
1330 // In Single Paragraph mode, collect here the
1331 // y1 and y2 of the (one) paragraph the cursor is in
1332 y1 = y - par.ascent();
1333 y2 = y + par.descent();
1339 // collect cursor paragraph iter bounds
1340 pit1 = cursor_.bottom().pit();
1341 pit2 = cursor_.bottom().pit();
1344 lyxerr[Debug::DEBUG]
1345 << BOOST_CURRENT_FUNCTION
1348 << " pit1: " << pit1
1349 << " pit2: " << pit2
1350 << " npit: " << npit
1351 << " singlepar: " << singlepar
1355 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);