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 lyx::frontend::Gui & BufferView::Pimpl::gui() const
236 return owner_->gui();
240 int BufferView::Pimpl::width() const
246 int BufferView::Pimpl::height() const
252 void BufferView::Pimpl::setBuffer(Buffer * b)
254 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
255 << "[ b = " << b << "]" << endl;
258 // Save the actual cursor position and anchor inside the
259 // buffer so that it can be restored in case we rechange
260 // to this buffer later on.
261 buffer_->saveCursor(cursor_.selectionBegin(),
262 cursor_.selectionEnd());
263 // current buffer is going to be switched-off, save cursor pos
264 LyX::ref().session().saveFilePosition(buffer_->fileName(),
265 boost::tie(cursor_.pit(), cursor_.pos()) );
268 // If we are closing current buffer, switch to the first in
271 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
272 << " No Buffer!" << endl;
273 // We are closing the buffer, use the first buffer as current
274 buffer_ = bufferlist.first();
275 owner_->getDialogs().hideBufferDependent();
277 // Set current buffer
282 cursor_ = LCursor(*bv_);
287 // If we're quitting lyx, don't bother updating stuff
292 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
293 << "Buffer addr: " << buffer_ << endl;
294 cursor_.push(buffer_->inset());
295 cursor_.resetAnchor();
296 buffer_->text().init(bv_);
297 buffer_->text().setCurrentFont(cursor_);
298 if (buffer_->getCursor().size() > 0 &&
299 buffer_->getAnchor().size() > 0)
301 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
302 cursor_.resetAnchor();
303 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
304 cursor_.setSelection();
307 // Buffer-dependent dialogs should be updated or
308 // hidden. This should go here because some dialogs (eg ToC)
309 // require bv_->text.
310 owner_->getDialogs().updateBufferDependent(true);
315 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
316 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
319 string BufferView::Pimpl::firstLayout()
323 // This is done after the layout combox has been populated
325 size_t i = cursor_.depth() - 1;
326 // we know we'll eventually find a paragraph
328 CursorSlice const & slice = cursor_[i];
329 if (!slice.inset().inMathed()) {
330 LyXLayout_ptr const layout = slice.paragraph().layout();
331 firstlayout = layout->name();
342 void BufferView::Pimpl::resizeCurrentBuffer()
344 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
346 owner_->message(_("Formatting document..."));
348 LyXText * text = bv_->text();
358 // Reset the "Formatting..." message
359 owner_->clearMessage();
363 void BufferView::Pimpl::updateScrollbar()
366 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
367 << " no text in updateScrollbar" << endl;
368 scrollbarParameters_.reset();
372 LyXText & t = *bv_->text();
373 int const parsize = int(t.paragraphs().size() - 1);
374 if (anchor_ref_ > parsize) {
375 anchor_ref_ = parsize;
380 << BOOST_CURRENT_FUNCTION
381 << " Updating scrollbar: height: " << t.paragraphs().size()
382 << " curr par: " << cursor_.bottom().pit()
383 << " default height " << defaultRowHeight() << endl;
385 // It would be better to fix the scrollbar to understand
386 // values in [0..1] and divide everything by wh
388 // estimated average paragraph height:
391 int h = t.getPar(anchor_ref_).height();
393 // Normalize anchor/offset (MV):
394 while (offset_ref_ > h && anchor_ref_ < parsize) {
397 h = t.getPar(anchor_ref_).height();
399 // Look at paragraph heights on-screen
402 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
405 int const h2 = t.getPar(pit).height();
409 int const hav = sumh / nh;
410 // More realistic average paragraph height
414 scrollbarParameters_.height = (parsize + 1) * wh_;
415 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
416 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
420 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
422 return scrollbarParameters_;
426 void BufferView::Pimpl::scrollDocView(int value)
428 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
429 << "[ value = " << value << "]" << endl;
434 LyXText & t = *bv_->text();
436 float const bar = value / float(wh_ * t.paragraphs().size());
438 anchor_ref_ = int(bar * t.paragraphs().size());
439 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
440 anchor_ref_ = int(t.paragraphs().size()) - 1;
441 t.redoParagraph(anchor_ref_);
442 int const h = t.getPar(anchor_ref_).height();
443 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
446 if (!lyxrc.cursor_follows_scrollbar)
449 int const height = 2 * defaultRowHeight();
450 int const first = height;
451 int const last = height_ - height;
452 LCursor & cur = cursor_;
454 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
457 case bv_funcs::CUR_ABOVE:
458 t.setCursorFromCoordinates(cur, 0, first);
459 cur.clearSelection();
461 case bv_funcs::CUR_BELOW:
462 t.setCursorFromCoordinates(cur, 0, last);
463 cur.clearSelection();
465 case bv_funcs::CUR_INSIDE:
466 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
467 int const newy = min(last, max(y, first));
469 cur.reset(buffer_->inset());
470 t.setCursorFromCoordinates(cur, 0, newy);
473 owner_->updateLayoutChoice();
477 void BufferView::Pimpl::scroll(int /*lines*/)
482 // LyXText const * t = bv_->text();
483 // int const line_height = defaultRowHeight();
485 // // The new absolute coordinate
486 // int new_top_y = top_y() + lines * line_height;
488 // // Restrict to a valid value
489 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
490 // new_top_y = std::max(0, new_top_y);
492 // scrollDocView(new_top_y);
494 // // Update the scrollbar.
495 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
499 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
500 key_modifier::state state)
502 owner_->getLyXFunc().processKeySym(key, state);
506 void BufferView::Pimpl::selectionRequested()
513 LCursor & cur = cursor_;
515 if (!cur.selection()) {
516 xsel_cache_.set = false;
520 if (!xsel_cache_.set ||
521 cur.top() != xsel_cache_.cursor ||
522 cur.anchor_.top() != xsel_cache_.anchor)
524 xsel_cache_.cursor = cur.top();
525 xsel_cache_.anchor = cur.anchor_.top();
526 xsel_cache_.set = cur.selection();
527 sel = cur.selectionAsString(false);
529 owner_->gui().selection().put(sel);
534 void BufferView::Pimpl::selectionLost()
537 cursor_.clearSelection();
538 xsel_cache_.set = false;
543 void BufferView::Pimpl::workAreaResize(int width, int height)
545 bool const widthChange = width != width_;
546 bool const heightChange = height != height_;
548 // Update from work area
552 if (buffer_ && widthChange) {
553 // The visible LyXView need a resize
554 resizeCurrentBuffer();
557 if (widthChange || heightChange)
560 owner_->updateLayoutChoice();
564 bool BufferView::Pimpl::fitCursor()
566 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
567 LyXFont const font = cursor_.getFont();
568 int const asc = font_metrics::maxAscent(font);
569 int const des = font_metrics::maxDescent(font);
570 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
571 if (p.y_ - asc >= 0 && p.y_ + des < height_)
579 bool BufferView::Pimpl::multiParSel()
581 if (!cursor_.selection())
583 bool ret = multiparsel_cache_;
584 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
585 // Either this, or previous selection spans paragraphs
586 return ret || multiparsel_cache_;
590 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
592 return metrics_info_;
596 bool BufferView::Pimpl::update(Update::flags flags)
598 // This is close to a hot-path.
599 if (lyxerr.debugging(Debug::DEBUG)) {
601 << BOOST_CURRENT_FUNCTION
602 << "[fitcursor = " << (flags & Update::FitCursor)
603 << ", forceupdate = " << (flags & Update::Force)
604 << ", singlepar = " << (flags & Update::SinglePar)
605 << "] buffer: " << buffer_ << endl;
608 // Check needed to survive LyX startup
612 // Update macro store
613 buffer_->buildMacros();
615 // First drawing step
616 updateMetrics(flags & Update::SinglePar);
618 // The second drawing step is done in WorkArea::redraw() if needed.
619 bool const need_second_step =
620 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
621 && (fitCursor() || multiParSel());
623 return need_second_step;
627 bool BufferView::Pimpl::available() const
629 return buffer_ && bv_->text();
633 Change const BufferView::Pimpl::getCurrentChange()
635 if (!buffer_->params().tracking_changes)
636 return Change(Change::UNCHANGED);
638 LyXText * text = bv_->getLyXText();
639 LCursor & cur = cursor_;
641 if (!cur.selection())
642 return Change(Change::UNCHANGED);
644 return text->getPar(cur.selBegin().pit()).
645 lookupChange(cur.selBegin().pos());
649 void BufferView::Pimpl::savePosition(unsigned int i)
651 if (i >= saved_positions_num)
653 BOOST_ASSERT(cursor_.inTexted());
654 saved_positions[i] = Position(buffer_->fileName(),
655 cursor_.paragraph().id(),
658 owner_->message(bformat(_("Saved bookmark %1$d"), i));
662 void BufferView::Pimpl::restorePosition(unsigned int i)
664 if (i >= saved_positions_num)
667 string const fname = saved_positions[i].filename;
669 cursor_.clearSelection();
671 if (fname != buffer_->fileName()) {
673 if (bufferlist.exists(fname))
674 b = bufferlist.getBuffer(fname);
676 b = bufferlist.newBuffer(fname);
677 // Don't ask, just load it
678 ::loadLyXFile(b, fname);
684 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
685 if (par == buffer_->par_iterator_end())
688 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
691 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
695 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
697 return i < saved_positions_num && !saved_positions[i].filename.empty();
701 void BufferView::Pimpl::saveSavedPositions()
703 // save bookmarks. It is better to use the pit interface
704 // but I do not know how to effectively convert between
706 for (unsigned int i=1; i < saved_positions_num; ++i) {
707 if ( isSavedPosition(i) )
708 LyX::ref().session().saveBookmark( boost::tie(
710 saved_positions[i].filename,
711 saved_positions[i].par_id,
712 saved_positions[i].par_pos) );
717 void BufferView::Pimpl::switchKeyMap()
719 if (!lyxrc.rtl_support)
722 Intl & intl = owner_->getIntl();
723 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
724 if (intl.keymap == Intl::PRIMARY)
727 if (intl.keymap == Intl::SECONDARY)
733 void BufferView::Pimpl::center()
735 CursorSlice & bot = cursor_.bottom();
736 lyx::pit_type const pit = bot.pit();
737 bot.text()->redoParagraph(pit);
738 Paragraph const & par = bot.text()->paragraphs()[pit];
740 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
741 + par.ascent() - height_ / 2;
745 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
747 BOOST_ASSERT(cursor_.inTexted());
748 string filename = filenm;
750 if (filename.empty()) {
751 // Launch a file browser
752 string initpath = lyxrc.document_path;
755 string const trypath = buffer_->filePath();
756 // If directory is writeable, use this as default.
757 if (isDirWriteable(trypath))
761 FileDialog fileDlg(_("Select LyX document to insert"),
763 make_pair(string(_("Documents|#o#O")),
764 string(lyxrc.document_path)),
765 make_pair(string(_("Examples|#E#e")),
766 string(addPath(package().system_support(), "examples"))));
768 FileDialog::Result result =
769 fileDlg.open(initpath,
770 FileFilterList(_("LyX Documents (*.lyx)")),
773 if (result.first == FileDialog::Later)
776 filename = result.second;
778 // check selected filename
779 if (filename.empty()) {
780 owner_->message(_("Canceled."));
785 // Get absolute path of file and add ".lyx"
786 // to the filename if necessary
787 filename = fileSearch(string(), filename, "lyx");
789 string const disp_fn = makeDisplayPath(filename);
790 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
793 Buffer buf("", false);
794 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
795 ErrorList & el = buffer_->errorList("Parse");
796 // Copy the inserted document error list into the current buffer one.
797 el = buf.errorList("Parse");
798 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
799 buf.params().textclass, el);
800 res = _("Document %1$s inserted.");
802 res = _("Could not insert document %1$s");
804 owner_->message(bformat(res, disp_fn));
805 buffer_->errors("Parse");
806 resizeCurrentBuffer();
810 void BufferView::Pimpl::trackChanges()
812 bool const tracking = buffer_->params().tracking_changes;
815 for_each(buffer_->par_iterator_begin(),
816 buffer_->par_iterator_end(),
817 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
818 buffer_->params().tracking_changes = true;
820 // We cannot allow undos beyond the freeze point
821 buffer_->undostack().clear();
823 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
824 if (lyx::find::findNextChange(bv_)) {
825 owner_->getDialogs().show("changes");
829 for_each(buffer_->par_iterator_begin(),
830 buffer_->par_iterator_end(),
831 mem_fun_ref(&Paragraph::untrackChanges));
833 buffer_->params().tracking_changes = false;
836 buffer_->redostack().clear();
840 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
842 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
844 // This is only called for mouse related events including
845 // LFUN_FILE_OPEN generated by drag-and-drop.
846 FuncRequest cmd = cmd0;
849 if (cmd.action == LFUN_FILE_OPEN) {
850 owner_->dispatch(cmd);
858 cur.push(buffer_->inset());
859 cur.selection() = cursor_.selection();
861 // Doesn't go through lyxfunc, so we need to update
862 // the layout choice etc. ourselves
864 // E.g. Qt mouse press when no buffer
868 // Either the inset under the cursor or the
869 // surrounding LyXText will handle this event.
871 // Build temporary cursor.
872 cmd.y = min(max(cmd.y, -1), height_);
873 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
874 //lyxerr << BOOST_CURRENT_FUNCTION
875 // << " * hit inset at tip: " << inset << endl;
876 //lyxerr << BOOST_CURRENT_FUNCTION
877 // << " * created temp cursor:" << cur << endl;
879 // Put anchor at the same position.
882 // Try to dispatch to an non-editable inset near this position
883 // via the temp cursor. If the inset wishes to change the real
884 // cursor it has to do so explicitly by using
885 // cur.bv().cursor() = cur; (or similar)
887 inset->dispatch(cur, cmd);
889 // Now dispatch to the temporary cursor. If the real cursor should
890 // be modified, the inset's dispatch has to do so explicitly.
891 if (!cur.result().dispatched())
894 if (cur.result().dispatched()) {
895 // Redraw if requested or necessary.
896 if (cur.result().update())
897 update(Update::FitCursor | Update::Force);
899 update(Update::FitCursor | Update::MultiParSel);
902 // Skip these when selecting
903 if (cmd.action != LFUN_MOUSE_MOTION) {
904 owner_->updateLayoutChoice();
905 owner_->updateToolbars();
908 // Slight hack: this is only called currently when we
909 // clicked somewhere, so we force through the display
910 // of the new status here.
911 owner_->clearMessage();
916 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
920 switch (cmd.action) {
923 flag.enabled(!buffer_->undostack().empty());
926 flag.enabled(!buffer_->redostack().empty());
928 case LFUN_FILE_INSERT:
929 case LFUN_FILE_INSERT_ASCII_PARA:
930 case LFUN_FILE_INSERT_ASCII:
931 case LFUN_BOOKMARK_SAVE:
932 // FIXME: Actually, these LFUNS should be moved to LyXText
933 flag.enabled(cursor_.inTexted());
935 case LFUN_FONT_STATE:
936 case LFUN_LABEL_INSERT:
937 case LFUN_PARAGRAPH_GOTO:
938 // FIXME handle non-trivially
939 case LFUN_OUTLINE_UP:
940 case LFUN_OUTLINE_DOWN:
941 case LFUN_OUTLINE_IN:
942 case LFUN_OUTLINE_OUT:
943 case LFUN_ERROR_NEXT:
945 case LFUN_REFERENCE_NEXT:
947 case LFUN_WORD_REPLACE:
950 case LFUN_MARK_TOGGLE:
951 case LFUN_SCREEN_RECENTER:
952 case LFUN_BIBTEX_DATABASE_ADD:
953 case LFUN_BIBTEX_DATABASE_DEL:
954 case LFUN_WORDS_COUNT:
955 case LFUN_NEXT_INSET_TOGGLE:
959 case LFUN_LABEL_GOTO: {
960 flag.enabled(!cmd.argument.empty()
961 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
965 case LFUN_BOOKMARK_GOTO:
966 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
968 case LFUN_CHANGES_TRACK:
970 flag.setOnOff(buffer_->params().tracking_changes);
973 case LFUN_CHANGES_OUTPUT: {
974 OutputParams runparams;
975 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
976 flag.enabled(buffer_ && buffer_->params().tracking_changes
977 && features.isAvailable("dvipost"));
978 flag.setOnOff(buffer_->params().output_changes);
982 case LFUN_CHANGES_MERGE:
983 case LFUN_CHANGE_ACCEPT: // what about these two
984 case LFUN_CHANGE_REJECT: // what about these two
985 case LFUN_ALL_CHANGES_ACCEPT:
986 case LFUN_ALL_CHANGES_REJECT:
987 flag.enabled(buffer_ && buffer_->params().tracking_changes);
990 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
991 flag.setOnOff(buffer_->params().compressed);
1004 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1006 //lyxerr << BOOST_CURRENT_FUNCTION
1007 // << [ cmd = " << cmd << "]" << endl;
1009 // Make sure that the cached BufferView is correct.
1010 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1011 << " action[" << cmd.action << ']'
1012 << " arg[" << cmd.argument << ']'
1013 << " x[" << cmd.x << ']'
1014 << " y[" << cmd.y << ']'
1015 << " button[" << cmd.button() << ']'
1018 LCursor & cur = cursor_;
1020 switch (cmd.action) {
1024 cur.message(_("Undo"));
1025 cur.clearSelection();
1026 if (!textUndo(*bv_))
1027 cur.message(_("No further undo information"));
1035 cur.message(_("Redo"));
1036 cur.clearSelection();
1037 if (!textRedo(*bv_))
1038 cur.message(_("No further redo information"));
1044 case LFUN_FILE_INSERT:
1045 menuInsertLyXFile(cmd.argument);
1048 case LFUN_FILE_INSERT_ASCII_PARA:
1049 insertAsciiFile(bv_, cmd.argument, true);
1052 case LFUN_FILE_INSERT_ASCII:
1053 insertAsciiFile(bv_, cmd.argument, false);
1056 case LFUN_FONT_STATE:
1057 cur.message(cur.currentState());
1060 case LFUN_BOOKMARK_SAVE:
1061 savePosition(convert<unsigned int>(cmd.argument));
1064 case LFUN_BOOKMARK_GOTO:
1065 restorePosition(convert<unsigned int>(cmd.argument));
1068 case LFUN_LABEL_GOTO: {
1069 string label = cmd.argument;
1070 if (label.empty()) {
1072 getInsetByCode<InsetRef>(cursor_,
1073 InsetBase::REF_CODE);
1075 label = inset->getContents();
1081 bv_->gotoLabel(label);
1085 case LFUN_PARAGRAPH_GOTO: {
1086 int const id = convert<int>(cmd.argument);
1087 ParIterator par = buffer_->getParFromID(id);
1088 if (par == buffer_->par_iterator_end()) {
1089 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1090 << id << ']' << endl;
1093 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1094 << " found." << endl;
1098 bv_->setCursor(makeDocIterator(par, 0));
1105 case LFUN_OUTLINE_UP:
1106 lyx::toc::outline(lyx::toc::Up, cursor_);
1107 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1108 updateLabels(*buffer_);
1110 case LFUN_OUTLINE_DOWN:
1111 lyx::toc::outline(lyx::toc::Down, cursor_);
1112 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1113 updateLabels(*buffer_);
1115 case LFUN_OUTLINE_IN:
1116 lyx::toc::outline(lyx::toc::In, cursor_);
1117 updateLabels(*buffer_);
1119 case LFUN_OUTLINE_OUT:
1120 lyx::toc::outline(lyx::toc::Out, cursor_);
1121 updateLabels(*buffer_);
1124 case LFUN_ERROR_NEXT:
1125 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1128 case LFUN_NOTE_NEXT:
1129 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1132 case LFUN_REFERENCE_NEXT: {
1133 vector<InsetBase_code> tmp;
1134 tmp.push_back(InsetBase::LABEL_CODE);
1135 tmp.push_back(InsetBase::REF_CODE);
1136 bv_funcs::gotoInset(bv_, tmp, true);
1140 case LFUN_CHANGES_TRACK:
1144 case LFUN_CHANGES_OUTPUT: {
1145 bool const state = buffer_->params().output_changes;
1146 buffer_->params().output_changes = !state;
1150 case LFUN_CHANGES_MERGE:
1151 if (lyx::find::findNextChange(bv_))
1152 owner_->getDialogs().show("changes");
1155 case LFUN_ALL_CHANGES_ACCEPT: {
1156 cursor_.reset(buffer_->inset());
1157 #ifdef WITH_WARNINGS
1158 #warning FIXME changes
1160 while (lyx::find::findNextChange(bv_))
1161 bv_->getLyXText()->acceptChange(cursor_);
1166 case LFUN_ALL_CHANGES_REJECT: {
1167 cursor_.reset(buffer_->inset());
1168 #ifdef WITH_WARNINGS
1169 #warning FIXME changes
1171 while (lyx::find::findNextChange(bv_))
1172 bv_->getLyXText()->rejectChange(cursor_);
1176 case LFUN_WORD_FIND:
1177 lyx::find::find(bv_, cmd);
1180 case LFUN_WORD_REPLACE:
1181 lyx::find::replace(bv_, cmd);
1185 cur.clearSelection();
1187 cur.message(N_("Mark off"));
1191 cur.clearSelection();
1194 cur.message(N_("Mark on"));
1197 case LFUN_MARK_TOGGLE:
1198 cur.clearSelection();
1201 cur.message(N_("Mark removed"));
1204 cur.message(N_("Mark set"));
1209 case LFUN_SCREEN_RECENTER:
1213 case LFUN_BIBTEX_DATABASE_ADD: {
1214 LCursor tmpcur = cursor_;
1215 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1216 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1217 InsetBase::BIBTEX_CODE);
1219 if (inset->addDatabase(cmd.argument))
1220 buffer_->updateBibfilesCache();
1225 case LFUN_BIBTEX_DATABASE_DEL: {
1226 LCursor tmpcur = cursor_;
1227 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1228 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1229 InsetBase::BIBTEX_CODE);
1231 if (inset->delDatabase(cmd.argument))
1232 buffer_->updateBibfilesCache();
1237 case LFUN_WORDS_COUNT: {
1238 DocIterator from, to;
1239 if (cur.selection()) {
1240 from = cur.selectionBegin();
1241 to = cur.selectionEnd();
1243 from = doc_iterator_begin(buffer_->inset());
1244 to = doc_iterator_end(buffer_->inset());
1246 int const count = countWords(from, to);
1249 if (cur.selection())
1250 message = bformat(_("%1$d words in selection."),
1253 message = bformat(_("%1$d words in document."),
1257 if (cur.selection())
1258 message = _("One word in selection.");
1260 message = _("One word in document.");
1263 Alert::information(_("Count words"), message);
1267 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1268 // turn compression on/off
1269 buffer_->params().compressed = !buffer_->params().compressed;
1272 case LFUN_NEXT_INSET_TOGGLE: {
1273 // this is the real function we want to invoke
1274 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1275 // if there is an inset at cursor, see whether it
1277 InsetBase * inset = cur.nextInset();
1278 if (inset && inset->isActive()) {
1279 LCursor tmpcur = cur;
1280 tmpcur.pushLeft(*inset);
1281 inset->dispatch(tmpcur, tmpcmd);
1282 if (tmpcur.result().dispatched()) {
1286 // if it did not work, try the underlying inset.
1287 if (!cur.result().dispatched())
1288 cur.dispatch(tmpcmd);
1290 if (cur.result().dispatched())
1291 cur.clearSelection();
1304 void BufferView::Pimpl::updateMetrics(bool singlepar)
1306 // Remove old position cache
1308 BufferView & bv = *bv_;
1309 LyXText * const text = bv.text();
1310 lyx::pit_type size = int(text->paragraphs().size());
1312 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1313 anchor_ref_ = int(text->paragraphs().size() - 1);
1317 lyx::pit_type const pit = anchor_ref_;
1320 size_t const npit = text->paragraphs().size();
1322 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1323 // the (main text, not inset!) paragraph containing the cursor.
1324 // (if this paragraph contains insets etc., rebreaking will
1325 // recursively descend)
1326 if (!singlepar || pit == cursor_.bottom().pit())
1327 text->redoParagraph(pit);
1328 int y0 = text->getPar(pit).ascent() - offset_ref_;
1330 // Redo paragraphs above anchor if necessary; again, in Single Par
1331 // mode, only if we encounter the (main text) one having the cursor.
1333 while (y1 > 0 && pit1 > 0) {
1334 y1 -= text->getPar(pit1).ascent();
1336 if (!singlepar || pit1 == cursor_.bottom().pit())
1337 text->redoParagraph(pit1);
1338 y1 -= text->getPar(pit1).descent();
1342 // Take care of ascent of first line
1343 y1 -= text->getPar(pit1).ascent();
1345 // Normalize anchor for next time
1349 // Grey at the beginning is ugly
1350 if (pit1 == 0 && y1 > 0) {
1356 // Redo paragraphs below the anchor if necessary. Single par mode:
1357 // only the one containing the cursor if encountered.
1359 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1360 y2 += text->getPar(pit2).descent();
1362 if (!singlepar || pit2 == cursor_.bottom().pit())
1363 text->redoParagraph(pit2);
1364 y2 += text->getPar(pit2).ascent();
1367 // Take care of descent of last line
1368 y2 += text->getPar(pit2).descent();
1370 // The coordinates of all these paragraphs are correct, cache them
1372 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1373 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1374 Paragraph const & par = text->getPar(pit);
1376 parPos[pit] = Point(0, y);
1377 if (singlepar && pit == cursor_.bottom().pit()) {
1378 // In Single Paragraph mode, collect here the
1379 // y1 and y2 of the (one) paragraph the cursor is in
1380 y1 = y - par.ascent();
1381 y2 = y + par.descent();
1387 // collect cursor paragraph iter bounds
1388 pit1 = cursor_.bottom().pit();
1389 pit2 = cursor_.bottom().pit();
1392 lyxerr[Debug::DEBUG]
1393 << BOOST_CURRENT_FUNCTION
1396 << " pit1: " << pit1
1397 << " pit2: " << pit2
1398 << " npit: " << npit
1399 << " singlepar: " << singlepar
1403 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);