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 "callback.h" // added for Dispatch functions
44 #include "TextClass.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(Cursor & cur, Inset::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 top_id or bottom_pit, bottom_pos has been changed, update bookmark
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
167 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
171 // current buffer is going to be switched-off, save cursor pos
172 // Ideally, the whole cursor stack should be saved, but session
173 // currently can only handle bottom (whole document) level pit and pos.
174 // That is to say, if a cursor is in a nested inset, it will be
175 // restore to the left of the top level inset.
176 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180 // If we're quitting lyx, don't bother updating stuff
186 //FIXME Fix for bug 3440 is here.
187 // If we are closing current buffer, switch to the first in
190 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191 << " No Buffer!" << endl;
192 // We are closing the buffer, use the first buffer as current
194 // if (last_buffer_) buffer_ = last_buffer_;
195 // also check that this is in theBufferList()?
196 buffer_ = theBufferList().first();
199 // last_buffer = buffer_;
200 // Set current buffer
205 cursor_ = Cursor(*this);
212 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().setCurrentFont(cursor_);
218 // Update the metrics now that we have a proper Cursor.
219 updateMetrics(false);
221 // FIXME: This code won't be needed once we switch to
222 // "one Buffer" / "one BufferView".
223 if (buffer_->getCursor().size() > 0 &&
224 buffer_->getAnchor().size() > 0)
226 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
227 cursor_.resetAnchor();
228 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
229 cursor_.setSelection();
230 // do not set selection to the new buffer because we
231 // only paste recent selection.
233 // Make sure that the restored cursor is not broken. This can happen for
234 // example if this Buffer has been modified by another view.
235 cursor_.fixIfBroken();
238 // Update the metrics if the cursor new position was off screen.
239 updateMetrics(false);
242 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
243 graphics::Previews::get().generateBufferPreviews(*buffer_);
247 void BufferView::resize()
252 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
254 updateMetrics(false);
258 bool BufferView::fitCursor()
260 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
261 frontend::FontMetrics const & fm =
262 theFontMetrics(cursor_.getFont());
263 int const asc = fm.maxAscent();
264 int const des = fm.maxDescent();
265 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
266 if (p.y_ - asc >= 0 && p.y_ + des < height_)
274 bool BufferView::multiParSel()
276 if (!cursor_.selection())
278 bool ret = multiparsel_cache_;
279 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
280 // Either this, or previous selection spans paragraphs
281 return ret || multiparsel_cache_;
285 bool BufferView::update(Update::flags flags)
287 // last_inset_ points to the last visited inset. This pointer may become
288 // invalid because of keyboard editing. Since all such operations
289 // causes screen update(), I reset last_inset_ to avoid such a problem.
291 // This is close to a hot-path.
293 << BOOST_CURRENT_FUNCTION
294 << "[fitcursor = " << (flags & Update::FitCursor)
295 << ", forceupdate = " << (flags & Update::Force)
296 << ", singlepar = " << (flags & Update::SinglePar)
297 << "] buffer: " << buffer_ << endl;
299 // Check needed to survive LyX startup
303 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
305 // Update macro store
306 if (!(cursor().inMathed() && cursor().inMacroMode()))
307 buffer_->buildMacros();
309 // Now do the first drawing step if needed. This consists on updating
310 // the CoordCache in updateMetrics().
311 // The second drawing step is done in WorkArea::redraw() if needed.
313 // Case when no explicit update is requested.
315 // no need to redraw anything.
316 metrics_info_.update_strategy = NoScreenUpdate;
320 if (flags == Update::Decoration) {
321 metrics_info_.update_strategy = DecorationUpdate;
325 if (flags == Update::FitCursor
326 || flags == (Update::Decoration | Update::FitCursor)) {
327 bool const fit_cursor = fitCursor();
328 // tell the frontend to update the screen if needed.
330 updateMetrics(false);
333 if (flags & Update::Decoration) {
334 metrics_info_.update_strategy = DecorationUpdate;
337 // no screen update is needed.
338 metrics_info_.update_strategy = NoScreenUpdate;
342 bool full_metrics = flags & Update::Force;
343 if (flags & Update::MultiParSel)
344 full_metrics |= multiParSel();
346 bool const single_par = !full_metrics;
347 updateMetrics(single_par);
349 if (flags & Update::FitCursor && fitCursor())
350 updateMetrics(false);
352 // tell the frontend to update the screen.
357 void BufferView::updateScrollbar()
360 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
361 << " no text in updateScrollbar" << endl;
362 scrollbarParameters_.reset();
366 Text & t = buffer_->text();
367 TextMetrics & tm = text_metrics_[&t];
369 int const parsize = int(t.paragraphs().size() - 1);
370 if (anchor_ref_ > parsize) {
371 anchor_ref_ = parsize;
376 << BOOST_CURRENT_FUNCTION
377 << " Updating scrollbar: height: " << t.paragraphs().size()
378 << " curr par: " << cursor_.bottom().pit()
379 << " default height " << defaultRowHeight() << endl;
381 // It would be better to fix the scrollbar to understand
382 // values in [0..1] and divide everything by wh
384 // estimated average paragraph height:
388 int h = tm.parMetrics(anchor_ref_).height();
390 // Normalize anchor/offset (MV):
391 while (offset_ref_ > h && anchor_ref_ < parsize) {
394 h = tm.parMetrics(anchor_ref_).height();
396 // Look at paragraph heights on-screen
399 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
402 int const h2 = tm.parMetrics(pit).height();
408 int const hav = sumh / nh;
409 // More realistic average paragraph height
414 scrollbarParameters_.height = (parsize + 1) * wh_;
415 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
416 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
420 ScrollbarParameters const & BufferView::scrollbarParameters() const
422 return scrollbarParameters_;
426 void BufferView::scrollDocView(int value)
428 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
429 << "[ value = " << value << "]" << endl;
434 Text & t = buffer_->text();
435 TextMetrics & tm = text_metrics_[&t];
437 float const bar = value / float(wh_ * t.paragraphs().size());
439 anchor_ref_ = int(bar * t.paragraphs().size());
440 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
441 anchor_ref_ = int(t.paragraphs().size()) - 1;
443 tm.redoParagraph(anchor_ref_);
444 int const h = tm.parMetrics(anchor_ref_).height();
445 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
446 updateMetrics(false);
450 void BufferView::setCursorFromScrollbar()
455 Text & t = buffer_->text();
457 int const height = 2 * defaultRowHeight();
458 int const first = height;
459 int const last = height_ - height;
460 Cursor & cur = cursor_;
462 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
465 case bv_funcs::CUR_ABOVE:
466 // We reset the cursor because bv_funcs::status() does not
467 // work when the cursor is within mathed.
468 cur.reset(buffer_->inset());
469 t.setCursorFromCoordinates(cur, 0, first);
470 cur.clearSelection();
472 case bv_funcs::CUR_BELOW:
473 // We reset the cursor because bv_funcs::status() does not
474 // work when the cursor is within mathed.
475 cur.reset(buffer_->inset());
476 t.setCursorFromCoordinates(cur, 0, last);
477 cur.clearSelection();
479 case bv_funcs::CUR_INSIDE:
480 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
481 int const newy = min(last, max(y, first));
483 cur.reset(buffer_->inset());
484 t.setCursorFromCoordinates(cur, 0, newy);
490 Change const BufferView::getCurrentChange() const
492 if (!cursor_.selection())
493 return Change(Change::UNCHANGED);
495 DocIterator dit = cursor_.selectionBegin();
496 return dit.paragraph().lookupChange(dit.pos());
500 void BufferView::saveBookmark(unsigned int idx)
502 // tenatively save bookmark, id and pos will be used to
503 // acturately locate a bookmark in a 'live' lyx session.
504 // pit and pos will be updated with bottom level pit/pos
506 LyX::ref().session().bookmarks().save(
507 FileName(buffer_->fileName()),
508 cursor_.bottom().pit(),
509 cursor_.bottom().pos(),
510 cursor_.paragraph().id(),
515 // emit message signal.
516 message(_("Save bookmark"));
520 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
521 int top_id, pos_type top_pos)
523 cursor_.clearSelection();
525 // if a valid par_id is given, try it first
526 // This is the case for a 'live' bookmark when unique paragraph ID
527 // is used to track bookmarks.
529 ParIterator par = buffer_->getParFromID(top_id);
530 if (par != buffer_->par_iterator_end()) {
531 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
532 // Some slices of the iterator may not be
533 // reachable (e.g. closed collapsable inset)
534 // so the dociterator may need to be
535 // shortened. Otherwise, setCursor may crash
536 // lyx when the cursor can not be set to these
538 size_t const n = dit.depth();
539 for (size_t i = 0; i < n; ++i)
540 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
545 // Note: return bottom (document) level pit.
546 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
549 // if top_id == 0, or searching through top_id failed
550 // This is the case for a 'restored' bookmark when only bottom
551 // (document level) pit was saved. Because of this, bookmark
552 // restoration is inaccurate. If a bookmark was within an inset,
553 // it will be restored to the left of the outmost inset that contains
555 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
556 DocIterator it = doc_iterator_begin(buffer_->inset());
557 it.pit() = bottom_pit;
558 it.pos() = min(bottom_pos, it.paragraph().size());
560 return boost::make_tuple(it.pit(), it.pos(),
561 it.paragraph().id());
564 return boost::make_tuple(pit_type(0), pos_type(0), 0);
568 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
570 if (lyxrc.rtl_support) {
571 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
572 if (intl_->keymap == Intl::PRIMARY)
575 if (intl_->keymap == Intl::SECONDARY)
580 intl_->getTransManager().translateAndInsert(c, t, cur);
584 int BufferView::workWidth() const
590 void BufferView::center()
592 CursorSlice & bot = cursor_.bottom();
593 TextMetrics & tm = text_metrics_[bot.text()];
594 pit_type const pit = bot.pit();
595 tm.redoParagraph(pit);
596 ParagraphMetrics const & pm = tm.parMetrics(pit);
598 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
599 + pm.ascent() - height_ / 2;
603 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
607 Cursor & cur = cursor_;
609 switch (cmd.action) {
612 flag.enabled(!buffer_->undostack().empty());
615 flag.enabled(!buffer_->redostack().empty());
617 case LFUN_FILE_INSERT:
618 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
619 case LFUN_FILE_INSERT_PLAINTEXT:
620 case LFUN_BOOKMARK_SAVE:
621 // FIXME: Actually, these LFUNS should be moved to Text
622 flag.enabled(cur.inTexted());
624 case LFUN_FONT_STATE:
625 case LFUN_LABEL_INSERT:
626 case LFUN_PARAGRAPH_GOTO:
627 // FIXME handle non-trivially
628 case LFUN_OUTLINE_UP:
629 case LFUN_OUTLINE_DOWN:
630 case LFUN_OUTLINE_IN:
631 case LFUN_OUTLINE_OUT:
633 case LFUN_REFERENCE_NEXT:
635 case LFUN_WORD_REPLACE:
638 case LFUN_MARK_TOGGLE:
639 case LFUN_SCREEN_RECENTER:
640 case LFUN_BIBTEX_DATABASE_ADD:
641 case LFUN_BIBTEX_DATABASE_DEL:
642 case LFUN_WORDS_COUNT:
643 case LFUN_NEXT_INSET_TOGGLE:
647 case LFUN_LABEL_GOTO: {
648 flag.enabled(!cmd.argument().empty()
649 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
653 case LFUN_CHANGES_TRACK:
655 flag.setOnOff(buffer_->params().trackChanges);
658 case LFUN_CHANGES_OUTPUT:
659 flag.enabled(buffer_);
660 flag.setOnOff(buffer_->params().outputChanges);
663 case LFUN_CHANGES_MERGE:
664 case LFUN_CHANGE_NEXT:
665 case LFUN_ALL_CHANGES_ACCEPT:
666 case LFUN_ALL_CHANGES_REJECT:
667 // TODO: context-sensitive enabling of LFUNs
668 // In principle, these command should only be enabled if there
669 // is a change in the document. However, without proper
670 // optimizations, this will inevitably result in poor performance.
671 flag.enabled(buffer_);
674 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
675 flag.setOnOff(buffer_->params().compressed);
687 Update::flags BufferView::dispatch(FuncRequest const & cmd)
689 //lyxerr << BOOST_CURRENT_FUNCTION
690 // << [ cmd = " << cmd << "]" << endl;
692 // Make sure that the cached BufferView is correct.
693 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
694 << " action[" << cmd.action << ']'
695 << " arg[" << to_utf8(cmd.argument()) << ']'
696 << " x[" << cmd.x << ']'
697 << " y[" << cmd.y << ']'
698 << " button[" << cmd.button() << ']'
701 // FIXME: this should not be possible.
705 Cursor & cur = cursor_;
706 // Default Update flags.
707 Update::flags updateFlags = Update::Force | Update::FitCursor;
709 switch (cmd.action) {
712 cur.message(_("Undo"));
713 cur.clearSelection();
714 if (!textUndo(*this)) {
715 cur.message(_("No further undo information"));
716 updateFlags = Update::None;
721 cur.message(_("Redo"));
722 cur.clearSelection();
723 if (!textRedo(*this)) {
724 cur.message(_("No further redo information"));
725 updateFlags = Update::None;
729 case LFUN_FILE_INSERT:
731 menuInsertLyXFile(to_utf8(cmd.argument()));
734 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
736 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
739 case LFUN_FILE_INSERT_PLAINTEXT:
741 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
744 case LFUN_FONT_STATE:
745 cur.message(cur.currentState());
748 case LFUN_BOOKMARK_SAVE:
749 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
752 case LFUN_LABEL_GOTO: {
753 docstring label = cmd.argument();
756 getInsetByCode<InsetRef>(cursor_,
759 label = inset->getParam("reference");
760 // persistent=false: use temp_bookmark
770 case LFUN_PARAGRAPH_GOTO: {
771 int const id = convert<int>(to_utf8(cmd.argument()));
773 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
774 ParIterator par = b->getParFromID(id);
775 if (par == b->par_iterator_end()) {
777 << "No matching paragraph found! ["
778 << id << "]." << endl;
781 << "Paragraph " << par->id()
782 << " found in buffer `"
783 << b->fileName() << "'." << endl;
787 setCursor(makeDocIterator(par, 0));
789 // Switch to other buffer view and resend cmd
790 theLyXFunc().dispatch(FuncRequest(
791 LFUN_BUFFER_SWITCH, b->fileName()));
792 theLyXFunc().dispatch(cmd);
793 updateFlags = Update::None;
802 case LFUN_OUTLINE_UP:
803 toc::outline(toc::Up, cursor_);
804 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
805 updateLabels(*buffer_);
807 case LFUN_OUTLINE_DOWN:
808 toc::outline(toc::Down, cursor_);
809 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
810 updateLabels(*buffer_);
812 case LFUN_OUTLINE_IN:
813 toc::outline(toc::In, cursor_);
814 updateLabels(*buffer_);
816 case LFUN_OUTLINE_OUT:
817 toc::outline(toc::Out, cursor_);
818 updateLabels(*buffer_);
822 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
825 case LFUN_REFERENCE_NEXT: {
826 vector<Inset_code> tmp;
827 tmp.push_back(Inset::LABEL_CODE);
828 tmp.push_back(Inset::REF_CODE);
829 bv_funcs::gotoInset(this, tmp, true);
833 case LFUN_CHANGES_TRACK:
834 buffer_->params().trackChanges = !buffer_->params().trackChanges;
837 case LFUN_CHANGES_OUTPUT:
838 buffer_->params().outputChanges = !buffer_->params().outputChanges;
839 if (buffer_->params().outputChanges) {
840 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
841 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
842 LaTeXFeatures::isAvailable("xcolor");
844 if (!dvipost && !xcolorsoul) {
845 Alert::warning(_("Changes not shown in LaTeX output"),
846 _("Changes will not be highlighted in LaTeX output, "
847 "because neither dvipost nor xcolor/soul are installed.\n"
848 "Please install these packages or redefine "
849 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
850 } else if (!xcolorsoul) {
851 Alert::warning(_("Changes not shown in LaTeX output"),
852 _("Changes will not be highlighted in LaTeX output "
853 "when using pdflatex, because xcolor and soul are not installed.\n"
854 "Please install both packages or redefine "
855 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
860 case LFUN_CHANGE_NEXT:
861 findNextChange(this);
864 case LFUN_CHANGES_MERGE:
865 if (findNextChange(this))
866 showDialog("changes");
869 case LFUN_ALL_CHANGES_ACCEPT:
870 // select complete document
871 cursor_.reset(buffer_->inset());
872 cursor_.selHandle(true);
873 buffer_->text().cursorBottom(cursor_);
874 // accept everything in a single step to support atomic undo
875 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
878 case LFUN_ALL_CHANGES_REJECT:
879 // select complete document
880 cursor_.reset(buffer_->inset());
881 cursor_.selHandle(true);
882 buffer_->text().cursorBottom(cursor_);
883 // reject everything in a single step to support atomic undo
884 // Note: reject does not work recursively; the user may have to repeat the operation
885 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
892 case LFUN_WORD_REPLACE: {
893 bool has_deleted = false;
894 if (cur.selection()) {
895 DocIterator beg = cur.selectionBegin();
896 DocIterator end = cur.selectionEnd();
897 if (beg.pit() == end.pit()) {
898 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
899 if (cur.paragraph().isDeleted(p))
904 replace(this, cmd, has_deleted);
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 Cursor tmpcur = cursor_;
939 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
940 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
943 if (inset->addDatabase(to_utf8(cmd.argument())))
944 buffer_->updateBibfilesCache();
949 case LFUN_BIBTEX_DATABASE_DEL: {
950 Cursor tmpcur = cursor_;
951 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
952 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
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 Inset * inset = cur.nextInset();
1002 if (inset && inset->isActive()) {
1003 Cursor 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 Cursor & 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 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1085 pit_type pit = text.getPitNearY(*this, y);
1086 BOOST_ASSERT(pit != -1);
1087 Paragraph const & par = text.getPar(pit);
1089 LYXERR(Debug::DEBUG)
1090 << BOOST_CURRENT_FUNCTION
1095 InsetList::const_iterator iit = par.insetlist.begin();
1096 InsetList::const_iterator iend = par.insetlist.end();
1097 for (; iit != iend; ++iit) {
1098 Inset * const inset = iit->inset;
1099 if (inset->covers(*this, x, y)) {
1100 if (!inset->descendable())
1101 // No need to go further down if the inset is not
1105 size_t cell_number = inset->nargs();
1106 // Check all the inner cell.
1107 for (size_t i = 0; i != cell_number; ++i) {
1108 Text const * inner_text = inset->getText(i);
1111 Inset const * inset_deeper =
1112 getCoveringInset(*inner_text, x, y);
1114 return inset_deeper;
1118 LYXERR(Debug::DEBUG)
1119 << BOOST_CURRENT_FUNCTION
1120 << ": Hit inset: " << inset << endl;
1124 LYXERR(Debug::DEBUG)
1125 << BOOST_CURRENT_FUNCTION
1126 << ": No inset hit. " << endl;
1131 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1133 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1135 // This is only called for mouse related events including
1136 // LFUN_FILE_OPEN generated by drag-and-drop.
1137 FuncRequest cmd = cmd0;
1139 // E.g. Qt mouse press when no buffer
1144 cur.push(buffer_->inset());
1145 cur.selection() = cursor_.selection();
1147 // Either the inset under the cursor or the
1148 // surrounding Text will handle this event.
1150 // make sure we stay within the screen...
1151 cmd.y = min(max(cmd.y, -1), height_);
1153 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1155 // Get inset under mouse, if there is one.
1156 Inset const * covering_inset =
1157 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1158 if (covering_inset == last_inset_)
1159 // Same inset, no need to do anything...
1162 bool need_redraw = false;
1163 // const_cast because of setMouseHover().
1164 Inset * inset = const_cast<Inset *>(covering_inset);
1166 // Remove the hint on the last hovered inset (if any).
1167 need_redraw |= last_inset_->setMouseHover(false);
1169 // Highlighted the newly hovered inset (if any).
1170 need_redraw |= inset->setMouseHover(true);
1171 last_inset_ = inset;
1173 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1174 // not expose the button for redraw. We adjust here the metrics dimension
1175 // to enable a full redraw.
1176 // FIXME: It is possible to redraw only the area around the button!
1178 && metrics_info_.update_strategy == SingleParUpdate) {
1179 // FIXME: It should be possible to redraw only the area around
1180 // the button by doing this:
1182 //metrics_info_.singlepar = false;
1183 //metrics_info_.y1 = ymin of button;
1184 //metrics_info_.y2 = ymax of button;
1186 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1187 // between background updates and text updates. So we use the hammer
1188 // solution for now. We could also avoid the updateMetrics() below
1189 // by using the first and last pit of the CoordCache. Have a look
1190 // at Text::getPitNearY() to see what I mean.
1192 //metrics_info_.pit1 = first pit of CoordCache;
1193 //metrics_info_.pit2 = last pit of CoordCache;
1194 //metrics_info_.singlepar = false;
1195 //metrics_info_.y1 = 0;
1196 //metrics_info_.y2 = height_;
1198 updateMetrics(false);
1201 // This event (moving without mouse click) is not passed further.
1202 // This should be changed if it is further utilized.
1206 // Build temporary cursor.
1207 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1209 // Put anchor at the same position.
1212 // Try to dispatch to an non-editable inset near this position
1213 // via the temp cursor. If the inset wishes to change the real
1214 // cursor it has to do so explicitly by using
1215 // cur.bv().cursor() = cur; (or similar)
1217 inset->dispatch(cur, cmd);
1220 // Now dispatch to the temporary cursor. If the real cursor should
1221 // be modified, the inset's dispatch has to do so explicitly.
1222 if (!cur.result().dispatched())
1225 // Redraw if requested and necessary.
1226 if (cur.result().dispatched() && cur.result().update())
1227 return update(cur.result().update());
1233 void BufferView::scroll(int /*lines*/)
1238 // Text const * t = &buffer_->text();
1239 // int const line_height = defaultRowHeight();
1241 // // The new absolute coordinate
1242 // int new_top_y = top_y() + lines * line_height;
1244 // // Restrict to a valid value
1245 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1246 // new_top_y = std::max(0, new_top_y);
1248 // scrollDocView(new_top_y);
1253 void BufferView::setCursorFromRow(int row)
1258 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1261 buffer_->text().setCursor(cursor_, 0, 0);
1263 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1267 void BufferView::gotoLabel(docstring const & label)
1269 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1270 vector<docstring> labels;
1271 it->getLabelList(*buffer_, labels);
1272 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1281 TextMetrics const & BufferView::textMetrics(Text const * t) const
1283 return const_cast<BufferView *>(this)->textMetrics(t);
1287 TextMetrics & BufferView::textMetrics(Text const * t)
1289 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1290 if (tmc_it == text_metrics_.end()) {
1291 tmc_it = text_metrics_.insert(
1292 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1294 return tmc_it->second;
1298 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1301 return textMetrics(t).parMetrics(pit);
1305 int BufferView::workHeight() const
1311 void BufferView::setCursor(DocIterator const & dit)
1313 size_t const n = dit.depth();
1314 for (size_t i = 0; i < n; ++i)
1315 dit[i].inset().edit(cursor_, true);
1317 cursor_.setCursor(dit);
1318 cursor_.selection() = false;
1322 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1324 // Would be wrong to delete anything if we have a selection.
1325 if (cur.selection())
1328 bool need_anchor_change = false;
1329 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1330 need_anchor_change);
1332 if (need_anchor_change)
1338 updateLabels(*buffer_);
1340 updateMetrics(false);
1346 bool BufferView::mouseSetCursor(Cursor & cur)
1348 BOOST_ASSERT(&cur.bv() == this);
1350 // Has the cursor just left the inset?
1351 bool badcursor = false;
1352 bool leftinset = (&cursor_.inset() != &cur.inset());
1354 badcursor = notifyCursorLeaves(cursor_, cur);
1356 // do the dEPM magic if needed
1357 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1358 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1359 // the leftinset bool would not be necessary (badcursor instead).
1360 bool update = leftinset;
1361 if (!badcursor && cursor_.inTexted())
1362 update |= checkDepm(cur, cursor_);
1364 // if the cursor was in an empty script inset and the new
1365 // position is in the nucleus of the inset, notifyCursorLeaves
1366 // will kill the script inset itself. So we check all the
1367 // elements of the cursor to make sure that they are correct.
1368 // For an example, see bug 2933:
1369 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1370 // The code below could maybe be moved to a DocIterator method.
1371 //lyxerr << "cur before " << cur <<std::endl;
1372 DocIterator dit(cur.inset());
1373 dit.push_back(cur.bottom());
1375 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1376 dit.push_back(cur[i]);
1379 //lyxerr << "5 cur after" << dit <<std::endl;
1381 cursor_.setCursor(dit);
1382 cursor_.boundary(cur.boundary());
1383 cursor_.clearSelection();
1389 void BufferView::putSelectionAt(DocIterator const & cur,
1390 int length, bool backwards)
1392 cursor_.clearSelection();
1398 cursor_.pos() += length;
1399 cursor_.setSelection(cursor_, -length);
1401 cursor_.setSelection(cursor_, length);
1402 cap::saveSelection(cursor_);
1407 Cursor & BufferView::cursor()
1413 Cursor const & BufferView::cursor() const
1419 pit_type BufferView::anchor_ref() const
1425 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1427 return metrics_info_;
1431 // FIXME: We should split-up updateMetrics() for the singlepar case.
1432 void BufferView::updateMetrics(bool singlepar)
1434 Text & buftext = buffer_->text();
1435 TextMetrics & tm = textMetrics(&buftext);
1436 pit_type size = int(buftext.paragraphs().size());
1438 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1439 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1444 // Clear out the position cache in case of full screen redraw,
1445 coord_cache_.clear();
1447 // Clear out paragraph metrics to avoid having invalid metrics
1448 // in the cache from paragraphs not relayouted below
1452 // If the paragraph metrics has changed, we can not
1453 // use the singlepar optimisation.
1455 // In Single Paragraph mode, rebreak only
1456 // the (main text, not inset!) paragraph containing the cursor.
1457 // (if this paragraph contains insets etc., rebreaking will
1458 // recursively descend)
1459 && tm.redoParagraph(cursor_.bottom().pit()))
1462 pit_type const pit = anchor_ref_;
1465 size_t const npit = buftext.paragraphs().size();
1467 // Rebreak anchor paragraph.
1469 tm.redoParagraph(pit);
1471 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1473 // Redo paragraphs above anchor if necessary.
1475 while (y1 > 0 && pit1 > 0) {
1476 y1 -= tm.parMetrics(pit1).ascent();
1479 tm.redoParagraph(pit1);
1480 y1 -= tm.parMetrics(pit1).descent();
1484 // Take care of ascent of first line
1485 y1 -= tm.parMetrics(pit1).ascent();
1487 // Normalize anchor for next time
1491 // Grey at the beginning is ugly
1492 if (pit1 == 0 && y1 > 0) {
1498 // Redo paragraphs below the anchor if necessary.
1500 while (y2 < height_ && pit2 < int(npit) - 1) {
1501 y2 += tm.parMetrics(pit2).descent();
1504 tm.redoParagraph(pit2);
1505 y2 += tm.parMetrics(pit2).ascent();
1508 // Take care of descent of last line
1509 y2 += tm.parMetrics(pit2).descent();
1511 // The coordinates of all these paragraphs are correct, cache them
1513 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1514 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1515 ParagraphMetrics const & pm = tm.parMetrics(pit);
1517 parPos[pit] = Point(0, y);
1518 if (singlepar && pit == cursor_.bottom().pit()) {
1519 // In Single Paragraph mode, collect here the
1520 // y1 and y2 of the (one) paragraph the cursor is in
1521 y1 = y - pm.ascent();
1522 y2 = y + pm.descent();
1528 // collect cursor paragraph iter bounds
1529 pit1 = cursor_.bottom().pit();
1530 pit2 = cursor_.bottom().pit();
1533 LYXERR(Debug::DEBUG)
1534 << BOOST_CURRENT_FUNCTION
1537 << " pit1: " << pit1
1538 << " pit2: " << pit2
1539 << " npit: " << npit
1540 << " singlepar: " << singlepar
1544 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1545 singlepar? SingleParUpdate: FullScreenUpdate, size);
1547 if (lyxerr.debugging(Debug::WORKAREA)) {
1548 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1549 coord_cache_.dump();
1554 void BufferView::menuInsertLyXFile(string const & filenm)
1556 BOOST_ASSERT(cursor_.inTexted());
1557 string filename = filenm;
1559 if (filename.empty()) {
1560 // Launch a file browser
1562 string initpath = lyxrc.document_path;
1565 string const trypath = buffer_->filePath();
1566 // If directory is writeable, use this as default.
1567 if (isDirWriteable(FileName(trypath)))
1572 FileDialog fileDlg(_("Select LyX document to insert"),
1574 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1575 make_pair(_("Examples|#E#e"),
1576 from_utf8(addPath(package().system_support().absFilename(),
1579 FileDialog::Result result =
1580 fileDlg.open(from_utf8(initpath),
1581 FileFilterList(_("LyX Documents (*.lyx)")),
1584 if (result.first == FileDialog::Later)
1588 filename = to_utf8(result.second);
1590 // check selected filename
1591 if (filename.empty()) {
1592 // emit message signal.
1593 message(_("Canceled."));
1598 // Get absolute path of file and add ".lyx"
1599 // to the filename if necessary
1600 filename = fileSearch(string(), filename, "lyx").absFilename();
1602 docstring const disp_fn = makeDisplayPath(filename);
1603 // emit message signal.
1604 message(bformat(_("Inserting document %1$s..."), disp_fn));
1607 Buffer buf("", false);
1608 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1609 ErrorList & el = buffer_->errorList("Parse");
1610 // Copy the inserted document error list into the current buffer one.
1611 el = buf.errorList("Parse");
1612 recordUndo(cursor_);
1613 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1614 buf.params().textclass, el);
1615 res = _("Document %1$s inserted.");
1617 res = _("Could not insert document %1$s");
1619 // emit message signal.
1620 message(bformat(res, disp_fn));
1621 buffer_->errors("Parse");