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
15 * \author Abdelrazak Younes
17 * Full author contact details are available in file CREDITS.
22 #include "BufferView_pimpl.h"
24 #include "buffer_funcs.h"
25 #include "bufferlist.h"
26 #include "bufferparams.h"
27 #include "coordcache.h"
29 #include "CutAndPaste.h"
31 #include "dispatchresult.h"
32 #include "errorlist.h"
34 #include "FloatList.h"
35 #include "funcrequest.h"
36 #include "FuncStatus.h"
39 #include "insetiterator.h"
40 #include "LaTeXFeatures.h"
41 #include "lyx_cb.h" // added for Dispatch functions
48 #include "metricsinfo.h"
49 #include "paragraph.h"
50 #include "paragraph_funcs.h"
51 #include "ParagraphParameters.h"
52 #include "pariterator.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetref.h"
59 #include "insets/insettext.h"
61 #include "frontends/Alert.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Selection.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/filefilterlist.h"
73 #include "support/filetools.h"
74 #include "support/package.h"
75 #include "support/types.h"
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
83 using lyx::frontend::Clipboard;
84 using lyx::frontend::Gui;
89 using lyx::support::addPath;
90 using lyx::support::bformat;
91 using lyx::support::FileFilterList;
92 using lyx::support::fileSearch;
93 using lyx::support::isDirWriteable;
94 using lyx::support::makeDisplayPath;
95 using lyx::support::makeAbsPath;
96 using lyx::support::package;
99 using std::istringstream;
100 using std::make_pair;
104 using std::mem_fun_ref;
107 extern BufferList bufferlist;
112 unsigned int const saved_positions_num = 20;
115 /// Return an inset of this class if it exists at the current cursor position
117 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
120 DocIterator it = cur;
121 if (it.nextInset() &&
122 it.nextInset()->lyxCode() == code) {
123 inset = static_cast<T*>(it.nextInset());
131 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
132 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
134 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
136 xsel_cache_.set = false;
138 saved_positions.resize(saved_positions_num);
139 // load saved bookmarks
140 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
141 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
142 bm != bmList.end(); ++bm)
143 if (bm->get<0>() < saved_positions_num)
144 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
145 // and then clear them
150 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
152 // Get absolute path of file and add ".lyx"
153 // to the filename if necessary
154 string s = fileSearch(string(), filename, "lyx");
156 bool const found = !s.empty();
161 // File already open?
162 if (bufferlist.exists(s)) {
163 docstring const file = makeDisplayPath(s, 20);
164 docstring text = bformat(_("The document %1$s is already "
165 "loaded.\n\nDo you want to revert "
166 "to the saved version?"), file);
167 int const ret = Alert::prompt(_("Revert to saved document?"),
168 text, 0, 1, _("&Revert"), _("&Switch to document"));
171 setBuffer(bufferlist.getBuffer(s));
174 // FIXME: should be LFUN_REVERT
175 if (!bufferlist.close(bufferlist.getBuffer(s), false))
177 // Fall through to new load. (Asger)
183 b = bufferlist.newBuffer(s);
184 if (!::loadLyXFile(b, s)) {
185 bufferlist.release(b);
189 docstring text = bformat(_("The document %1$s does not yet "
190 "exist.\n\nDo you want to create "
191 "a new document?"), lyx::from_utf8(s));
192 int const ret = Alert::prompt(_("Create new document?"),
193 text, 0, 1, _("&Create"), _("Cancel"));
196 b = newFile(s, string(), true);
204 // Send the "errors" signal in case of parsing errors
207 // scroll to the position when the file was last closed
208 if (lyxrc.use_lastfilepos) {
211 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
212 // I am not sure how to separate the following part to a function
213 // so I will leave this to Lars.
215 // check pit since the document may be externally changed.
216 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
217 ParIterator it = b->par_iterator_begin();
218 ParIterator const end = b->par_iterator_end();
219 for (; it != end; ++it)
220 if (it.pit() == pit) {
221 // restored pos may be bigger than it->size
222 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
223 bv_->update(Update::FitCursor);
230 LyX::ref().session().addLastFile(b->fileName());
236 int BufferView::Pimpl::width() const
242 int BufferView::Pimpl::height() const
248 void BufferView::Pimpl::setBuffer(Buffer * b)
250 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
251 << "[ b = " << b << "]" << endl;
254 // Save the actual cursor position and anchor inside the
255 // buffer so that it can be restored in case we rechange
256 // to this buffer later on.
257 buffer_->saveCursor(cursor_.selectionBegin(),
258 cursor_.selectionEnd());
259 // current buffer is going to be switched-off, save cursor pos
260 LyX::ref().session().saveFilePosition(buffer_->fileName(),
261 boost::tie(cursor_.pit(), cursor_.pos()) );
264 // If we're quitting lyx, don't bother updating stuff
270 // If we are closing current buffer, switch to the first in
273 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
274 << " No Buffer!" << endl;
275 // We are closing the buffer, use the first buffer as current
276 buffer_ = bufferlist.first();
278 // Set current buffer
283 cursor_ = LCursor(*bv_);
288 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
289 << "Buffer addr: " << buffer_ << endl;
290 cursor_.push(buffer_->inset());
291 cursor_.resetAnchor();
292 buffer_->text().init(bv_);
293 buffer_->text().setCurrentFont(cursor_);
294 if (buffer_->getCursor().size() > 0 &&
295 buffer_->getAnchor().size() > 0)
297 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
298 cursor_.resetAnchor();
299 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
300 cursor_.setSelection();
306 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
307 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
311 void BufferView::Pimpl::resizeCurrentBuffer()
313 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
315 LyXText * text = bv_->text();
325 void BufferView::Pimpl::updateScrollbar()
328 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
329 << " no text in updateScrollbar" << endl;
330 scrollbarParameters_.reset();
334 LyXText & t = *bv_->text();
335 int const parsize = int(t.paragraphs().size() - 1);
336 if (anchor_ref_ > parsize) {
337 anchor_ref_ = parsize;
342 << BOOST_CURRENT_FUNCTION
343 << " Updating scrollbar: height: " << t.paragraphs().size()
344 << " curr par: " << cursor_.bottom().pit()
345 << " default height " << defaultRowHeight() << endl;
347 // It would be better to fix the scrollbar to understand
348 // values in [0..1] and divide everything by wh
350 // estimated average paragraph height:
353 int h = t.getPar(anchor_ref_).height();
355 // Normalize anchor/offset (MV):
356 while (offset_ref_ > h && anchor_ref_ < parsize) {
359 h = t.getPar(anchor_ref_).height();
361 // Look at paragraph heights on-screen
364 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
367 int const h2 = t.getPar(pit).height();
371 int const hav = sumh / nh;
372 // More realistic average paragraph height
376 scrollbarParameters_.height = (parsize + 1) * wh_;
377 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
378 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
382 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
384 return scrollbarParameters_;
388 void BufferView::Pimpl::scrollDocView(int value)
390 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
391 << "[ value = " << value << "]" << endl;
396 LyXText & t = *bv_->text();
398 float const bar = value / float(wh_ * t.paragraphs().size());
400 anchor_ref_ = int(bar * t.paragraphs().size());
401 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
402 anchor_ref_ = int(t.paragraphs().size()) - 1;
403 t.redoParagraph(anchor_ref_);
404 int const h = t.getPar(anchor_ref_).height();
405 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
409 void BufferView::Pimpl::setCursorFromScrollbar()
411 LyXText & t = *bv_->text();
413 int const height = 2 * defaultRowHeight();
414 int const first = height;
415 int const last = height_ - height;
416 LCursor & cur = cursor_;
418 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
421 case bv_funcs::CUR_ABOVE:
422 t.setCursorFromCoordinates(cur, 0, first);
423 cur.clearSelection();
425 case bv_funcs::CUR_BELOW:
426 t.setCursorFromCoordinates(cur, 0, last);
427 cur.clearSelection();
429 case bv_funcs::CUR_INSIDE:
430 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
431 int const newy = min(last, max(y, first));
433 cur.reset(buffer_->inset());
434 t.setCursorFromCoordinates(cur, 0, newy);
440 void BufferView::Pimpl::scroll(int /*lines*/)
445 // LyXText const * t = bv_->text();
446 // int const line_height = defaultRowHeight();
448 // // The new absolute coordinate
449 // int new_top_y = top_y() + lines * line_height;
451 // // Restrict to a valid value
452 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
453 // new_top_y = std::max(0, new_top_y);
455 // scrollDocView(new_top_y);
457 // // Update the scrollbar.
458 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
462 void BufferView::Pimpl::selectionRequested()
464 static docstring sel;
469 LCursor & cur = cursor_;
471 if (!cur.selection()) {
472 xsel_cache_.set = false;
476 if (!xsel_cache_.set ||
477 cur.top() != xsel_cache_.cursor ||
478 cur.anchor_.top() != xsel_cache_.anchor)
480 xsel_cache_.cursor = cur.top();
481 xsel_cache_.anchor = cur.anchor_.top();
482 xsel_cache_.set = cur.selection();
483 sel = cur.selectionAsString(false);
485 owner_->gui().selection().put(sel);
490 void BufferView::Pimpl::selectionLost()
493 cursor_.clearSelection();
494 xsel_cache_.set = false;
499 void BufferView::Pimpl::workAreaResize(int width, int height)
501 bool const widthChange = width != width_;
502 bool const heightChange = height != height_;
504 // Update from work area
508 if (buffer_ && widthChange) {
509 // The WorkArea content needs a resize
510 resizeCurrentBuffer();
513 if (widthChange || heightChange)
518 bool BufferView::Pimpl::fitCursor()
520 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
521 LyXFont const font = cursor_.getFont();
522 int const asc = font_metrics::maxAscent(font);
523 int const des = font_metrics::maxDescent(font);
524 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
525 if (p.y_ - asc >= 0 && p.y_ + des < height_)
533 bool BufferView::Pimpl::multiParSel()
535 if (!cursor_.selection())
537 bool ret = multiparsel_cache_;
538 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
539 // Either this, or previous selection spans paragraphs
540 return ret || multiparsel_cache_;
544 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
546 return metrics_info_;
550 bool BufferView::Pimpl::update(Update::flags flags)
552 // This is close to a hot-path.
553 if (lyxerr.debugging(Debug::DEBUG)) {
555 << BOOST_CURRENT_FUNCTION
556 << "[fitcursor = " << (flags & Update::FitCursor)
557 << ", forceupdate = " << (flags & Update::Force)
558 << ", singlepar = " << (flags & Update::SinglePar)
559 << "] buffer: " << buffer_ << endl;
562 // Check needed to survive LyX startup
566 // Update macro store
567 buffer_->buildMacros();
569 // First drawing step
570 updateMetrics(flags & Update::SinglePar);
572 // The second drawing step is done in WorkArea::redraw() if needed.
573 bool const need_second_step =
574 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
575 && (fitCursor() || multiParSel());
577 return need_second_step;
581 bool BufferView::Pimpl::available() const
583 return buffer_ && bv_->text();
587 Change const BufferView::Pimpl::getCurrentChange()
589 if (!buffer_->params().tracking_changes || !cursor_.selection())
590 return Change(Change::UNCHANGED);
592 DocIterator dit = cursor_.selectionBegin();
593 return dit.paragraph().lookupChange(dit.pos());
597 void BufferView::Pimpl::savePosition(unsigned int i)
599 if (i >= saved_positions_num)
601 BOOST_ASSERT(cursor_.inTexted());
602 saved_positions[i] = Position(buffer_->fileName(),
603 cursor_.paragraph().id(),
606 // emit message signal.
607 bv_->message(bformat(_("Saved bookmark %1$d"), i));
611 void BufferView::Pimpl::restorePosition(unsigned int i)
613 if (i >= saved_positions_num)
616 string const fname = saved_positions[i].filename;
618 cursor_.clearSelection();
620 if (fname != buffer_->fileName()) {
622 if (bufferlist.exists(fname))
623 b = bufferlist.getBuffer(fname);
625 b = bufferlist.newBuffer(fname);
626 // Don't ask, just load it
627 ::loadLyXFile(b, fname);
633 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
634 if (par == buffer_->par_iterator_end())
637 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
640 // emit message signal.
641 bv_->message(bformat(_("Moved to bookmark %1$d"), i));
645 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
647 return i < saved_positions_num && !saved_positions[i].filename.empty();
651 void BufferView::Pimpl::saveSavedPositions()
653 // save bookmarks. It is better to use the pit interface
654 // but I do not know how to effectively convert between
656 for (unsigned int i=1; i < saved_positions_num; ++i) {
657 if ( isSavedPosition(i) )
658 LyX::ref().session().saveBookmark( boost::tie(
660 saved_positions[i].filename,
661 saved_positions[i].par_id,
662 saved_positions[i].par_pos) );
667 void BufferView::Pimpl::switchKeyMap()
669 if (!lyxrc.rtl_support)
672 Intl & intl = owner_->getIntl();
673 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
674 if (intl.keymap == Intl::PRIMARY)
677 if (intl.keymap == Intl::SECONDARY)
683 void BufferView::Pimpl::center()
685 CursorSlice & bot = cursor_.bottom();
686 lyx::pit_type const pit = bot.pit();
687 bot.text()->redoParagraph(pit);
688 Paragraph const & par = bot.text()->paragraphs()[pit];
690 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
691 + par.ascent() - height_ / 2;
695 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
697 BOOST_ASSERT(cursor_.inTexted());
698 string filename = filenm;
700 if (filename.empty()) {
701 // Launch a file browser
702 string initpath = lyxrc.document_path;
705 string const trypath = buffer_->filePath();
706 // If directory is writeable, use this as default.
707 if (isDirWriteable(trypath))
711 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
713 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
714 string(lyxrc.document_path)),
715 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
716 string(addPath(package().system_support(), "examples"))));
718 FileDialog::Result result =
719 fileDlg.open(initpath,
720 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
723 if (result.first == FileDialog::Later)
726 filename = result.second;
728 // check selected filename
729 if (filename.empty()) {
730 // emit message signal.
731 bv_->message(_("Canceled."));
736 // Get absolute path of file and add ".lyx"
737 // to the filename if necessary
738 filename = fileSearch(string(), filename, "lyx");
740 docstring const disp_fn = makeDisplayPath(filename);
741 // emit message signal.
742 bv_->message(bformat(_("Inserting document %1$s..."), disp_fn));
745 Buffer buf("", false);
746 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
747 ErrorList & el = buffer_->errorList("Parse");
748 // Copy the inserted document error list into the current buffer one.
749 el = buf.errorList("Parse");
750 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
751 buf.params().textclass, el);
752 res = _("Document %1$s inserted.");
754 res = _("Could not insert document %1$s");
756 // emit message signal.
757 bv_->message(bformat(res, disp_fn));
758 buffer_->errors("Parse");
759 resizeCurrentBuffer();
763 void BufferView::Pimpl::trackChanges()
765 bool const tracking = buffer_->params().tracking_changes;
768 for_each(buffer_->par_iterator_begin(),
769 buffer_->par_iterator_end(),
770 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
771 buffer_->params().tracking_changes = true;
773 // We cannot allow undos beyond the freeze point
774 buffer_->undostack().clear();
776 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
777 if (lyx::find::findNextChange(bv_)) {
778 owner_->getDialogs().show("changes");
782 for_each(buffer_->par_iterator_begin(),
783 buffer_->par_iterator_end(),
784 mem_fun_ref(&Paragraph::untrackChanges));
786 buffer_->params().tracking_changes = false;
789 buffer_->redostack().clear();
793 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
795 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
797 // This is only called for mouse related events including
798 // LFUN_FILE_OPEN generated by drag-and-drop.
799 FuncRequest cmd = cmd0;
805 cur.push(buffer_->inset());
806 cur.selection() = cursor_.selection();
808 // Doesn't go through lyxfunc, so we need to update
809 // the layout choice etc. ourselves
811 // E.g. Qt mouse press when no buffer
815 // Either the inset under the cursor or the
816 // surrounding LyXText will handle this event.
818 // Build temporary cursor.
819 cmd.y = min(max(cmd.y, -1), height_);
820 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
821 //lyxerr << BOOST_CURRENT_FUNCTION
822 // << " * hit inset at tip: " << inset << endl;
823 //lyxerr << BOOST_CURRENT_FUNCTION
824 // << " * created temp cursor:" << cur << endl;
826 // Put anchor at the same position.
829 // Try to dispatch to an non-editable inset near this position
830 // via the temp cursor. If the inset wishes to change the real
831 // cursor it has to do so explicitly by using
832 // cur.bv().cursor() = cur; (or similar)
834 inset->dispatch(cur, cmd);
836 // Now dispatch to the temporary cursor. If the real cursor should
837 // be modified, the inset's dispatch has to do so explicitly.
838 if (!cur.result().dispatched())
841 if (cur.result().dispatched()) {
842 // Redraw if requested or necessary.
843 if (cur.result().update())
844 update(Update::FitCursor | Update::Force);
846 update(Update::FitCursor | Update::MultiParSel);
853 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
857 switch (cmd.action) {
860 flag.enabled(!buffer_->undostack().empty());
863 flag.enabled(!buffer_->redostack().empty());
865 case LFUN_FILE_INSERT:
866 case LFUN_FILE_INSERT_ASCII_PARA:
867 case LFUN_FILE_INSERT_ASCII:
868 case LFUN_BOOKMARK_SAVE:
869 // FIXME: Actually, these LFUNS should be moved to LyXText
870 flag.enabled(cursor_.inTexted());
872 case LFUN_FONT_STATE:
873 case LFUN_LABEL_INSERT:
874 case LFUN_PARAGRAPH_GOTO:
875 // FIXME handle non-trivially
876 case LFUN_OUTLINE_UP:
877 case LFUN_OUTLINE_DOWN:
878 case LFUN_OUTLINE_IN:
879 case LFUN_OUTLINE_OUT:
881 case LFUN_REFERENCE_NEXT:
883 case LFUN_WORD_REPLACE:
886 case LFUN_MARK_TOGGLE:
887 case LFUN_SCREEN_RECENTER:
888 case LFUN_BIBTEX_DATABASE_ADD:
889 case LFUN_BIBTEX_DATABASE_DEL:
890 case LFUN_WORDS_COUNT:
891 case LFUN_NEXT_INSET_TOGGLE:
895 case LFUN_LABEL_GOTO: {
896 flag.enabled(!cmd.argument().empty()
897 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
901 case LFUN_BOOKMARK_GOTO:
902 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
904 case LFUN_CHANGES_TRACK:
906 flag.setOnOff(buffer_->params().tracking_changes);
909 case LFUN_CHANGES_OUTPUT: {
910 OutputParams runparams;
911 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
912 flag.enabled(buffer_ && buffer_->params().tracking_changes
913 && features.isAvailable("dvipost"));
914 flag.setOnOff(buffer_->params().output_changes);
918 case LFUN_CHANGES_MERGE:
919 case LFUN_CHANGE_ACCEPT: // what about these two
920 case LFUN_CHANGE_REJECT: // what about these two
921 case LFUN_ALL_CHANGES_ACCEPT:
922 case LFUN_ALL_CHANGES_REJECT:
923 flag.enabled(buffer_ && buffer_->params().tracking_changes);
926 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
927 flag.setOnOff(buffer_->params().compressed);
940 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
942 //lyxerr << BOOST_CURRENT_FUNCTION
943 // << [ cmd = " << cmd << "]" << endl;
945 // Make sure that the cached BufferView is correct.
946 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
947 << " action[" << cmd.action << ']'
948 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
949 << " x[" << cmd.x << ']'
950 << " y[" << cmd.y << ']'
951 << " button[" << cmd.button() << ']'
954 LCursor & cur = cursor_;
956 switch (cmd.action) {
960 cur.message(_("Undo"));
961 cur.clearSelection();
963 cur.message(_("No further undo information"));
971 cur.message(_("Redo"));
972 cur.clearSelection();
974 cur.message(_("No further redo information"));
980 case LFUN_FILE_INSERT:
981 // FIXME: We don't know the encoding of filenames
982 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
985 case LFUN_FILE_INSERT_ASCII_PARA:
986 // FIXME: We don't know the encoding of filenames
987 insertAsciiFile(bv_, lyx::to_utf8(cmd.argument()), true);
990 case LFUN_FILE_INSERT_ASCII:
991 // FIXME: We don't know the encoding of filenames
992 insertAsciiFile(bv_, lyx::to_utf8(cmd.argument()), false);
995 case LFUN_FONT_STATE:
996 cur.message(lyx::from_utf8(cur.currentState()));
999 case LFUN_BOOKMARK_SAVE:
1000 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
1003 case LFUN_BOOKMARK_GOTO:
1004 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
1007 case LFUN_LABEL_GOTO: {
1008 string label = lyx::to_utf8(cmd.argument());
1009 if (label.empty()) {
1011 getInsetByCode<InsetRef>(cursor_,
1012 InsetBase::REF_CODE);
1014 label = inset->getContents();
1020 bv_->gotoLabel(label);
1024 case LFUN_PARAGRAPH_GOTO: {
1025 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
1026 ParIterator par = buffer_->getParFromID(id);
1027 if (par == buffer_->par_iterator_end()) {
1028 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1029 << id << ']' << endl;
1032 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1033 << " found." << endl;
1037 bv_->setCursor(makeDocIterator(par, 0));
1044 case LFUN_OUTLINE_UP:
1045 lyx::toc::outline(lyx::toc::Up, cursor_);
1046 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1047 updateLabels(*buffer_);
1049 case LFUN_OUTLINE_DOWN:
1050 lyx::toc::outline(lyx::toc::Down, cursor_);
1051 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1052 updateLabels(*buffer_);
1054 case LFUN_OUTLINE_IN:
1055 lyx::toc::outline(lyx::toc::In, cursor_);
1056 updateLabels(*buffer_);
1058 case LFUN_OUTLINE_OUT:
1059 lyx::toc::outline(lyx::toc::Out, cursor_);
1060 updateLabels(*buffer_);
1063 case LFUN_NOTE_NEXT:
1064 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1067 case LFUN_REFERENCE_NEXT: {
1068 vector<InsetBase_code> tmp;
1069 tmp.push_back(InsetBase::LABEL_CODE);
1070 tmp.push_back(InsetBase::REF_CODE);
1071 bv_funcs::gotoInset(bv_, tmp, true);
1075 case LFUN_CHANGES_TRACK:
1079 case LFUN_CHANGES_OUTPUT: {
1080 bool const state = buffer_->params().output_changes;
1081 buffer_->params().output_changes = !state;
1085 case LFUN_CHANGES_MERGE:
1086 if (lyx::find::findNextChange(bv_))
1087 owner_->getDialogs().show("changes");
1090 case LFUN_ALL_CHANGES_ACCEPT: {
1091 cursor_.reset(buffer_->inset());
1092 #ifdef WITH_WARNINGS
1093 #warning FIXME changes
1095 while (lyx::find::findNextChange(bv_))
1096 bv_->getLyXText()->acceptChange(cursor_);
1101 case LFUN_ALL_CHANGES_REJECT: {
1102 cursor_.reset(buffer_->inset());
1103 #ifdef WITH_WARNINGS
1104 #warning FIXME changes
1106 while (lyx::find::findNextChange(bv_))
1107 bv_->getLyXText()->rejectChange(cursor_);
1111 case LFUN_WORD_FIND:
1112 lyx::find::find(bv_, cmd);
1115 case LFUN_WORD_REPLACE:
1116 lyx::find::replace(bv_, cmd);
1120 cur.clearSelection();
1122 cur.message(lyx::from_utf8(N_("Mark off")));
1126 cur.clearSelection();
1129 cur.message(lyx::from_utf8(N_("Mark on")));
1132 case LFUN_MARK_TOGGLE:
1133 cur.clearSelection();
1136 cur.message(lyx::from_utf8(N_("Mark removed")));
1139 cur.message(lyx::from_utf8(N_("Mark set")));
1144 case LFUN_SCREEN_RECENTER:
1148 case LFUN_BIBTEX_DATABASE_ADD: {
1149 LCursor tmpcur = cursor_;
1150 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1151 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1152 InsetBase::BIBTEX_CODE);
1154 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
1155 buffer_->updateBibfilesCache();
1160 case LFUN_BIBTEX_DATABASE_DEL: {
1161 LCursor tmpcur = cursor_;
1162 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1163 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1164 InsetBase::BIBTEX_CODE);
1166 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
1167 buffer_->updateBibfilesCache();
1172 case LFUN_WORDS_COUNT: {
1173 DocIterator from, to;
1174 if (cur.selection()) {
1175 from = cur.selectionBegin();
1176 to = cur.selectionEnd();
1178 from = doc_iterator_begin(buffer_->inset());
1179 to = doc_iterator_end(buffer_->inset());
1181 int const count = countWords(from, to);
1184 if (cur.selection())
1185 message = bformat(_("%1$d words in selection."),
1188 message = bformat(_("%1$d words in document."),
1192 if (cur.selection())
1193 message = _("One word in selection.");
1195 message = _("One word in document.");
1198 Alert::information(_("Count words"), message);
1202 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1203 // turn compression on/off
1204 buffer_->params().compressed = !buffer_->params().compressed;
1207 case LFUN_NEXT_INSET_TOGGLE: {
1208 // this is the real function we want to invoke
1209 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1210 // if there is an inset at cursor, see whether it
1212 InsetBase * inset = cur.nextInset();
1213 if (inset && inset->isActive()) {
1214 LCursor tmpcur = cur;
1215 tmpcur.pushLeft(*inset);
1216 inset->dispatch(tmpcur, tmpcmd);
1217 if (tmpcur.result().dispatched()) {
1221 // if it did not work, try the underlying inset.
1222 if (!cur.result().dispatched())
1223 cur.dispatch(tmpcmd);
1225 if (cur.result().dispatched())
1226 cur.clearSelection();
1239 void BufferView::Pimpl::updateMetrics(bool singlepar)
1241 // Remove old position cache
1243 BufferView & bv = *bv_;
1244 LyXText * const text = bv.text();
1245 lyx::pit_type size = int(text->paragraphs().size());
1247 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1248 anchor_ref_ = int(text->paragraphs().size() - 1);
1252 lyx::pit_type const pit = anchor_ref_;
1255 size_t const npit = text->paragraphs().size();
1257 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1258 // the (main text, not inset!) paragraph containing the cursor.
1259 // (if this paragraph contains insets etc., rebreaking will
1260 // recursively descend)
1261 if (!singlepar || pit == cursor_.bottom().pit())
1262 text->redoParagraph(pit);
1263 int y0 = text->getPar(pit).ascent() - offset_ref_;
1265 // Redo paragraphs above anchor if necessary; again, in Single Par
1266 // mode, only if we encounter the (main text) one having the cursor.
1268 while (y1 > 0 && pit1 > 0) {
1269 y1 -= text->getPar(pit1).ascent();
1271 if (!singlepar || pit1 == cursor_.bottom().pit())
1272 text->redoParagraph(pit1);
1273 y1 -= text->getPar(pit1).descent();
1277 // Take care of ascent of first line
1278 y1 -= text->getPar(pit1).ascent();
1280 // Normalize anchor for next time
1284 // Grey at the beginning is ugly
1285 if (pit1 == 0 && y1 > 0) {
1291 // Redo paragraphs below the anchor if necessary. Single par mode:
1292 // only the one containing the cursor if encountered.
1294 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1295 y2 += text->getPar(pit2).descent();
1297 if (!singlepar || pit2 == cursor_.bottom().pit())
1298 text->redoParagraph(pit2);
1299 y2 += text->getPar(pit2).ascent();
1302 // Take care of descent of last line
1303 y2 += text->getPar(pit2).descent();
1305 // The coordinates of all these paragraphs are correct, cache them
1307 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1308 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1309 Paragraph const & par = text->getPar(pit);
1311 parPos[pit] = Point(0, y);
1312 if (singlepar && pit == cursor_.bottom().pit()) {
1313 // In Single Paragraph mode, collect here the
1314 // y1 and y2 of the (one) paragraph the cursor is in
1315 y1 = y - par.ascent();
1316 y2 = y + par.descent();
1322 // collect cursor paragraph iter bounds
1323 pit1 = cursor_.bottom().pit();
1324 pit2 = cursor_.bottom().pit();
1327 lyxerr[Debug::DEBUG]
1328 << BOOST_CURRENT_FUNCTION
1331 << " pit1: " << pit1
1332 << " pit2: " << pit2
1333 << " npit: " << npit
1334 << " singlepar: " << singlepar
1338 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);