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_);
310 void BufferView::Pimpl::resizeCurrentBuffer()
312 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
314 LyXText * text = bv_->text();
324 void BufferView::Pimpl::updateScrollbar()
327 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
328 << " no text in updateScrollbar" << endl;
329 scrollbarParameters_.reset();
333 LyXText & t = *bv_->text();
334 int const parsize = int(t.paragraphs().size() - 1);
335 if (anchor_ref_ > parsize) {
336 anchor_ref_ = parsize;
341 << BOOST_CURRENT_FUNCTION
342 << " Updating scrollbar: height: " << t.paragraphs().size()
343 << " curr par: " << cursor_.bottom().pit()
344 << " default height " << defaultRowHeight() << endl;
346 // It would be better to fix the scrollbar to understand
347 // values in [0..1] and divide everything by wh
349 // estimated average paragraph height:
352 int h = t.getPar(anchor_ref_).height();
354 // Normalize anchor/offset (MV):
355 while (offset_ref_ > h && anchor_ref_ < parsize) {
358 h = t.getPar(anchor_ref_).height();
360 // Look at paragraph heights on-screen
363 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
366 int const h2 = t.getPar(pit).height();
370 int const hav = sumh / nh;
371 // More realistic average paragraph height
375 scrollbarParameters_.height = (parsize + 1) * wh_;
376 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
377 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
381 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
383 return scrollbarParameters_;
387 void BufferView::Pimpl::scrollDocView(int value)
389 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
390 << "[ value = " << value << "]" << endl;
395 LyXText & t = *bv_->text();
397 float const bar = value / float(wh_ * t.paragraphs().size());
399 anchor_ref_ = int(bar * t.paragraphs().size());
400 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
401 anchor_ref_ = int(t.paragraphs().size()) - 1;
402 t.redoParagraph(anchor_ref_);
403 int const h = t.getPar(anchor_ref_).height();
404 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
408 void BufferView::Pimpl::setCursorFromScrollbar()
410 LyXText & t = *bv_->text();
412 int const height = 2 * defaultRowHeight();
413 int const first = height;
414 int const last = height_ - height;
415 LCursor & cur = cursor_;
417 bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
420 case bv_funcs::CUR_ABOVE:
421 t.setCursorFromCoordinates(cur, 0, first);
422 cur.clearSelection();
424 case bv_funcs::CUR_BELOW:
425 t.setCursorFromCoordinates(cur, 0, last);
426 cur.clearSelection();
428 case bv_funcs::CUR_INSIDE:
429 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
430 int const newy = min(last, max(y, first));
432 cur.reset(buffer_->inset());
433 t.setCursorFromCoordinates(cur, 0, newy);
439 void BufferView::Pimpl::scroll(int /*lines*/)
444 // LyXText const * t = bv_->text();
445 // int const line_height = defaultRowHeight();
447 // // The new absolute coordinate
448 // int new_top_y = top_y() + lines * line_height;
450 // // Restrict to a valid value
451 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
452 // new_top_y = std::max(0, new_top_y);
454 // scrollDocView(new_top_y);
456 // // Update the scrollbar.
457 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
461 void BufferView::Pimpl::selectionRequested()
468 LCursor & cur = cursor_;
470 if (!cur.selection()) {
471 xsel_cache_.set = false;
475 if (!xsel_cache_.set ||
476 cur.top() != xsel_cache_.cursor ||
477 cur.anchor_.top() != xsel_cache_.anchor)
479 xsel_cache_.cursor = cur.top();
480 xsel_cache_.anchor = cur.anchor_.top();
481 xsel_cache_.set = cur.selection();
482 sel = cur.selectionAsString(false);
484 owner_->gui().selection().put(sel);
489 void BufferView::Pimpl::selectionLost()
492 cursor_.clearSelection();
493 xsel_cache_.set = false;
498 void BufferView::Pimpl::workAreaResize(int width, int height)
500 bool const widthChange = width != width_;
501 bool const heightChange = height != height_;
503 // Update from work area
507 if (buffer_ && widthChange) {
508 // The WorkArea content needs a resize
509 resizeCurrentBuffer();
512 if (widthChange || heightChange)
517 bool BufferView::Pimpl::fitCursor()
519 if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
520 LyXFont const font = cursor_.getFont();
521 int const asc = font_metrics::maxAscent(font);
522 int const des = font_metrics::maxDescent(font);
523 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
524 if (p.y_ - asc >= 0 && p.y_ + des < height_)
532 bool BufferView::Pimpl::multiParSel()
534 if (!cursor_.selection())
536 bool ret = multiparsel_cache_;
537 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
538 // Either this, or previous selection spans paragraphs
539 return ret || multiparsel_cache_;
543 ViewMetricsInfo const & BufferView::Pimpl::viewMetricsInfo()
545 return metrics_info_;
549 bool BufferView::Pimpl::update(Update::flags flags)
551 // This is close to a hot-path.
552 if (lyxerr.debugging(Debug::DEBUG)) {
554 << BOOST_CURRENT_FUNCTION
555 << "[fitcursor = " << (flags & Update::FitCursor)
556 << ", forceupdate = " << (flags & Update::Force)
557 << ", singlepar = " << (flags & Update::SinglePar)
558 << "] buffer: " << buffer_ << endl;
561 // Check needed to survive LyX startup
565 // Update macro store
566 buffer_->buildMacros();
568 // First drawing step
569 updateMetrics(flags & Update::SinglePar);
571 // The second drawing step is done in WorkArea::redraw() if needed.
572 bool const need_second_step =
573 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
574 && (fitCursor() || multiParSel());
576 return need_second_step;
580 bool BufferView::Pimpl::available() const
582 return buffer_ && bv_->text();
586 Change const BufferView::Pimpl::getCurrentChange()
588 if (!buffer_->params().tracking_changes)
589 return Change(Change::UNCHANGED);
591 LyXText * text = bv_->getLyXText();
592 LCursor & cur = cursor_;
594 if (!cur.selection())
595 return Change(Change::UNCHANGED);
597 return text->getPar(cur.selBegin().pit()).
598 lookupChange(cur.selBegin().pos());
602 void BufferView::Pimpl::savePosition(unsigned int i)
604 if (i >= saved_positions_num)
606 BOOST_ASSERT(cursor_.inTexted());
607 saved_positions[i] = Position(buffer_->fileName(),
608 cursor_.paragraph().id(),
611 // emit message signal.
612 bv_->message(bformat(_("Saved bookmark %1$d"), i));
616 void BufferView::Pimpl::restorePosition(unsigned int i)
618 if (i >= saved_positions_num)
621 string const fname = saved_positions[i].filename;
623 cursor_.clearSelection();
625 if (fname != buffer_->fileName()) {
627 if (bufferlist.exists(fname))
628 b = bufferlist.getBuffer(fname);
630 b = bufferlist.newBuffer(fname);
631 // Don't ask, just load it
632 ::loadLyXFile(b, fname);
638 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
639 if (par == buffer_->par_iterator_end())
642 bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
645 // emit message signal.
646 bv_->message(bformat(_("Moved to bookmark %1$d"), i));
650 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
652 return i < saved_positions_num && !saved_positions[i].filename.empty();
656 void BufferView::Pimpl::saveSavedPositions()
658 // save bookmarks. It is better to use the pit interface
659 // but I do not know how to effectively convert between
661 for (unsigned int i=1; i < saved_positions_num; ++i) {
662 if ( isSavedPosition(i) )
663 LyX::ref().session().saveBookmark( boost::tie(
665 saved_positions[i].filename,
666 saved_positions[i].par_id,
667 saved_positions[i].par_pos) );
672 void BufferView::Pimpl::switchKeyMap()
674 if (!lyxrc.rtl_support)
677 Intl & intl = owner_->getIntl();
678 if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
679 if (intl.keymap == Intl::PRIMARY)
682 if (intl.keymap == Intl::SECONDARY)
688 void BufferView::Pimpl::center()
690 CursorSlice & bot = cursor_.bottom();
691 lyx::pit_type const pit = bot.pit();
692 bot.text()->redoParagraph(pit);
693 Paragraph const & par = bot.text()->paragraphs()[pit];
695 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
696 + par.ascent() - height_ / 2;
700 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
702 BOOST_ASSERT(cursor_.inTexted());
703 string filename = filenm;
705 if (filename.empty()) {
706 // Launch a file browser
707 string initpath = lyxrc.document_path;
710 string const trypath = buffer_->filePath();
711 // If directory is writeable, use this as default.
712 if (isDirWriteable(trypath))
716 FileDialog fileDlg(_("Select LyX document to insert"),
718 make_pair(string(_("Documents|#o#O")),
719 string(lyxrc.document_path)),
720 make_pair(string(_("Examples|#E#e")),
721 string(addPath(package().system_support(), "examples"))));
723 FileDialog::Result result =
724 fileDlg.open(initpath,
725 FileFilterList(_("LyX Documents (*.lyx)")),
728 if (result.first == FileDialog::Later)
731 filename = result.second;
733 // check selected filename
734 if (filename.empty()) {
735 // emit message signal.
736 bv_->message(_("Canceled."));
741 // Get absolute path of file and add ".lyx"
742 // to the filename if necessary
743 filename = fileSearch(string(), filename, "lyx");
745 string const disp_fn = makeDisplayPath(filename);
746 // emit message signal.
747 bv_->message(bformat(_("Inserting document %1$s..."), disp_fn));
750 Buffer buf("", false);
751 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
752 ErrorList & el = buffer_->errorList("Parse");
753 // Copy the inserted document error list into the current buffer one.
754 el = buf.errorList("Parse");
755 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
756 buf.params().textclass, el);
757 res = _("Document %1$s inserted.");
759 res = _("Could not insert document %1$s");
761 // emit message signal.
762 bv_->message(bformat(res, disp_fn));
763 buffer_->errors("Parse");
764 resizeCurrentBuffer();
768 void BufferView::Pimpl::trackChanges()
770 bool const tracking = buffer_->params().tracking_changes;
773 for_each(buffer_->par_iterator_begin(),
774 buffer_->par_iterator_end(),
775 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
776 buffer_->params().tracking_changes = true;
778 // We cannot allow undos beyond the freeze point
779 buffer_->undostack().clear();
781 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
782 if (lyx::find::findNextChange(bv_)) {
783 owner_->getDialogs().show("changes");
787 for_each(buffer_->par_iterator_begin(),
788 buffer_->par_iterator_end(),
789 mem_fun_ref(&Paragraph::untrackChanges));
791 buffer_->params().tracking_changes = false;
794 buffer_->redostack().clear();
798 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
800 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
802 // This is only called for mouse related events including
803 // LFUN_FILE_OPEN generated by drag-and-drop.
804 FuncRequest cmd = cmd0;
810 cur.push(buffer_->inset());
811 cur.selection() = cursor_.selection();
813 // Doesn't go through lyxfunc, so we need to update
814 // the layout choice etc. ourselves
816 // E.g. Qt mouse press when no buffer
820 // Either the inset under the cursor or the
821 // surrounding LyXText will handle this event.
823 // Build temporary cursor.
824 cmd.y = min(max(cmd.y, -1), height_);
825 InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
826 //lyxerr << BOOST_CURRENT_FUNCTION
827 // << " * hit inset at tip: " << inset << endl;
828 //lyxerr << BOOST_CURRENT_FUNCTION
829 // << " * created temp cursor:" << cur << endl;
831 // Put anchor at the same position.
834 // Try to dispatch to an non-editable inset near this position
835 // via the temp cursor. If the inset wishes to change the real
836 // cursor it has to do so explicitly by using
837 // cur.bv().cursor() = cur; (or similar)
839 inset->dispatch(cur, cmd);
841 // Now dispatch to the temporary cursor. If the real cursor should
842 // be modified, the inset's dispatch has to do so explicitly.
843 if (!cur.result().dispatched())
846 if (cur.result().dispatched()) {
847 // Redraw if requested or necessary.
848 if (cur.result().update())
849 update(Update::FitCursor | Update::Force);
851 update(Update::FitCursor | Update::MultiParSel);
858 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
862 switch (cmd.action) {
865 flag.enabled(!buffer_->undostack().empty());
868 flag.enabled(!buffer_->redostack().empty());
870 case LFUN_FILE_INSERT:
871 case LFUN_FILE_INSERT_ASCII_PARA:
872 case LFUN_FILE_INSERT_ASCII:
873 case LFUN_BOOKMARK_SAVE:
874 // FIXME: Actually, these LFUNS should be moved to LyXText
875 flag.enabled(cursor_.inTexted());
877 case LFUN_FONT_STATE:
878 case LFUN_LABEL_INSERT:
879 case LFUN_PARAGRAPH_GOTO:
880 // FIXME handle non-trivially
881 case LFUN_OUTLINE_UP:
882 case LFUN_OUTLINE_DOWN:
883 case LFUN_OUTLINE_IN:
884 case LFUN_OUTLINE_OUT:
886 case LFUN_REFERENCE_NEXT:
888 case LFUN_WORD_REPLACE:
891 case LFUN_MARK_TOGGLE:
892 case LFUN_SCREEN_RECENTER:
893 case LFUN_BIBTEX_DATABASE_ADD:
894 case LFUN_BIBTEX_DATABASE_DEL:
895 case LFUN_WORDS_COUNT:
896 case LFUN_NEXT_INSET_TOGGLE:
900 case LFUN_LABEL_GOTO: {
901 flag.enabled(!cmd.argument.empty()
902 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
906 case LFUN_BOOKMARK_GOTO:
907 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
909 case LFUN_CHANGES_TRACK:
911 flag.setOnOff(buffer_->params().tracking_changes);
914 case LFUN_CHANGES_OUTPUT: {
915 OutputParams runparams;
916 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
917 flag.enabled(buffer_ && buffer_->params().tracking_changes
918 && features.isAvailable("dvipost"));
919 flag.setOnOff(buffer_->params().output_changes);
923 case LFUN_CHANGES_MERGE:
924 case LFUN_CHANGE_ACCEPT: // what about these two
925 case LFUN_CHANGE_REJECT: // what about these two
926 case LFUN_ALL_CHANGES_ACCEPT:
927 case LFUN_ALL_CHANGES_REJECT:
928 flag.enabled(buffer_ && buffer_->params().tracking_changes);
931 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
932 flag.setOnOff(buffer_->params().compressed);
945 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
947 //lyxerr << BOOST_CURRENT_FUNCTION
948 // << [ cmd = " << cmd << "]" << endl;
950 // Make sure that the cached BufferView is correct.
951 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
952 << " action[" << cmd.action << ']'
953 << " arg[" << cmd.argument << ']'
954 << " x[" << cmd.x << ']'
955 << " y[" << cmd.y << ']'
956 << " button[" << cmd.button() << ']'
959 LCursor & cur = cursor_;
961 switch (cmd.action) {
965 cur.message(_("Undo"));
966 cur.clearSelection();
968 cur.message(_("No further undo information"));
976 cur.message(_("Redo"));
977 cur.clearSelection();
979 cur.message(_("No further redo information"));
985 case LFUN_FILE_INSERT:
986 menuInsertLyXFile(cmd.argument);
989 case LFUN_FILE_INSERT_ASCII_PARA:
990 insertAsciiFile(bv_, cmd.argument, true);
993 case LFUN_FILE_INSERT_ASCII:
994 insertAsciiFile(bv_, cmd.argument, false);
997 case LFUN_FONT_STATE:
998 cur.message(cur.currentState());
1001 case LFUN_BOOKMARK_SAVE:
1002 savePosition(convert<unsigned int>(cmd.argument));
1005 case LFUN_BOOKMARK_GOTO:
1006 restorePosition(convert<unsigned int>(cmd.argument));
1009 case LFUN_LABEL_GOTO: {
1010 string label = cmd.argument;
1011 if (label.empty()) {
1013 getInsetByCode<InsetRef>(cursor_,
1014 InsetBase::REF_CODE);
1016 label = inset->getContents();
1022 bv_->gotoLabel(label);
1026 case LFUN_PARAGRAPH_GOTO: {
1027 int const id = convert<int>(cmd.argument);
1028 ParIterator par = buffer_->getParFromID(id);
1029 if (par == buffer_->par_iterator_end()) {
1030 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1031 << id << ']' << endl;
1034 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1035 << " found." << endl;
1039 bv_->setCursor(makeDocIterator(par, 0));
1046 case LFUN_OUTLINE_UP:
1047 lyx::toc::outline(lyx::toc::Up, cursor_);
1048 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1049 updateLabels(*buffer_);
1051 case LFUN_OUTLINE_DOWN:
1052 lyx::toc::outline(lyx::toc::Down, cursor_);
1053 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1054 updateLabels(*buffer_);
1056 case LFUN_OUTLINE_IN:
1057 lyx::toc::outline(lyx::toc::In, cursor_);
1058 updateLabels(*buffer_);
1060 case LFUN_OUTLINE_OUT:
1061 lyx::toc::outline(lyx::toc::Out, cursor_);
1062 updateLabels(*buffer_);
1065 case LFUN_NOTE_NEXT:
1066 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1069 case LFUN_REFERENCE_NEXT: {
1070 vector<InsetBase_code> tmp;
1071 tmp.push_back(InsetBase::LABEL_CODE);
1072 tmp.push_back(InsetBase::REF_CODE);
1073 bv_funcs::gotoInset(bv_, tmp, true);
1077 case LFUN_CHANGES_TRACK:
1081 case LFUN_CHANGES_OUTPUT: {
1082 bool const state = buffer_->params().output_changes;
1083 buffer_->params().output_changes = !state;
1087 case LFUN_CHANGES_MERGE:
1088 if (lyx::find::findNextChange(bv_))
1089 owner_->getDialogs().show("changes");
1092 case LFUN_ALL_CHANGES_ACCEPT: {
1093 cursor_.reset(buffer_->inset());
1094 #ifdef WITH_WARNINGS
1095 #warning FIXME changes
1097 while (lyx::find::findNextChange(bv_))
1098 bv_->getLyXText()->acceptChange(cursor_);
1103 case LFUN_ALL_CHANGES_REJECT: {
1104 cursor_.reset(buffer_->inset());
1105 #ifdef WITH_WARNINGS
1106 #warning FIXME changes
1108 while (lyx::find::findNextChange(bv_))
1109 bv_->getLyXText()->rejectChange(cursor_);
1113 case LFUN_WORD_FIND:
1114 lyx::find::find(bv_, cmd);
1117 case LFUN_WORD_REPLACE:
1118 lyx::find::replace(bv_, cmd);
1122 cur.clearSelection();
1124 cur.message(N_("Mark off"));
1128 cur.clearSelection();
1131 cur.message(N_("Mark on"));
1134 case LFUN_MARK_TOGGLE:
1135 cur.clearSelection();
1138 cur.message(N_("Mark removed"));
1141 cur.message(N_("Mark set"));
1146 case LFUN_SCREEN_RECENTER:
1150 case LFUN_BIBTEX_DATABASE_ADD: {
1151 LCursor tmpcur = cursor_;
1152 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1153 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1154 InsetBase::BIBTEX_CODE);
1156 if (inset->addDatabase(cmd.argument))
1157 buffer_->updateBibfilesCache();
1162 case LFUN_BIBTEX_DATABASE_DEL: {
1163 LCursor tmpcur = cursor_;
1164 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1165 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1166 InsetBase::BIBTEX_CODE);
1168 if (inset->delDatabase(cmd.argument))
1169 buffer_->updateBibfilesCache();
1174 case LFUN_WORDS_COUNT: {
1175 DocIterator from, to;
1176 if (cur.selection()) {
1177 from = cur.selectionBegin();
1178 to = cur.selectionEnd();
1180 from = doc_iterator_begin(buffer_->inset());
1181 to = doc_iterator_end(buffer_->inset());
1183 int const count = countWords(from, to);
1186 if (cur.selection())
1187 message = bformat(_("%1$d words in selection."),
1190 message = bformat(_("%1$d words in document."),
1194 if (cur.selection())
1195 message = _("One word in selection.");
1197 message = _("One word in document.");
1200 Alert::information(_("Count words"), message);
1204 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1205 // turn compression on/off
1206 buffer_->params().compressed = !buffer_->params().compressed;
1209 case LFUN_NEXT_INSET_TOGGLE: {
1210 // this is the real function we want to invoke
1211 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1212 // if there is an inset at cursor, see whether it
1214 InsetBase * inset = cur.nextInset();
1215 if (inset && inset->isActive()) {
1216 LCursor tmpcur = cur;
1217 tmpcur.pushLeft(*inset);
1218 inset->dispatch(tmpcur, tmpcmd);
1219 if (tmpcur.result().dispatched()) {
1223 // if it did not work, try the underlying inset.
1224 if (!cur.result().dispatched())
1225 cur.dispatch(tmpcmd);
1227 if (cur.result().dispatched())
1228 cur.clearSelection();
1241 void BufferView::Pimpl::updateMetrics(bool singlepar)
1243 // Remove old position cache
1245 BufferView & bv = *bv_;
1246 LyXText * const text = bv.text();
1247 lyx::pit_type size = int(text->paragraphs().size());
1249 if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1250 anchor_ref_ = int(text->paragraphs().size() - 1);
1254 lyx::pit_type const pit = anchor_ref_;
1257 size_t const npit = text->paragraphs().size();
1259 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1260 // the (main text, not inset!) paragraph containing the cursor.
1261 // (if this paragraph contains insets etc., rebreaking will
1262 // recursively descend)
1263 if (!singlepar || pit == cursor_.bottom().pit())
1264 text->redoParagraph(pit);
1265 int y0 = text->getPar(pit).ascent() - offset_ref_;
1267 // Redo paragraphs above anchor if necessary; again, in Single Par
1268 // mode, only if we encounter the (main text) one having the cursor.
1270 while (y1 > 0 && pit1 > 0) {
1271 y1 -= text->getPar(pit1).ascent();
1273 if (!singlepar || pit1 == cursor_.bottom().pit())
1274 text->redoParagraph(pit1);
1275 y1 -= text->getPar(pit1).descent();
1279 // Take care of ascent of first line
1280 y1 -= text->getPar(pit1).ascent();
1282 // Normalize anchor for next time
1286 // Grey at the beginning is ugly
1287 if (pit1 == 0 && y1 > 0) {
1293 // Redo paragraphs below the anchor if necessary. Single par mode:
1294 // only the one containing the cursor if encountered.
1296 while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1297 y2 += text->getPar(pit2).descent();
1299 if (!singlepar || pit2 == cursor_.bottom().pit())
1300 text->redoParagraph(pit2);
1301 y2 += text->getPar(pit2).ascent();
1304 // Take care of descent of last line
1305 y2 += text->getPar(pit2).descent();
1307 // The coordinates of all these paragraphs are correct, cache them
1309 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[text];
1310 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1311 Paragraph const & par = text->getPar(pit);
1313 parPos[pit] = Point(0, y);
1314 if (singlepar && pit == cursor_.bottom().pit()) {
1315 // In Single Paragraph mode, collect here the
1316 // y1 and y2 of the (one) paragraph the cursor is in
1317 y1 = y - par.ascent();
1318 y2 = y + par.descent();
1324 // collect cursor paragraph iter bounds
1325 pit1 = cursor_.bottom().pit();
1326 pit2 = cursor_.bottom().pit();
1329 lyxerr[Debug::DEBUG]
1330 << BOOST_CURRENT_FUNCTION
1333 << " pit1: " << pit1
1334 << " pit2: " << pit2
1335 << " npit: " << npit
1336 << " singlepar: " << singlepar
1340 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);