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"
32 #include "FloatList.h"
33 #include "funcrequest.h"
34 #include "FuncStatus.h"
37 #include "insetiterator.h"
38 #include "LaTeXFeatures.h"
39 #include "lyx_cb.h" // added for Dispatch functions
46 #include "metricsinfo.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetref.h"
57 #include "insets/insettext.h"
59 #include "frontends/Alert.h"
60 #include "frontends/Dialogs.h"
61 #include "frontends/FileDialog.h"
62 #include "frontends/font_metrics.h"
63 #include "frontends/Gui.h"
64 #include "frontends/LyXView.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/filefilterlist.h"
71 #include "support/filetools.h"
72 #include "support/package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
81 using lyx::frontend::Clipboard;
82 using lyx::frontend::Gui;
86 using lyx::support::addPath;
87 using lyx::support::bformat;
88 using lyx::support::FileFilterList;
89 using lyx::support::fileSearch;
90 using lyx::support::isDirWriteable;
91 using lyx::support::makeDisplayPath;
92 using lyx::support::makeAbsPath;
93 using lyx::support::package;
96 using std::istringstream;
101 using std::mem_fun_ref;
104 extern BufferList bufferlist;
109 unsigned int const saved_positions_num = 20;
112 /// Return an inset of this class if it exists at the current cursor position
114 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
117 DocIterator it = cur;
118 if (it.nextInset() &&
119 it.nextInset()->lyxCode() == code) {
120 inset = static_cast<T*>(it.nextInset());
128 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
129 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
131 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
133 xsel_cache_.set = false;
135 saved_positions.resize(saved_positions_num);
136 // load saved bookmarks
137 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
138 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
139 bm != bmList.end(); ++bm)
140 if (bm->get<0>() < saved_positions_num)
141 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
142 // and then clear them
147 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
149 // Get absolute path of file and add ".lyx"
150 // to the filename if necessary
151 string s = fileSearch(string(), filename, "lyx");
153 bool const found = !s.empty();
158 // File already open?
159 if (bufferlist.exists(s)) {
160 string const file = makeDisplayPath(s, 20);
161 string text = bformat(_("The document %1$s is already "
162 "loaded.\n\nDo you want to revert "
163 "to the saved version?"), file);
164 int const ret = Alert::prompt(_("Revert to saved document?"),
165 text, 0, 1, _("&Revert"), _("&Switch to document"));
168 setBuffer(bufferlist.getBuffer(s));
171 // FIXME: should be LFUN_REVERT
172 if (!bufferlist.close(bufferlist.getBuffer(s), false))
174 // Fall through to new load. (Asger)
180 b = bufferlist.newBuffer(s);
181 if (!::loadLyXFile(b, s)) {
182 bufferlist.release(b);
186 string text = bformat(_("The document %1$s does not yet "
187 "exist.\n\nDo you want to create "
188 "a new document?"), s);
189 int const ret = Alert::prompt(_("Create new document?"),
190 text, 0, 1, _("&Create"), _("Cancel"));
193 b = newFile(s, string(), true);
201 owner_->showErrorList(_("Parse"));
203 // scroll to the position when the file was last closed
204 if (lyxrc.use_lastfilepos) {
207 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
208 // I am not sure how to separate the following part to a function
209 // so I will leave this to Lars.
211 // check pit since the document may be externally changed.
212 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
213 ParIterator it = b->par_iterator_begin();
214 ParIterator const end = b->par_iterator_end();
215 for (; it != end; ++it)
216 if (it.pit() == pit) {
217 // restored pos may be bigger than it->size
218 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
219 bv_->update(Update::FitCursor);
226 LyX::ref().session().addLastFile(b->fileName());
232 lyx::frontend::Gui & BufferView::Pimpl::gui() const
234 return owner_->gui();
238 int BufferView::Pimpl::width() const
244 int BufferView::Pimpl::height() const
250 void BufferView::Pimpl::setBuffer(Buffer * b)
252 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
253 << "[ b = " << b << "]" << endl;
256 // Save the actual cursor position and anchor inside the
257 // buffer so that it can be restored in case we rechange
258 // to this buffer later on.
259 buffer_->saveCursor(cursor_.selectionBegin(),
260 cursor_.selectionEnd());
261 // current buffer is going to be switched-off, save cursor pos
262 LyX::ref().session().saveFilePosition(buffer_->fileName(),
263 boost::tie(cursor_.pit(), cursor_.pos()) );
266 // If we are closing current buffer, switch to the first in
269 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
270 << " No Buffer!" << endl;
271 // We are closing the buffer, use the first buffer as current
272 buffer_ = bufferlist.first();
273 owner_->getDialogs().hideBufferDependent();
275 // Set current buffer
280 cursor_ = LCursor(*bv_);
285 // If we're quitting lyx, don't bother updating stuff
290 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
291 << "Buffer addr: " << buffer_ << endl;
292 cursor_.push(buffer_->inset());
293 cursor_.resetAnchor();
294 buffer_->text().init(bv_);
295 buffer_->text().setCurrentFont(cursor_);
296 if (buffer_->getCursor().size() > 0 &&
297 buffer_->getAnchor().size() > 0)
299 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
300 cursor_.resetAnchor();
301 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
302 cursor_.setSelection();
305 // Buffer-dependent dialogs should be updated or
306 // hidden. This should go here because some dialogs (eg ToC)
307 // require bv_->text.
308 owner_->getDialogs().updateBufferDependent(true);
313 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
314 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
317 string BufferView::Pimpl::firstLayout()
321 // This is done after the layout combox has been populated
323 size_t i = cursor_.depth() - 1;
324 // we know we'll eventually find a paragraph
326 CursorSlice const & slice = cursor_[i];
327 if (!slice.inset().inMathed()) {
328 LyXLayout_ptr const layout = slice.paragraph().layout();
329 firstlayout = layout->name();
340 void BufferView::Pimpl::resizeCurrentBuffer()
342 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
344 owner_->message(_("Formatting document..."));
346 LyXText * text = bv_->text();
356 // Reset the "Formatting..." message
357 owner_->clearMessage();
361 void BufferView::Pimpl::updateScrollbar()
364 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
365 << " no text in updateScrollbar" << endl;
366 scrollbarParameters_.reset();
370 LyXText & t = *bv_->text();
371 int const parsize = int(t.paragraphs().size() - 1);
372 if (anchor_ref_ > parsize) {
373 anchor_ref_ = parsize;
378 << BOOST_CURRENT_FUNCTION
379 << " Updating scrollbar: height: " << t.paragraphs().size()
380 << " curr par: " << cursor_.bottom().pit()
381 << " default height " << defaultRowHeight() << endl;
383 // It would be better to fix the scrollbar to understand
384 // values in [0..1] and divide everything by wh
386 // estimated average paragraph height:
389 int h = t.getPar(anchor_ref_).height();
391 // Normalize anchor/offset (MV):
392 while (offset_ref_ > h && anchor_ref_ < parsize) {
395 h = t.getPar(anchor_ref_).height();
397 // Look at paragraph heights on-screen
400 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
403 int const h2 = t.getPar(pit).height();
407 int const hav = sumh / nh;
408 // More realistic average paragraph height
412 scrollbarParameters_.height = (parsize + 1) * wh_;
413 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
414 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
418 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
420 return scrollbarParameters_;
424 void BufferView::Pimpl::scrollDocView(int value)
426 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
427 << "[ value = " << value << "]" << endl;
432 LyXText & t = *bv_->text();
434 float const bar = value / float(wh_ * t.paragraphs().size());
436 anchor_ref_ = int(bar * t.paragraphs().size());
437 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
438 anchor_ref_ = int(t.paragraphs().size()) - 1;
439 t.redoParagraph(anchor_ref_);
440 int const h = t.getPar(anchor_ref_).height();
441 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
444 if (!lyxrc.cursor_follows_scrollbar)
447 int const height = 2 * defaultRowHeight();
448 int const first = height;
449 int const last = height_ - height;
450 LCursor & cur = cursor_;
452 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
455 case bv_funcs::CUR_ABOVE:
456 t.setCursorFromCoordinates(cur, 0, first);
457 cur.clearSelection();
459 case bv_funcs::CUR_BELOW:
460 t.setCursorFromCoordinates(cur, 0, last);
461 cur.clearSelection();
463 case bv_funcs::CUR_INSIDE:
464 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
465 int const newy = min(last, max(y, first));
467 cur.reset(buffer_->inset());
468 t.setCursorFromCoordinates(cur, 0, newy);
471 owner_->updateLayoutChoice();
475 void BufferView::Pimpl::scroll(int /*lines*/)
480 // LyXText const * t = bv_->text();
481 // int const line_height = defaultRowHeight();
483 // // The new absolute coordinate
484 // int new_top_y = top_y() + lines * line_height;
486 // // Restrict to a valid value
487 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
488 // new_top_y = std::max(0, new_top_y);
490 // scrollDocView(new_top_y);
492 // // Update the scrollbar.
493 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
497 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
498 key_modifier::state state)
500 owner_->getLyXFunc().processKeySym(key, state);
504 void BufferView::Pimpl::selectionRequested()
511 LCursor & cur = cursor_;
513 if (!cur.selection()) {
514 xsel_cache_.set = false;
518 if (!xsel_cache_.set ||
519 cur.top() != xsel_cache_.cursor ||
520 cur.anchor_.top() != xsel_cache_.anchor)
522 xsel_cache_.cursor = cur.top();
523 xsel_cache_.anchor = cur.anchor_.top();
524 xsel_cache_.set = cur.selection();
525 sel = cur.selectionAsString(false);
527 owner_->gui().selection().put(sel);
532 void BufferView::Pimpl::selectionLost()
535 cursor_.clearSelection();
536 xsel_cache_.set = false;
541 void BufferView::Pimpl::workAreaResize(int width, int height)
543 bool const widthChange = width != width_;
544 bool const heightChange = height != height_;
546 // Update from work area
550 if (buffer_ && widthChange) {
551 // The visible LyXView need a resize
552 resizeCurrentBuffer();
555 if (widthChange || heightChange)
558 owner_->updateLayoutChoice();
562 bool BufferView::Pimpl::fitCursor()
564 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
565 LyXFont const font = cursor_.getFont();
566 int const asc = font_metrics::maxAscent(font);
567 int const des = font_metrics::maxDescent(font);
568 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
569 if (p.y_ - asc >= 0 && p.y_ + des < height_)
577 bool BufferView::Pimpl::multiParSel()
579 if (!cursor_.selection())
581 bool ret = multiparsel_cache_;
582 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
583 // Either this, or previous selection spans paragraphs
584 return ret || multiparsel_cache_;
588 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
590 return metrics_info_;
594 bool BufferView::Pimpl::update(Update::flags flags)
596 // This is close to a hot-path.
597 if (lyxerr.debugging(Debug::DEBUG)) {
599 << BOOST_CURRENT_FUNCTION
600 << "[fitcursor = " << (flags & Update::FitCursor)
601 << ", forceupdate = " << (flags & Update::Force)
602 << ", singlepar = " << (flags & Update::SinglePar)
603 << "] buffer: " << buffer_ << endl;
606 // Check needed to survive LyX startup
610 // Update macro store
611 buffer_->buildMacros();
613 // First drawing step
614 updateMetrics(flags & Update::SinglePar);
616 // The second drawing step is done in WorkArea::redraw() if needed.
617 bool const need_second_step =
618 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
619 && (fitCursor() || multiParSel());
621 return need_second_step;
625 bool BufferView::Pimpl::available() const
627 return buffer_ && bv_->text();
631 Change const BufferView::Pimpl::getCurrentChange()
633 if (!buffer_->params().tracking_changes)
634 return Change(Change::UNCHANGED);
636 LyXText * text = bv_->getLyXText();
637 LCursor & cur = cursor_;
639 if (!cur.selection())
640 return Change(Change::UNCHANGED);
642 return text->getPar(cur.selBegin().pit()).
643 lookupChange(cur.selBegin().pos());
647 void BufferView::Pimpl::savePosition(unsigned int i)
649 if (i >= saved_positions_num)
651 BOOST_ASSERT(cursor_.inTexted());
652 saved_positions[i] = Position(buffer_->fileName(),
653 cursor_.paragraph().id(),
656 owner_->message(bformat(_("Saved bookmark %1$d"), i));
660 void BufferView::Pimpl::restorePosition(unsigned int i)
662 if (i >= saved_positions_num)
665 string const fname = saved_positions[i].filename;
667 cursor_.clearSelection();
669 if (fname != buffer_->fileName()) {
671 if (bufferlist.exists(fname))
672 b = bufferlist.getBuffer(fname);
674 b = bufferlist.newBuffer(fname);
675 // Don't ask, just load it
676 ::loadLyXFile(b, fname);
682 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
683 if (par == buffer_->par_iterator_end())
686 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
689 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
693 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
695 return i < saved_positions_num && !saved_positions[i].filename.empty();
699 void BufferView::Pimpl::saveSavedPositions()
701 // save bookmarks. It is better to use the pit interface
702 // but I do not know how to effectively convert between
704 for (unsigned int i=1; i < saved_positions_num; ++i) {
705 if ( isSavedPosition(i) )
706 LyX::ref().session().saveBookmark( boost::tie(
708 saved_positions[i].filename,
709 saved_positions[i].par_id,
710 saved_positions[i].par_pos) );
715 void BufferView::Pimpl::switchKeyMap()
717 if (!lyxrc.rtl_support)
720 Intl & intl = owner_->getIntl();
721 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
722 if (intl.keymap == Intl::PRIMARY)
725 if (intl.keymap == Intl::SECONDARY)
731 void BufferView::Pimpl::center()
733 CursorSlice & bot = cursor_.bottom();
734 lyx::pit_type const pit = bot.pit();
735 bot.text()->redoParagraph(pit);
736 Paragraph const & par = bot.text()->paragraphs()[pit];
738 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
739 + par.ascent() - height_ / 2;
743 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
745 BOOST_ASSERT(cursor_.inTexted());
746 string filename = filenm;
748 if (filename.empty()) {
749 // Launch a file browser
750 string initpath = lyxrc.document_path;
753 string const trypath = buffer_->filePath();
754 // If directory is writeable, use this as default.
755 if (isDirWriteable(trypath))
759 FileDialog fileDlg(_("Select LyX document to insert"),
761 make_pair(string(_("Documents|#o#O")),
762 string(lyxrc.document_path)),
763 make_pair(string(_("Examples|#E#e")),
764 string(addPath(package().system_support(), "examples"))));
766 FileDialog::Result result =
767 fileDlg.open(initpath,
768 FileFilterList(_("LyX Documents (*.lyx)")),
771 if (result.first == FileDialog::Later)
774 filename = result.second;
776 // check selected filename
777 if (filename.empty()) {
778 owner_->message(_("Canceled."));
783 // Get absolute path of file and add ".lyx"
784 // to the filename if necessary
785 filename = fileSearch(string(), filename, "lyx");
787 string const disp_fn = makeDisplayPath(filename);
788 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
791 Buffer buf("", false);
792 // FIXME: is there a need for something like that?
793 //buf.errors.connect(boost::bind(&LyXView::showErrorList, owner_, _1));
794 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
795 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
796 buf.params().textclass);
797 res = _("Document %1$s inserted.");
799 res = _("Could not insert document %1$s");
801 owner_->message(bformat(res, disp_fn));
802 owner_->showErrorList(_("Document insertion"));
803 resizeCurrentBuffer();
807 void BufferView::Pimpl::trackChanges()
809 bool const tracking = buffer_->params().tracking_changes;
812 for_each(buffer_->par_iterator_begin(),
813 buffer_->par_iterator_end(),
814 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
815 buffer_->params().tracking_changes = true;
817 // We cannot allow undos beyond the freeze point
818 buffer_->undostack().clear();
820 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
821 if (lyx::find::findNextChange(bv_)) {
822 owner_->getDialogs().show("changes");
826 for_each(buffer_->par_iterator_begin(),
827 buffer_->par_iterator_end(),
828 mem_fun_ref(&Paragraph::untrackChanges));
830 buffer_->params().tracking_changes = false;
833 buffer_->redostack().clear();
837 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
839 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
841 // This is only called for mouse related events including
842 // LFUN_FILE_OPEN generated by drag-and-drop.
843 FuncRequest cmd = cmd0;
846 if (cmd.action == LFUN_FILE_OPEN) {
847 owner_->dispatch(cmd);
855 cur.push(buffer_->inset());
856 cur.selection() = cursor_.selection();
858 // Doesn't go through lyxfunc, so we need to update
859 // the layout choice etc. ourselves
861 // E.g. Qt mouse press when no buffer
865 // Either the inset under the cursor or the
866 // surrounding LyXText will handle this event.
868 // Build temporary cursor.
869 cmd.y = min(max(cmd.y, -1), height_);
870 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
871 //lyxerr << BOOST_CURRENT_FUNCTION
872 // << " * hit inset at tip: " << inset << endl;
873 //lyxerr << BOOST_CURRENT_FUNCTION
874 // << " * created temp cursor:" << cur << endl;
876 // Put anchor at the same position.
879 // Try to dispatch to an non-editable inset near this position
880 // via the temp cursor. If the inset wishes to change the real
881 // cursor it has to do so explicitly by using
882 // cur.bv().cursor() = cur; (or similar)
884 inset->dispatch(cur, cmd);
886 // Now dispatch to the temporary cursor. If the real cursor should
887 // be modified, the inset's dispatch has to do so explicitly.
888 if (!cur.result().dispatched())
891 if (cur.result().dispatched()) {
892 // Redraw if requested or necessary.
893 if (cur.result().update())
894 update(Update::FitCursor | Update::Force);
896 update(Update::FitCursor | Update::MultiParSel);
899 // Skip these when selecting
900 if (cmd.action != LFUN_MOUSE_MOTION) {
901 owner_->updateLayoutChoice();
902 owner_->updateToolbars();
905 // Slight hack: this is only called currently when we
906 // clicked somewhere, so we force through the display
907 // of the new status here.
908 owner_->clearMessage();
913 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
917 switch (cmd.action) {
920 flag.enabled(!buffer_->undostack().empty());
923 flag.enabled(!buffer_->redostack().empty());
925 case LFUN_FILE_INSERT:
926 case LFUN_FILE_INSERT_ASCII_PARA:
927 case LFUN_FILE_INSERT_ASCII:
928 case LFUN_BOOKMARK_SAVE:
929 // FIXME: Actually, these LFUNS should be moved to LyXText
930 flag.enabled(cursor_.inTexted());
932 case LFUN_FONT_STATE:
933 case LFUN_LABEL_INSERT:
934 case LFUN_PARAGRAPH_GOTO:
935 // FIXME handle non-trivially
936 case LFUN_OUTLINE_UP:
937 case LFUN_OUTLINE_DOWN:
938 case LFUN_OUTLINE_IN:
939 case LFUN_OUTLINE_OUT:
940 case LFUN_ERROR_NEXT:
942 case LFUN_REFERENCE_NEXT:
944 case LFUN_WORD_REPLACE:
947 case LFUN_MARK_TOGGLE:
948 case LFUN_SCREEN_RECENTER:
949 case LFUN_BIBTEX_DATABASE_ADD:
950 case LFUN_BIBTEX_DATABASE_DEL:
951 case LFUN_WORDS_COUNT:
955 case LFUN_LABEL_GOTO: {
956 flag.enabled(!cmd.argument.empty()
957 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
961 case LFUN_BOOKMARK_GOTO:
962 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
964 case LFUN_CHANGES_TRACK:
966 flag.setOnOff(buffer_->params().tracking_changes);
969 case LFUN_CHANGES_OUTPUT: {
970 OutputParams runparams;
971 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
972 flag.enabled(buffer_ && buffer_->params().tracking_changes
973 && features.isAvailable("dvipost"));
974 flag.setOnOff(buffer_->params().output_changes);
978 case LFUN_CHANGES_MERGE:
979 case LFUN_CHANGE_ACCEPT: // what about these two
980 case LFUN_CHANGE_REJECT: // what about these two
981 case LFUN_ALL_CHANGES_ACCEPT:
982 case LFUN_ALL_CHANGES_REJECT:
983 flag.enabled(buffer_ && buffer_->params().tracking_changes);
986 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
987 flag.setOnOff(buffer_->params().compressed);
1000 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1002 //lyxerr << BOOST_CURRENT_FUNCTION
1003 // << [ cmd = " << cmd << "]" << endl;
1005 // Make sure that the cached BufferView is correct.
1006 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1007 << " action[" << cmd.action << ']'
1008 << " arg[" << cmd.argument << ']'
1009 << " x[" << cmd.x << ']'
1010 << " y[" << cmd.y << ']'
1011 << " button[" << cmd.button() << ']'
1014 LCursor & cur = cursor_;
1016 switch (cmd.action) {
1020 cur.message(_("Undo"));
1021 cur.clearSelection();
1022 if (!textUndo(*bv_))
1023 cur.message(_("No further undo information"));
1031 cur.message(_("Redo"));
1032 cur.clearSelection();
1033 if (!textRedo(*bv_))
1034 cur.message(_("No further redo information"));
1040 case LFUN_FILE_INSERT:
1041 menuInsertLyXFile(cmd.argument);
1044 case LFUN_FILE_INSERT_ASCII_PARA:
1045 insertAsciiFile(bv_, cmd.argument, true);
1048 case LFUN_FILE_INSERT_ASCII:
1049 insertAsciiFile(bv_, cmd.argument, false);
1052 case LFUN_FONT_STATE:
1053 cur.message(cur.currentState());
1056 case LFUN_BOOKMARK_SAVE:
1057 savePosition(convert<unsigned int>(cmd.argument));
1060 case LFUN_BOOKMARK_GOTO:
1061 restorePosition(convert<unsigned int>(cmd.argument));
1064 case LFUN_LABEL_GOTO: {
1065 string label = cmd.argument;
1066 if (label.empty()) {
1068 getInsetByCode<InsetRef>(cursor_,
1069 InsetBase::REF_CODE);
1071 label = inset->getContents();
1077 bv_->gotoLabel(label);
1081 case LFUN_PARAGRAPH_GOTO: {
1082 int const id = convert<int>(cmd.argument);
1083 ParIterator par = buffer_->getParFromID(id);
1084 if (par == buffer_->par_iterator_end()) {
1085 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1086 << id << ']' << endl;
1089 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1090 << " found." << endl;
1094 bv_->setCursor(makeDocIterator(par, 0));
1101 case LFUN_OUTLINE_UP:
1102 lyx::toc::outline(lyx::toc::Up, cursor_);
1103 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1104 updateLabels(*buffer_);
1106 case LFUN_OUTLINE_DOWN:
1107 lyx::toc::outline(lyx::toc::Down, cursor_);
1108 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1109 updateLabels(*buffer_);
1111 case LFUN_OUTLINE_IN:
1112 lyx::toc::outline(lyx::toc::In, cursor_);
1113 updateLabels(*buffer_);
1115 case LFUN_OUTLINE_OUT:
1116 lyx::toc::outline(lyx::toc::Out, cursor_);
1117 updateLabels(*buffer_);
1120 case LFUN_ERROR_NEXT:
1121 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1124 case LFUN_NOTE_NEXT:
1125 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1128 case LFUN_REFERENCE_NEXT: {
1129 vector<InsetBase_code> tmp;
1130 tmp.push_back(InsetBase::LABEL_CODE);
1131 tmp.push_back(InsetBase::REF_CODE);
1132 bv_funcs::gotoInset(bv_, tmp, true);
1136 case LFUN_CHANGES_TRACK:
1140 case LFUN_CHANGES_OUTPUT: {
1141 bool const state = buffer_->params().output_changes;
1142 buffer_->params().output_changes = !state;
1146 case LFUN_CHANGES_MERGE:
1147 if (lyx::find::findNextChange(bv_))
1148 owner_->getDialogs().show("changes");
1151 case LFUN_ALL_CHANGES_ACCEPT: {
1152 cursor_.reset(buffer_->inset());
1153 #ifdef WITH_WARNINGS
1154 #warning FIXME changes
1156 while (lyx::find::findNextChange(bv_))
1157 bv_->getLyXText()->acceptChange(cursor_);
1162 case LFUN_ALL_CHANGES_REJECT: {
1163 cursor_.reset(buffer_->inset());
1164 #ifdef WITH_WARNINGS
1165 #warning FIXME changes
1167 while (lyx::find::findNextChange(bv_))
1168 bv_->getLyXText()->rejectChange(cursor_);
1172 case LFUN_WORD_FIND:
1173 lyx::find::find(bv_, cmd);
1176 case LFUN_WORD_REPLACE:
1177 lyx::find::replace(bv_, cmd);
1181 cur.clearSelection();
1183 cur.message(N_("Mark off"));
1187 cur.clearSelection();
1190 cur.message(N_("Mark on"));
1193 case LFUN_MARK_TOGGLE:
1194 cur.clearSelection();
1197 cur.message(N_("Mark removed"));
1200 cur.message(N_("Mark set"));
1205 case LFUN_SCREEN_RECENTER:
1209 case LFUN_BIBTEX_DATABASE_ADD: {
1210 LCursor tmpcur = cursor_;
1211 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1212 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1213 InsetBase::BIBTEX_CODE);
1215 if (inset->addDatabase(cmd.argument))
1216 buffer_->updateBibfilesCache();
1221 case LFUN_BIBTEX_DATABASE_DEL: {
1222 LCursor tmpcur = cursor_;
1223 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1224 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1225 InsetBase::BIBTEX_CODE);
1227 if (inset->delDatabase(cmd.argument))
1228 buffer_->updateBibfilesCache();
1233 case LFUN_WORDS_COUNT: {
1234 DocIterator from, to;
1235 if (cur.selection()) {
1236 from = cur.selectionBegin();
1237 to = cur.selectionEnd();
1239 from = doc_iterator_begin(buffer_->inset());
1240 to = doc_iterator_end(buffer_->inset());
1242 int const count = countWords(from, to);
1245 if (cur.selection())
1246 message = bformat(_("%1$d words in selection."),
1249 message = bformat(_("%1$d words in document."),
1253 if (cur.selection())
1254 message = _("One word in selection.");
1256 message = _("One word in document.");
1259 Alert::information(_("Count words"), message);
1263 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1264 // turn compression on/off
1265 buffer_->params().compressed = !buffer_->params().compressed;
1276 void BufferView::Pimpl::updateMetrics(bool singlepar)
1278 // Remove old position cache
1280 BufferView & bv = *bv_;
1281 LyXText * const text = bv.text();
1282 lyx::pit_type size = int(text->paragraphs().size());
1284 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1285 anchor_ref_ = int(text->paragraphs().size() - 1);
1289 lyx::pit_type const pit = anchor_ref_;
1292 size_t const npit = text->paragraphs().size();
1294 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1295 // the (main text, not inset!) paragraph containing the cursor.
1296 // (if this paragraph contains insets etc., rebreaking will
1297 // recursively descend)
1298 if (!singlepar || pit == cursor_.bottom().pit())
1299 text->redoParagraph(pit);
1300 int y0 = text->getPar(pit).ascent() - offset_ref_;
1302 // Redo paragraphs above anchor if necessary; again, in Single Par
1303 // mode, only if we encounter the (main text) one having the cursor.
1305 while (y1 > 0 && pit1 > 0) {
1306 y1 -= text->getPar(pit1).ascent();
1308 if (!singlepar || pit1 == cursor_.bottom().pit())
1309 text->redoParagraph(pit1);
1310 y1 -= text->getPar(pit1).descent();
1314 // Take care of ascent of first line
1315 y1 -= text->getPar(pit1).ascent();
1317 // Normalize anchor for next time
1321 // Grey at the beginning is ugly
1322 if (pit1 == 0 && y1 > 0) {
1328 // Redo paragraphs below the anchor if necessary. Single par mode:
1329 // only the one containing the cursor if encountered.
1331 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1332 y2 += text->getPar(pit2).descent();
1334 if (!singlepar || pit2 == cursor_.bottom().pit())
1335 text->redoParagraph(pit2);
1336 y2 += text->getPar(pit2).ascent();
1339 // Take care of descent of last line
1340 y2 += text->getPar(pit2).descent();
1342 // The coordinates of all these paragraphs are correct, cache them
1344 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1345 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1346 Paragraph const & par = text->getPar(pit);
1348 parPos[pit] = Point(0, y);
1349 if (singlepar && pit == cursor_.bottom().pit()) {
1350 // In Single Paragraph mode, collect here the
1351 // y1 and y2 of the (one) paragraph the cursor is in
1352 y1 = y - par.ascent();
1353 y2 = y + par.descent();
1359 // collect cursor paragraph iter bounds
1360 pit1 = cursor_.bottom().pit();
1361 pit2 = cursor_.bottom().pit();
1364 lyxerr[Debug::DEBUG]
1365 << BOOST_CURRENT_FUNCTION
1368 << " pit1: " << pit1
1369 << " pit2: " << pit2
1370 << " npit: " << npit
1371 << " singlepar: " << singlepar
1375 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);