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 and reset font
281 if (moveToPosition(pit, 0, pos).get<1>()) {
283 updateMetrics(false);
284 buffer_->text().setCurrentFont(cursor_);
289 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
295 void BufferView::resize()
300 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
302 updateMetrics(false);
307 bool BufferView::fitCursor()
309 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
310 frontend::FontMetrics const & fm =
311 theFontMetrics(cursor_.getFont());
312 int const asc = fm.maxAscent();
313 int const des = fm.maxDescent();
314 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
315 if (p.y_ - asc >= 0 && p.y_ + des < height_)
323 bool BufferView::multiParSel()
325 if (!cursor_.selection())
327 bool ret = multiparsel_cache_;
328 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
329 // Either this, or previous selection spans paragraphs
330 return ret || multiparsel_cache_;
334 bool BufferView::update(Update::flags flags)
336 // last_inset_ points to the last visited inset. This pointer may become
337 // invalid because of keyboard editing. Since all such operations
338 // causes screen update(), I reset last_inset_ to avoid such a problem.
340 // This is close to a hot-path.
342 << BOOST_CURRENT_FUNCTION
343 << "[fitcursor = " << (flags & Update::FitCursor)
344 << ", forceupdate = " << (flags & Update::Force)
345 << ", singlepar = " << (flags & Update::SinglePar)
346 << "] buffer: " << buffer_ << endl;
348 // Check needed to survive LyX startup
352 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
354 // Update macro store
355 buffer_->buildMacros();
357 // Now do the first drawing step if needed. This consists on updating
358 // the CoordCache in updateMetrics().
359 // The second drawing step is done in WorkArea::redraw() if needed.
361 // Case when no explicit update is requested.
363 // no need to redraw anything.
364 metrics_info_.update_strategy = NoScreenUpdate;
368 if (flags == Update::Decoration) {
369 metrics_info_.update_strategy = DecorationUpdate;
373 if (flags == Update::FitCursor
374 || flags == (Update::Decoration | Update::FitCursor)) {
375 bool const fit_cursor = fitCursor();
376 // tell the frontend to update the screen if needed.
378 updateMetrics(false);
381 if (flags & Update::Decoration) {
382 metrics_info_.update_strategy = DecorationUpdate;
385 // no screen update is needed.
386 metrics_info_.update_strategy = NoScreenUpdate;
390 bool full_metrics = flags & Update::Force;
391 if (flags & Update::MultiParSel)
392 full_metrics |= multiParSel();
394 bool const single_par = !full_metrics;
395 updateMetrics(single_par);
397 if (flags & Update::FitCursor && fitCursor())
398 updateMetrics(false);
400 // tell the frontend to update the screen.
405 void BufferView::updateScrollbar()
408 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
409 << " no text in updateScrollbar" << endl;
410 scrollbarParameters_.reset();
414 LyXText & t = buffer_->text();
415 TextMetrics & tm = text_metrics_[&t];
417 int const parsize = int(t.paragraphs().size() - 1);
418 if (anchor_ref_ > parsize) {
419 anchor_ref_ = parsize;
424 << BOOST_CURRENT_FUNCTION
425 << " Updating scrollbar: height: " << t.paragraphs().size()
426 << " curr par: " << cursor_.bottom().pit()
427 << " default height " << defaultRowHeight() << endl;
429 // It would be better to fix the scrollbar to understand
430 // values in [0..1] and divide everything by wh
432 // estimated average paragraph height:
436 int h = tm.parMetrics(anchor_ref_).height();
438 // Normalize anchor/offset (MV):
439 while (offset_ref_ > h && anchor_ref_ < parsize) {
442 h = tm.parMetrics(anchor_ref_).height();
444 // Look at paragraph heights on-screen
447 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
450 int const h2 = tm.parMetrics(pit).height();
456 int const hav = sumh / nh;
457 // More realistic average paragraph height
462 scrollbarParameters_.height = (parsize + 1) * wh_;
463 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
464 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
468 ScrollbarParameters const & BufferView::scrollbarParameters() const
470 return scrollbarParameters_;
474 void BufferView::scrollDocView(int value)
476 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
477 << "[ value = " << value << "]" << endl;
482 LyXText & t = buffer_->text();
483 TextMetrics & tm = text_metrics_[&t];
485 float const bar = value / float(wh_ * t.paragraphs().size());
487 anchor_ref_ = int(bar * t.paragraphs().size());
488 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
489 anchor_ref_ = int(t.paragraphs().size()) - 1;
491 tm.redoParagraph(anchor_ref_);
492 int const h = tm.parMetrics(anchor_ref_).height();
493 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
494 updateMetrics(false);
498 void BufferView::setCursorFromScrollbar()
503 LyXText & t = buffer_->text();
505 int const height = 2 * defaultRowHeight();
506 int const first = height;
507 int const last = height_ - height;
508 LCursor & cur = cursor_;
510 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
513 case bv_funcs::CUR_ABOVE:
514 // We reset the cursor because bv_funcs::status() does not
515 // work when the cursor is within mathed.
516 cur.reset(buffer_->inset());
517 t.setCursorFromCoordinates(cur, 0, first);
518 cur.clearSelection();
520 case bv_funcs::CUR_BELOW:
521 // We reset the cursor because bv_funcs::status() does not
522 // work when the cursor is within mathed.
523 cur.reset(buffer_->inset());
524 t.setCursorFromCoordinates(cur, 0, last);
525 cur.clearSelection();
527 case bv_funcs::CUR_INSIDE:
528 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
529 int const newy = min(last, max(y, first));
531 cur.reset(buffer_->inset());
532 t.setCursorFromCoordinates(cur, 0, newy);
538 Change const BufferView::getCurrentChange() const
540 if (!cursor_.selection())
541 return Change(Change::UNCHANGED);
543 DocIterator dit = cursor_.selectionBegin();
544 return dit.paragraph().lookupChange(dit.pos());
548 void BufferView::saveBookmark(unsigned int idx)
550 LyX::ref().session().bookmarks().save(
551 FileName(buffer_->fileName()),
553 cursor_.paragraph().id(),
558 // emit message signal.
559 message(_("Save bookmark"));
563 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
565 cursor_.clearSelection();
567 // if a valid par_id is given, try it first
569 ParIterator par = buffer_->getParFromID(par_id);
570 if (par != buffer_->par_iterator_end()) {
571 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
572 return boost::make_tuple(cursor_.pit(), par_id);
575 // if par_id == 0, or searching through par_id failed
576 if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
577 ParIterator it = buffer_->par_iterator_begin();
578 ParIterator const end = buffer_->par_iterator_end();
579 for (; it != end; ++it)
580 if (it.pit() == par_pit) {
581 // restored pos may be bigger than it->size
582 setCursor(makeDocIterator(it, min(par_pos, it->size())));
583 return boost::make_tuple(par_pit, it->id());
587 return boost::make_tuple(pit_type(0), 0);
591 void BufferView::switchKeyMap()
593 if (!lyxrc.rtl_support)
596 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
597 if (intl_->keymap == Intl::PRIMARY)
600 if (intl_->keymap == Intl::SECONDARY)
606 int BufferView::workWidth() const
612 void BufferView::center()
614 CursorSlice & bot = cursor_.bottom();
615 TextMetrics & tm = text_metrics_[bot.text()];
616 pit_type const pit = bot.pit();
617 tm.redoParagraph(pit);
618 ParagraphMetrics const & pm = tm.parMetrics(pit);
620 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
621 + pm.ascent() - height_ / 2;
625 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
629 switch (cmd.action) {
632 flag.enabled(!buffer_->undostack().empty());
635 flag.enabled(!buffer_->redostack().empty());
637 case LFUN_FILE_INSERT:
638 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
639 case LFUN_FILE_INSERT_PLAINTEXT:
640 case LFUN_BOOKMARK_SAVE:
641 // FIXME: Actually, these LFUNS should be moved to LyXText
642 flag.enabled(cursor_.inTexted());
644 case LFUN_FONT_STATE:
645 case LFUN_LABEL_INSERT:
646 case LFUN_PARAGRAPH_GOTO:
647 // FIXME handle non-trivially
648 case LFUN_OUTLINE_UP:
649 case LFUN_OUTLINE_DOWN:
650 case LFUN_OUTLINE_IN:
651 case LFUN_OUTLINE_OUT:
653 case LFUN_REFERENCE_NEXT:
655 case LFUN_WORD_REPLACE:
658 case LFUN_MARK_TOGGLE:
659 case LFUN_SCREEN_RECENTER:
660 case LFUN_BIBTEX_DATABASE_ADD:
661 case LFUN_BIBTEX_DATABASE_DEL:
662 case LFUN_WORDS_COUNT:
663 case LFUN_NEXT_INSET_TOGGLE:
667 case LFUN_LABEL_GOTO: {
668 flag.enabled(!cmd.argument().empty()
669 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
673 case LFUN_CHANGES_TRACK:
675 flag.setOnOff(buffer_->params().trackChanges);
678 case LFUN_CHANGES_OUTPUT:
679 flag.enabled(buffer_ && LaTeXFeatures::isAvailable("dvipost"));
680 flag.setOnOff(buffer_->params().outputChanges);
683 case LFUN_CHANGES_MERGE:
684 case LFUN_CHANGE_NEXT:
685 case LFUN_ALL_CHANGES_ACCEPT:
686 case LFUN_ALL_CHANGES_REJECT:
687 // TODO: context-sensitive enabling of LFUNs
688 // In principle, these command should only be enabled if there
689 // is a change in the document. However, without proper
690 // optimizations, this will inevitably result in poor performance.
691 flag.enabled(buffer_);
694 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
695 flag.setOnOff(buffer_->params().compressed);
707 Update::flags BufferView::dispatch(FuncRequest const & cmd)
709 //lyxerr << BOOST_CURRENT_FUNCTION
710 // << [ cmd = " << cmd << "]" << endl;
712 // Make sure that the cached BufferView is correct.
713 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
714 << " action[" << cmd.action << ']'
715 << " arg[" << to_utf8(cmd.argument()) << ']'
716 << " x[" << cmd.x << ']'
717 << " y[" << cmd.y << ']'
718 << " button[" << cmd.button() << ']'
721 // FIXME: this should not be possible.
725 LCursor & cur = cursor_;
726 // Default Update flags.
727 Update::flags updateFlags = Update::Force | Update::FitCursor;
729 switch (cmd.action) {
732 cur.message(_("Undo"));
733 cur.clearSelection();
734 if (!textUndo(*this)) {
735 cur.message(_("No further undo information"));
736 updateFlags = Update::None;
742 cur.message(_("Redo"));
743 cur.clearSelection();
744 if (!textRedo(*this)) {
745 cur.message(_("No further redo information"));
746 updateFlags = Update::None;
751 case LFUN_FILE_INSERT:
753 menuInsertLyXFile(to_utf8(cmd.argument()));
756 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
758 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
761 case LFUN_FILE_INSERT_PLAINTEXT:
763 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
766 case LFUN_FONT_STATE:
767 cur.message(cur.currentState());
770 case LFUN_BOOKMARK_SAVE:
771 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
774 case LFUN_LABEL_GOTO: {
775 docstring label = cmd.argument();
778 getInsetByCode<InsetRef>(cursor_,
779 InsetBase::REF_CODE);
781 label = inset->getParam("reference");
782 // persistent=false: use temp_bookmark
792 case LFUN_PARAGRAPH_GOTO: {
793 int const id = convert<int>(to_utf8(cmd.argument()));
795 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
796 ParIterator par = b->getParFromID(id);
797 if (par == b->par_iterator_end()) {
799 << "No matching paragraph found! ["
800 << id << "]." << endl;
803 << "Paragraph " << par->id()
804 << " found in buffer `"
805 << b->fileName() << "'." << endl;
809 setCursor(makeDocIterator(par, 0));
812 // Switch to other buffer view and resend cmd
813 theLyXFunc().dispatch(FuncRequest(
814 LFUN_BUFFER_SWITCH, b->fileName()));
815 theLyXFunc().dispatch(cmd);
816 updateFlags = Update::None;
825 case LFUN_OUTLINE_UP:
826 toc::outline(toc::Up, cursor_);
827 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
828 updateLabels(*buffer_);
830 case LFUN_OUTLINE_DOWN:
831 toc::outline(toc::Down, cursor_);
832 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
833 updateLabels(*buffer_);
835 case LFUN_OUTLINE_IN:
836 toc::outline(toc::In, cursor_);
837 updateLabels(*buffer_);
839 case LFUN_OUTLINE_OUT:
840 toc::outline(toc::Out, cursor_);
841 updateLabels(*buffer_);
845 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
848 case LFUN_REFERENCE_NEXT: {
849 vector<InsetBase_code> tmp;
850 tmp.push_back(InsetBase::LABEL_CODE);
851 tmp.push_back(InsetBase::REF_CODE);
852 bv_funcs::gotoInset(this, tmp, true);
856 case LFUN_CHANGES_TRACK:
857 buffer_->params().trackChanges = !buffer_->params().trackChanges;
860 case LFUN_CHANGES_OUTPUT:
861 buffer_->params().outputChanges = !buffer_->params().outputChanges;
864 case LFUN_CHANGE_NEXT:
865 findNextChange(this);
868 case LFUN_CHANGES_MERGE:
869 if (findNextChange(this))
870 showDialog("changes");
873 case LFUN_ALL_CHANGES_ACCEPT:
874 // select complete document
875 cursor_.reset(buffer_->inset());
876 cursor_.selHandle(true);
877 buffer_->text().cursorBottom(cursor_);
878 // accept everything in a single step to support atomic undo
879 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
882 case LFUN_ALL_CHANGES_REJECT:
883 // select complete document
884 cursor_.reset(buffer_->inset());
885 cursor_.selHandle(true);
886 buffer_->text().cursorBottom(cursor_);
887 // reject everything in a single step to support atomic undo
888 // Note: reject does not work recursively; the user may have to repeat the operation
889 buffer_->text().acceptOrRejectChanges(cursor_, LyXText::REJECT);
896 case LFUN_WORD_REPLACE:
901 cur.clearSelection();
903 cur.message(from_utf8(N_("Mark off")));
907 cur.clearSelection();
910 cur.message(from_utf8(N_("Mark on")));
913 case LFUN_MARK_TOGGLE:
914 cur.clearSelection();
917 cur.message(from_utf8(N_("Mark removed")));
920 cur.message(from_utf8(N_("Mark set")));
925 case LFUN_SCREEN_RECENTER:
929 case LFUN_BIBTEX_DATABASE_ADD: {
930 LCursor tmpcur = cursor_;
931 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
932 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
933 InsetBase::BIBTEX_CODE);
935 if (inset->addDatabase(to_utf8(cmd.argument())))
936 buffer_->updateBibfilesCache();
941 case LFUN_BIBTEX_DATABASE_DEL: {
942 LCursor tmpcur = cursor_;
943 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
944 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
945 InsetBase::BIBTEX_CODE);
947 if (inset->delDatabase(to_utf8(cmd.argument())))
948 buffer_->updateBibfilesCache();
953 case LFUN_WORDS_COUNT: {
954 DocIterator from, to;
955 if (cur.selection()) {
956 from = cur.selectionBegin();
957 to = cur.selectionEnd();
959 from = doc_iterator_begin(buffer_->inset());
960 to = doc_iterator_end(buffer_->inset());
962 int const count = countWords(from, to);
966 message = bformat(_("%1$d words in selection."),
969 message = bformat(_("%1$d words in document."),
974 message = _("One word in selection.");
976 message = _("One word in document.");
979 Alert::information(_("Count words"), message);
983 case LFUN_BUFFER_TOGGLE_COMPRESSION:
984 // turn compression on/off
985 buffer_->params().compressed = !buffer_->params().compressed;
988 case LFUN_NEXT_INSET_TOGGLE: {
989 // this is the real function we want to invoke
990 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
991 // if there is an inset at cursor, see whether it
993 InsetBase * inset = cur.nextInset();
994 if (inset && inset->isActive()) {
995 LCursor tmpcur = cur;
996 tmpcur.pushLeft(*inset);
997 inset->dispatch(tmpcur, tmpcmd);
998 if (tmpcur.result().dispatched()) {
1002 // if it did not work, try the underlying inset.
1003 if (!cur.result().dispatched())
1004 cur.dispatch(tmpcmd);
1006 if (cur.result().dispatched())
1007 cur.clearSelection();
1013 updateFlags = Update::None;
1020 docstring const BufferView::requestSelection()
1025 LCursor & cur = cursor_;
1027 if (!cur.selection()) {
1028 xsel_cache_.set = false;
1032 if (!xsel_cache_.set ||
1033 cur.top() != xsel_cache_.cursor ||
1034 cur.anchor_.top() != xsel_cache_.anchor)
1036 xsel_cache_.cursor = cur.top();
1037 xsel_cache_.anchor = cur.anchor_.top();
1038 xsel_cache_.set = cur.selection();
1039 return cur.selectionAsString(false);
1045 void BufferView::clearSelection()
1048 cursor_.clearSelection();
1049 // Clear the selection buffer. Otherwise a subsequent
1050 // middle-mouse-button paste would use the selection buffer,
1051 // not the more current external selection.
1052 cap::clearSelection();
1053 xsel_cache_.set = false;
1054 // The buffer did not really change, but this causes the
1055 // redraw we need because we cleared the selection above.
1061 void BufferView::workAreaResize(int width, int height)
1063 // Update from work area
1067 // The complete text metrics will be redone.
1068 text_metrics_.clear();
1075 InsetBase const * BufferView::getCoveringInset(LyXText const & text, int x, int y)
1077 pit_type pit = text.getPitNearY(*this, y);
1078 BOOST_ASSERT(pit != -1);
1079 Paragraph const & par = text.getPar(pit);
1081 LYXERR(Debug::DEBUG)
1082 << BOOST_CURRENT_FUNCTION
1087 InsetList::const_iterator iit = par.insetlist.begin();
1088 InsetList::const_iterator iend = par.insetlist.end();
1089 for (; iit != iend; ++iit) {
1090 InsetBase * const inset = iit->inset;
1091 if (inset->covers(*this, x, y)) {
1092 if (!inset->descendable())
1093 // No need to go further down if the inset is not
1097 size_t cell_number = inset->nargs();
1098 // Check all the inner cell.
1099 for (size_t i = 0; i != cell_number; ++i) {
1100 LyXText const * inner_text = inset->getText(i);
1103 InsetBase const * inset_deeper =
1104 getCoveringInset(*inner_text, x, y);
1106 return inset_deeper;
1110 LYXERR(Debug::DEBUG)
1111 << BOOST_CURRENT_FUNCTION
1112 << ": Hit inset: " << inset << endl;
1116 LYXERR(Debug::DEBUG)
1117 << BOOST_CURRENT_FUNCTION
1118 << ": No inset hit. " << endl;
1123 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1125 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1127 // This is only called for mouse related events including
1128 // LFUN_FILE_OPEN generated by drag-and-drop.
1129 FuncRequest cmd = cmd0;
1131 // E.g. Qt mouse press when no buffer
1136 cur.push(buffer_->inset());
1137 cur.selection() = cursor_.selection();
1139 // Either the inset under the cursor or the
1140 // surrounding LyXText will handle this event.
1142 // make sure we stay within the screen...
1143 cmd.y = min(max(cmd.y, -1), height_);
1145 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1147 // Get inset under mouse, if there is one.
1148 InsetBase const * covering_inset =
1149 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1150 if (covering_inset == last_inset_)
1151 // Same inset, no need to do anything...
1154 bool need_redraw = false;
1155 // const_cast because of setMouseHover().
1156 InsetBase * inset = const_cast<InsetBase *>(covering_inset);
1158 // Remove the hint on the last hovered inset (if any).
1159 need_redraw |= last_inset_->setMouseHover(false);
1161 // Highlighted the newly hovered inset (if any).
1162 need_redraw |= inset->setMouseHover(true);
1163 last_inset_ = inset;
1165 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1166 // not expose the button for redraw. We adjust here the metrics dimension
1167 // to enable a full redraw.
1168 // FIXME: It is possible to redraw only the area around the button!
1170 && metrics_info_.update_strategy == SingleParUpdate) {
1171 // FIXME: It should be possible to redraw only the area around
1172 // the button by doing this:
1174 //metrics_info_.singlepar = false;
1175 //metrics_info_.y1 = ymin of button;
1176 //metrics_info_.y2 = ymax of button;
1178 // Unfortunately, rowpainter.C:paintText() does not distinguish
1179 // between background updates and text updates. So we use the hammer
1180 // solution for now. We could also avoid the updateMetrics() below
1181 // by using the first and last pit of the CoordCache. Have a look
1182 // at LyXText::getPitNearY() to see what I mean.
1184 //metrics_info_.pit1 = first pit of CoordCache;
1185 //metrics_info_.pit2 = last pit of CoordCache;
1186 //metrics_info_.singlepar = false;
1187 //metrics_info_.y1 = 0;
1188 //metrics_info_.y2 = height_;
1190 updateMetrics(false);
1193 // This event (moving without mouse click) is not passed further.
1194 // This should be changed if it is further utilized.
1198 // Build temporary cursor.
1199 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1201 // Put anchor at the same position.
1204 // Try to dispatch to an non-editable inset near this position
1205 // via the temp cursor. If the inset wishes to change the real
1206 // cursor it has to do so explicitly by using
1207 // cur.bv().cursor() = cur; (or similar)
1209 inset->dispatch(cur, cmd);
1212 // Now dispatch to the temporary cursor. If the real cursor should
1213 // be modified, the inset's dispatch has to do so explicitly.
1214 if (!cur.result().dispatched())
1217 // Redraw if requested and necessary.
1218 if (cur.result().dispatched() && cur.result().update())
1219 return update(cur.result().update());
1225 void BufferView::scroll(int /*lines*/)
1230 // LyXText const * t = &buffer_->text();
1231 // int const line_height = defaultRowHeight();
1233 // // The new absolute coordinate
1234 // int new_top_y = top_y() + lines * line_height;
1236 // // Restrict to a valid value
1237 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1238 // new_top_y = std::max(0, new_top_y);
1240 // scrollDocView(new_top_y);
1245 void BufferView::setCursorFromRow(int row)
1250 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1253 buffer_->text().setCursor(cursor_, 0, 0);
1255 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1259 void BufferView::gotoLabel(docstring const & label)
1261 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1262 vector<docstring> labels;
1263 it->getLabelList(*buffer_, labels);
1264 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1273 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1275 return const_cast<BufferView *>(this)->textMetrics(t);
1279 TextMetrics & BufferView::textMetrics(LyXText const * t)
1281 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1282 if (tmc_it == text_metrics_.end()) {
1283 tmc_it = text_metrics_.insert(
1284 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1286 return tmc_it->second;
1290 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1293 return textMetrics(t).parMetrics(pit);
1297 int BufferView::workHeight() const
1303 void BufferView::setCursor(DocIterator const & dit)
1305 size_t const n = dit.depth();
1306 for (size_t i = 0; i < n; ++i)
1307 dit[i].inset().edit(cursor_, true);
1309 cursor_.setCursor(dit);
1310 cursor_.selection() = false;
1314 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1316 // Would be wrong to delete anything if we have a selection.
1317 if (cur.selection())
1320 bool need_anchor_change = false;
1321 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1322 need_anchor_change);
1324 if (need_anchor_change)
1330 updateLabels(*buffer_);
1332 updateMetrics(false);
1338 bool BufferView::mouseSetCursor(LCursor & cur)
1340 BOOST_ASSERT(&cur.bv() == this);
1342 // Has the cursor just left the inset?
1343 bool badcursor = false;
1344 if (&cursor_.inset() != &cur.inset())
1345 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1347 // do the dEPM magic if needed
1348 // FIXME: move this to InsetText::notifyCursorLeaves?
1349 bool update = false;
1350 if (!badcursor && cursor_.inTexted())
1351 checkDepm(cur, cursor_);
1353 // if the cursor was in an empty script inset and the new
1354 // position is in the nucleus of the inset, notifyCursorLeaves
1355 // will kill the script inset itself. So we check all the
1356 // elements of the cursor to make sure that they are correct.
1357 // For an example, see bug 2933:
1358 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1359 // The code below could maybe be moved to a DocIterator method.
1360 //lyxerr << "cur before " << cur <<std::endl;
1361 DocIterator dit(cur.inset());
1362 dit.push_back(cur.bottom());
1364 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1365 dit.push_back(cur[i]);
1368 //lyxerr << "5 cur after" << dit <<std::endl;
1370 cursor_.setCursor(dit);
1371 cursor_.clearSelection();
1377 void BufferView::putSelectionAt(DocIterator const & cur,
1378 int length, bool backwards)
1380 cursor_.clearSelection();
1386 cursor_.pos() += length;
1387 cursor_.setSelection(cursor_, -length);
1389 cursor_.setSelection(cursor_, length);
1390 cap::saveSelection(cursor_);
1395 LCursor & BufferView::cursor()
1401 LCursor const & BufferView::cursor() const
1407 pit_type BufferView::anchor_ref() const
1413 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1415 return metrics_info_;
1419 // FIXME: We should split-up updateMetrics() for the singlepar case.
1420 void BufferView::updateMetrics(bool singlepar)
1422 LyXText & buftext = buffer_->text();
1423 TextMetrics & tm = textMetrics(&buftext);
1424 pit_type size = int(buftext.paragraphs().size());
1426 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1427 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1431 // If the paragraph metrics has changed, we can not
1432 // use the singlepar optimisation.
1434 // In Single Paragraph mode, rebreak only
1435 // the (main text, not inset!) paragraph containing the cursor.
1436 // (if this paragraph contains insets etc., rebreaking will
1437 // recursively descend)
1438 && tm.redoParagraph(cursor_.bottom().pit()))
1441 pit_type const pit = anchor_ref_;
1444 size_t const npit = buftext.paragraphs().size();
1446 // Rebreak anchor paragraph.
1448 tm.redoParagraph(pit);
1450 // Clear out the position cache in case of full screen redraw.
1452 coord_cache_.clear();
1454 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1456 // Redo paragraphs above anchor if necessary.
1458 while (y1 > 0 && pit1 > 0) {
1459 y1 -= tm.parMetrics(pit1).ascent();
1462 tm.redoParagraph(pit1);
1463 y1 -= tm.parMetrics(pit1).descent();
1467 // Take care of ascent of first line
1468 y1 -= tm.parMetrics(pit1).ascent();
1470 // Normalize anchor for next time
1474 // Grey at the beginning is ugly
1475 if (pit1 == 0 && y1 > 0) {
1481 // Redo paragraphs below the anchor if necessary.
1483 while (y2 < height_ && pit2 < int(npit) - 1) {
1484 y2 += tm.parMetrics(pit2).descent();
1487 tm.redoParagraph(pit2);
1488 y2 += tm.parMetrics(pit2).ascent();
1491 // Take care of descent of last line
1492 y2 += tm.parMetrics(pit2).descent();
1494 // The coordinates of all these paragraphs are correct, cache them
1496 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1497 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1498 ParagraphMetrics const & pm = tm.parMetrics(pit);
1500 parPos[pit] = Point(0, y);
1501 if (singlepar && pit == cursor_.bottom().pit()) {
1502 // In Single Paragraph mode, collect here the
1503 // y1 and y2 of the (one) paragraph the cursor is in
1504 y1 = y - pm.ascent();
1505 y2 = y + pm.descent();
1511 // collect cursor paragraph iter bounds
1512 pit1 = cursor_.bottom().pit();
1513 pit2 = cursor_.bottom().pit();
1516 LYXERR(Debug::DEBUG)
1517 << BOOST_CURRENT_FUNCTION
1520 << " pit1: " << pit1
1521 << " pit2: " << pit2
1522 << " npit: " << npit
1523 << " singlepar: " << singlepar
1527 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1528 singlepar? SingleParUpdate: FullScreenUpdate, size);
1530 if (lyxerr.debugging(Debug::WORKAREA)) {
1531 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1532 coord_cache_.dump();
1537 void BufferView::menuInsertLyXFile(string const & filenm)
1539 BOOST_ASSERT(cursor_.inTexted());
1540 string filename = filenm;
1542 if (filename.empty()) {
1543 // Launch a file browser
1545 string initpath = lyxrc.document_path;
1548 string const trypath = buffer_->filePath();
1549 // If directory is writeable, use this as default.
1550 if (isDirWriteable(FileName(trypath)))
1555 FileDialog fileDlg(_("Select LyX document to insert"),
1557 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1558 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1560 FileDialog::Result result =
1561 fileDlg.open(from_utf8(initpath),
1562 FileFilterList(_("LyX Documents (*.lyx)")),
1565 if (result.first == FileDialog::Later)
1569 filename = to_utf8(result.second);
1571 // check selected filename
1572 if (filename.empty()) {
1573 // emit message signal.
1574 message(_("Canceled."));
1579 // Get absolute path of file and add ".lyx"
1580 // to the filename if necessary
1581 filename = fileSearch(string(), filename, "lyx").absFilename();
1583 docstring const disp_fn = makeDisplayPath(filename);
1584 // emit message signal.
1585 message(bformat(_("Inserting document %1$s..."), disp_fn));
1588 Buffer buf("", false);
1589 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1590 ErrorList & el = buffer_->errorList("Parse");
1591 // Copy the inserted document error list into the current buffer one.
1592 el = buf.errorList("Parse");
1593 recordUndo(cursor_);
1594 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1595 buf.params().textclass, el);
1596 res = _("Document %1$s inserted.");
1598 res = _("Could not insert document %1$s");
1600 // emit message signal.
1601 message(bformat(res, disp_fn));
1602 buffer_->errors("Parse");