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;
111 /// Return an inset of this class if it exists at the current cursor position
113 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
116 DocIterator it = cur;
117 if (it.nextInset() &&
118 it.nextInset()->lyxCode() == code) {
119 inset = static_cast<T*>(it.nextInset());
127 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
128 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
130 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0), needs_redraw_(false)
132 xsel_cache_.set = false;
134 saved_positions.resize(saved_positions_num);
135 // load saved bookmarks
136 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
137 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
138 bm != bmList.end(); ++bm)
139 if (bm->get<0>() < saved_positions_num)
140 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
141 // and then clear them
146 void BufferView::Pimpl::addError(ErrorItem const & ei)
148 errorlist_.push_back(ei);
152 void BufferView::Pimpl::showReadonly(bool)
154 owner_->updateWindowTitle();
155 owner_->getDialogs().updateBufferDependent(false);
159 void BufferView::Pimpl::connectBuffer(Buffer & buf)
161 if (errorConnection_.connected())
166 boost::bind(&BufferView::Pimpl::addError, this, _1));
170 boost::bind(&LyXView::message, owner_, _1));
174 boost::bind(&LyXView::busy, owner_, _1));
177 buf.updateTitles.connect(
178 boost::bind(&LyXView::updateWindowTitle, owner_));
181 buf.resetAutosaveTimers.connect(
182 boost::bind(&LyXView::resetAutosaveTimer, owner_));
184 readonlyConnection_ =
185 buf.readonly.connect(
186 boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
190 boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
194 void BufferView::Pimpl::disconnectBuffer()
196 errorConnection_.disconnect();
197 messageConnection_.disconnect();
198 busyConnection_.disconnect();
199 titleConnection_.disconnect();
200 timerConnection_.disconnect();
201 readonlyConnection_.disconnect();
202 closingConnection_.disconnect();
206 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
209 setBuffer(::newFile(filename, tname, isNamed));
213 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
215 // Get absolute path of file and add ".lyx"
216 // to the filename if necessary
217 string s = fileSearch(string(), filename, "lyx");
219 bool const found = !s.empty();
224 // File already open?
225 if (bufferlist.exists(s)) {
226 string const file = makeDisplayPath(s, 20);
227 string text = bformat(_("The document %1$s is already "
228 "loaded.\n\nDo you want to revert "
229 "to the saved version?"), file);
230 int const ret = Alert::prompt(_("Revert to saved document?"),
231 text, 0, 1, _("&Revert"), _("&Switch to document"));
234 setBuffer(bufferlist.getBuffer(s));
237 // FIXME: should be LFUN_REVERT
238 if (!bufferlist.close(bufferlist.getBuffer(s), false))
240 // Fall through to new load. (Asger)
246 b = bufferlist.newBuffer(s);
248 if (!::loadLyXFile(b, s)) {
249 bufferlist.release(b);
253 string text = bformat(_("The document %1$s does not yet "
254 "exist.\n\nDo you want to create "
255 "a new document?"), s);
256 int const ret = Alert::prompt(_("Create new document?"),
257 text, 0, 1, _("&Create"), _("Cancel"));
260 b = ::newFile(s, string(), true);
266 bv_->showErrorList(_("Parse"));
268 // scroll to the position when the file was last closed
269 if (lyxrc.use_lastfilepos) {
272 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
273 // I am not sure how to separate the following part to a function
274 // so I will leave this to Lars.
276 // check pit since the document may be externally changed.
277 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
278 ParIterator it = b->par_iterator_begin();
279 ParIterator const end = b->par_iterator_end();
280 for (; it != end; ++it)
281 if (it.pit() == pit) {
282 // restored pos may be bigger than it->size
283 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
284 bv_->update(Update::FitCursor);
291 LyX::ref().session().addLastFile(b->fileName());
297 lyx::frontend::Gui & BufferView::Pimpl::gui() const
299 return owner_->gui();
303 int BufferView::Pimpl::width() const
309 int BufferView::Pimpl::height() const
315 void BufferView::Pimpl::setBuffer(Buffer * b)
317 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
318 << "[ b = " << b << "]" << endl;
322 // Save the actual cursor position and anchor inside the
323 // buffer so that it can be restored in case we rechange
324 // to this buffer later on.
325 buffer_->saveCursor(cursor_.selectionBegin(),
326 cursor_.selectionEnd());
327 // current buffer is going to be switched-off, save cursor pos
328 LyX::ref().session().saveFilePosition(buffer_->fileName(),
329 boost::tie(cursor_.pit(), cursor_.pos()) );
332 // If we are closing current buffer, switch to the first in
335 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
336 << " No Buffer!" << endl;
337 // We are closing the buffer, use the first buffer as current
338 buffer_ = bufferlist.first();
339 owner_->getDialogs().hideBufferDependent();
341 // Set current buffer
346 cursor_ = LCursor(*bv_);
351 // If we're quitting lyx, don't bother updating stuff
356 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
357 << "Buffer addr: " << buffer_ << endl;
358 connectBuffer(*buffer_);
359 cursor_.push(buffer_->inset());
360 cursor_.resetAnchor();
361 buffer_->text().init(bv_);
362 buffer_->text().setCurrentFont(cursor_);
363 if (buffer_->getCursor().size() > 0 &&
364 buffer_->getAnchor().size() > 0)
366 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
367 cursor_.resetAnchor();
368 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
369 cursor_.setSelection();
372 // Buffer-dependent dialogs should be updated or
373 // hidden. This should go here because some dialogs (eg ToC)
374 // require bv_->text.
375 owner_->getDialogs().updateBufferDependent(true);
379 owner_->updateMenubar();
380 owner_->updateToolbars();
381 owner_->updateLayoutChoice();
382 owner_->updateWindowTitle();
384 // This is done after the layout combox has been populated
386 size_t i = cursor_.depth() - 1;
387 // we know we'll eventually find a paragraph
389 CursorSlice const & slice = cursor_[i];
390 if (!slice.inset().inMathed()) {
391 LyXLayout_ptr const layout = slice.paragraph().layout();
392 owner_->setLayout(layout->name());
400 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
401 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
405 void BufferView::Pimpl::resizeCurrentBuffer()
407 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
409 owner_->message(_("Formatting document..."));
411 LyXText * text = bv_->text();
421 // Reset the "Formatting..." message
422 owner_->clearMessage();
426 void BufferView::Pimpl::updateScrollbar()
429 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
430 << " no text in updateScrollbar" << endl;
431 scrollbarParameters_.reset();
435 LyXText & t = *bv_->text();
436 int const parsize = int(t.paragraphs().size() - 1);
437 if (anchor_ref_ > parsize) {
438 anchor_ref_ = parsize;
443 << BOOST_CURRENT_FUNCTION
444 << " Updating scrollbar: height: " << t.paragraphs().size()
445 << " curr par: " << cursor_.bottom().pit()
446 << " default height " << defaultRowHeight() << endl;
448 // It would be better to fix the scrollbar to understand
449 // values in [0..1] and divide everything by wh
451 // estimated average paragraph height:
454 int h = t.getPar(anchor_ref_).height();
456 // Normalize anchor/offset (MV):
457 while (offset_ref_ > h && anchor_ref_ < parsize) {
460 h = t.getPar(anchor_ref_).height();
462 // Look at paragraph heights on-screen
465 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
468 int const h2 = t.getPar(pit).height();
472 int const hav = sumh / nh;
473 // More realistic average paragraph height
477 scrollbarParameters_.height = (parsize + 1) * wh_;
478 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
479 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
483 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
485 return scrollbarParameters_;
489 void BufferView::Pimpl::scrollDocView(int value)
491 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
492 << "[ value = " << value << "]" << endl;
497 LyXText & t = *bv_->text();
499 float const bar = value / float(wh_ * t.paragraphs().size());
501 anchor_ref_ = int(bar * t.paragraphs().size());
502 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
503 anchor_ref_ = int(t.paragraphs().size()) - 1;
504 t.redoParagraph(anchor_ref_);
505 int const h = t.getPar(anchor_ref_).height();
506 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
509 if (!lyxrc.cursor_follows_scrollbar)
512 int const height = 2 * defaultRowHeight();
513 int const first = height;
514 int const last = height_ - height;
515 LCursor & cur = cursor_;
517 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
520 case bv_funcs::CUR_ABOVE:
521 t.setCursorFromCoordinates(cur, 0, first);
522 cur.clearSelection();
524 case bv_funcs::CUR_BELOW:
525 t.setCursorFromCoordinates(cur, 0, last);
526 cur.clearSelection();
528 case bv_funcs::CUR_INSIDE:
529 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
530 int const newy = min(last, max(y, first));
532 cur.reset(buffer_->inset());
533 t.setCursorFromCoordinates(cur, 0, newy);
536 owner_->updateLayoutChoice();
540 void BufferView::Pimpl::scroll(int /*lines*/)
545 // LyXText const * t = bv_->text();
546 // int const line_height = defaultRowHeight();
548 // // The new absolute coordinate
549 // int new_top_y = top_y() + lines * line_height;
551 // // Restrict to a valid value
552 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
553 // new_top_y = std::max(0, new_top_y);
555 // scrollDocView(new_top_y);
557 // // Update the scrollbar.
558 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());
562 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
563 key_modifier::state state)
565 owner_->getLyXFunc().processKeySym(key, state);
569 void BufferView::Pimpl::selectionRequested()
576 LCursor & cur = cursor_;
578 if (!cur.selection()) {
579 xsel_cache_.set = false;
583 if (!xsel_cache_.set ||
584 cur.top() != xsel_cache_.cursor ||
585 cur.anchor_.top() != xsel_cache_.anchor)
587 xsel_cache_.cursor = cur.top();
588 xsel_cache_.anchor = cur.anchor_.top();
589 xsel_cache_.set = cur.selection();
590 sel = cur.selectionAsString(false);
592 owner_->gui().selection().put(sel);
597 void BufferView::Pimpl::selectionLost()
600 cursor_.clearSelection();
601 xsel_cache_.set = false;
606 void BufferView::Pimpl::workAreaResize(int width, int height)
608 bool const widthChange = width != width_;
609 bool const heightChange = height != height_;
611 // Update from work area
615 if (buffer_ && widthChange) {
616 // The visible LyXView need a resize
617 resizeCurrentBuffer();
620 if (widthChange || heightChange)
623 owner_->updateLayoutChoice();
627 bool BufferView::Pimpl::fitCursor()
629 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
630 LyXFont const font = cursor_.getFont();
631 int const asc = font_metrics::maxAscent(font);
632 int const des = font_metrics::maxDescent(font);
633 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
634 if (p.y_ - asc >= 0 && p.y_ + des < height_)
642 bool BufferView::Pimpl::multiParSel()
644 if (!cursor_.selection())
646 bool ret = multiparsel_cache_;
647 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
648 // Either this, or previous selection spans paragraphs
649 return ret || multiparsel_cache_;
653 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
655 return metrics_info_;
659 void BufferView::Pimpl::update(Update::flags flags)
661 // This is close to a hot-path.
662 if (lyxerr.debugging(Debug::DEBUG)) {
664 << BOOST_CURRENT_FUNCTION
665 << "[fitcursor = " << (flags & Update::FitCursor)
666 << ", forceupdate = " << (flags & Update::Force)
667 << ", singlepar = " << (flags & Update::SinglePar)
668 << "] buffer: " << buffer_ << endl;
671 // Check needed to survive LyX startup
673 // Update macro store
674 buffer_->buildMacros();
676 // First drawing step
677 bool singlePar = flags & Update::SinglePar;
678 needs_redraw_ = flags & (Update::Force | Update::SinglePar);
680 if ((flags & (Update::FitCursor | Update::MultiParSel))
681 && (fitCursor() || multiParSel())) {
682 needs_redraw_ = true;
687 // Second drawing step
688 updateMetrics(singlePar);
692 owner_->redrawWorkArea();
693 owner_->view_state_changed();
697 bool BufferView::Pimpl::available() const
699 return buffer_ && bv_->text();
703 Change const BufferView::Pimpl::getCurrentChange()
705 if (!buffer_->params().tracking_changes)
706 return Change(Change::UNCHANGED);
708 LyXText * text = bv_->getLyXText();
709 LCursor & cur = cursor_;
711 if (!cur.selection())
712 return Change(Change::UNCHANGED);
714 return text->getPar(cur.selBegin().pit()).
715 lookupChange(cur.selBegin().pos());
719 void BufferView::Pimpl::savePosition(unsigned int i)
721 if (i >= saved_positions_num)
723 BOOST_ASSERT(cursor_.inTexted());
724 saved_positions[i] = Position(buffer_->fileName(),
725 cursor_.paragraph().id(),
728 owner_->message(bformat(_("Saved bookmark %1$d"), i));
732 void BufferView::Pimpl::restorePosition(unsigned int i)
734 if (i >= saved_positions_num)
737 string const fname = saved_positions[i].filename;
739 cursor_.clearSelection();
741 if (fname != buffer_->fileName()) {
743 if (bufferlist.exists(fname))
744 b = bufferlist.getBuffer(fname);
746 b = bufferlist.newBuffer(fname);
747 // Don't ask, just load it
748 ::loadLyXFile(b, fname);
754 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
755 if (par == buffer_->par_iterator_end())
758 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
761 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
765 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
767 return i < saved_positions_num && !saved_positions[i].filename.empty();
771 void BufferView::Pimpl::saveSavedPositions()
773 // save bookmarks. It is better to use the pit interface
774 // but I do not know how to effectively convert between
776 for (unsigned int i=1; i < saved_positions_num; ++i) {
777 if ( isSavedPosition(i) )
778 LyX::ref().session().saveBookmark( boost::tie(
780 saved_positions[i].filename,
781 saved_positions[i].par_id,
782 saved_positions[i].par_pos) );
787 void BufferView::Pimpl::switchKeyMap()
789 if (!lyxrc.rtl_support)
792 Intl & intl = owner_->getIntl();
793 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
794 if (intl.keymap == Intl::PRIMARY)
797 if (intl.keymap == Intl::SECONDARY)
803 void BufferView::Pimpl::center()
805 CursorSlice & bot = cursor_.bottom();
806 lyx::pit_type const pit = bot.pit();
807 bot.text()->redoParagraph(pit);
808 Paragraph const & par = bot.text()->paragraphs()[pit];
810 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
811 + par.ascent() - height_ / 2;
816 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
818 BOOST_ASSERT(cursor_.inTexted());
819 string filename = filenm;
821 if (filename.empty()) {
822 // Launch a file browser
823 string initpath = lyxrc.document_path;
826 string const trypath = owner_->buffer()->filePath();
827 // If directory is writeable, use this as default.
828 if (isDirWriteable(trypath))
832 FileDialog fileDlg(_("Select LyX document to insert"),
834 make_pair(string(_("Documents|#o#O")),
835 string(lyxrc.document_path)),
836 make_pair(string(_("Examples|#E#e")),
837 string(addPath(package().system_support(), "examples"))));
839 FileDialog::Result result =
840 fileDlg.open(initpath,
841 FileFilterList(_("LyX Documents (*.lyx)")),
844 if (result.first == FileDialog::Later)
847 filename = result.second;
849 // check selected filename
850 if (filename.empty()) {
851 owner_->message(_("Canceled."));
856 // Get absolute path of file and add ".lyx"
857 // to the filename if necessary
858 filename = fileSearch(string(), filename, "lyx");
860 string const disp_fn = makeDisplayPath(filename);
861 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
864 Buffer buf("", false);
865 buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
866 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
867 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
868 buf.params().textclass);
869 res = _("Document %1$s inserted.");
871 res = _("Could not insert document %1$s");
873 owner_->message(bformat(res, disp_fn));
874 bv_->showErrorList(_("Document insertion"));
875 resizeCurrentBuffer();
879 void BufferView::Pimpl::trackChanges()
881 bool const tracking = buffer_->params().tracking_changes;
884 for_each(buffer_->par_iterator_begin(),
885 buffer_->par_iterator_end(),
886 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
887 buffer_->params().tracking_changes = true;
889 // We cannot allow undos beyond the freeze point
890 buffer_->undostack().clear();
892 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
893 if (lyx::find::findNextChange(bv_)) {
894 owner_->getDialogs().show("changes");
898 for_each(buffer_->par_iterator_begin(),
899 buffer_->par_iterator_end(),
900 mem_fun_ref(&Paragraph::untrackChanges));
902 buffer_->params().tracking_changes = false;
905 buffer_->redostack().clear();
909 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
911 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
913 // This is only called for mouse related events including
914 // LFUN_FILE_OPEN generated by drag-and-drop.
915 FuncRequest cmd = cmd0;
918 if (cmd.action == LFUN_FILE_OPEN) {
919 owner_->dispatch(cmd);
927 cur.push(buffer_->inset());
928 cur.selection() = cursor_.selection();
930 // Doesn't go through lyxfunc, so we need to update
931 // the layout choice etc. ourselves
933 // E.g. Qt mouse press when no buffer
937 // Either the inset under the cursor or the
938 // surrounding LyXText will handle this event.
940 // Build temporary cursor.
941 cmd.y = min(max(cmd.y, -1), height_);
942 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
943 //lyxerr << BOOST_CURRENT_FUNCTION
944 // << " * hit inset at tip: " << inset << endl;
945 //lyxerr << BOOST_CURRENT_FUNCTION
946 // << " * created temp cursor:" << cur << endl;
948 // Put anchor at the same position.
951 // Try to dispatch to an non-editable inset near this position
952 // via the temp cursor. If the inset wishes to change the real
953 // cursor it has to do so explicitly by using
954 // cur.bv().cursor() = cur; (or similar)
956 inset->dispatch(cur, cmd);
958 // Now dispatch to the temporary cursor. If the real cursor should
959 // be modified, the inset's dispatch has to do so explicitly.
960 if (!cur.result().dispatched())
963 if (cur.result().dispatched()) {
964 // Redraw if requested or necessary.
965 if (cur.result().update())
966 update(Update::FitCursor | Update::Force);
968 update(Update::FitCursor | Update::MultiParSel);
971 // Skip these when selecting
972 if (cmd.action != LFUN_MOUSE_MOTION) {
973 owner_->updateLayoutChoice();
974 owner_->updateToolbars();
977 // Slight hack: this is only called currently when we
978 // clicked somewhere, so we force through the display
979 // of the new status here.
980 owner_->clearMessage();
985 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
989 switch (cmd.action) {
992 flag.enabled(!buffer_->undostack().empty());
995 flag.enabled(!buffer_->redostack().empty());
997 case LFUN_FILE_INSERT:
998 case LFUN_FILE_INSERT_ASCII_PARA:
999 case LFUN_FILE_INSERT_ASCII:
1000 case LFUN_BOOKMARK_SAVE:
1001 // FIXME: Actually, these LFUNS should be moved to LyXText
1002 flag.enabled(cursor_.inTexted());
1004 case LFUN_FONT_STATE:
1005 case LFUN_LABEL_INSERT:
1006 case LFUN_PARAGRAPH_GOTO:
1007 // FIXME handle non-trivially
1008 case LFUN_OUTLINE_UP:
1009 case LFUN_OUTLINE_DOWN:
1010 case LFUN_OUTLINE_IN:
1011 case LFUN_OUTLINE_OUT:
1012 case LFUN_ERROR_NEXT:
1013 case LFUN_NOTE_NEXT:
1014 case LFUN_REFERENCE_NEXT:
1015 case LFUN_WORD_FIND:
1016 case LFUN_WORD_REPLACE:
1019 case LFUN_MARK_TOGGLE:
1020 case LFUN_SCREEN_RECENTER:
1021 case LFUN_BIBTEX_DATABASE_ADD:
1022 case LFUN_BIBTEX_DATABASE_DEL:
1023 case LFUN_WORDS_COUNT:
1027 case LFUN_LABEL_GOTO: {
1028 flag.enabled(!cmd.argument.empty()
1029 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1033 case LFUN_BOOKMARK_GOTO:
1034 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1036 case LFUN_CHANGES_TRACK:
1038 flag.setOnOff(buffer_->params().tracking_changes);
1041 case LFUN_CHANGES_OUTPUT: {
1042 OutputParams runparams;
1043 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1044 flag.enabled(buffer_ && buffer_->params().tracking_changes
1045 && features.isAvailable("dvipost"));
1046 flag.setOnOff(buffer_->params().output_changes);
1050 case LFUN_CHANGES_MERGE:
1051 case LFUN_CHANGE_ACCEPT: // what about these two
1052 case LFUN_CHANGE_REJECT: // what about these two
1053 case LFUN_ALL_CHANGES_ACCEPT:
1054 case LFUN_ALL_CHANGES_REJECT:
1055 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1058 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1059 flag.setOnOff(buffer_->params().compressed);
1064 flag.enabled(false);
1072 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1074 //lyxerr << BOOST_CURRENT_FUNCTION
1075 // << [ cmd = " << cmd << "]" << endl;
1077 // Make sure that the cached BufferView is correct.
1078 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1079 << " action[" << cmd.action << ']'
1080 << " arg[" << cmd.argument << ']'
1081 << " x[" << cmd.x << ']'
1082 << " y[" << cmd.y << ']'
1083 << " button[" << cmd.button() << ']'
1086 LCursor & cur = cursor_;
1088 switch (cmd.action) {
1092 cur.message(_("Undo"));
1093 cur.clearSelection();
1094 if (!textUndo(*bv_))
1095 cur.message(_("No further undo information"));
1103 cur.message(_("Redo"));
1104 cur.clearSelection();
1105 if (!textRedo(*bv_))
1106 cur.message(_("No further redo information"));
1112 case LFUN_FILE_INSERT:
1113 menuInsertLyXFile(cmd.argument);
1116 case LFUN_FILE_INSERT_ASCII_PARA:
1117 insertAsciiFile(bv_, cmd.argument, true);
1120 case LFUN_FILE_INSERT_ASCII:
1121 insertAsciiFile(bv_, cmd.argument, false);
1124 case LFUN_FONT_STATE:
1125 cur.message(cur.currentState());
1128 case LFUN_BOOKMARK_SAVE:
1129 savePosition(convert<unsigned int>(cmd.argument));
1132 case LFUN_BOOKMARK_GOTO:
1133 restorePosition(convert<unsigned int>(cmd.argument));
1136 case LFUN_LABEL_GOTO: {
1137 string label = cmd.argument;
1138 if (label.empty()) {
1140 getInsetByCode<InsetRef>(cursor_,
1141 InsetBase::REF_CODE);
1143 label = inset->getContents();
1149 bv_->gotoLabel(label);
1153 case LFUN_PARAGRAPH_GOTO: {
1154 int const id = convert<int>(cmd.argument);
1155 ParIterator par = buffer_->getParFromID(id);
1156 if (par == buffer_->par_iterator_end()) {
1157 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1158 << id << ']' << endl;
1161 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1162 << " found." << endl;
1166 bv_->setCursor(makeDocIterator(par, 0));
1173 case LFUN_OUTLINE_UP:
1174 lyx::toc::outline(lyx::toc::Up, cursor_);
1175 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1176 updateLabels(*buffer_);
1178 case LFUN_OUTLINE_DOWN:
1179 lyx::toc::outline(lyx::toc::Down, cursor_);
1180 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1181 updateLabels(*buffer_);
1183 case LFUN_OUTLINE_IN:
1184 lyx::toc::outline(lyx::toc::In, cursor_);
1185 updateLabels(*buffer_);
1187 case LFUN_OUTLINE_OUT:
1188 lyx::toc::outline(lyx::toc::Out, cursor_);
1189 updateLabels(*buffer_);
1192 case LFUN_ERROR_NEXT:
1193 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1196 case LFUN_NOTE_NEXT:
1197 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1200 case LFUN_REFERENCE_NEXT: {
1201 vector<InsetBase_code> tmp;
1202 tmp.push_back(InsetBase::LABEL_CODE);
1203 tmp.push_back(InsetBase::REF_CODE);
1204 bv_funcs::gotoInset(bv_, tmp, true);
1208 case LFUN_CHANGES_TRACK:
1212 case LFUN_CHANGES_OUTPUT: {
1213 bool const state = buffer_->params().output_changes;
1214 buffer_->params().output_changes = !state;
1218 case LFUN_CHANGES_MERGE:
1219 if (lyx::find::findNextChange(bv_))
1220 owner_->getDialogs().show("changes");
1223 case LFUN_ALL_CHANGES_ACCEPT: {
1224 cursor_.reset(buffer_->inset());
1225 #ifdef WITH_WARNINGS
1226 #warning FIXME changes
1228 while (lyx::find::findNextChange(bv_))
1229 bv_->getLyXText()->acceptChange(cursor_);
1234 case LFUN_ALL_CHANGES_REJECT: {
1235 cursor_.reset(buffer_->inset());
1236 #ifdef WITH_WARNINGS
1237 #warning FIXME changes
1239 while (lyx::find::findNextChange(bv_))
1240 bv_->getLyXText()->rejectChange(cursor_);
1244 case LFUN_WORD_FIND:
1245 lyx::find::find(bv_, cmd);
1248 case LFUN_WORD_REPLACE:
1249 lyx::find::replace(bv_, cmd);
1253 cur.clearSelection();
1255 cur.message(N_("Mark off"));
1259 cur.clearSelection();
1262 cur.message(N_("Mark on"));
1265 case LFUN_MARK_TOGGLE:
1266 cur.clearSelection();
1269 cur.message(N_("Mark removed"));
1272 cur.message(N_("Mark set"));
1277 case LFUN_SCREEN_RECENTER:
1281 case LFUN_BIBTEX_DATABASE_ADD: {
1282 LCursor tmpcur = cursor_;
1283 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1284 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1285 InsetBase::BIBTEX_CODE);
1287 if (inset->addDatabase(cmd.argument))
1288 buffer_->updateBibfilesCache();
1293 case LFUN_BIBTEX_DATABASE_DEL: {
1294 LCursor tmpcur = cursor_;
1295 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1296 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1297 InsetBase::BIBTEX_CODE);
1299 if (inset->delDatabase(cmd.argument))
1300 buffer_->updateBibfilesCache();
1305 case LFUN_WORDS_COUNT: {
1306 DocIterator from, to;
1307 if (cur.selection()) {
1308 from = cur.selectionBegin();
1309 to = cur.selectionEnd();
1311 from = doc_iterator_begin(buffer_->inset());
1312 to = doc_iterator_end(buffer_->inset());
1314 int const count = countWords(from, to);
1317 if (cur.selection())
1318 message = bformat(_("%1$d words in selection."),
1321 message = bformat(_("%1$d words in document."),
1325 if (cur.selection())
1326 message = _("One word in selection.");
1328 message = _("One word in document.");
1331 Alert::information(_("Count words"), message);
1335 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1336 // turn compression on/off
1337 buffer_->params().compressed = !buffer_->params().compressed;
1348 void BufferView::Pimpl::updateMetrics(bool singlepar)
1350 // Remove old position cache
1352 BufferView & bv = *bv_;
1353 LyXText * const text = bv.text();
1354 lyx::pit_type size = int(text->paragraphs().size());
1356 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1357 anchor_ref_ = int(text->paragraphs().size() - 1);
1361 lyx::pit_type const pit = anchor_ref_;
1364 size_t const npit = text->paragraphs().size();
1366 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1367 // the (main text, not inset!) paragraph containing the cursor.
1368 // (if this paragraph contains insets etc., rebreaking will
1369 // recursively descend)
1370 if (!singlepar || pit == cursor_.bottom().pit())
1371 text->redoParagraph(pit);
1372 int y0 = text->getPar(pit).ascent() - offset_ref_;
1374 // Redo paragraphs above anchor if necessary; again, in Single Par
1375 // mode, only if we encounter the (main text) one having the cursor.
1377 while (y1 > 0 && pit1 > 0) {
1378 y1 -= text->getPar(pit1).ascent();
1380 if (!singlepar || pit1 == cursor_.bottom().pit())
1381 text->redoParagraph(pit1);
1382 y1 -= text->getPar(pit1).descent();
1386 // Take care of ascent of first line
1387 y1 -= text->getPar(pit1).ascent();
1389 // Normalize anchor for next time
1393 // Grey at the beginning is ugly
1394 if (pit1 == 0 && y1 > 0) {
1400 // Redo paragraphs below the anchor if necessary. Single par mode:
1401 // only the one containing the cursor if encountered.
1403 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1404 y2 += text->getPar(pit2).descent();
1406 if (!singlepar || pit2 == cursor_.bottom().pit())
1407 text->redoParagraph(pit2);
1408 y2 += text->getPar(pit2).ascent();
1411 // Take care of descent of last line
1412 y2 += text->getPar(pit2).descent();
1414 // The coordinates of all these paragraphs are correct, cache them
1416 CoordCache::InnerParPosCache parPos = theCoords.parPos()[text];
1417 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1418 Paragraph & par = text->getPar(pit);
1420 parPos[pit] = Point(0, y);
1421 if (singlepar && pit == cursor_.bottom().pit()) {
1422 // In Single Paragraph mode, collect here the
1423 // y1 and y2 of the (one) paragraph the cursor is in
1424 y1 = y - par.ascent();
1425 y2 = y + par.descent();
1431 // collect cursor paragraph iter bounds
1432 pit1 = cursor_.bottom().pit();
1433 pit2 = cursor_.bottom().pit();
1436 lyxerr[Debug::DEBUG]
1437 << BOOST_CURRENT_FUNCTION
1440 << " pit1: " << pit1
1441 << " pit2: " << pit2
1442 << " npit: " << npit
1443 << " singlepar: " << singlepar
1447 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);