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);
440 if (!lyxrc.cursor_follows_scrollbar)
443 int const height = 2 * defaultRowHeight();
444 int const first = height;
445 int const last = height_ - height;
446 LCursor & cur = cursor_;
448 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
451 case bv_funcs::CUR_ABOVE:
452 t.setCursorFromCoordinates(cur, 0, first);
453 cur.clearSelection();
455 case bv_funcs::CUR_BELOW:
456 t.setCursorFromCoordinates(cur, 0, last);
457 cur.clearSelection();
459 case bv_funcs::CUR_INSIDE:
460 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
461 int const newy = min(last, max(y, first));
463 cur.reset(buffer_->inset());
464 t.setCursorFromCoordinates(cur, 0, newy);
470 void BufferView::Pimpl::scroll(int /*lines*/)
475 // LyXText const * t = bv_->text();
476 // int const line_height = defaultRowHeight();
478 // // The new absolute coordinate
479 // int new_top_y = top_y() + lines * line_height;
481 // // Restrict to a valid value
482 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
483 // new_top_y = std::max(0, new_top_y);
485 // scrollDocView(new_top_y);
487 // // Update the scrollbar.
488 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
492 void BufferView::Pimpl::selectionRequested()
499 LCursor & cur = cursor_;
501 if (!cur.selection()) {
502 xsel_cache_.set = false;
506 if (!xsel_cache_.set ||
507 cur.top() != xsel_cache_.cursor ||
508 cur.anchor_.top() != xsel_cache_.anchor)
510 xsel_cache_.cursor = cur.top();
511 xsel_cache_.anchor = cur.anchor_.top();
512 xsel_cache_.set = cur.selection();
513 sel = cur.selectionAsString(false);
515 owner_->gui().selection().put(sel);
520 void BufferView::Pimpl::selectionLost()
523 cursor_.clearSelection();
524 xsel_cache_.set = false;
529 void BufferView::Pimpl::workAreaResize(int width, int height)
531 bool const widthChange = width != width_;
532 bool const heightChange = height != height_;
534 // Update from work area
538 if (buffer_ && widthChange) {
539 // The visible LyXView need a resize
540 resizeCurrentBuffer();
543 if (widthChange || heightChange)
548 bool BufferView::Pimpl::fitCursor()
550 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
551 LyXFont const font = cursor_.getFont();
552 int const asc = font_metrics::maxAscent(font);
553 int const des = font_metrics::maxDescent(font);
554 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
555 if (p.y_ - asc >= 0 && p.y_ + des < height_)
563 bool BufferView::Pimpl::multiParSel()
565 if (!cursor_.selection())
567 bool ret = multiparsel_cache_;
568 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
569 // Either this, or previous selection spans paragraphs
570 return ret || multiparsel_cache_;
574 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
576 return metrics_info_;
580 bool BufferView::Pimpl::update(Update::flags flags)
582 // This is close to a hot-path.
583 if (lyxerr.debugging(Debug::DEBUG)) {
585 << BOOST_CURRENT_FUNCTION
586 << "[fitcursor = " << (flags & Update::FitCursor)
587 << ", forceupdate = " << (flags & Update::Force)
588 << ", singlepar = " << (flags & Update::SinglePar)
589 << "] buffer: " << buffer_ << endl;
592 // Check needed to survive LyX startup
596 // Update macro store
597 buffer_->buildMacros();
599 // First drawing step
600 updateMetrics(flags & Update::SinglePar);
602 // The second drawing step is done in WorkArea::redraw() if needed.
603 bool const need_second_step =
604 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
605 && (fitCursor() || multiParSel());
607 return need_second_step;
611 bool BufferView::Pimpl::available() const
613 return buffer_ && bv_->text();
617 Change const BufferView::Pimpl::getCurrentChange()
619 if (!buffer_->params().tracking_changes)
620 return Change(Change::UNCHANGED);
622 LyXText * text = bv_->getLyXText();
623 LCursor & cur = cursor_;
625 if (!cur.selection())
626 return Change(Change::UNCHANGED);
628 return text->getPar(cur.selBegin().pit()).
629 lookupChange(cur.selBegin().pos());
633 void BufferView::Pimpl::savePosition(unsigned int i)
635 if (i >= saved_positions_num)
637 BOOST_ASSERT(cursor_.inTexted());
638 saved_positions[i] = Position(buffer_->fileName(),
639 cursor_.paragraph().id(),
642 owner_->message(bformat(_("Saved bookmark %1$d"), i));
646 void BufferView::Pimpl::restorePosition(unsigned int i)
648 if (i >= saved_positions_num)
651 string const fname = saved_positions[i].filename;
653 cursor_.clearSelection();
655 if (fname != buffer_->fileName()) {
657 if (bufferlist.exists(fname))
658 b = bufferlist.getBuffer(fname);
660 b = bufferlist.newBuffer(fname);
661 // Don't ask, just load it
662 ::loadLyXFile(b, fname);
668 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
669 if (par == buffer_->par_iterator_end())
672 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
675 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
679 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
681 return i < saved_positions_num && !saved_positions[i].filename.empty();
685 void BufferView::Pimpl::saveSavedPositions()
687 // save bookmarks. It is better to use the pit interface
688 // but I do not know how to effectively convert between
690 for (unsigned int i=1; i < saved_positions_num; ++i) {
691 if ( isSavedPosition(i) )
692 LyX::ref().session().saveBookmark( boost::tie(
694 saved_positions[i].filename,
695 saved_positions[i].par_id,
696 saved_positions[i].par_pos) );
701 void BufferView::Pimpl::switchKeyMap()
703 if (!lyxrc.rtl_support)
706 Intl & intl = owner_->getIntl();
707 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
708 if (intl.keymap == Intl::PRIMARY)
711 if (intl.keymap == Intl::SECONDARY)
717 void BufferView::Pimpl::center()
719 CursorSlice & bot = cursor_.bottom();
720 lyx::pit_type const pit = bot.pit();
721 bot.text()->redoParagraph(pit);
722 Paragraph const & par = bot.text()->paragraphs()[pit];
724 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
725 + par.ascent() - height_ / 2;
729 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
731 BOOST_ASSERT(cursor_.inTexted());
732 string filename = filenm;
734 if (filename.empty()) {
735 // Launch a file browser
736 string initpath = lyxrc.document_path;
739 string const trypath = buffer_->filePath();
740 // If directory is writeable, use this as default.
741 if (isDirWriteable(trypath))
745 FileDialog fileDlg(_("Select LyX document to insert"),
747 make_pair(string(_("Documents|#o#O")),
748 string(lyxrc.document_path)),
749 make_pair(string(_("Examples|#E#e")),
750 string(addPath(package().system_support(), "examples"))));
752 FileDialog::Result result =
753 fileDlg.open(initpath,
754 FileFilterList(_("LyX Documents (*.lyx)")),
757 if (result.first == FileDialog::Later)
760 filename = result.second;
762 // check selected filename
763 if (filename.empty()) {
764 owner_->message(_("Canceled."));
769 // Get absolute path of file and add ".lyx"
770 // to the filename if necessary
771 filename = fileSearch(string(), filename, "lyx");
773 string const disp_fn = makeDisplayPath(filename);
774 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
777 Buffer buf("", false);
778 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
779 ErrorList & el = buffer_->errorList("Parse");
780 // Copy the inserted document error list into the current buffer one.
781 el = buf.errorList("Parse");
782 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
783 buf.params().textclass, el);
784 res = _("Document %1$s inserted.");
786 res = _("Could not insert document %1$s");
788 owner_->message(bformat(res, disp_fn));
789 buffer_->errors("Parse");
790 resizeCurrentBuffer();
794 void BufferView::Pimpl::trackChanges()
796 bool const tracking = buffer_->params().tracking_changes;
799 for_each(buffer_->par_iterator_begin(),
800 buffer_->par_iterator_end(),
801 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
802 buffer_->params().tracking_changes = true;
804 // We cannot allow undos beyond the freeze point
805 buffer_->undostack().clear();
807 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
808 if (lyx::find::findNextChange(bv_)) {
809 owner_->getDialogs().show("changes");
813 for_each(buffer_->par_iterator_begin(),
814 buffer_->par_iterator_end(),
815 mem_fun_ref(&Paragraph::untrackChanges));
817 buffer_->params().tracking_changes = false;
820 buffer_->redostack().clear();
824 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
826 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
828 // This is only called for mouse related events including
829 // LFUN_FILE_OPEN generated by drag-and-drop.
830 FuncRequest cmd = cmd0;
836 cur.push(buffer_->inset());
837 cur.selection() = cursor_.selection();
839 // Doesn't go through lyxfunc, so we need to update
840 // the layout choice etc. ourselves
842 // E.g. Qt mouse press when no buffer
846 // Either the inset under the cursor or the
847 // surrounding LyXText will handle this event.
849 // Build temporary cursor.
850 cmd.y = min(max(cmd.y, -1), height_);
851 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
852 //lyxerr << BOOST_CURRENT_FUNCTION
853 // << " * hit inset at tip: " << inset << endl;
854 //lyxerr << BOOST_CURRENT_FUNCTION
855 // << " * created temp cursor:" << cur << endl;
857 // Put anchor at the same position.
860 // Try to dispatch to an non-editable inset near this position
861 // via the temp cursor. If the inset wishes to change the real
862 // cursor it has to do so explicitly by using
863 // cur.bv().cursor() = cur; (or similar)
865 inset->dispatch(cur, cmd);
867 // Now dispatch to the temporary cursor. If the real cursor should
868 // be modified, the inset's dispatch has to do so explicitly.
869 if (!cur.result().dispatched())
872 if (cur.result().dispatched()) {
873 // Redraw if requested or necessary.
874 if (cur.result().update())
875 update(Update::FitCursor | Update::Force);
877 update(Update::FitCursor | Update::MultiParSel);
884 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
888 switch (cmd.action) {
891 flag.enabled(!buffer_->undostack().empty());
894 flag.enabled(!buffer_->redostack().empty());
896 case LFUN_FILE_INSERT:
897 case LFUN_FILE_INSERT_ASCII_PARA:
898 case LFUN_FILE_INSERT_ASCII:
899 case LFUN_BOOKMARK_SAVE:
900 // FIXME: Actually, these LFUNS should be moved to LyXText
901 flag.enabled(cursor_.inTexted());
903 case LFUN_FONT_STATE:
904 case LFUN_LABEL_INSERT:
905 case LFUN_PARAGRAPH_GOTO:
906 // FIXME handle non-trivially
907 case LFUN_OUTLINE_UP:
908 case LFUN_OUTLINE_DOWN:
909 case LFUN_OUTLINE_IN:
910 case LFUN_OUTLINE_OUT:
911 case LFUN_ERROR_NEXT:
913 case LFUN_REFERENCE_NEXT:
915 case LFUN_WORD_REPLACE:
918 case LFUN_MARK_TOGGLE:
919 case LFUN_SCREEN_RECENTER:
920 case LFUN_BIBTEX_DATABASE_ADD:
921 case LFUN_BIBTEX_DATABASE_DEL:
922 case LFUN_WORDS_COUNT:
923 case LFUN_NEXT_INSET_TOGGLE:
927 case LFUN_LABEL_GOTO: {
928 flag.enabled(!cmd.argument.empty()
929 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
933 case LFUN_BOOKMARK_GOTO:
934 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
936 case LFUN_CHANGES_TRACK:
938 flag.setOnOff(buffer_->params().tracking_changes);
941 case LFUN_CHANGES_OUTPUT: {
942 OutputParams runparams;
943 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
944 flag.enabled(buffer_ && buffer_->params().tracking_changes
945 && features.isAvailable("dvipost"));
946 flag.setOnOff(buffer_->params().output_changes);
950 case LFUN_CHANGES_MERGE:
951 case LFUN_CHANGE_ACCEPT: // what about these two
952 case LFUN_CHANGE_REJECT: // what about these two
953 case LFUN_ALL_CHANGES_ACCEPT:
954 case LFUN_ALL_CHANGES_REJECT:
955 flag.enabled(buffer_ && buffer_->params().tracking_changes);
958 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
959 flag.setOnOff(buffer_->params().compressed);
972 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
974 //lyxerr << BOOST_CURRENT_FUNCTION
975 // << [ cmd = " << cmd << "]" << endl;
977 // Make sure that the cached BufferView is correct.
978 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
979 << " action[" << cmd.action << ']'
980 << " arg[" << cmd.argument << ']'
981 << " x[" << cmd.x << ']'
982 << " y[" << cmd.y << ']'
983 << " button[" << cmd.button() << ']'
986 LCursor & cur = cursor_;
988 switch (cmd.action) {
992 cur.message(_("Undo"));
993 cur.clearSelection();
995 cur.message(_("No further undo information"));
1003 cur.message(_("Redo"));
1004 cur.clearSelection();
1005 if (!textRedo(*bv_))
1006 cur.message(_("No further redo information"));
1012 case LFUN_FILE_INSERT:
1013 menuInsertLyXFile(cmd.argument);
1016 case LFUN_FILE_INSERT_ASCII_PARA:
1017 insertAsciiFile(bv_, cmd.argument, true);
1020 case LFUN_FILE_INSERT_ASCII:
1021 insertAsciiFile(bv_, cmd.argument, false);
1024 case LFUN_FONT_STATE:
1025 cur.message(cur.currentState());
1028 case LFUN_BOOKMARK_SAVE:
1029 savePosition(convert<unsigned int>(cmd.argument));
1032 case LFUN_BOOKMARK_GOTO:
1033 restorePosition(convert<unsigned int>(cmd.argument));
1036 case LFUN_LABEL_GOTO: {
1037 string label = cmd.argument;
1038 if (label.empty()) {
1040 getInsetByCode<InsetRef>(cursor_,
1041 InsetBase::REF_CODE);
1043 label = inset->getContents();
1049 bv_->gotoLabel(label);
1053 case LFUN_PARAGRAPH_GOTO: {
1054 int const id = convert<int>(cmd.argument);
1055 ParIterator par = buffer_->getParFromID(id);
1056 if (par == buffer_->par_iterator_end()) {
1057 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1058 << id << ']' << endl;
1061 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1062 << " found." << endl;
1066 bv_->setCursor(makeDocIterator(par, 0));
1073 case LFUN_OUTLINE_UP:
1074 lyx::toc::outline(lyx::toc::Up, cursor_);
1075 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1076 updateLabels(*buffer_);
1078 case LFUN_OUTLINE_DOWN:
1079 lyx::toc::outline(lyx::toc::Down, cursor_);
1080 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1081 updateLabels(*buffer_);
1083 case LFUN_OUTLINE_IN:
1084 lyx::toc::outline(lyx::toc::In, cursor_);
1085 updateLabels(*buffer_);
1087 case LFUN_OUTLINE_OUT:
1088 lyx::toc::outline(lyx::toc::Out, cursor_);
1089 updateLabels(*buffer_);
1092 case LFUN_ERROR_NEXT:
1093 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1096 case LFUN_NOTE_NEXT:
1097 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1100 case LFUN_REFERENCE_NEXT: {
1101 vector<InsetBase_code> tmp;
1102 tmp.push_back(InsetBase::LABEL_CODE);
1103 tmp.push_back(InsetBase::REF_CODE);
1104 bv_funcs::gotoInset(bv_, tmp, true);
1108 case LFUN_CHANGES_TRACK:
1112 case LFUN_CHANGES_OUTPUT: {
1113 bool const state = buffer_->params().output_changes;
1114 buffer_->params().output_changes = !state;
1118 case LFUN_CHANGES_MERGE:
1119 if (lyx::find::findNextChange(bv_))
1120 owner_->getDialogs().show("changes");
1123 case LFUN_ALL_CHANGES_ACCEPT: {
1124 cursor_.reset(buffer_->inset());
1125 #ifdef WITH_WARNINGS
1126 #warning FIXME changes
1128 while (lyx::find::findNextChange(bv_))
1129 bv_->getLyXText()->acceptChange(cursor_);
1134 case LFUN_ALL_CHANGES_REJECT: {
1135 cursor_.reset(buffer_->inset());
1136 #ifdef WITH_WARNINGS
1137 #warning FIXME changes
1139 while (lyx::find::findNextChange(bv_))
1140 bv_->getLyXText()->rejectChange(cursor_);
1144 case LFUN_WORD_FIND:
1145 lyx::find::find(bv_, cmd);
1148 case LFUN_WORD_REPLACE:
1149 lyx::find::replace(bv_, cmd);
1153 cur.clearSelection();
1155 cur.message(N_("Mark off"));
1159 cur.clearSelection();
1162 cur.message(N_("Mark on"));
1165 case LFUN_MARK_TOGGLE:
1166 cur.clearSelection();
1169 cur.message(N_("Mark removed"));
1172 cur.message(N_("Mark set"));
1177 case LFUN_SCREEN_RECENTER:
1181 case LFUN_BIBTEX_DATABASE_ADD: {
1182 LCursor tmpcur = cursor_;
1183 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1184 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1185 InsetBase::BIBTEX_CODE);
1187 if (inset->addDatabase(cmd.argument))
1188 buffer_->updateBibfilesCache();
1193 case LFUN_BIBTEX_DATABASE_DEL: {
1194 LCursor tmpcur = cursor_;
1195 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1196 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1197 InsetBase::BIBTEX_CODE);
1199 if (inset->delDatabase(cmd.argument))
1200 buffer_->updateBibfilesCache();
1205 case LFUN_WORDS_COUNT: {
1206 DocIterator from, to;
1207 if (cur.selection()) {
1208 from = cur.selectionBegin();
1209 to = cur.selectionEnd();
1211 from = doc_iterator_begin(buffer_->inset());
1212 to = doc_iterator_end(buffer_->inset());
1214 int const count = countWords(from, to);
1217 if (cur.selection())
1218 message = bformat(_("%1$d words in selection."),
1221 message = bformat(_("%1$d words in document."),
1225 if (cur.selection())
1226 message = _("One word in selection.");
1228 message = _("One word in document.");
1231 Alert::information(_("Count words"), message);
1235 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1236 // turn compression on/off
1237 buffer_->params().compressed = !buffer_->params().compressed;
1240 case LFUN_NEXT_INSET_TOGGLE: {
1241 // this is the real function we want to invoke
1242 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1243 // if there is an inset at cursor, see whether it
1245 InsetBase * inset = cur.nextInset();
1246 if (inset && inset->isActive()) {
1247 LCursor tmpcur = cur;
1248 tmpcur.pushLeft(*inset);
1249 inset->dispatch(tmpcur, tmpcmd);
1250 if (tmpcur.result().dispatched()) {
1254 // if it did not work, try the underlying inset.
1255 if (!cur.result().dispatched())
1256 cur.dispatch(tmpcmd);
1258 if (cur.result().dispatched())
1259 cur.clearSelection();
1272 void BufferView::Pimpl::updateMetrics(bool singlepar)
1274 // Remove old position cache
1276 BufferView & bv = *bv_;
1277 LyXText * const text = bv.text();
1278 lyx::pit_type size = int(text->paragraphs().size());
1280 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1281 anchor_ref_ = int(text->paragraphs().size() - 1);
1285 lyx::pit_type const pit = anchor_ref_;
1288 size_t const npit = text->paragraphs().size();
1290 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1291 // the (main text, not inset!) paragraph containing the cursor.
1292 // (if this paragraph contains insets etc., rebreaking will
1293 // recursively descend)
1294 if (!singlepar || pit == cursor_.bottom().pit())
1295 text->redoParagraph(pit);
1296 int y0 = text->getPar(pit).ascent() - offset_ref_;
1298 // Redo paragraphs above anchor if necessary; again, in Single Par
1299 // mode, only if we encounter the (main text) one having the cursor.
1301 while (y1 > 0 && pit1 > 0) {
1302 y1 -= text->getPar(pit1).ascent();
1304 if (!singlepar || pit1 == cursor_.bottom().pit())
1305 text->redoParagraph(pit1);
1306 y1 -= text->getPar(pit1).descent();
1310 // Take care of ascent of first line
1311 y1 -= text->getPar(pit1).ascent();
1313 // Normalize anchor for next time
1317 // Grey at the beginning is ugly
1318 if (pit1 == 0 && y1 > 0) {
1324 // Redo paragraphs below the anchor if necessary. Single par mode:
1325 // only the one containing the cursor if encountered.
1327 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1328 y2 += text->getPar(pit2).descent();
1330 if (!singlepar || pit2 == cursor_.bottom().pit())
1331 text->redoParagraph(pit2);
1332 y2 += text->getPar(pit2).ascent();
1335 // Take care of descent of last line
1336 y2 += text->getPar(pit2).descent();
1338 // The coordinates of all these paragraphs are correct, cache them
1340 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1341 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1342 Paragraph const & par = text->getPar(pit);
1344 parPos[pit] = Point(0, y);
1345 if (singlepar && pit == cursor_.bottom().pit()) {
1346 // In Single Paragraph mode, collect here the
1347 // y1 and y2 of the (one) paragraph the cursor is in
1348 y1 = y - par.ascent();
1349 y2 = y + par.descent();
1355 // collect cursor paragraph iter bounds
1356 pit1 = cursor_.bottom().pit();
1357 pit2 = cursor_.bottom().pit();
1360 lyxerr[Debug::DEBUG]
1361 << BOOST_CURRENT_FUNCTION
1364 << " pit1: " << pit1
1365 << " pit2: " << pit2
1366 << " npit: " << npit
1367 << " singlepar: " << singlepar
1371 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);