3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "bufferview_funcs.h"
24 #include "coordcache.h"
25 #include "CutAndPaste.h"
27 #include "dispatchresult.h"
28 #include "errorlist.h"
30 #include "FloatList.h"
31 #include "funcrequest.h"
32 #include "FuncStatus.h"
35 #include "insetiterator.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
42 #include "lyxlayout.h"
44 #include "lyxtextclass.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
55 #include "WordLangTuple.h"
56 #include "metricsinfo.h"
58 #include "insets/insetbibtex.h"
59 #include "insets/insetcommand.h" // ChangeRefs
60 #include "insets/insetref.h"
61 #include "insets/insettext.h"
63 #include "frontends/Alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/filefilterlist.h"
71 #include "support/filetools.h"
72 #include "support/package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // update bookmark pit of the current buffer before switch
158 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160 if (buffer()->fileName() != bm.filename.absFilename())
162 // if par_id or pit has been changed, reset par_pit and par_id
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
166 boost::tie(new_pit, new_id) = moveToPosition(bm.par_pit, bm.par_id, bm.par_pos);
167 if (bm.par_pit != new_pit || bm.par_id != new_id)
168 const_cast<BookmarksSection::Bookmark &>(bm).setPos(new_pit, new_id);
170 // current buffer is going to be switched-off, save cursor pos
171 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
172 boost::tie(cursor_.pit(), cursor_.pos()) );
175 // If we're quitting lyx, don't bother updating stuff
181 // If we are closing current buffer, switch to the first in
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << " No Buffer!" << endl;
186 // We are closing the buffer, use the first buffer as current
187 buffer_ = theBufferList().first();
189 // Set current buffer
194 cursor_ = LCursor(*this);
199 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
200 << "Buffer addr: " << buffer_ << endl;
201 cursor_.push(buffer_->inset());
202 cursor_.resetAnchor();
203 buffer_->text().setCurrentFont(cursor_);
204 if (buffer_->getCursor().size() > 0 &&
205 buffer_->getAnchor().size() > 0)
207 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
208 cursor_.resetAnchor();
209 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
210 cursor_.setSelection();
211 // do not set selection to the new buffer because we
212 // only paste recent selection.
217 updateMetrics(false);
219 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
220 graphics::Previews::get().generateBufferPreviews(*buffer_);
224 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
226 // File already open?
227 if (theBufferList().exists(filename.absFilename())) {
228 docstring const file = makeDisplayPath(filename.absFilename(), 20);
229 docstring text = bformat(_("The document %1$s is already "
230 "loaded.\n\nDo you want to revert "
231 "to the saved version?"), file);
232 int const ret = Alert::prompt(_("Revert to saved document?"),
233 text, 0, 1, _("&Revert"), _("&Switch to document"));
236 setBuffer(theBufferList().getBuffer(filename.absFilename()));
239 // FIXME: should be LFUN_REVERT
240 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
242 // Fall through to new load. (Asger)
248 if (isFileReadable(filename)) {
249 b = theBufferList().newBuffer(filename.absFilename());
250 if (!lyx::loadLyXFile(b, filename)) {
251 theBufferList().release(b);
255 docstring text = bformat(_("The document %1$s does not yet "
256 "exist.\n\nDo you want to create "
257 "a new document?"), from_utf8(filename.absFilename()));
258 int const ret = Alert::prompt(_("Create new document?"),
259 text, 0, 1, _("&Create"), _("Cancel"));
262 b = newFile(filename.absFilename(), string(), true);
270 // Send the "errors" signal in case of parsing errors
273 // Update the labels and section numbering.
274 updateLabels(*buffer_);
275 // scroll to the position when the file was last closed
276 if (lyxrc.use_lastfilepos) {
279 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
280 // if successfully move to pit (returned par_id is not zero), update metrics
281 if (moveToPosition(pit, 0, pos).get<1>()) {
283 updateMetrics(false);
288 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
294 void BufferView::resize()
299 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
301 updateMetrics(false);
306 bool BufferView::fitCursor()
308 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
309 frontend::FontMetrics const & fm =
310 theFontMetrics(cursor_.getFont());
311 int const asc = fm.maxAscent();
312 int const des = fm.maxDescent();
313 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
314 if (p.y_ - asc >= 0 && p.y_ + des < height_)
322 bool BufferView::multiParSel()
324 if (!cursor_.selection())
326 bool ret = multiparsel_cache_;
327 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
328 // Either this, or previous selection spans paragraphs
329 return ret || multiparsel_cache_;
333 bool BufferView::update(Update::flags flags)
335 // last_inset_ points to the last visited inset. This pointer may become
336 // invalid because of keyboard editing. Since all such operations
337 // causes screen update(), I reset last_inset_ to avoid such a problem.
339 // This is close to a hot-path.
340 if (lyxerr.debugging(Debug::DEBUG)) {
342 << BOOST_CURRENT_FUNCTION
343 << "[fitcursor = " << (flags & Update::FitCursor)
344 << ", forceupdate = " << (flags & Update::Force)
345 << ", singlepar = " << (flags & Update::SinglePar)
346 << "] buffer: " << buffer_ << endl;
349 // Check needed to survive LyX startup
353 if (lyxerr.debugging(Debug::WORKAREA)) {
354 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
357 // Update macro store
358 buffer_->buildMacros();
360 // Now do the first drawing step if needed. This consists on updating
361 // the CoordCache in updateMetrics().
362 // The second drawing step is done in WorkArea::redraw() if needed.
364 // Case when no explicit update is requested.
366 // no need to redraw anything.
367 metrics_info_.update_strategy = NoScreenUpdate;
371 if (flags == Update::Decoration) {
372 metrics_info_.update_strategy = DecorationUpdate;
376 if (flags == Update::FitCursor
377 || flags == (Update::Decoration | Update::FitCursor)) {
378 bool const fit_cursor = fitCursor();
379 // tell the frontend to update the screen if needed.
381 updateMetrics(false);
384 if (flags & Update::Decoration) {
385 metrics_info_.update_strategy = DecorationUpdate;
388 // no screen update is needed.
389 metrics_info_.update_strategy = NoScreenUpdate;
393 bool full_metrics = flags & Update::Force;
394 if (flags & Update::MultiParSel)
395 full_metrics |= multiParSel();
397 bool const single_par = !full_metrics;
398 updateMetrics(single_par);
400 if (flags & Update::FitCursor && fitCursor())
401 updateMetrics(false);
403 // tell the frontend to update the screen.
408 void BufferView::updateScrollbar()
411 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
412 << " no text in updateScrollbar" << endl;
413 scrollbarParameters_.reset();
417 LyXText & t = buffer_->text();
418 TextMetrics & tm = text_metrics_[&t];
420 int const parsize = int(t.paragraphs().size() - 1);
421 if (anchor_ref_ > parsize) {
422 anchor_ref_ = parsize;
426 if (lyxerr.debugging(Debug::GUI)) {
428 << BOOST_CURRENT_FUNCTION
429 << " Updating scrollbar: height: " << t.paragraphs().size()
430 << " curr par: " << cursor_.bottom().pit()
431 << " default height " << defaultRowHeight() << endl;
434 // It would be better to fix the scrollbar to understand
435 // values in [0..1] and divide everything by wh
437 // estimated average paragraph height:
441 int h = tm.parMetrics(anchor_ref_).height();
443 // Normalize anchor/offset (MV):
444 while (offset_ref_ > h && anchor_ref_ < parsize) {
447 h = tm.parMetrics(anchor_ref_).height();
449 // Look at paragraph heights on-screen
452 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
455 int const h2 = tm.parMetrics(pit).height();
461 int const hav = sumh / nh;
462 // More realistic average paragraph height
467 scrollbarParameters_.height = (parsize + 1) * wh_;
468 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
469 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 return scrollbarParameters_;
479 void BufferView::scrollDocView(int value)
481 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
482 << "[ value = " << value << "]" << endl;
487 LyXText & t = buffer_->text();
488 TextMetrics & tm = text_metrics_[&t];
490 float const bar = value / float(wh_ * t.paragraphs().size());
492 anchor_ref_ = int(bar * t.paragraphs().size());
493 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
494 anchor_ref_ = int(t.paragraphs().size()) - 1;
496 tm.redoParagraph(anchor_ref_);
497 int const h = tm.parMetrics(anchor_ref_).height();
498 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
499 updateMetrics(false);
503 void BufferView::setCursorFromScrollbar()
508 LyXText & t = buffer_->text();
510 int const height = 2 * defaultRowHeight();
511 int const first = height;
512 int const last = height_ - height;
513 LCursor & cur = cursor_;
515 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
518 case bv_funcs::CUR_ABOVE:
519 // We reset the cursor because bv_funcs::status() does not
520 // work when the cursor is within mathed.
521 cur.reset(buffer_->inset());
522 t.setCursorFromCoordinates(cur, 0, first);
523 cur.clearSelection();
525 case bv_funcs::CUR_BELOW:
526 // We reset the cursor because bv_funcs::status() does not
527 // work when the cursor is within mathed.
528 cur.reset(buffer_->inset());
529 t.setCursorFromCoordinates(cur, 0, last);
530 cur.clearSelection();
532 case bv_funcs::CUR_INSIDE:
533 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
534 int const newy = min(last, max(y, first));
536 cur.reset(buffer_->inset());
537 t.setCursorFromCoordinates(cur, 0, newy);
543 Change const BufferView::getCurrentChange() const
545 if (!cursor_.selection())
546 return Change(Change::UNCHANGED);
548 DocIterator dit = cursor_.selectionBegin();
549 return dit.paragraph().lookupChange(dit.pos());
553 void BufferView::saveBookmark(bool persistent)
555 LyX::ref().session().bookmarks().save(
556 FileName(buffer_->fileName()),
558 cursor_.paragraph().id(),
563 // emit message signal.
564 message(_("Save bookmark"));
568 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
570 cursor_.clearSelection();
572 // if a valid par_id is given, try it first
574 ParIterator par = buffer_->getParFromID(par_id);
575 if (par != buffer_->par_iterator_end()) {
576 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
577 return boost::make_tuple(cursor_.pit(), par_id);
580 // if par_id == 0, or searching through par_id failed
581 if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
582 ParIterator it = buffer_->par_iterator_begin();
583 ParIterator const end = buffer_->par_iterator_end();
584 for (; it != end; ++it)
585 if (it.pit() == par_pit) {
586 // restored pos may be bigger than it->size
587 setCursor(makeDocIterator(it, min(par_pos, it->size())));
588 return boost::make_tuple(par_pit, it->id());
592 return boost::make_tuple(pit_type(0), 0);
596 void BufferView::switchKeyMap()
598 if (!lyxrc.rtl_support)
601 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
602 if (intl_->keymap == Intl::PRIMARY)
605 if (intl_->keymap == Intl::SECONDARY)
611 int BufferView::workWidth() const
617 void BufferView::center()
619 CursorSlice & bot = cursor_.bottom();
620 TextMetrics & tm = text_metrics_[bot.text()];
621 pit_type const pit = bot.pit();
622 tm.redoParagraph(pit);
623 ParagraphMetrics const & pm = tm.parMetrics(pit);
625 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
626 + pm.ascent() - height_ / 2;
630 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
634 switch (cmd.action) {
637 flag.enabled(!buffer_->undostack().empty());
640 flag.enabled(!buffer_->redostack().empty());
642 case LFUN_FILE_INSERT:
643 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
644 case LFUN_FILE_INSERT_PLAINTEXT:
645 case LFUN_BOOKMARK_SAVE:
646 // FIXME: Actually, these LFUNS should be moved to LyXText
647 flag.enabled(cursor_.inTexted());
649 case LFUN_FONT_STATE:
650 case LFUN_LABEL_INSERT:
651 case LFUN_PARAGRAPH_GOTO:
652 // FIXME handle non-trivially
653 case LFUN_OUTLINE_UP:
654 case LFUN_OUTLINE_DOWN:
655 case LFUN_OUTLINE_IN:
656 case LFUN_OUTLINE_OUT:
658 case LFUN_REFERENCE_NEXT:
660 case LFUN_WORD_REPLACE:
663 case LFUN_MARK_TOGGLE:
664 case LFUN_SCREEN_RECENTER:
665 case LFUN_BIBTEX_DATABASE_ADD:
666 case LFUN_BIBTEX_DATABASE_DEL:
667 case LFUN_WORDS_COUNT:
668 case LFUN_NEXT_INSET_TOGGLE:
672 case LFUN_LABEL_GOTO: {
673 flag.enabled(!cmd.argument().empty()
674 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
678 case LFUN_CHANGES_TRACK:
680 flag.setOnOff(buffer_->params().trackChanges);
683 case LFUN_CHANGES_OUTPUT: {
684 OutputParams runparams;
685 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
686 flag.enabled(buffer_ && features.isAvailable("dvipost"));
687 flag.setOnOff(buffer_->params().outputChanges);
691 case LFUN_CHANGES_MERGE:
692 case LFUN_CHANGE_NEXT:
693 case LFUN_ALL_CHANGES_ACCEPT:
694 case LFUN_ALL_CHANGES_REJECT:
695 // TODO: context-sensitive enabling of LFUNs
696 // In principle, these command should only be enabled if there
697 // is a change in the document. However, without proper
698 // optimizations, this will inevitably result in poor performance.
699 flag.enabled(buffer_);
702 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
703 flag.setOnOff(buffer_->params().compressed);
715 Update::flags BufferView::dispatch(FuncRequest const & cmd)
717 //lyxerr << BOOST_CURRENT_FUNCTION
718 // << [ cmd = " << cmd << "]" << endl;
720 // Make sure that the cached BufferView is correct.
721 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
722 << " action[" << cmd.action << ']'
723 << " arg[" << to_utf8(cmd.argument()) << ']'
724 << " x[" << cmd.x << ']'
725 << " y[" << cmd.y << ']'
726 << " button[" << cmd.button() << ']'
729 // FIXME: this should not be possible.
733 LCursor & cur = cursor_;
734 // Default Update flags.
735 Update::flags updateFlags = Update::Force | Update::FitCursor;
737 switch (cmd.action) {
740 cur.message(_("Undo"));
741 cur.clearSelection();
742 if (!textUndo(*this)) {
743 cur.message(_("No further undo information"));
744 updateFlags = Update::None;
750 cur.message(_("Redo"));
751 cur.clearSelection();
752 if (!textRedo(*this)) {
753 cur.message(_("No further redo information"));
754 updateFlags = Update::None;
759 case LFUN_FILE_INSERT:
761 menuInsertLyXFile(to_utf8(cmd.argument()));
764 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
766 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
769 case LFUN_FILE_INSERT_PLAINTEXT:
771 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
774 case LFUN_FONT_STATE:
775 cur.message(cur.currentState());
778 case LFUN_BOOKMARK_SAVE:
779 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
782 case LFUN_LABEL_GOTO: {
783 docstring label = cmd.argument();
786 getInsetByCode<InsetRef>(cursor_,
787 InsetBase::REF_CODE);
789 label = inset->getParam("reference");
790 // persistent=false: use temp_bookmark
800 case LFUN_PARAGRAPH_GOTO: {
801 int const id = convert<int>(to_utf8(cmd.argument()));
803 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
804 ParIterator par = b->getParFromID(id);
805 if (par == b->par_iterator_end()) {
807 << "No matching paragraph found! ["
808 << id << "]." << endl;
811 << "Paragraph " << par->id()
812 << " found in buffer `"
813 << b->fileName() << "'." << endl;
817 setCursor(makeDocIterator(par, 0));
820 // Switch to other buffer view and resend cmd
821 theLyXFunc().dispatch(FuncRequest(
822 LFUN_BUFFER_SWITCH, b->fileName()));
823 theLyXFunc().dispatch(cmd);
824 updateFlags = Update::None;
833 case LFUN_OUTLINE_UP:
834 toc::outline(toc::Up, cursor_);
835 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
836 updateLabels(*buffer_);
838 case LFUN_OUTLINE_DOWN:
839 toc::outline(toc::Down, cursor_);
840 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
841 updateLabels(*buffer_);
843 case LFUN_OUTLINE_IN:
844 toc::outline(toc::In, cursor_);
845 updateLabels(*buffer_);
847 case LFUN_OUTLINE_OUT:
848 toc::outline(toc::Out, cursor_);
849 updateLabels(*buffer_);
853 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
856 case LFUN_REFERENCE_NEXT: {
857 vector<InsetBase_code> tmp;
858 tmp.push_back(InsetBase::LABEL_CODE);
859 tmp.push_back(InsetBase::REF_CODE);
860 bv_funcs::gotoInset(this, tmp, true);
864 case LFUN_CHANGES_TRACK:
865 buffer_->params().trackChanges = !buffer_->params().trackChanges;
868 case LFUN_CHANGES_OUTPUT:
869 buffer_->params().outputChanges = !buffer_->params().outputChanges;
872 case LFUN_CHANGE_NEXT:
873 findNextChange(this);
876 case LFUN_CHANGES_MERGE:
877 if (findNextChange(this))
878 showDialog("changes");
881 case LFUN_ALL_CHANGES_ACCEPT:
882 // select complete document
883 cursor_.reset(buffer_->inset());
884 cursor_.selHandle(true);
885 buffer_->text().cursorBottom(cursor_);
886 // accept everything in a single step to support atomic undo
887 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
890 case LFUN_ALL_CHANGES_REJECT:
891 // select complete document
892 cursor_.reset(buffer_->inset());
893 cursor_.selHandle(true);
894 buffer_->text().cursorBottom(cursor_);
895 // reject everything in a single step to support atomic undo
896 // Note: reject does not work recursively; the user may have to repeat the operation
897 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::REJECT);
904 case LFUN_WORD_REPLACE:
909 cur.clearSelection();
911 cur.message(from_utf8(N_("Mark off")));
915 cur.clearSelection();
918 cur.message(from_utf8(N_("Mark on")));
921 case LFUN_MARK_TOGGLE:
922 cur.clearSelection();
925 cur.message(from_utf8(N_("Mark removed")));
928 cur.message(from_utf8(N_("Mark set")));
933 case LFUN_SCREEN_RECENTER:
937 case LFUN_BIBTEX_DATABASE_ADD: {
938 LCursor tmpcur = cursor_;
939 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
940 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
941 InsetBase::BIBTEX_CODE);
943 if (inset->addDatabase(to_utf8(cmd.argument())))
944 buffer_->updateBibfilesCache();
949 case LFUN_BIBTEX_DATABASE_DEL: {
950 LCursor tmpcur = cursor_;
951 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
952 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
953 InsetBase::BIBTEX_CODE);
955 if (inset->delDatabase(to_utf8(cmd.argument())))
956 buffer_->updateBibfilesCache();
961 case LFUN_WORDS_COUNT: {
962 DocIterator from, to;
963 if (cur.selection()) {
964 from = cur.selectionBegin();
965 to = cur.selectionEnd();
967 from = doc_iterator_begin(buffer_->inset());
968 to = doc_iterator_end(buffer_->inset());
970 int const count = countWords(from, to);
974 message = bformat(_("%1$d words in selection."),
977 message = bformat(_("%1$d words in document."),
982 message = _("One word in selection.");
984 message = _("One word in document.");
987 Alert::information(_("Count words"), message);
991 case LFUN_BUFFER_TOGGLE_COMPRESSION:
992 // turn compression on/off
993 buffer_->params().compressed = !buffer_->params().compressed;
996 case LFUN_NEXT_INSET_TOGGLE: {
997 // this is the real function we want to invoke
998 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
999 // if there is an inset at cursor, see whether it
1001 InsetBase * inset = cur.nextInset();
1002 if (inset && inset->isActive()) {
1003 LCursor tmpcur = cur;
1004 tmpcur.pushLeft(*inset);
1005 inset->dispatch(tmpcur, tmpcmd);
1006 if (tmpcur.result().dispatched()) {
1010 // if it did not work, try the underlying inset.
1011 if (!cur.result().dispatched())
1012 cur.dispatch(tmpcmd);
1014 if (cur.result().dispatched())
1015 cur.clearSelection();
1021 updateFlags = Update::None;
1028 docstring const BufferView::requestSelection()
1033 LCursor & cur = cursor_;
1035 if (!cur.selection()) {
1036 xsel_cache_.set = false;
1040 if (!xsel_cache_.set ||
1041 cur.top() != xsel_cache_.cursor ||
1042 cur.anchor_.top() != xsel_cache_.anchor)
1044 xsel_cache_.cursor = cur.top();
1045 xsel_cache_.anchor = cur.anchor_.top();
1046 xsel_cache_.set = cur.selection();
1047 return cur.selectionAsString(false);
1053 void BufferView::clearSelection()
1056 cursor_.clearSelection();
1057 // Clear the selection buffer. Otherwise a subsequent
1058 // middle-mouse-button paste would use the selection buffer,
1059 // not the more current external selection.
1060 cap::clearSelection();
1061 xsel_cache_.set = false;
1062 // The buffer did not really change, but this causes the
1063 // redraw we need because we cleared the selection above.
1069 void BufferView::workAreaResize(int width, int height)
1071 // Update from work area
1075 // The complete text metrics will be redone.
1076 text_metrics_.clear();
1083 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1085 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1087 // This is only called for mouse related events including
1088 // LFUN_FILE_OPEN generated by drag-and-drop.
1089 FuncRequest cmd = cmd0;
1091 // E.g. Qt mouse press when no buffer
1096 cur.push(buffer_->inset());
1097 cur.selection() = cursor_.selection();
1099 // Either the inset under the cursor or the
1100 // surrounding LyXText will handle this event.
1102 // Build temporary cursor.
1103 cmd.y = min(max(cmd.y, -1), height_);
1104 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1106 //lyxerr << BOOST_CURRENT_FUNCTION
1107 // << " * hit inset at tip: " << inset << endl;
1108 //lyxerr << BOOST_CURRENT_FUNCTION
1109 // << " * created temp cursor:" << cur << endl;
1111 // NOTE: editXY returns the top level inset of nested insets. If you happen
1112 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1113 // footnote inset, again inset=0), that inset will not be redrawn.
1114 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1115 bool need_redraw = false;
1117 if (inset != last_inset_) {
1119 need_redraw |= last_inset_->setMouseHover(false);
1121 need_redraw |= inset->setMouseHover(true);
1122 last_inset_ = inset;
1125 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1126 // not expose the button for redraw. We adjust here the metrics dimension
1127 // to enable a full redraw.
1128 // FIXME: It is possible to redraw only the area around the button!
1130 && metrics_info_.update_strategy == SingleParUpdate) {
1131 // FIXME: It should be possible to redraw only the area around
1132 // the button by doing this:
1134 //metrics_info_.singlepar = false;
1135 //metrics_info_.y1 = ymin of button;
1136 //metrics_info_.y2 = ymax of button;
1138 // Unfortunately, rowpainter.C:paintText() does not distinguish
1139 // between background updates and text updates. So we use the hammer
1140 // solution for now. We could also avoid the updateMetrics() below
1141 // by using the first and last pit of the CoordCache. Have a look
1142 // at LyXText::getPitNearY() to see what I mean.
1144 //metrics_info_.pit1 = first pit of CoordCache;
1145 //metrics_info_.pit2 = last pit of CoordCache;
1146 //metrics_info_.singlepar = false;
1147 //metrics_info_.y1 = 0;
1148 //metrics_info_.y2 = height_;
1150 updateMetrics(false);
1153 // This event (moving without mouse click) is not passed further.
1154 // This should be changed if it is further utilized.
1158 // Put anchor at the same position.
1161 // Try to dispatch to an non-editable inset near this position
1162 // via the temp cursor. If the inset wishes to change the real
1163 // cursor it has to do so explicitly by using
1164 // cur.bv().cursor() = cur; (or similar)
1166 inset->dispatch(cur, cmd);
1169 // Now dispatch to the temporary cursor. If the real cursor should
1170 // be modified, the inset's dispatch has to do so explicitly.
1171 if (!cur.result().dispatched())
1174 // Redraw if requested and necessary.
1175 if (cur.result().dispatched() && cur.result().update())
1176 return update(cur.result().update());
1182 void BufferView::scroll(int /*lines*/)
1187 // LyXText const * t = &buffer_->text();
1188 // int const line_height = defaultRowHeight();
1190 // // The new absolute coordinate
1191 // int new_top_y = top_y() + lines * line_height;
1193 // // Restrict to a valid value
1194 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1195 // new_top_y = std::max(0, new_top_y);
1197 // scrollDocView(new_top_y);
1202 void BufferView::setCursorFromRow(int row)
1207 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1210 buffer_->text().setCursor(cursor_, 0, 0);
1212 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1216 void BufferView::gotoLabel(docstring const & label)
1218 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1219 vector<docstring> labels;
1220 it->getLabelList(*buffer_, labels);
1221 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1230 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1232 return const_cast<BufferView *>(this)->textMetrics(t);
1236 TextMetrics & BufferView::textMetrics(LyXText const * t)
1238 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1239 if (tmc_it == text_metrics_.end()) {
1240 tmc_it = text_metrics_.insert(
1241 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1243 return tmc_it->second;
1247 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1250 return textMetrics(t).parMetrics(pit);
1254 int BufferView::workHeight() const
1260 void BufferView::setCursor(DocIterator const & dit)
1262 size_t const n = dit.depth();
1263 for (size_t i = 0; i < n; ++i)
1264 dit[i].inset().edit(cursor_, true);
1266 cursor_.setCursor(dit);
1267 cursor_.selection() = false;
1271 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1273 // Would be wrong to delete anything if we have a selection.
1274 if (cur.selection())
1277 bool need_anchor_change = false;
1278 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1279 need_anchor_change);
1281 if (need_anchor_change)
1287 updateLabels(*buffer_);
1289 updateMetrics(false);
1295 bool BufferView::mouseSetCursor(LCursor & cur)
1297 BOOST_ASSERT(&cur.bv() == this);
1299 // Has the cursor just left the inset?
1300 bool badcursor = false;
1301 if (&cursor_.inset() != &cur.inset())
1302 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1304 // do the dEPM magic if needed
1305 // FIXME: move this to InsetText::notifyCursorLeaves?
1306 bool update = false;
1307 if (!badcursor && cursor_.inTexted())
1308 checkDepm(cur, cursor_);
1310 // if the cursor was in an empty script inset and the new
1311 // position is in the nucleus of the inset, notifyCursorLeaves
1312 // will kill the script inset itself. So we check all the
1313 // elements of the cursor to make sure that they are correct.
1314 // For an example, see bug 2933:
1315 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1316 // The code below could maybe be moved to a DocIterator method.
1317 //lyxerr << "cur before " << cur <<std::endl;
1318 DocIterator dit(cur.inset());
1319 dit.push_back(cur.bottom());
1321 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1322 dit.push_back(cur[i]);
1325 //lyxerr << "5 cur after" << dit <<std::endl;
1327 cursor_.setCursor(dit);
1328 cursor_.clearSelection();
1329 // remember new position.
1330 cursor_.setTargetX();
1336 void BufferView::putSelectionAt(DocIterator const & cur,
1337 int length, bool backwards)
1339 cursor_.clearSelection();
1345 cursor_.pos() += length;
1346 cursor_.setSelection(cursor_, -length);
1348 cursor_.setSelection(cursor_, length);
1349 cap::saveSelection(cursor_);
1354 LCursor & BufferView::cursor()
1360 LCursor const & BufferView::cursor() const
1366 pit_type BufferView::anchor_ref() const
1372 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1374 return metrics_info_;
1378 // FIXME: We should split-up updateMetrics() for the singlepar case.
1379 void BufferView::updateMetrics(bool singlepar)
1381 LyXText & buftext = buffer_->text();
1382 TextMetrics & tm = textMetrics(&buftext);
1383 pit_type size = int(buftext.paragraphs().size());
1385 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1386 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1390 // If the paragraph metrics has changed, we can not
1391 // use the singlepar optimisation.
1393 // In Single Paragraph mode, rebreak only
1394 // the (main text, not inset!) paragraph containing the cursor.
1395 // (if this paragraph contains insets etc., rebreaking will
1396 // recursively descend)
1397 && tm.redoParagraph(cursor_.bottom().pit()))
1400 pit_type const pit = anchor_ref_;
1403 size_t const npit = buftext.paragraphs().size();
1405 // Rebreak anchor paragraph.
1407 tm.redoParagraph(pit);
1409 // Clear out the position cache in case of full screen redraw.
1411 coord_cache_.clear();
1413 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1415 // Redo paragraphs above anchor if necessary.
1417 while (y1 > 0 && pit1 > 0) {
1418 y1 -= tm.parMetrics(pit1).ascent();
1421 tm.redoParagraph(pit1);
1422 y1 -= tm.parMetrics(pit1).descent();
1426 // Take care of ascent of first line
1427 y1 -= tm.parMetrics(pit1).ascent();
1429 // Normalize anchor for next time
1433 // Grey at the beginning is ugly
1434 if (pit1 == 0 && y1 > 0) {
1440 // Redo paragraphs below the anchor if necessary.
1442 while (y2 < height_ && pit2 < int(npit) - 1) {
1443 y2 += tm.parMetrics(pit2).descent();
1446 tm.redoParagraph(pit2);
1447 y2 += tm.parMetrics(pit2).ascent();
1450 // Take care of descent of last line
1451 y2 += tm.parMetrics(pit2).descent();
1453 // The coordinates of all these paragraphs are correct, cache them
1455 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1456 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1457 ParagraphMetrics const & pm = tm.parMetrics(pit);
1459 parPos[pit] = Point(0, y);
1460 if (singlepar && pit == cursor_.bottom().pit()) {
1461 // In Single Paragraph mode, collect here the
1462 // y1 and y2 of the (one) paragraph the cursor is in
1463 y1 = y - pm.ascent();
1464 y2 = y + pm.descent();
1470 // collect cursor paragraph iter bounds
1471 pit1 = cursor_.bottom().pit();
1472 pit2 = cursor_.bottom().pit();
1475 lyxerr[Debug::DEBUG]
1476 << BOOST_CURRENT_FUNCTION
1479 << " pit1: " << pit1
1480 << " pit2: " << pit2
1481 << " npit: " << npit
1482 << " singlepar: " << singlepar
1486 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1487 singlepar? SingleParUpdate: FullScreenUpdate, size);
1489 if (lyxerr.debugging(Debug::WORKAREA)) {
1490 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1491 coord_cache_.dump();
1496 void BufferView::menuInsertLyXFile(string const & filenm)
1498 BOOST_ASSERT(cursor_.inTexted());
1499 string filename = filenm;
1501 if (filename.empty()) {
1502 // Launch a file browser
1504 string initpath = lyxrc.document_path;
1507 string const trypath = buffer_->filePath();
1508 // If directory is writeable, use this as default.
1509 if (isDirWriteable(FileName(trypath)))
1514 FileDialog fileDlg(_("Select LyX document to insert"),
1516 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1517 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1519 FileDialog::Result result =
1520 fileDlg.open(from_utf8(initpath),
1521 FileFilterList(_("LyX Documents (*.lyx)")),
1524 if (result.first == FileDialog::Later)
1528 filename = to_utf8(result.second);
1530 // check selected filename
1531 if (filename.empty()) {
1532 // emit message signal.
1533 message(_("Canceled."));
1538 // Get absolute path of file and add ".lyx"
1539 // to the filename if necessary
1540 filename = fileSearch(string(), filename, "lyx").absFilename();
1542 docstring const disp_fn = makeDisplayPath(filename);
1543 // emit message signal.
1544 message(bformat(_("Inserting document %1$s..."), disp_fn));
1547 Buffer buf("", false);
1548 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1549 ErrorList & el = buffer_->errorList("Parse");
1550 // Copy the inserted document error list into the current buffer one.
1551 el = buf.errorList("Parse");
1552 recordUndo(cursor_);
1553 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1554 buf.params().textclass, el);
1555 res = _("Document %1$s inserted.");
1557 res = _("Could not insert document %1$s");
1559 // emit message signal.
1560 message(bformat(res, disp_fn));
1561 buffer_->errors("Parse");