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
16 * Full author contact details are available in file CREDITS.
21 #include "BufferView_pimpl.h"
23 #include "buffer_funcs.h"
24 #include "bufferlist.h"
25 #include "bufferparams.h"
26 #include "coordcache.h"
28 #include "CutAndPaste.h"
30 #include "dispatchresult.h"
31 #include "errorlist.h"
33 #include "FloatList.h"
34 #include "funcrequest.h"
35 #include "FuncStatus.h"
38 #include "insetiterator.h"
39 #include "LaTeXFeatures.h"
40 #include "lyx_cb.h" // added for Dispatch functions
47 #include "metricsinfo.h"
48 #include "paragraph.h"
49 #include "paragraph_funcs.h"
50 #include "ParagraphParameters.h"
51 #include "pariterator.h"
56 #include "insets/insetbibtex.h"
57 #include "insets/insetref.h"
58 #include "insets/insettext.h"
60 #include "frontends/Alert.h"
61 #include "frontends/Dialogs.h"
62 #include "frontends/FileDialog.h"
63 #include "frontends/font_metrics.h"
64 #include "frontends/Gui.h"
65 #include "frontends/LyXView.h"
66 #include "frontends/Selection.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/filefilterlist.h"
72 #include "support/filetools.h"
73 #include "support/package.h"
74 #include "support/types.h"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
82 using lyx::frontend::Clipboard;
83 using lyx::frontend::Gui;
87 using lyx::support::addPath;
88 using lyx::support::bformat;
89 using lyx::support::FileFilterList;
90 using lyx::support::fileSearch;
91 using lyx::support::isDirWriteable;
92 using lyx::support::makeDisplayPath;
93 using lyx::support::makeAbsPath;
94 using lyx::support::package;
97 using std::istringstream;
102 using std::mem_fun_ref;
105 extern BufferList bufferlist;
110 unsigned int const saved_positions_num = 20;
113 /// Return an inset of this class if it exists at the current cursor position
115 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
118 DocIterator it = cur;
119 if (it.nextInset() &&
120 it.nextInset()->lyxCode() == code) {
121 inset = static_cast<T*>(it.nextInset());
129 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
130 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
132 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
148 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
150 // Get absolute path of file and add ".lyx"
151 // to the filename if necessary
152 string s = fileSearch(string(), filename, "lyx");
154 bool const found = !s.empty();
159 // File already open?
160 if (bufferlist.exists(s)) {
161 string const file = makeDisplayPath(s, 20);
162 string text = bformat(_("The document %1$s is already "
163 "loaded.\n\nDo you want to revert "
164 "to the saved version?"), file);
165 int const ret = Alert::prompt(_("Revert to saved document?"),
166 text, 0, 1, _("&Revert"), _("&Switch to document"));
169 setBuffer(bufferlist.getBuffer(s));
172 // FIXME: should be LFUN_REVERT
173 if (!bufferlist.close(bufferlist.getBuffer(s), false))
175 // Fall through to new load. (Asger)
181 b = bufferlist.newBuffer(s);
182 if (!::loadLyXFile(b, s)) {
183 bufferlist.release(b);
187 string text = bformat(_("The document %1$s does not yet "
188 "exist.\n\nDo you want to create "
189 "a new document?"), s);
190 int const ret = Alert::prompt(_("Create new document?"),
191 text, 0, 1, _("&Create"), _("Cancel"));
194 b = newFile(s, string(), true);
202 // Send the "errors" signal in case of parsing errors
205 // scroll to the position when the file was last closed
206 if (lyxrc.use_lastfilepos) {
209 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
210 // I am not sure how to separate the following part to a function
211 // so I will leave this to Lars.
213 // check pit since the document may be externally changed.
214 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
215 ParIterator it = b->par_iterator_begin();
216 ParIterator const end = b->par_iterator_end();
217 for (; it != end; ++it)
218 if (it.pit() == pit) {
219 // restored pos may be bigger than it->size
220 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
221 bv_->update(Update::FitCursor);
228 LyX::ref().session().addLastFile(b->fileName());
234 int BufferView::Pimpl::width() const
240 int BufferView::Pimpl::height() const
246 void BufferView::Pimpl::setBuffer(Buffer * b)
248 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
249 << "[ b = " << b << "]" << endl;
252 // Save the actual cursor position and anchor inside the
253 // buffer so that it can be restored in case we rechange
254 // to this buffer later on.
255 buffer_->saveCursor(cursor_.selectionBegin(),
256 cursor_.selectionEnd());
257 // current buffer is going to be switched-off, save cursor pos
258 LyX::ref().session().saveFilePosition(buffer_->fileName(),
259 boost::tie(cursor_.pit(), cursor_.pos()) );
262 // If we are closing current buffer, switch to the first in
265 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
266 << " No Buffer!" << endl;
267 // We are closing the buffer, use the first buffer as current
268 buffer_ = bufferlist.first();
269 owner_->getDialogs().hideBufferDependent();
271 // Set current buffer
276 cursor_ = LCursor(*bv_);
281 // If we're quitting lyx, don't bother updating stuff
286 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
287 << "Buffer addr: " << buffer_ << endl;
288 cursor_.push(buffer_->inset());
289 cursor_.resetAnchor();
290 buffer_->text().init(bv_);
291 buffer_->text().setCurrentFont(cursor_);
292 if (buffer_->getCursor().size() > 0 &&
293 buffer_->getAnchor().size() > 0)
295 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
296 cursor_.resetAnchor();
297 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
298 cursor_.setSelection();
301 // Buffer-dependent dialogs should be updated or
302 // hidden. This should go here because some dialogs (eg ToC)
303 // require bv_->text.
304 owner_->getDialogs().updateBufferDependent(true);
309 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
310 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
313 string BufferView::Pimpl::firstLayout()
317 // This is done after the layout combox has been populated
319 size_t i = cursor_.depth() - 1;
320 // we know we'll eventually find a paragraph
322 CursorSlice const & slice = cursor_[i];
323 if (!slice.inset().inMathed()) {
324 LyXLayout_ptr const layout = slice.paragraph().layout();
325 firstlayout = layout->name();
336 void BufferView::Pimpl::resizeCurrentBuffer()
338 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
340 owner_->message(_("Formatting document..."));
342 LyXText * text = bv_->text();
352 // Reset the "Formatting..." message
353 owner_->clearMessage();
357 void BufferView::Pimpl::updateScrollbar()
360 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
361 << " no text in updateScrollbar" << endl;
362 scrollbarParameters_.reset();
366 LyXText & t = *bv_->text();
367 int const parsize = int(t.paragraphs().size() - 1);
368 if (anchor_ref_ > parsize) {
369 anchor_ref_ = parsize;
374 << BOOST_CURRENT_FUNCTION
375 << " Updating scrollbar: height: " << t.paragraphs().size()
376 << " curr par: " << cursor_.bottom().pit()
377 << " default height " << defaultRowHeight() << endl;
379 // It would be better to fix the scrollbar to understand
380 // values in [0..1] and divide everything by wh
382 // estimated average paragraph height:
385 int h = t.getPar(anchor_ref_).height();
387 // Normalize anchor/offset (MV):
388 while (offset_ref_ > h && anchor_ref_ < parsize) {
391 h = t.getPar(anchor_ref_).height();
393 // Look at paragraph heights on-screen
396 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
399 int const h2 = t.getPar(pit).height();
403 int const hav = sumh / nh;
404 // More realistic average paragraph height
408 scrollbarParameters_.height = (parsize + 1) * wh_;
409 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
410 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
414 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
416 return scrollbarParameters_;
420 void BufferView::Pimpl::scrollDocView(int value)
422 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
423 << "[ value = " << value << "]" << endl;
428 LyXText & t = *bv_->text();
430 float const bar = value / float(wh_ * t.paragraphs().size());
432 anchor_ref_ = int(bar * t.paragraphs().size());
433 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
434 anchor_ref_ = int(t.paragraphs().size()) - 1;
435 t.redoParagraph(anchor_ref_);
436 int const h = t.getPar(anchor_ref_).height();
437 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
441 void BufferView::Pimpl::setCursorFromScrollbar()
443 LyXText & t = *bv_->text();
445 int const height = 2 * defaultRowHeight();
446 int const first = height;
447 int const last = height_ - height;
448 LCursor & cur = cursor_;
450 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
453 case bv_funcs::CUR_ABOVE:
454 t.setCursorFromCoordinates(cur, 0, first);
455 cur.clearSelection();
457 case bv_funcs::CUR_BELOW:
458 t.setCursorFromCoordinates(cur, 0, last);
459 cur.clearSelection();
461 case bv_funcs::CUR_INSIDE:
462 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
463 int const newy = min(last, max(y, first));
465 cur.reset(buffer_->inset());
466 t.setCursorFromCoordinates(cur, 0, newy);
472 void BufferView::Pimpl::scroll(int /*lines*/)
477 // LyXText const * t = bv_->text();
478 // int const line_height = defaultRowHeight();
480 // // The new absolute coordinate
481 // int new_top_y = top_y() + lines * line_height;
483 // // Restrict to a valid value
484 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
485 // new_top_y = std::max(0, new_top_y);
487 // scrollDocView(new_top_y);
489 // // Update the scrollbar.
490 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
494 void BufferView::Pimpl::selectionRequested()
501 LCursor & cur = cursor_;
503 if (!cur.selection()) {
504 xsel_cache_.set = false;
508 if (!xsel_cache_.set ||
509 cur.top() != xsel_cache_.cursor ||
510 cur.anchor_.top() != xsel_cache_.anchor)
512 xsel_cache_.cursor = cur.top();
513 xsel_cache_.anchor = cur.anchor_.top();
514 xsel_cache_.set = cur.selection();
515 sel = cur.selectionAsString(false);
517 owner_->gui().selection().put(sel);
522 void BufferView::Pimpl::selectionLost()
525 cursor_.clearSelection();
526 xsel_cache_.set = false;
531 void BufferView::Pimpl::workAreaResize(int width, int height)
533 bool const widthChange = width != width_;
534 bool const heightChange = height != height_;
536 // Update from work area
540 if (buffer_ && widthChange) {
541 // The visible LyXView need a resize
542 resizeCurrentBuffer();
545 if (widthChange || heightChange)
550 bool BufferView::Pimpl::fitCursor()
552 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
553 LyXFont const font = cursor_.getFont();
554 int const asc = font_metrics::maxAscent(font);
555 int const des = font_metrics::maxDescent(font);
556 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
557 if (p.y_ - asc >= 0 && p.y_ + des < height_)
565 bool BufferView::Pimpl::multiParSel()
567 if (!cursor_.selection())
569 bool ret = multiparsel_cache_;
570 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
571 // Either this, or previous selection spans paragraphs
572 return ret || multiparsel_cache_;
576 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
578 return metrics_info_;
582 bool BufferView::Pimpl::update(Update::flags flags)
584 // This is close to a hot-path.
585 if (lyxerr.debugging(Debug::DEBUG)) {
587 << BOOST_CURRENT_FUNCTION
588 << "[fitcursor = " << (flags & Update::FitCursor)
589 << ", forceupdate = " << (flags & Update::Force)
590 << ", singlepar = " << (flags & Update::SinglePar)
591 << "] buffer: " << buffer_ << endl;
594 // Check needed to survive LyX startup
598 // Update macro store
599 buffer_->buildMacros();
601 // First drawing step
602 updateMetrics(flags & Update::SinglePar);
604 // The second drawing step is done in WorkArea::redraw() if needed.
605 bool const need_second_step =
606 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
607 && (fitCursor() || multiParSel());
609 return need_second_step;
613 bool BufferView::Pimpl::available() const
615 return buffer_ && bv_->text();
619 Change const BufferView::Pimpl::getCurrentChange()
621 if (!buffer_->params().tracking_changes)
622 return Change(Change::UNCHANGED);
624 LyXText * text = bv_->getLyXText();
625 LCursor & cur = cursor_;
627 if (!cur.selection())
628 return Change(Change::UNCHANGED);
630 return text->getPar(cur.selBegin().pit()).
631 lookupChange(cur.selBegin().pos());
635 void BufferView::Pimpl::savePosition(unsigned int i)
637 if (i >= saved_positions_num)
639 BOOST_ASSERT(cursor_.inTexted());
640 saved_positions[i] = Position(buffer_->fileName(),
641 cursor_.paragraph().id(),
644 owner_->message(bformat(_("Saved bookmark %1$d"), i));
648 void BufferView::Pimpl::restorePosition(unsigned int i)
650 if (i >= saved_positions_num)
653 string const fname = saved_positions[i].filename;
655 cursor_.clearSelection();
657 if (fname != buffer_->fileName()) {
659 if (bufferlist.exists(fname))
660 b = bufferlist.getBuffer(fname);
662 b = bufferlist.newBuffer(fname);
663 // Don't ask, just load it
664 ::loadLyXFile(b, fname);
670 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
671 if (par == buffer_->par_iterator_end())
674 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
677 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
681 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
683 return i < saved_positions_num && !saved_positions[i].filename.empty();
687 void BufferView::Pimpl::saveSavedPositions()
689 // save bookmarks. It is better to use the pit interface
690 // but I do not know how to effectively convert between
692 for (unsigned int i=1; i < saved_positions_num; ++i) {
693 if ( isSavedPosition(i) )
694 LyX::ref().session().saveBookmark( boost::tie(
696 saved_positions[i].filename,
697 saved_positions[i].par_id,
698 saved_positions[i].par_pos) );
703 void BufferView::Pimpl::switchKeyMap()
705 if (!lyxrc.rtl_support)
708 Intl & intl = owner_->getIntl();
709 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
710 if (intl.keymap == Intl::PRIMARY)
713 if (intl.keymap == Intl::SECONDARY)
719 void BufferView::Pimpl::center()
721 CursorSlice & bot = cursor_.bottom();
722 lyx::pit_type const pit = bot.pit();
723 bot.text()->redoParagraph(pit);
724 Paragraph const & par = bot.text()->paragraphs()[pit];
726 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
727 + par.ascent() - height_ / 2;
731 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
733 BOOST_ASSERT(cursor_.inTexted());
734 string filename = filenm;
736 if (filename.empty()) {
737 // Launch a file browser
738 string initpath = lyxrc.document_path;
741 string const trypath = buffer_->filePath();
742 // If directory is writeable, use this as default.
743 if (isDirWriteable(trypath))
747 FileDialog fileDlg(_("Select LyX document to insert"),
749 make_pair(string(_("Documents|#o#O")),
750 string(lyxrc.document_path)),
751 make_pair(string(_("Examples|#E#e")),
752 string(addPath(package().system_support(), "examples"))));
754 FileDialog::Result result =
755 fileDlg.open(initpath,
756 FileFilterList(_("LyX Documents (*.lyx)")),
759 if (result.first == FileDialog::Later)
762 filename = result.second;
764 // check selected filename
765 if (filename.empty()) {
766 owner_->message(_("Canceled."));
771 // Get absolute path of file and add ".lyx"
772 // to the filename if necessary
773 filename = fileSearch(string(), filename, "lyx");
775 string const disp_fn = makeDisplayPath(filename);
776 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
779 Buffer buf("", false);
780 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
781 ErrorList & el = buffer_->errorList("Parse");
782 // Copy the inserted document error list into the current buffer one.
783 el = buf.errorList("Parse");
784 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
785 buf.params().textclass, el);
786 res = _("Document %1$s inserted.");
788 res = _("Could not insert document %1$s");
790 owner_->message(bformat(res, disp_fn));
791 buffer_->errors("Parse");
792 resizeCurrentBuffer();
796 void BufferView::Pimpl::trackChanges()
798 bool const tracking = buffer_->params().tracking_changes;
801 for_each(buffer_->par_iterator_begin(),
802 buffer_->par_iterator_end(),
803 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
804 buffer_->params().tracking_changes = true;
806 // We cannot allow undos beyond the freeze point
807 buffer_->undostack().clear();
809 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
810 if (lyx::find::findNextChange(bv_)) {
811 owner_->getDialogs().show("changes");
815 for_each(buffer_->par_iterator_begin(),
816 buffer_->par_iterator_end(),
817 mem_fun_ref(&Paragraph::untrackChanges));
819 buffer_->params().tracking_changes = false;
822 buffer_->redostack().clear();
826 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
828 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
830 // This is only called for mouse related events including
831 // LFUN_FILE_OPEN generated by drag-and-drop.
832 FuncRequest cmd = cmd0;
838 cur.push(buffer_->inset());
839 cur.selection() = cursor_.selection();
841 // Doesn't go through lyxfunc, so we need to update
842 // the layout choice etc. ourselves
844 // E.g. Qt mouse press when no buffer
848 // Either the inset under the cursor or the
849 // surrounding LyXText will handle this event.
851 // Build temporary cursor.
852 cmd.y = min(max(cmd.y, -1), height_);
853 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
854 //lyxerr << BOOST_CURRENT_FUNCTION
855 // << " * hit inset at tip: " << inset << endl;
856 //lyxerr << BOOST_CURRENT_FUNCTION
857 // << " * created temp cursor:" << cur << endl;
859 // Put anchor at the same position.
862 // Try to dispatch to an non-editable inset near this position
863 // via the temp cursor. If the inset wishes to change the real
864 // cursor it has to do so explicitly by using
865 // cur.bv().cursor() = cur; (or similar)
867 inset->dispatch(cur, cmd);
869 // Now dispatch to the temporary cursor. If the real cursor should
870 // be modified, the inset's dispatch has to do so explicitly.
871 if (!cur.result().dispatched())
874 if (cur.result().dispatched()) {
875 // Redraw if requested or necessary.
876 if (cur.result().update())
877 update(Update::FitCursor | Update::Force);
879 update(Update::FitCursor | Update::MultiParSel);
886 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
890 switch (cmd.action) {
893 flag.enabled(!buffer_->undostack().empty());
896 flag.enabled(!buffer_->redostack().empty());
898 case LFUN_FILE_INSERT:
899 case LFUN_FILE_INSERT_ASCII_PARA:
900 case LFUN_FILE_INSERT_ASCII:
901 case LFUN_BOOKMARK_SAVE:
902 // FIXME: Actually, these LFUNS should be moved to LyXText
903 flag.enabled(cursor_.inTexted());
905 case LFUN_FONT_STATE:
906 case LFUN_LABEL_INSERT:
907 case LFUN_PARAGRAPH_GOTO:
908 // FIXME handle non-trivially
909 case LFUN_OUTLINE_UP:
910 case LFUN_OUTLINE_DOWN:
911 case LFUN_OUTLINE_IN:
912 case LFUN_OUTLINE_OUT:
914 case LFUN_REFERENCE_NEXT:
916 case LFUN_WORD_REPLACE:
919 case LFUN_MARK_TOGGLE:
920 case LFUN_SCREEN_RECENTER:
921 case LFUN_BIBTEX_DATABASE_ADD:
922 case LFUN_BIBTEX_DATABASE_DEL:
923 case LFUN_WORDS_COUNT:
924 case LFUN_NEXT_INSET_TOGGLE:
928 case LFUN_LABEL_GOTO: {
929 flag.enabled(!cmd.argument.empty()
930 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
934 case LFUN_BOOKMARK_GOTO:
935 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
937 case LFUN_CHANGES_TRACK:
939 flag.setOnOff(buffer_->params().tracking_changes);
942 case LFUN_CHANGES_OUTPUT: {
943 OutputParams runparams;
944 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
945 flag.enabled(buffer_ && buffer_->params().tracking_changes
946 && features.isAvailable("dvipost"));
947 flag.setOnOff(buffer_->params().output_changes);
951 case LFUN_CHANGES_MERGE:
952 case LFUN_CHANGE_ACCEPT: // what about these two
953 case LFUN_CHANGE_REJECT: // what about these two
954 case LFUN_ALL_CHANGES_ACCEPT:
955 case LFUN_ALL_CHANGES_REJECT:
956 flag.enabled(buffer_ && buffer_->params().tracking_changes);
959 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
960 flag.setOnOff(buffer_->params().compressed);
973 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
975 //lyxerr << BOOST_CURRENT_FUNCTION
976 // << [ cmd = " << cmd << "]" << endl;
978 // Make sure that the cached BufferView is correct.
979 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
980 << " action[" << cmd.action << ']'
981 << " arg[" << cmd.argument << ']'
982 << " x[" << cmd.x << ']'
983 << " y[" << cmd.y << ']'
984 << " button[" << cmd.button() << ']'
987 LCursor & cur = cursor_;
989 switch (cmd.action) {
993 cur.message(_("Undo"));
994 cur.clearSelection();
996 cur.message(_("No further undo information"));
1004 cur.message(_("Redo"));
1005 cur.clearSelection();
1006 if (!textRedo(*bv_))
1007 cur.message(_("No further redo information"));
1013 case LFUN_FILE_INSERT:
1014 menuInsertLyXFile(cmd.argument);
1017 case LFUN_FILE_INSERT_ASCII_PARA:
1018 insertAsciiFile(bv_, cmd.argument, true);
1021 case LFUN_FILE_INSERT_ASCII:
1022 insertAsciiFile(bv_, cmd.argument, false);
1025 case LFUN_FONT_STATE:
1026 cur.message(cur.currentState());
1029 case LFUN_BOOKMARK_SAVE:
1030 savePosition(convert<unsigned int>(cmd.argument));
1033 case LFUN_BOOKMARK_GOTO:
1034 restorePosition(convert<unsigned int>(cmd.argument));
1037 case LFUN_LABEL_GOTO: {
1038 string label = cmd.argument;
1039 if (label.empty()) {
1041 getInsetByCode<InsetRef>(cursor_,
1042 InsetBase::REF_CODE);
1044 label = inset->getContents();
1050 bv_->gotoLabel(label);
1054 case LFUN_PARAGRAPH_GOTO: {
1055 int const id = convert<int>(cmd.argument);
1056 ParIterator par = buffer_->getParFromID(id);
1057 if (par == buffer_->par_iterator_end()) {
1058 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1059 << id << ']' << endl;
1062 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1063 << " found." << endl;
1067 bv_->setCursor(makeDocIterator(par, 0));
1074 case LFUN_OUTLINE_UP:
1075 lyx::toc::outline(lyx::toc::Up, cursor_);
1076 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1077 updateLabels(*buffer_);
1079 case LFUN_OUTLINE_DOWN:
1080 lyx::toc::outline(lyx::toc::Down, cursor_);
1081 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1082 updateLabels(*buffer_);
1084 case LFUN_OUTLINE_IN:
1085 lyx::toc::outline(lyx::toc::In, cursor_);
1086 updateLabels(*buffer_);
1088 case LFUN_OUTLINE_OUT:
1089 lyx::toc::outline(lyx::toc::Out, cursor_);
1090 updateLabels(*buffer_);
1093 case LFUN_NOTE_NEXT:
1094 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1097 case LFUN_REFERENCE_NEXT: {
1098 vector<InsetBase_code> tmp;
1099 tmp.push_back(InsetBase::LABEL_CODE);
1100 tmp.push_back(InsetBase::REF_CODE);
1101 bv_funcs::gotoInset(bv_, tmp, true);
1105 case LFUN_CHANGES_TRACK:
1109 case LFUN_CHANGES_OUTPUT: {
1110 bool const state = buffer_->params().output_changes;
1111 buffer_->params().output_changes = !state;
1115 case LFUN_CHANGES_MERGE:
1116 if (lyx::find::findNextChange(bv_))
1117 owner_->getDialogs().show("changes");
1120 case LFUN_ALL_CHANGES_ACCEPT: {
1121 cursor_.reset(buffer_->inset());
1122 #ifdef WITH_WARNINGS
1123 #warning FIXME changes
1125 while (lyx::find::findNextChange(bv_))
1126 bv_->getLyXText()->acceptChange(cursor_);
1131 case LFUN_ALL_CHANGES_REJECT: {
1132 cursor_.reset(buffer_->inset());
1133 #ifdef WITH_WARNINGS
1134 #warning FIXME changes
1136 while (lyx::find::findNextChange(bv_))
1137 bv_->getLyXText()->rejectChange(cursor_);
1141 case LFUN_WORD_FIND:
1142 lyx::find::find(bv_, cmd);
1145 case LFUN_WORD_REPLACE:
1146 lyx::find::replace(bv_, cmd);
1150 cur.clearSelection();
1152 cur.message(N_("Mark off"));
1156 cur.clearSelection();
1159 cur.message(N_("Mark on"));
1162 case LFUN_MARK_TOGGLE:
1163 cur.clearSelection();
1166 cur.message(N_("Mark removed"));
1169 cur.message(N_("Mark set"));
1174 case LFUN_SCREEN_RECENTER:
1178 case LFUN_BIBTEX_DATABASE_ADD: {
1179 LCursor tmpcur = cursor_;
1180 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1181 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1182 InsetBase::BIBTEX_CODE);
1184 if (inset->addDatabase(cmd.argument))
1185 buffer_->updateBibfilesCache();
1190 case LFUN_BIBTEX_DATABASE_DEL: {
1191 LCursor tmpcur = cursor_;
1192 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1193 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1194 InsetBase::BIBTEX_CODE);
1196 if (inset->delDatabase(cmd.argument))
1197 buffer_->updateBibfilesCache();
1202 case LFUN_WORDS_COUNT: {
1203 DocIterator from, to;
1204 if (cur.selection()) {
1205 from = cur.selectionBegin();
1206 to = cur.selectionEnd();
1208 from = doc_iterator_begin(buffer_->inset());
1209 to = doc_iterator_end(buffer_->inset());
1211 int const count = countWords(from, to);
1214 if (cur.selection())
1215 message = bformat(_("%1$d words in selection."),
1218 message = bformat(_("%1$d words in document."),
1222 if (cur.selection())
1223 message = _("One word in selection.");
1225 message = _("One word in document.");
1228 Alert::information(_("Count words"), message);
1232 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1233 // turn compression on/off
1234 buffer_->params().compressed = !buffer_->params().compressed;
1237 case LFUN_NEXT_INSET_TOGGLE: {
1238 // this is the real function we want to invoke
1239 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1240 // if there is an inset at cursor, see whether it
1242 InsetBase * inset = cur.nextInset();
1243 if (inset && inset->isActive()) {
1244 LCursor tmpcur = cur;
1245 tmpcur.pushLeft(*inset);
1246 inset->dispatch(tmpcur, tmpcmd);
1247 if (tmpcur.result().dispatched()) {
1251 // if it did not work, try the underlying inset.
1252 if (!cur.result().dispatched())
1253 cur.dispatch(tmpcmd);
1255 if (cur.result().dispatched())
1256 cur.clearSelection();
1269 void BufferView::Pimpl::updateMetrics(bool singlepar)
1271 // Remove old position cache
1273 BufferView & bv = *bv_;
1274 LyXText * const text = bv.text();
1275 lyx::pit_type size = int(text->paragraphs().size());
1277 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1278 anchor_ref_ = int(text->paragraphs().size() - 1);
1282 lyx::pit_type const pit = anchor_ref_;
1285 size_t const npit = text->paragraphs().size();
1287 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1288 // the (main text, not inset!) paragraph containing the cursor.
1289 // (if this paragraph contains insets etc., rebreaking will
1290 // recursively descend)
1291 if (!singlepar || pit == cursor_.bottom().pit())
1292 text->redoParagraph(pit);
1293 int y0 = text->getPar(pit).ascent() - offset_ref_;
1295 // Redo paragraphs above anchor if necessary; again, in Single Par
1296 // mode, only if we encounter the (main text) one having the cursor.
1298 while (y1 > 0 && pit1 > 0) {
1299 y1 -= text->getPar(pit1).ascent();
1301 if (!singlepar || pit1 == cursor_.bottom().pit())
1302 text->redoParagraph(pit1);
1303 y1 -= text->getPar(pit1).descent();
1307 // Take care of ascent of first line
1308 y1 -= text->getPar(pit1).ascent();
1310 // Normalize anchor for next time
1314 // Grey at the beginning is ugly
1315 if (pit1 == 0 && y1 > 0) {
1321 // Redo paragraphs below the anchor if necessary. Single par mode:
1322 // only the one containing the cursor if encountered.
1324 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1325 y2 += text->getPar(pit2).descent();
1327 if (!singlepar || pit2 == cursor_.bottom().pit())
1328 text->redoParagraph(pit2);
1329 y2 += text->getPar(pit2).ascent();
1332 // Take care of descent of last line
1333 y2 += text->getPar(pit2).descent();
1335 // The coordinates of all these paragraphs are correct, cache them
1337 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1338 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1339 Paragraph const & par = text->getPar(pit);
1341 parPos[pit] = Point(0, y);
1342 if (singlepar && pit == cursor_.bottom().pit()) {
1343 // In Single Paragraph mode, collect here the
1344 // y1 and y2 of the (one) paragraph the cursor is in
1345 y1 = y - par.ascent();
1346 y2 = y + par.descent();
1352 // collect cursor paragraph iter bounds
1353 pit1 = cursor_.bottom().pit();
1354 pit2 = cursor_.bottom().pit();
1357 lyxerr[Debug::DEBUG]
1358 << BOOST_CURRENT_FUNCTION
1361 << " pit1: " << pit1
1362 << " pit2: " << pit2
1363 << " npit: " << npit
1364 << " singlepar: " << singlepar
1368 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);