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;
88 using lyx::support::addPath;
89 using lyx::support::bformat;
90 using lyx::support::FileFilterList;
91 using lyx::support::fileSearch;
92 using lyx::support::isDirWriteable;
93 using lyx::support::makeDisplayPath;
94 using lyx::support::makeAbsPath;
95 using lyx::support::package;
98 using std::istringstream;
103 using std::mem_fun_ref;
106 extern BufferList bufferlist;
111 unsigned int const saved_positions_num = 20;
114 /// Return an inset of this class if it exists at the current cursor position
116 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
119 DocIterator it = cur;
120 if (it.nextInset() &&
121 it.nextInset()->lyxCode() == code) {
122 inset = static_cast<T*>(it.nextInset());
130 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner)
131 : bv_(&bv), owner_(owner), buffer_(0), wh_(0),
133 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0)
135 xsel_cache_.set = false;
137 saved_positions.resize(saved_positions_num);
138 // load saved bookmarks
139 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
140 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
141 bm != bmList.end(); ++bm)
142 if (bm->get<0>() < saved_positions_num)
143 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
144 // and then clear them
149 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
151 // Get absolute path of file and add ".lyx"
152 // to the filename if necessary
153 string s = fileSearch(string(), filename, "lyx");
155 bool const found = !s.empty();
160 // File already open?
161 if (bufferlist.exists(s)) {
162 string const file = makeDisplayPath(s, 20);
163 string text = bformat(_("The document %1$s is already "
164 "loaded.\n\nDo you want to revert "
165 "to the saved version?"), file);
166 int const ret = Alert::prompt(_("Revert to saved document?"),
167 text, 0, 1, _("&Revert"), _("&Switch to document"));
170 setBuffer(bufferlist.getBuffer(s));
173 // FIXME: should be LFUN_REVERT
174 if (!bufferlist.close(bufferlist.getBuffer(s), false))
176 // Fall through to new load. (Asger)
182 b = bufferlist.newBuffer(s);
183 if (!::loadLyXFile(b, s)) {
184 bufferlist.release(b);
188 string text = bformat(_("The document %1$s does not yet "
189 "exist.\n\nDo you want to create "
190 "a new document?"), s);
191 int const ret = Alert::prompt(_("Create new document?"),
192 text, 0, 1, _("&Create"), _("Cancel"));
195 b = newFile(s, string(), true);
203 // Send the "errors" signal in case of parsing errors
206 // scroll to the position when the file was last closed
207 if (lyxrc.use_lastfilepos) {
210 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
211 // I am not sure how to separate the following part to a function
212 // so I will leave this to Lars.
214 // check pit since the document may be externally changed.
215 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
216 ParIterator it = b->par_iterator_begin();
217 ParIterator const end = b->par_iterator_end();
218 for (; it != end; ++it)
219 if (it.pit() == pit) {
220 // restored pos may be bigger than it->size
221 bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
222 bv_->update(Update::FitCursor);
229 LyX::ref().session().addLastFile(b->fileName());
235 int BufferView::Pimpl::width() const
241 int BufferView::Pimpl::height() const
247 void BufferView::Pimpl::setBuffer(Buffer * b)
249 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
250 << "[ b = " << b << "]" << endl;
253 // Save the actual cursor position and anchor inside the
254 // buffer so that it can be restored in case we rechange
255 // to this buffer later on.
256 buffer_->saveCursor(cursor_.selectionBegin(),
257 cursor_.selectionEnd());
258 // current buffer is going to be switched-off, save cursor pos
259 LyX::ref().session().saveFilePosition(buffer_->fileName(),
260 boost::tie(cursor_.pit(), cursor_.pos()) );
263 // If we're quitting lyx, don't bother updating stuff
269 // If we are closing current buffer, switch to the first in
272 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
273 << " No Buffer!" << endl;
274 // We are closing the buffer, use the first buffer as current
275 buffer_ = bufferlist.first();
277 // Set current buffer
282 cursor_ = LCursor(*bv_);
287 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
288 << "Buffer addr: " << buffer_ << endl;
289 cursor_.push(buffer_->inset());
290 cursor_.resetAnchor();
291 buffer_->text().init(bv_);
292 buffer_->text().setCurrentFont(cursor_);
293 if (buffer_->getCursor().size() > 0 &&
294 buffer_->getAnchor().size() > 0)
296 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
297 cursor_.resetAnchor();
298 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
299 cursor_.setSelection();
305 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
306 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
309 string BufferView::Pimpl::firstLayout()
313 // This is done after the layout combox has been populated
315 size_t i = cursor_.depth() - 1;
316 // we know we'll eventually find a paragraph
318 CursorSlice const & slice = cursor_[i];
319 if (!slice.inset().inMathed()) {
320 LyXLayout_ptr const layout = slice.paragraph().layout();
321 firstlayout = layout->name();
332 void BufferView::Pimpl::resizeCurrentBuffer()
334 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
336 LyXText * text = bv_->text();
346 void BufferView::Pimpl::updateScrollbar()
349 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
350 << " no text in updateScrollbar" << endl;
351 scrollbarParameters_.reset();
355 LyXText & t = *bv_->text();
356 int const parsize = int(t.paragraphs().size() - 1);
357 if (anchor_ref_ > parsize) {
358 anchor_ref_ = parsize;
363 << BOOST_CURRENT_FUNCTION
364 << " Updating scrollbar: height: " << t.paragraphs().size()
365 << " curr par: " << cursor_.bottom().pit()
366 << " default height " << defaultRowHeight() << endl;
368 // It would be better to fix the scrollbar to understand
369 // values in [0..1] and divide everything by wh
371 // estimated average paragraph height:
374 int h = t.getPar(anchor_ref_).height();
376 // Normalize anchor/offset (MV):
377 while (offset_ref_ > h && anchor_ref_ < parsize) {
380 h = t.getPar(anchor_ref_).height();
382 // Look at paragraph heights on-screen
385 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
388 int const h2 = t.getPar(pit).height();
392 int const hav = sumh / nh;
393 // More realistic average paragraph height
397 scrollbarParameters_.height = (parsize + 1) * wh_;
398 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
399 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
403 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
405 return scrollbarParameters_;
409 void BufferView::Pimpl::scrollDocView(int value)
411 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
412 << "[ value = " << value << "]" << endl;
417 LyXText & t = *bv_->text();
419 float const bar = value / float(wh_ * t.paragraphs().size());
421 anchor_ref_ = int(bar * t.paragraphs().size());
422 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
423 anchor_ref_ = int(t.paragraphs().size()) - 1;
424 t.redoParagraph(anchor_ref_);
425 int const h = t.getPar(anchor_ref_).height();
426 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
430 void BufferView::Pimpl::setCursorFromScrollbar()
432 LyXText & t = *bv_->text();
434 int const height = 2 * defaultRowHeight();
435 int const first = height;
436 int const last = height_ - height;
437 LCursor & cur = cursor_;
439 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
442 case bv_funcs::CUR_ABOVE:
443 t.setCursorFromCoordinates(cur, 0, first);
444 cur.clearSelection();
446 case bv_funcs::CUR_BELOW:
447 t.setCursorFromCoordinates(cur, 0, last);
448 cur.clearSelection();
450 case bv_funcs::CUR_INSIDE:
451 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
452 int const newy = min(last, max(y, first));
454 cur.reset(buffer_->inset());
455 t.setCursorFromCoordinates(cur, 0, newy);
461 void BufferView::Pimpl::scroll(int /*lines*/)
466 // LyXText const * t = bv_->text();
467 // int const line_height = defaultRowHeight();
469 // // The new absolute coordinate
470 // int new_top_y = top_y() + lines * line_height;
472 // // Restrict to a valid value
473 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
474 // new_top_y = std::max(0, new_top_y);
476 // scrollDocView(new_top_y);
478 // // Update the scrollbar.
479 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
483 void BufferView::Pimpl::selectionRequested()
490 LCursor & cur = cursor_;
492 if (!cur.selection()) {
493 xsel_cache_.set = false;
497 if (!xsel_cache_.set ||
498 cur.top() != xsel_cache_.cursor ||
499 cur.anchor_.top() != xsel_cache_.anchor)
501 xsel_cache_.cursor = cur.top();
502 xsel_cache_.anchor = cur.anchor_.top();
503 xsel_cache_.set = cur.selection();
504 sel = cur.selectionAsString(false);
506 owner_->gui().selection().put(sel);
511 void BufferView::Pimpl::selectionLost()
514 cursor_.clearSelection();
515 xsel_cache_.set = false;
520 void BufferView::Pimpl::workAreaResize(int width, int height)
522 bool const widthChange = width != width_;
523 bool const heightChange = height != height_;
525 // Update from work area
529 if (buffer_ && widthChange) {
530 // The WorkArea content needs a resize
531 resizeCurrentBuffer();
534 if (widthChange || heightChange)
539 bool BufferView::Pimpl::fitCursor()
541 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
542 LyXFont const font = cursor_.getFont();
543 int const asc = font_metrics::maxAscent(font);
544 int const des = font_metrics::maxDescent(font);
545 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
546 if (p.y_ - asc >= 0 && p.y_ + des < height_)
554 bool BufferView::Pimpl::multiParSel()
556 if (!cursor_.selection())
558 bool ret = multiparsel_cache_;
559 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
560 // Either this, or previous selection spans paragraphs
561 return ret || multiparsel_cache_;
565 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
567 return metrics_info_;
571 bool BufferView::Pimpl::update(Update::flags flags)
573 // This is close to a hot-path.
574 if (lyxerr.debugging(Debug::DEBUG)) {
576 << BOOST_CURRENT_FUNCTION
577 << "[fitcursor = " << (flags & Update::FitCursor)
578 << ", forceupdate = " << (flags & Update::Force)
579 << ", singlepar = " << (flags & Update::SinglePar)
580 << "] buffer: " << buffer_ << endl;
583 // Check needed to survive LyX startup
587 // Update macro store
588 buffer_->buildMacros();
590 // First drawing step
591 updateMetrics(flags & Update::SinglePar);
593 // The second drawing step is done in WorkArea::redraw() if needed.
594 bool const need_second_step =
595 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
596 && (fitCursor() || multiParSel());
598 return need_second_step;
602 bool BufferView::Pimpl::available() const
604 return buffer_ && bv_->text();
608 Change const BufferView::Pimpl::getCurrentChange()
610 if (!buffer_->params().tracking_changes)
611 return Change(Change::UNCHANGED);
613 LyXText * text = bv_->getLyXText();
614 LCursor & cur = cursor_;
616 if (!cur.selection())
617 return Change(Change::UNCHANGED);
619 return text->getPar(cur.selBegin().pit()).
620 lookupChange(cur.selBegin().pos());
624 void BufferView::Pimpl::savePosition(unsigned int i)
626 if (i >= saved_positions_num)
628 BOOST_ASSERT(cursor_.inTexted());
629 saved_positions[i] = Position(buffer_->fileName(),
630 cursor_.paragraph().id(),
633 owner_->message(bformat(_("Saved bookmark %1$d"), i));
637 void BufferView::Pimpl::restorePosition(unsigned int i)
639 if (i >= saved_positions_num)
642 string const fname = saved_positions[i].filename;
644 cursor_.clearSelection();
646 if (fname != buffer_->fileName()) {
648 if (bufferlist.exists(fname))
649 b = bufferlist.getBuffer(fname);
651 b = bufferlist.newBuffer(fname);
652 // Don't ask, just load it
653 ::loadLyXFile(b, fname);
659 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
660 if (par == buffer_->par_iterator_end())
663 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
666 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
670 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
672 return i < saved_positions_num && !saved_positions[i].filename.empty();
676 void BufferView::Pimpl::saveSavedPositions()
678 // save bookmarks. It is better to use the pit interface
679 // but I do not know how to effectively convert between
681 for (unsigned int i=1; i < saved_positions_num; ++i) {
682 if ( isSavedPosition(i) )
683 LyX::ref().session().saveBookmark( boost::tie(
685 saved_positions[i].filename,
686 saved_positions[i].par_id,
687 saved_positions[i].par_pos) );
692 void BufferView::Pimpl::switchKeyMap()
694 if (!lyxrc.rtl_support)
697 Intl & intl = owner_->getIntl();
698 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
699 if (intl.keymap == Intl::PRIMARY)
702 if (intl.keymap == Intl::SECONDARY)
708 void BufferView::Pimpl::center()
710 CursorSlice & bot = cursor_.bottom();
711 lyx::pit_type const pit = bot.pit();
712 bot.text()->redoParagraph(pit);
713 Paragraph const & par = bot.text()->paragraphs()[pit];
715 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
716 + par.ascent() - height_ / 2;
720 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
722 BOOST_ASSERT(cursor_.inTexted());
723 string filename = filenm;
725 if (filename.empty()) {
726 // Launch a file browser
727 string initpath = lyxrc.document_path;
730 string const trypath = buffer_->filePath();
731 // If directory is writeable, use this as default.
732 if (isDirWriteable(trypath))
736 FileDialog fileDlg(_("Select LyX document to insert"),
738 make_pair(string(_("Documents|#o#O")),
739 string(lyxrc.document_path)),
740 make_pair(string(_("Examples|#E#e")),
741 string(addPath(package().system_support(), "examples"))));
743 FileDialog::Result result =
744 fileDlg.open(initpath,
745 FileFilterList(_("LyX Documents (*.lyx)")),
748 if (result.first == FileDialog::Later)
751 filename = result.second;
753 // check selected filename
754 if (filename.empty()) {
755 owner_->message(_("Canceled."));
760 // Get absolute path of file and add ".lyx"
761 // to the filename if necessary
762 filename = fileSearch(string(), filename, "lyx");
764 string const disp_fn = makeDisplayPath(filename);
765 owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
768 Buffer buf("", false);
769 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
770 ErrorList & el = buffer_->errorList("Parse");
771 // Copy the inserted document error list into the current buffer one.
772 el = buf.errorList("Parse");
773 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
774 buf.params().textclass, el);
775 res = _("Document %1$s inserted.");
777 res = _("Could not insert document %1$s");
779 owner_->message(bformat(res, disp_fn));
780 buffer_->errors("Parse");
781 resizeCurrentBuffer();
785 void BufferView::Pimpl::trackChanges()
787 bool const tracking = buffer_->params().tracking_changes;
790 for_each(buffer_->par_iterator_begin(),
791 buffer_->par_iterator_end(),
792 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
793 buffer_->params().tracking_changes = true;
795 // We cannot allow undos beyond the freeze point
796 buffer_->undostack().clear();
798 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
799 if (lyx::find::findNextChange(bv_)) {
800 owner_->getDialogs().show("changes");
804 for_each(buffer_->par_iterator_begin(),
805 buffer_->par_iterator_end(),
806 mem_fun_ref(&Paragraph::untrackChanges));
808 buffer_->params().tracking_changes = false;
811 buffer_->redostack().clear();
815 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
817 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
819 // This is only called for mouse related events including
820 // LFUN_FILE_OPEN generated by drag-and-drop.
821 FuncRequest cmd = cmd0;
827 cur.push(buffer_->inset());
828 cur.selection() = cursor_.selection();
830 // Doesn't go through lyxfunc, so we need to update
831 // the layout choice etc. ourselves
833 // E.g. Qt mouse press when no buffer
837 // Either the inset under the cursor or the
838 // surrounding LyXText will handle this event.
840 // Build temporary cursor.
841 cmd.y = min(max(cmd.y, -1), height_);
842 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
843 //lyxerr << BOOST_CURRENT_FUNCTION
844 // << " * hit inset at tip: " << inset << endl;
845 //lyxerr << BOOST_CURRENT_FUNCTION
846 // << " * created temp cursor:" << cur << endl;
848 // Put anchor at the same position.
851 // Try to dispatch to an non-editable inset near this position
852 // via the temp cursor. If the inset wishes to change the real
853 // cursor it has to do so explicitly by using
854 // cur.bv().cursor() = cur; (or similar)
856 inset->dispatch(cur, cmd);
858 // Now dispatch to the temporary cursor. If the real cursor should
859 // be modified, the inset's dispatch has to do so explicitly.
860 if (!cur.result().dispatched())
863 if (cur.result().dispatched()) {
864 // Redraw if requested or necessary.
865 if (cur.result().update())
866 update(Update::FitCursor | Update::Force);
868 update(Update::FitCursor | Update::MultiParSel);
875 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
879 switch (cmd.action) {
882 flag.enabled(!buffer_->undostack().empty());
885 flag.enabled(!buffer_->redostack().empty());
887 case LFUN_FILE_INSERT:
888 case LFUN_FILE_INSERT_ASCII_PARA:
889 case LFUN_FILE_INSERT_ASCII:
890 case LFUN_BOOKMARK_SAVE:
891 // FIXME: Actually, these LFUNS should be moved to LyXText
892 flag.enabled(cursor_.inTexted());
894 case LFUN_FONT_STATE:
895 case LFUN_LABEL_INSERT:
896 case LFUN_PARAGRAPH_GOTO:
897 // FIXME handle non-trivially
898 case LFUN_OUTLINE_UP:
899 case LFUN_OUTLINE_DOWN:
900 case LFUN_OUTLINE_IN:
901 case LFUN_OUTLINE_OUT:
903 case LFUN_REFERENCE_NEXT:
905 case LFUN_WORD_REPLACE:
908 case LFUN_MARK_TOGGLE:
909 case LFUN_SCREEN_RECENTER:
910 case LFUN_BIBTEX_DATABASE_ADD:
911 case LFUN_BIBTEX_DATABASE_DEL:
912 case LFUN_WORDS_COUNT:
913 case LFUN_NEXT_INSET_TOGGLE:
917 case LFUN_LABEL_GOTO: {
918 flag.enabled(!cmd.argument.empty()
919 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
923 case LFUN_BOOKMARK_GOTO:
924 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
926 case LFUN_CHANGES_TRACK:
928 flag.setOnOff(buffer_->params().tracking_changes);
931 case LFUN_CHANGES_OUTPUT: {
932 OutputParams runparams;
933 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
934 flag.enabled(buffer_ && buffer_->params().tracking_changes
935 && features.isAvailable("dvipost"));
936 flag.setOnOff(buffer_->params().output_changes);
940 case LFUN_CHANGES_MERGE:
941 case LFUN_CHANGE_ACCEPT: // what about these two
942 case LFUN_CHANGE_REJECT: // what about these two
943 case LFUN_ALL_CHANGES_ACCEPT:
944 case LFUN_ALL_CHANGES_REJECT:
945 flag.enabled(buffer_ && buffer_->params().tracking_changes);
948 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
949 flag.setOnOff(buffer_->params().compressed);
962 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
964 //lyxerr << BOOST_CURRENT_FUNCTION
965 // << [ cmd = " << cmd << "]" << endl;
967 // Make sure that the cached BufferView is correct.
968 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
969 << " action[" << cmd.action << ']'
970 << " arg[" << cmd.argument << ']'
971 << " x[" << cmd.x << ']'
972 << " y[" << cmd.y << ']'
973 << " button[" << cmd.button() << ']'
976 LCursor & cur = cursor_;
978 switch (cmd.action) {
982 cur.message(_("Undo"));
983 cur.clearSelection();
985 cur.message(_("No further undo information"));
993 cur.message(_("Redo"));
994 cur.clearSelection();
996 cur.message(_("No further redo information"));
1002 case LFUN_FILE_INSERT:
1003 menuInsertLyXFile(cmd.argument);
1006 case LFUN_FILE_INSERT_ASCII_PARA:
1007 insertAsciiFile(bv_, cmd.argument, true);
1010 case LFUN_FILE_INSERT_ASCII:
1011 insertAsciiFile(bv_, cmd.argument, false);
1014 case LFUN_FONT_STATE:
1015 cur.message(cur.currentState());
1018 case LFUN_BOOKMARK_SAVE:
1019 savePosition(convert<unsigned int>(cmd.argument));
1022 case LFUN_BOOKMARK_GOTO:
1023 restorePosition(convert<unsigned int>(cmd.argument));
1026 case LFUN_LABEL_GOTO: {
1027 string label = cmd.argument;
1028 if (label.empty()) {
1030 getInsetByCode<InsetRef>(cursor_,
1031 InsetBase::REF_CODE);
1033 label = inset->getContents();
1039 bv_->gotoLabel(label);
1043 case LFUN_PARAGRAPH_GOTO: {
1044 int const id = convert<int>(cmd.argument);
1045 ParIterator par = buffer_->getParFromID(id);
1046 if (par == buffer_->par_iterator_end()) {
1047 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1048 << id << ']' << endl;
1051 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1052 << " found." << endl;
1056 bv_->setCursor(makeDocIterator(par, 0));
1063 case LFUN_OUTLINE_UP:
1064 lyx::toc::outline(lyx::toc::Up, cursor_);
1065 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1066 updateLabels(*buffer_);
1068 case LFUN_OUTLINE_DOWN:
1069 lyx::toc::outline(lyx::toc::Down, cursor_);
1070 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1071 updateLabels(*buffer_);
1073 case LFUN_OUTLINE_IN:
1074 lyx::toc::outline(lyx::toc::In, cursor_);
1075 updateLabels(*buffer_);
1077 case LFUN_OUTLINE_OUT:
1078 lyx::toc::outline(lyx::toc::Out, cursor_);
1079 updateLabels(*buffer_);
1082 case LFUN_NOTE_NEXT:
1083 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1086 case LFUN_REFERENCE_NEXT: {
1087 vector<InsetBase_code> tmp;
1088 tmp.push_back(InsetBase::LABEL_CODE);
1089 tmp.push_back(InsetBase::REF_CODE);
1090 bv_funcs::gotoInset(bv_, tmp, true);
1094 case LFUN_CHANGES_TRACK:
1098 case LFUN_CHANGES_OUTPUT: {
1099 bool const state = buffer_->params().output_changes;
1100 buffer_->params().output_changes = !state;
1104 case LFUN_CHANGES_MERGE:
1105 if (lyx::find::findNextChange(bv_))
1106 owner_->getDialogs().show("changes");
1109 case LFUN_ALL_CHANGES_ACCEPT: {
1110 cursor_.reset(buffer_->inset());
1111 #ifdef WITH_WARNINGS
1112 #warning FIXME changes
1114 while (lyx::find::findNextChange(bv_))
1115 bv_->getLyXText()->acceptChange(cursor_);
1120 case LFUN_ALL_CHANGES_REJECT: {
1121 cursor_.reset(buffer_->inset());
1122 #ifdef WITH_WARNINGS
1123 #warning FIXME changes
1125 while (lyx::find::findNextChange(bv_))
1126 bv_->getLyXText()->rejectChange(cursor_);
1130 case LFUN_WORD_FIND:
1131 lyx::find::find(bv_, cmd);
1134 case LFUN_WORD_REPLACE:
1135 lyx::find::replace(bv_, cmd);
1139 cur.clearSelection();
1141 cur.message(N_("Mark off"));
1145 cur.clearSelection();
1148 cur.message(N_("Mark on"));
1151 case LFUN_MARK_TOGGLE:
1152 cur.clearSelection();
1155 cur.message(N_("Mark removed"));
1158 cur.message(N_("Mark set"));
1163 case LFUN_SCREEN_RECENTER:
1167 case LFUN_BIBTEX_DATABASE_ADD: {
1168 LCursor tmpcur = cursor_;
1169 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1170 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1171 InsetBase::BIBTEX_CODE);
1173 if (inset->addDatabase(cmd.argument))
1174 buffer_->updateBibfilesCache();
1179 case LFUN_BIBTEX_DATABASE_DEL: {
1180 LCursor tmpcur = cursor_;
1181 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1182 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1183 InsetBase::BIBTEX_CODE);
1185 if (inset->delDatabase(cmd.argument))
1186 buffer_->updateBibfilesCache();
1191 case LFUN_WORDS_COUNT: {
1192 DocIterator from, to;
1193 if (cur.selection()) {
1194 from = cur.selectionBegin();
1195 to = cur.selectionEnd();
1197 from = doc_iterator_begin(buffer_->inset());
1198 to = doc_iterator_end(buffer_->inset());
1200 int const count = countWords(from, to);
1203 if (cur.selection())
1204 message = bformat(_("%1$d words in selection."),
1207 message = bformat(_("%1$d words in document."),
1211 if (cur.selection())
1212 message = _("One word in selection.");
1214 message = _("One word in document.");
1217 Alert::information(_("Count words"), message);
1221 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1222 // turn compression on/off
1223 buffer_->params().compressed = !buffer_->params().compressed;
1226 case LFUN_NEXT_INSET_TOGGLE: {
1227 // this is the real function we want to invoke
1228 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1229 // if there is an inset at cursor, see whether it
1231 InsetBase * inset = cur.nextInset();
1232 if (inset && inset->isActive()) {
1233 LCursor tmpcur = cur;
1234 tmpcur.pushLeft(*inset);
1235 inset->dispatch(tmpcur, tmpcmd);
1236 if (tmpcur.result().dispatched()) {
1240 // if it did not work, try the underlying inset.
1241 if (!cur.result().dispatched())
1242 cur.dispatch(tmpcmd);
1244 if (cur.result().dispatched())
1245 cur.clearSelection();
1258 void BufferView::Pimpl::updateMetrics(bool singlepar)
1260 // Remove old position cache
1262 BufferView & bv = *bv_;
1263 LyXText * const text = bv.text();
1264 lyx::pit_type size = int(text->paragraphs().size());
1266 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1267 anchor_ref_ = int(text->paragraphs().size() - 1);
1271 lyx::pit_type const pit = anchor_ref_;
1274 size_t const npit = text->paragraphs().size();
1276 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1277 // the (main text, not inset!) paragraph containing the cursor.
1278 // (if this paragraph contains insets etc., rebreaking will
1279 // recursively descend)
1280 if (!singlepar || pit == cursor_.bottom().pit())
1281 text->redoParagraph(pit);
1282 int y0 = text->getPar(pit).ascent() - offset_ref_;
1284 // Redo paragraphs above anchor if necessary; again, in Single Par
1285 // mode, only if we encounter the (main text) one having the cursor.
1287 while (y1 > 0 && pit1 > 0) {
1288 y1 -= text->getPar(pit1).ascent();
1290 if (!singlepar || pit1 == cursor_.bottom().pit())
1291 text->redoParagraph(pit1);
1292 y1 -= text->getPar(pit1).descent();
1296 // Take care of ascent of first line
1297 y1 -= text->getPar(pit1).ascent();
1299 // Normalize anchor for next time
1303 // Grey at the beginning is ugly
1304 if (pit1 == 0 && y1 > 0) {
1310 // Redo paragraphs below the anchor if necessary. Single par mode:
1311 // only the one containing the cursor if encountered.
1313 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1314 y2 += text->getPar(pit2).descent();
1316 if (!singlepar || pit2 == cursor_.bottom().pit())
1317 text->redoParagraph(pit2);
1318 y2 += text->getPar(pit2).ascent();
1321 // Take care of descent of last line
1322 y2 += text->getPar(pit2).descent();
1324 // The coordinates of all these paragraphs are correct, cache them
1326 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1327 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1328 Paragraph const & par = text->getPar(pit);
1330 parPos[pit] = Point(0, y);
1331 if (singlepar && pit == cursor_.bottom().pit()) {
1332 // In Single Paragraph mode, collect here the
1333 // y1 and y2 of the (one) paragraph the cursor is in
1334 y1 = y - par.ascent();
1335 y2 = y + par.descent();
1341 // collect cursor paragraph iter bounds
1342 pit1 = cursor_.bottom().pit();
1343 pit2 = cursor_.bottom().pit();
1346 lyxerr[Debug::DEBUG]
1347 << BOOST_CURRENT_FUNCTION
1350 << " pit1: " << pit1
1351 << " pit2: " << pit2
1352 << " npit: " << npit
1353 << " singlepar: " << singlepar
1357 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);