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:
637 case LFUN_MARK_TOGGLE:
638 case LFUN_SCREEN_RECENTER:
639 case LFUN_BIBTEX_DATABASE_ADD:
640 case LFUN_BIBTEX_DATABASE_DEL:
641 case LFUN_WORDS_COUNT:
642 case LFUN_NEXT_INSET_TOGGLE:
646 case LFUN_WORD_REPLACE:
647 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
650 case LFUN_LABEL_GOTO: {
651 flag.enabled(!cmd.argument().empty()
652 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
656 case LFUN_CHANGES_TRACK:
658 flag.setOnOff(buffer_->params().trackChanges);
661 case LFUN_CHANGES_OUTPUT:
662 flag.enabled(buffer_);
663 flag.setOnOff(buffer_->params().outputChanges);
666 case LFUN_CHANGES_MERGE:
667 case LFUN_CHANGE_NEXT:
668 case LFUN_ALL_CHANGES_ACCEPT:
669 case LFUN_ALL_CHANGES_REJECT:
670 // TODO: context-sensitive enabling of LFUNs
671 // In principle, these command should only be enabled if there
672 // is a change in the document. However, without proper
673 // optimizations, this will inevitably result in poor performance.
674 flag.enabled(buffer_);
677 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
678 flag.setOnOff(buffer_->params().compressed);
690 Update::flags BufferView::dispatch(FuncRequest const & cmd)
692 //lyxerr << BOOST_CURRENT_FUNCTION
693 // << [ cmd = " << cmd << "]" << endl;
695 // Make sure that the cached BufferView is correct.
696 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
697 << " action[" << cmd.action << ']'
698 << " arg[" << to_utf8(cmd.argument()) << ']'
699 << " x[" << cmd.x << ']'
700 << " y[" << cmd.y << ']'
701 << " button[" << cmd.button() << ']'
704 // FIXME: this should not be possible.
708 Cursor & cur = cursor_;
709 // Default Update flags.
710 Update::flags updateFlags = Update::Force | Update::FitCursor;
712 switch (cmd.action) {
715 cur.message(_("Undo"));
716 cur.clearSelection();
717 if (!textUndo(*this)) {
718 cur.message(_("No further undo information"));
719 updateFlags = Update::None;
724 cur.message(_("Redo"));
725 cur.clearSelection();
726 if (!textRedo(*this)) {
727 cur.message(_("No further redo information"));
728 updateFlags = Update::None;
732 case LFUN_FILE_INSERT:
734 menuInsertLyXFile(to_utf8(cmd.argument()));
737 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
739 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
742 case LFUN_FILE_INSERT_PLAINTEXT:
744 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
747 case LFUN_FONT_STATE:
748 cur.message(cur.currentState());
751 case LFUN_BOOKMARK_SAVE:
752 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
755 case LFUN_LABEL_GOTO: {
756 docstring label = cmd.argument();
759 getInsetByCode<InsetRef>(cursor_,
762 label = inset->getParam("reference");
763 // persistent=false: use temp_bookmark
773 case LFUN_PARAGRAPH_GOTO: {
774 int const id = convert<int>(to_utf8(cmd.argument()));
776 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
777 ParIterator par = b->getParFromID(id);
778 if (par == b->par_iterator_end()) {
780 << "No matching paragraph found! ["
781 << id << "]." << endl;
784 << "Paragraph " << par->id()
785 << " found in buffer `"
786 << b->fileName() << "'." << endl;
790 setCursor(makeDocIterator(par, 0));
792 // Switch to other buffer view and resend cmd
793 theLyXFunc().dispatch(FuncRequest(
794 LFUN_BUFFER_SWITCH, b->fileName()));
795 theLyXFunc().dispatch(cmd);
796 updateFlags = Update::None;
805 case LFUN_OUTLINE_UP:
806 toc::outline(toc::Up, cursor_);
807 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
808 updateLabels(*buffer_);
810 case LFUN_OUTLINE_DOWN:
811 toc::outline(toc::Down, cursor_);
812 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
813 updateLabels(*buffer_);
815 case LFUN_OUTLINE_IN:
816 toc::outline(toc::In, cursor_);
817 updateLabels(*buffer_);
819 case LFUN_OUTLINE_OUT:
820 toc::outline(toc::Out, cursor_);
821 updateLabels(*buffer_);
825 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
828 case LFUN_REFERENCE_NEXT: {
829 vector<Inset_code> tmp;
830 tmp.push_back(Inset::LABEL_CODE);
831 tmp.push_back(Inset::REF_CODE);
832 bv_funcs::gotoInset(this, tmp, true);
836 case LFUN_CHANGES_TRACK:
837 buffer_->params().trackChanges = !buffer_->params().trackChanges;
840 case LFUN_CHANGES_OUTPUT:
841 buffer_->params().outputChanges = !buffer_->params().outputChanges;
842 if (buffer_->params().outputChanges) {
843 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
844 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
845 LaTeXFeatures::isAvailable("xcolor");
847 if (!dvipost && !xcolorsoul) {
848 Alert::warning(_("Changes not shown in LaTeX output"),
849 _("Changes will not be highlighted in LaTeX output, "
850 "because neither dvipost nor xcolor/soul are installed.\n"
851 "Please install these packages or redefine "
852 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
853 } else if (!xcolorsoul) {
854 Alert::warning(_("Changes not shown in LaTeX output"),
855 _("Changes will not be highlighted in LaTeX output "
856 "when using pdflatex, because xcolor and soul are not installed.\n"
857 "Please install both packages or redefine "
858 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
863 case LFUN_CHANGE_NEXT:
864 findNextChange(this);
867 case LFUN_CHANGES_MERGE:
868 if (findNextChange(this))
869 showDialog("changes");
872 case LFUN_ALL_CHANGES_ACCEPT:
873 // select complete document
874 cursor_.reset(buffer_->inset());
875 cursor_.selHandle(true);
876 buffer_->text().cursorBottom(cursor_);
877 // accept everything in a single step to support atomic undo
878 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
881 case LFUN_ALL_CHANGES_REJECT:
882 // select complete document
883 cursor_.reset(buffer_->inset());
884 cursor_.selHandle(true);
885 buffer_->text().cursorBottom(cursor_);
886 // reject everything in a single step to support atomic undo
887 // Note: reject does not work recursively; the user may have to repeat the operation
888 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
895 case LFUN_WORD_REPLACE:
900 cur.clearSelection();
902 cur.message(from_utf8(N_("Mark off")));
906 cur.clearSelection();
909 cur.message(from_utf8(N_("Mark on")));
912 case LFUN_MARK_TOGGLE:
913 cur.clearSelection();
916 cur.message(from_utf8(N_("Mark removed")));
919 cur.message(from_utf8(N_("Mark set")));
924 case LFUN_SCREEN_RECENTER:
928 case LFUN_BIBTEX_DATABASE_ADD: {
929 Cursor tmpcur = cursor_;
930 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
931 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
934 if (inset->addDatabase(to_utf8(cmd.argument())))
935 buffer_->updateBibfilesCache();
940 case LFUN_BIBTEX_DATABASE_DEL: {
941 Cursor tmpcur = cursor_;
942 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
943 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
946 if (inset->delDatabase(to_utf8(cmd.argument())))
947 buffer_->updateBibfilesCache();
952 case LFUN_WORDS_COUNT: {
953 DocIterator from, to;
954 if (cur.selection()) {
955 from = cur.selectionBegin();
956 to = cur.selectionEnd();
958 from = doc_iterator_begin(buffer_->inset());
959 to = doc_iterator_end(buffer_->inset());
961 int const count = countWords(from, to);
965 message = bformat(_("%1$d words in selection."),
968 message = bformat(_("%1$d words in document."),
973 message = _("One word in selection.");
975 message = _("One word in document.");
978 Alert::information(_("Count words"), message);
982 case LFUN_BUFFER_TOGGLE_COMPRESSION:
983 // turn compression on/off
984 buffer_->params().compressed = !buffer_->params().compressed;
987 case LFUN_NEXT_INSET_TOGGLE: {
988 // this is the real function we want to invoke
989 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
990 // if there is an inset at cursor, see whether it
992 Inset * inset = cur.nextInset();
993 if (inset && inset->isActive()) {
995 tmpcur.pushLeft(*inset);
996 inset->dispatch(tmpcur, tmpcmd);
997 if (tmpcur.result().dispatched()) {
1001 // if it did not work, try the underlying inset.
1002 if (!cur.result().dispatched())
1003 cur.dispatch(tmpcmd);
1005 if (cur.result().dispatched())
1006 cur.clearSelection();
1012 updateFlags = Update::None;
1019 docstring const BufferView::requestSelection()
1024 Cursor & cur = cursor_;
1026 if (!cur.selection()) {
1027 xsel_cache_.set = false;
1031 if (!xsel_cache_.set ||
1032 cur.top() != xsel_cache_.cursor ||
1033 cur.anchor_.top() != xsel_cache_.anchor)
1035 xsel_cache_.cursor = cur.top();
1036 xsel_cache_.anchor = cur.anchor_.top();
1037 xsel_cache_.set = cur.selection();
1038 return cur.selectionAsString(false);
1044 void BufferView::clearSelection()
1047 cursor_.clearSelection();
1048 // Clear the selection buffer. Otherwise a subsequent
1049 // middle-mouse-button paste would use the selection buffer,
1050 // not the more current external selection.
1051 cap::clearSelection();
1052 xsel_cache_.set = false;
1053 // The buffer did not really change, but this causes the
1054 // redraw we need because we cleared the selection above.
1060 void BufferView::workAreaResize(int width, int height)
1062 // Update from work area
1066 // The complete text metrics will be redone.
1067 text_metrics_.clear();
1074 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1076 pit_type pit = text.getPitNearY(*this, y);
1077 BOOST_ASSERT(pit != -1);
1078 Paragraph const & par = text.getPar(pit);
1080 LYXERR(Debug::DEBUG)
1081 << BOOST_CURRENT_FUNCTION
1086 InsetList::const_iterator iit = par.insetlist.begin();
1087 InsetList::const_iterator iend = par.insetlist.end();
1088 for (; iit != iend; ++iit) {
1089 Inset * const inset = iit->inset;
1090 if (inset->covers(*this, x, y)) {
1091 if (!inset->descendable())
1092 // No need to go further down if the inset is not
1096 size_t cell_number = inset->nargs();
1097 // Check all the inner cell.
1098 for (size_t i = 0; i != cell_number; ++i) {
1099 Text const * inner_text = inset->getText(i);
1102 Inset const * inset_deeper =
1103 getCoveringInset(*inner_text, x, y);
1105 return inset_deeper;
1109 LYXERR(Debug::DEBUG)
1110 << BOOST_CURRENT_FUNCTION
1111 << ": Hit inset: " << inset << endl;
1115 LYXERR(Debug::DEBUG)
1116 << BOOST_CURRENT_FUNCTION
1117 << ": No inset hit. " << endl;
1122 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1124 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1126 // This is only called for mouse related events including
1127 // LFUN_FILE_OPEN generated by drag-and-drop.
1128 FuncRequest cmd = cmd0;
1130 // E.g. Qt mouse press when no buffer
1135 cur.push(buffer_->inset());
1136 cur.selection() = cursor_.selection();
1138 // Either the inset under the cursor or the
1139 // surrounding Text will handle this event.
1141 // make sure we stay within the screen...
1142 cmd.y = min(max(cmd.y, -1), height_);
1144 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1146 // Get inset under mouse, if there is one.
1147 Inset const * covering_inset =
1148 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1149 if (covering_inset == last_inset_)
1150 // Same inset, no need to do anything...
1153 bool need_redraw = false;
1154 // const_cast because of setMouseHover().
1155 Inset * inset = const_cast<Inset *>(covering_inset);
1157 // Remove the hint on the last hovered inset (if any).
1158 need_redraw |= last_inset_->setMouseHover(false);
1160 // Highlighted the newly hovered inset (if any).
1161 need_redraw |= inset->setMouseHover(true);
1162 last_inset_ = inset;
1164 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1165 // not expose the button for redraw. We adjust here the metrics dimension
1166 // to enable a full redraw.
1167 // FIXME: It is possible to redraw only the area around the button!
1169 && metrics_info_.update_strategy == SingleParUpdate) {
1170 // FIXME: It should be possible to redraw only the area around
1171 // the button by doing this:
1173 //metrics_info_.singlepar = false;
1174 //metrics_info_.y1 = ymin of button;
1175 //metrics_info_.y2 = ymax of button;
1177 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1178 // between background updates and text updates. So we use the hammer
1179 // solution for now. We could also avoid the updateMetrics() below
1180 // by using the first and last pit of the CoordCache. Have a look
1181 // at Text::getPitNearY() to see what I mean.
1183 //metrics_info_.pit1 = first pit of CoordCache;
1184 //metrics_info_.pit2 = last pit of CoordCache;
1185 //metrics_info_.singlepar = false;
1186 //metrics_info_.y1 = 0;
1187 //metrics_info_.y2 = height_;
1189 updateMetrics(false);
1192 // This event (moving without mouse click) is not passed further.
1193 // This should be changed if it is further utilized.
1197 // Build temporary cursor.
1198 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1200 // Put anchor at the same position.
1203 // Try to dispatch to an non-editable inset near this position
1204 // via the temp cursor. If the inset wishes to change the real
1205 // cursor it has to do so explicitly by using
1206 // cur.bv().cursor() = cur; (or similar)
1208 inset->dispatch(cur, cmd);
1211 // Now dispatch to the temporary cursor. If the real cursor should
1212 // be modified, the inset's dispatch has to do so explicitly.
1213 if (!cur.result().dispatched())
1216 // Redraw if requested and necessary.
1217 if (cur.result().dispatched() && cur.result().update())
1218 return update(cur.result().update());
1224 void BufferView::scroll(int /*lines*/)
1229 // Text const * t = &buffer_->text();
1230 // int const line_height = defaultRowHeight();
1232 // // The new absolute coordinate
1233 // int new_top_y = top_y() + lines * line_height;
1235 // // Restrict to a valid value
1236 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1237 // new_top_y = std::max(0, new_top_y);
1239 // scrollDocView(new_top_y);
1244 void BufferView::setCursorFromRow(int row)
1249 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1252 buffer_->text().setCursor(cursor_, 0, 0);
1254 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1258 void BufferView::gotoLabel(docstring const & label)
1260 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1261 vector<docstring> labels;
1262 it->getLabelList(*buffer_, labels);
1263 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1272 TextMetrics const & BufferView::textMetrics(Text const * t) const
1274 return const_cast<BufferView *>(this)->textMetrics(t);
1278 TextMetrics & BufferView::textMetrics(Text const * t)
1280 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1281 if (tmc_it == text_metrics_.end()) {
1282 tmc_it = text_metrics_.insert(
1283 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1285 return tmc_it->second;
1289 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1292 return textMetrics(t).parMetrics(pit);
1296 int BufferView::workHeight() const
1302 void BufferView::setCursor(DocIterator const & dit)
1304 size_t const n = dit.depth();
1305 for (size_t i = 0; i < n; ++i)
1306 dit[i].inset().edit(cursor_, true);
1308 cursor_.setCursor(dit);
1309 cursor_.selection() = false;
1313 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1315 // Would be wrong to delete anything if we have a selection.
1316 if (cur.selection())
1319 bool need_anchor_change = false;
1320 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1321 need_anchor_change);
1323 if (need_anchor_change)
1329 updateLabels(*buffer_);
1331 updateMetrics(false);
1337 bool BufferView::mouseSetCursor(Cursor & cur)
1339 BOOST_ASSERT(&cur.bv() == this);
1341 // Has the cursor just left the inset?
1342 bool badcursor = false;
1343 bool leftinset = (&cursor_.inset() != &cur.inset());
1345 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1347 // do the dEPM magic if needed
1348 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1349 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1350 // the leftinset bool would not be necessary (badcursor instead).
1351 bool update = leftinset;
1352 if (!badcursor && cursor_.inTexted())
1353 update |= checkDepm(cur, cursor_);
1355 // if the cursor was in an empty script inset and the new
1356 // position is in the nucleus of the inset, notifyCursorLeaves
1357 // will kill the script inset itself. So we check all the
1358 // elements of the cursor to make sure that they are correct.
1359 // For an example, see bug 2933:
1360 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1361 // The code below could maybe be moved to a DocIterator method.
1362 //lyxerr << "cur before " << cur <<std::endl;
1363 DocIterator dit(cur.inset());
1364 dit.push_back(cur.bottom());
1366 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1367 dit.push_back(cur[i]);
1370 //lyxerr << "5 cur after" << dit <<std::endl;
1372 cursor_.setCursor(dit);
1373 cursor_.boundary(cur.boundary());
1374 cursor_.clearSelection();
1380 void BufferView::putSelectionAt(DocIterator const & cur,
1381 int length, bool backwards)
1383 cursor_.clearSelection();
1389 cursor_.pos() += length;
1390 cursor_.setSelection(cursor_, -length);
1392 cursor_.setSelection(cursor_, length);
1393 cap::saveSelection(cursor_);
1398 Cursor & BufferView::cursor()
1404 Cursor const & BufferView::cursor() const
1410 pit_type BufferView::anchor_ref() const
1416 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1418 return metrics_info_;
1422 // FIXME: We should split-up updateMetrics() for the singlepar case.
1423 void BufferView::updateMetrics(bool singlepar)
1425 Text & buftext = buffer_->text();
1426 TextMetrics & tm = textMetrics(&buftext);
1427 pit_type size = int(buftext.paragraphs().size());
1429 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1430 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1434 // If the paragraph metrics has changed, we can not
1435 // use the singlepar optimisation.
1437 // In Single Paragraph mode, rebreak only
1438 // the (main text, not inset!) paragraph containing the cursor.
1439 // (if this paragraph contains insets etc., rebreaking will
1440 // recursively descend)
1441 && tm.redoParagraph(cursor_.bottom().pit()))
1444 pit_type const pit = anchor_ref_;
1447 size_t const npit = buftext.paragraphs().size();
1449 // Rebreak anchor paragraph.
1451 tm.redoParagraph(pit);
1453 // Clear out the position cache in case of full screen redraw.
1455 coord_cache_.clear();
1457 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1459 // Redo paragraphs above anchor if necessary.
1461 while (y1 > 0 && pit1 > 0) {
1462 y1 -= tm.parMetrics(pit1).ascent();
1465 tm.redoParagraph(pit1);
1466 y1 -= tm.parMetrics(pit1).descent();
1470 // Take care of ascent of first line
1471 y1 -= tm.parMetrics(pit1).ascent();
1473 // Normalize anchor for next time
1477 // Grey at the beginning is ugly
1478 if (pit1 == 0 && y1 > 0) {
1484 // Redo paragraphs below the anchor if necessary.
1486 while (y2 < height_ && pit2 < int(npit) - 1) {
1487 y2 += tm.parMetrics(pit2).descent();
1490 tm.redoParagraph(pit2);
1491 y2 += tm.parMetrics(pit2).ascent();
1494 // Take care of descent of last line
1495 y2 += tm.parMetrics(pit2).descent();
1497 // The coordinates of all these paragraphs are correct, cache them
1499 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1500 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1501 ParagraphMetrics const & pm = tm.parMetrics(pit);
1503 parPos[pit] = Point(0, y);
1504 if (singlepar && pit == cursor_.bottom().pit()) {
1505 // In Single Paragraph mode, collect here the
1506 // y1 and y2 of the (one) paragraph the cursor is in
1507 y1 = y - pm.ascent();
1508 y2 = y + pm.descent();
1514 // collect cursor paragraph iter bounds
1515 pit1 = cursor_.bottom().pit();
1516 pit2 = cursor_.bottom().pit();
1519 LYXERR(Debug::DEBUG)
1520 << BOOST_CURRENT_FUNCTION
1523 << " pit1: " << pit1
1524 << " pit2: " << pit2
1525 << " npit: " << npit
1526 << " singlepar: " << singlepar
1530 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1531 singlepar? SingleParUpdate: FullScreenUpdate, size);
1533 if (lyxerr.debugging(Debug::WORKAREA)) {
1534 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1535 coord_cache_.dump();
1540 void BufferView::menuInsertLyXFile(string const & filenm)
1542 BOOST_ASSERT(cursor_.inTexted());
1543 string filename = filenm;
1545 if (filename.empty()) {
1546 // Launch a file browser
1548 string initpath = lyxrc.document_path;
1551 string const trypath = buffer_->filePath();
1552 // If directory is writeable, use this as default.
1553 if (isDirWriteable(FileName(trypath)))
1558 FileDialog fileDlg(_("Select LyX document to insert"),
1560 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1561 make_pair(_("Examples|#E#e"),
1562 from_utf8(addPath(package().system_support().absFilename(),
1565 FileDialog::Result result =
1566 fileDlg.open(from_utf8(initpath),
1567 FileFilterList(_("LyX Documents (*.lyx)")),
1570 if (result.first == FileDialog::Later)
1574 filename = to_utf8(result.second);
1576 // check selected filename
1577 if (filename.empty()) {
1578 // emit message signal.
1579 message(_("Canceled."));
1584 // Get absolute path of file and add ".lyx"
1585 // to the filename if necessary
1586 filename = fileSearch(string(), filename, "lyx").absFilename();
1588 docstring const disp_fn = makeDisplayPath(filename);
1589 // emit message signal.
1590 message(bformat(_("Inserting document %1$s..."), disp_fn));
1593 Buffer buf("", false);
1594 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1595 ErrorList & el = buffer_->errorList("Parse");
1596 // Copy the inserted document error list into the current buffer one.
1597 el = buf.errorList("Parse");
1598 recordUndo(cursor_);
1599 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1600 buf.params().textclass, el);
1601 res = _("Document %1$s inserted.");
1603 res = _("Could not insert document %1$s");
1605 // emit message signal.
1606 message(bformat(res, disp_fn));
1607 buffer_->errors("Parse");