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>
83 using std::istringstream;
87 using std::mem_fun_ref;
94 using support::addPath;
95 using support::bformat;
96 using support::FileFilterList;
97 using support::FileName;
98 using support::fileSearch;
99 using support::isDirWriteable;
100 using support::isFileReadable;
101 using support::makeDisplayPath;
102 using support::package;
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 Buffer * BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the current selection if any
153 cap::saveSelection(cursor_);
154 // Save the actual cursor position and anchor inside the
155 // buffer so that it can be restored in case we rechange
156 // to this buffer later on.
157 buffer_->saveCursor(cursor_.selectionBegin(),
158 cursor_.selectionEnd());
159 // update bookmark pit of the current buffer before switch
160 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
161 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
162 if (buffer()->fileName() != bm.filename.absFilename())
164 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
165 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
169 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
170 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
171 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
173 // current buffer is going to be switched-off, save cursor pos
174 // Ideally, the whole cursor stack should be saved, but session
175 // currently can only handle bottom (whole document) level pit and pos.
176 // That is to say, if a cursor is in a nested inset, it will be
177 // restore to the left of the top level inset.
178 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
179 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
182 // If we're quitting lyx, don't bother updating stuff
188 //FIXME Fix for bug 3440 is here.
189 // If we are closing current buffer, switch to the first in
192 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
193 << " No Buffer!" << endl;
194 // We are closing the buffer, use the first buffer as current
196 // if (last_buffer_) buffer_ = last_buffer_;
197 // also check that this is in theBufferList()?
198 buffer_ = theBufferList().first();
201 // last_buffer = buffer_;
202 // Set current buffer
207 cursor_ = Cursor(*this);
214 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
215 << "Buffer addr: " << buffer_ << endl;
216 cursor_.push(buffer_->inset());
217 cursor_.resetAnchor();
218 buffer_->text().setCurrentFont(cursor_);
220 // Update the metrics now that we have a proper Cursor.
221 updateMetrics(false);
223 // FIXME: This code won't be needed once we switch to
224 // "one Buffer" / "one BufferView".
225 if (buffer_->getCursor().size() > 0 &&
226 buffer_->getAnchor().size() > 0)
228 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
229 cursor_.resetAnchor();
230 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
231 cursor_.setSelection();
232 // do not set selection to the new buffer because we
233 // only paste recent selection.
235 // Make sure that the restored cursor is not broken. This can happen for
236 // example if this Buffer has been modified by another view.
237 cursor_.fixIfBroken();
240 // Update the metrics if the cursor new position was off screen.
241 updateMetrics(false);
244 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
245 graphics::Previews::get().generateBufferPreviews(*buffer_);
250 void BufferView::resize()
255 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
257 updateMetrics(false);
261 bool BufferView::fitCursor()
263 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
264 frontend::FontMetrics const & fm =
265 theFontMetrics(cursor_.getFont());
266 int const asc = fm.maxAscent();
267 int const des = fm.maxDescent();
268 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
269 if (p.y_ - asc >= 0 && p.y_ + des < height_)
277 bool BufferView::multiParSel()
279 if (!cursor_.selection())
281 bool ret = multiparsel_cache_;
282 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
283 // Either this, or previous selection spans paragraphs
284 return ret || multiparsel_cache_;
288 bool BufferView::update(Update::flags flags)
290 // last_inset_ points to the last visited inset. This pointer may become
291 // invalid because of keyboard editing. Since all such operations
292 // causes screen update(), I reset last_inset_ to avoid such a problem.
294 // This is close to a hot-path.
296 << BOOST_CURRENT_FUNCTION
297 << "[fitcursor = " << (flags & Update::FitCursor)
298 << ", forceupdate = " << (flags & Update::Force)
299 << ", singlepar = " << (flags & Update::SinglePar)
300 << "] buffer: " << buffer_ << endl;
302 // Check needed to survive LyX startup
306 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
308 // Update macro store
309 if (!(cursor().inMathed() && cursor().inMacroMode()))
310 buffer_->buildMacros();
312 // Now do the first drawing step if needed. This consists on updating
313 // the CoordCache in updateMetrics().
314 // The second drawing step is done in WorkArea::redraw() if needed.
316 // Case when no explicit update is requested.
318 // no need to redraw anything.
319 metrics_info_.update_strategy = NoScreenUpdate;
323 if (flags == Update::Decoration) {
324 metrics_info_.update_strategy = DecorationUpdate;
328 if (flags == Update::FitCursor
329 || flags == (Update::Decoration | Update::FitCursor)) {
330 bool const fit_cursor = fitCursor();
331 // tell the frontend to update the screen if needed.
333 updateMetrics(false);
336 if (flags & Update::Decoration) {
337 metrics_info_.update_strategy = DecorationUpdate;
340 // no screen update is needed.
341 metrics_info_.update_strategy = NoScreenUpdate;
345 bool full_metrics = flags & Update::Force;
346 if (flags & Update::MultiParSel)
347 full_metrics |= multiParSel();
349 bool const single_par = !full_metrics;
350 updateMetrics(single_par);
352 if (flags & Update::FitCursor && fitCursor())
353 updateMetrics(false);
355 // tell the frontend to update the screen.
360 void BufferView::updateScrollbar()
363 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
364 << " no text in updateScrollbar" << endl;
365 scrollbarParameters_.reset();
369 Text & t = buffer_->text();
370 TextMetrics & tm = text_metrics_[&t];
372 int const parsize = int(t.paragraphs().size() - 1);
373 if (anchor_ref_ > parsize) {
374 anchor_ref_ = parsize;
379 << BOOST_CURRENT_FUNCTION
380 << " Updating scrollbar: height: " << t.paragraphs().size()
381 << " curr par: " << cursor_.bottom().pit()
382 << " default height " << defaultRowHeight() << endl;
384 // It would be better to fix the scrollbar to understand
385 // values in [0..1] and divide everything by wh
387 // estimated average paragraph height:
391 int h = tm.parMetrics(anchor_ref_).height();
393 // Normalize anchor/offset (MV):
394 while (offset_ref_ > h && anchor_ref_ < parsize) {
397 h = tm.parMetrics(anchor_ref_).height();
399 // Look at paragraph heights on-screen
402 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
405 int const h2 = tm.parMetrics(pit).height();
411 int const hav = sumh / nh;
412 // More realistic average paragraph height
417 scrollbarParameters_.height = (parsize + 1) * wh_;
418 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
419 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
423 ScrollbarParameters const & BufferView::scrollbarParameters() const
425 return scrollbarParameters_;
429 void BufferView::scrollDocView(int value)
431 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
432 << "[ value = " << value << "]" << endl;
437 Text & t = buffer_->text();
438 TextMetrics & tm = text_metrics_[&t];
440 float const bar = value / float(wh_ * t.paragraphs().size());
442 anchor_ref_ = int(bar * t.paragraphs().size());
443 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
444 anchor_ref_ = int(t.paragraphs().size()) - 1;
446 tm.redoParagraph(anchor_ref_);
447 int const h = tm.parMetrics(anchor_ref_).height();
448 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
449 updateMetrics(false);
453 void BufferView::setCursorFromScrollbar()
458 Text & t = buffer_->text();
460 int const height = 2 * defaultRowHeight();
461 int const first = height;
462 int const last = height_ - height;
463 Cursor & cur = cursor_;
465 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
468 case bv_funcs::CUR_ABOVE:
469 // We reset the cursor because bv_funcs::status() does not
470 // work when the cursor is within mathed.
471 cur.reset(buffer_->inset());
472 t.setCursorFromCoordinates(cur, 0, first);
473 cur.clearSelection();
475 case bv_funcs::CUR_BELOW:
476 // We reset the cursor because bv_funcs::status() does not
477 // work when the cursor is within mathed.
478 cur.reset(buffer_->inset());
479 t.setCursorFromCoordinates(cur, 0, last);
480 cur.clearSelection();
482 case bv_funcs::CUR_INSIDE:
483 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
484 int const newy = min(last, max(y, first));
486 cur.reset(buffer_->inset());
487 t.setCursorFromCoordinates(cur, 0, newy);
493 Change const BufferView::getCurrentChange() const
495 if (!cursor_.selection())
496 return Change(Change::UNCHANGED);
498 DocIterator dit = cursor_.selectionBegin();
499 return dit.paragraph().lookupChange(dit.pos());
503 void BufferView::saveBookmark(unsigned int idx)
505 // tenatively save bookmark, id and pos will be used to
506 // acturately locate a bookmark in a 'live' lyx session.
507 // pit and pos will be updated with bottom level pit/pos
509 LyX::ref().session().bookmarks().save(
510 FileName(buffer_->fileName()),
511 cursor_.bottom().pit(),
512 cursor_.bottom().pos(),
513 cursor_.paragraph().id(),
518 // emit message signal.
519 message(_("Save bookmark"));
523 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
524 int top_id, pos_type top_pos)
526 cursor_.clearSelection();
528 // if a valid par_id is given, try it first
529 // This is the case for a 'live' bookmark when unique paragraph ID
530 // is used to track bookmarks.
532 ParIterator par = buffer_->getParFromID(top_id);
533 if (par != buffer_->par_iterator_end()) {
534 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
535 // Some slices of the iterator may not be
536 // reachable (e.g. closed collapsable inset)
537 // so the dociterator may need to be
538 // shortened. Otherwise, setCursor may crash
539 // lyx when the cursor can not be set to these
541 size_t const n = dit.depth();
542 for (size_t i = 0; i < n; ++i)
543 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
548 // Note: return bottom (document) level pit.
549 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
552 // if top_id == 0, or searching through top_id failed
553 // This is the case for a 'restored' bookmark when only bottom
554 // (document level) pit was saved. Because of this, bookmark
555 // restoration is inaccurate. If a bookmark was within an inset,
556 // it will be restored to the left of the outmost inset that contains
558 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
559 DocIterator it = doc_iterator_begin(buffer_->inset());
560 it.pit() = bottom_pit;
561 it.pos() = min(bottom_pos, it.paragraph().size());
563 return boost::make_tuple(it.pit(), it.pos(),
564 it.paragraph().id());
567 return boost::make_tuple(pit_type(0), pos_type(0), 0);
571 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
573 if (lyxrc.rtl_support) {
574 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
575 if (intl_->keymap == Intl::PRIMARY)
578 if (intl_->keymap == Intl::SECONDARY)
583 intl_->getTransManager().translateAndInsert(c, t, cur);
587 int BufferView::workWidth() const
593 void BufferView::center()
595 CursorSlice & bot = cursor_.bottom();
596 TextMetrics & tm = text_metrics_[bot.text()];
597 pit_type const pit = bot.pit();
598 tm.redoParagraph(pit);
599 ParagraphMetrics const & pm = tm.parMetrics(pit);
601 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
602 + pm.ascent() - height_ / 2;
606 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
610 Cursor & cur = cursor_;
612 switch (cmd.action) {
615 flag.enabled(!buffer_->undostack().empty());
618 flag.enabled(!buffer_->redostack().empty());
620 case LFUN_FILE_INSERT:
621 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
622 case LFUN_FILE_INSERT_PLAINTEXT:
623 case LFUN_BOOKMARK_SAVE:
624 // FIXME: Actually, these LFUNS should be moved to Text
625 flag.enabled(cur.inTexted());
627 case LFUN_FONT_STATE:
628 case LFUN_LABEL_INSERT:
629 case LFUN_PARAGRAPH_GOTO:
630 // FIXME handle non-trivially
631 case LFUN_OUTLINE_UP:
632 case LFUN_OUTLINE_DOWN:
633 case LFUN_OUTLINE_IN:
634 case LFUN_OUTLINE_OUT:
636 case LFUN_REFERENCE_NEXT:
638 case LFUN_WORD_REPLACE:
641 case LFUN_MARK_TOGGLE:
642 case LFUN_SCREEN_RECENTER:
643 case LFUN_BIBTEX_DATABASE_ADD:
644 case LFUN_BIBTEX_DATABASE_DEL:
645 case LFUN_WORDS_COUNT:
646 case LFUN_NEXT_INSET_TOGGLE:
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: {
896 bool has_deleted = false;
897 if (cur.selection()) {
898 DocIterator beg = cur.selectionBegin();
899 DocIterator end = cur.selectionEnd();
900 if (beg.pit() == end.pit()) {
901 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
902 if (cur.paragraph().isDeleted(p))
907 replace(this, cmd, has_deleted);
912 cur.clearSelection();
914 cur.message(from_utf8(N_("Mark off")));
918 cur.clearSelection();
921 cur.message(from_utf8(N_("Mark on")));
924 case LFUN_MARK_TOGGLE:
925 cur.clearSelection();
928 cur.message(from_utf8(N_("Mark removed")));
931 cur.message(from_utf8(N_("Mark set")));
936 case LFUN_SCREEN_RECENTER:
940 case LFUN_BIBTEX_DATABASE_ADD: {
941 Cursor tmpcur = cursor_;
942 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
943 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
946 if (inset->addDatabase(to_utf8(cmd.argument())))
947 buffer_->updateBibfilesCache();
952 case LFUN_BIBTEX_DATABASE_DEL: {
953 Cursor tmpcur = cursor_;
954 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
955 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
958 if (inset->delDatabase(to_utf8(cmd.argument())))
959 buffer_->updateBibfilesCache();
964 case LFUN_WORDS_COUNT: {
965 DocIterator from, to;
966 if (cur.selection()) {
967 from = cur.selectionBegin();
968 to = cur.selectionEnd();
970 from = doc_iterator_begin(buffer_->inset());
971 to = doc_iterator_end(buffer_->inset());
973 int const count = countWords(from, to);
977 message = bformat(_("%1$d words in selection."),
980 message = bformat(_("%1$d words in document."),
985 message = _("One word in selection.");
987 message = _("One word in document.");
990 Alert::information(_("Count words"), message);
994 case LFUN_BUFFER_TOGGLE_COMPRESSION:
995 // turn compression on/off
996 buffer_->params().compressed = !buffer_->params().compressed;
999 case LFUN_NEXT_INSET_TOGGLE: {
1000 // this is the real function we want to invoke
1001 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1002 // if there is an inset at cursor, see whether it
1004 Inset * inset = cur.nextInset();
1005 if (inset && inset->isActive()) {
1006 Cursor tmpcur = cur;
1007 tmpcur.pushLeft(*inset);
1008 inset->dispatch(tmpcur, tmpcmd);
1009 if (tmpcur.result().dispatched()) {
1013 // if it did not work, try the underlying inset.
1014 if (!cur.result().dispatched())
1015 cur.dispatch(tmpcmd);
1017 if (cur.result().dispatched())
1018 cur.clearSelection();
1024 updateFlags = Update::None;
1031 docstring const BufferView::requestSelection()
1036 Cursor & cur = cursor_;
1038 if (!cur.selection()) {
1039 xsel_cache_.set = false;
1043 if (!xsel_cache_.set ||
1044 cur.top() != xsel_cache_.cursor ||
1045 cur.anchor_.top() != xsel_cache_.anchor)
1047 xsel_cache_.cursor = cur.top();
1048 xsel_cache_.anchor = cur.anchor_.top();
1049 xsel_cache_.set = cur.selection();
1050 return cur.selectionAsString(false);
1056 void BufferView::clearSelection()
1059 cursor_.clearSelection();
1060 // Clear the selection buffer. Otherwise a subsequent
1061 // middle-mouse-button paste would use the selection buffer,
1062 // not the more current external selection.
1063 cap::clearSelection();
1064 xsel_cache_.set = false;
1065 // The buffer did not really change, but this causes the
1066 // redraw we need because we cleared the selection above.
1072 void BufferView::workAreaResize(int width, int height)
1074 // Update from work area
1078 // The complete text metrics will be redone.
1079 text_metrics_.clear();
1086 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1088 pit_type pit = text.getPitNearY(*this, y);
1089 BOOST_ASSERT(pit != -1);
1090 Paragraph const & par = text.getPar(pit);
1092 LYXERR(Debug::DEBUG)
1093 << BOOST_CURRENT_FUNCTION
1098 InsetList::const_iterator iit = par.insetlist.begin();
1099 InsetList::const_iterator iend = par.insetlist.end();
1100 for (; iit != iend; ++iit) {
1101 Inset * const inset = iit->inset;
1102 if (inset->covers(*this, x, y)) {
1103 if (!inset->descendable())
1104 // No need to go further down if the inset is not
1108 size_t cell_number = inset->nargs();
1109 // Check all the inner cell.
1110 for (size_t i = 0; i != cell_number; ++i) {
1111 Text const * inner_text = inset->getText(i);
1114 Inset const * inset_deeper =
1115 getCoveringInset(*inner_text, x, y);
1117 return inset_deeper;
1121 LYXERR(Debug::DEBUG)
1122 << BOOST_CURRENT_FUNCTION
1123 << ": Hit inset: " << inset << endl;
1127 LYXERR(Debug::DEBUG)
1128 << BOOST_CURRENT_FUNCTION
1129 << ": No inset hit. " << endl;
1134 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1136 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1138 // This is only called for mouse related events including
1139 // LFUN_FILE_OPEN generated by drag-and-drop.
1140 FuncRequest cmd = cmd0;
1142 // E.g. Qt mouse press when no buffer
1147 cur.push(buffer_->inset());
1148 cur.selection() = cursor_.selection();
1150 // Either the inset under the cursor or the
1151 // surrounding Text will handle this event.
1153 // make sure we stay within the screen...
1154 cmd.y = min(max(cmd.y, -1), height_);
1156 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1158 // Get inset under mouse, if there is one.
1159 Inset const * covering_inset =
1160 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1161 if (covering_inset == last_inset_)
1162 // Same inset, no need to do anything...
1165 bool need_redraw = false;
1166 // const_cast because of setMouseHover().
1167 Inset * inset = const_cast<Inset *>(covering_inset);
1169 // Remove the hint on the last hovered inset (if any).
1170 need_redraw |= last_inset_->setMouseHover(false);
1172 // Highlighted the newly hovered inset (if any).
1173 need_redraw |= inset->setMouseHover(true);
1174 last_inset_ = inset;
1176 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1177 // not expose the button for redraw. We adjust here the metrics dimension
1178 // to enable a full redraw.
1179 // FIXME: It is possible to redraw only the area around the button!
1181 && metrics_info_.update_strategy == SingleParUpdate) {
1182 // FIXME: It should be possible to redraw only the area around
1183 // the button by doing this:
1185 //metrics_info_.singlepar = false;
1186 //metrics_info_.y1 = ymin of button;
1187 //metrics_info_.y2 = ymax of button;
1189 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1190 // between background updates and text updates. So we use the hammer
1191 // solution for now. We could also avoid the updateMetrics() below
1192 // by using the first and last pit of the CoordCache. Have a look
1193 // at Text::getPitNearY() to see what I mean.
1195 //metrics_info_.pit1 = first pit of CoordCache;
1196 //metrics_info_.pit2 = last pit of CoordCache;
1197 //metrics_info_.singlepar = false;
1198 //metrics_info_.y1 = 0;
1199 //metrics_info_.y2 = height_;
1201 updateMetrics(false);
1204 // This event (moving without mouse click) is not passed further.
1205 // This should be changed if it is further utilized.
1209 // Build temporary cursor.
1210 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1212 // Put anchor at the same position.
1215 // Try to dispatch to an non-editable inset near this position
1216 // via the temp cursor. If the inset wishes to change the real
1217 // cursor it has to do so explicitly by using
1218 // cur.bv().cursor() = cur; (or similar)
1220 inset->dispatch(cur, cmd);
1223 // Now dispatch to the temporary cursor. If the real cursor should
1224 // be modified, the inset's dispatch has to do so explicitly.
1225 if (!cur.result().dispatched())
1228 // Redraw if requested and necessary.
1229 if (cur.result().dispatched() && cur.result().update())
1230 return update(cur.result().update());
1236 void BufferView::scroll(int /*lines*/)
1241 // Text const * t = &buffer_->text();
1242 // int const line_height = defaultRowHeight();
1244 // // The new absolute coordinate
1245 // int new_top_y = top_y() + lines * line_height;
1247 // // Restrict to a valid value
1248 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1249 // new_top_y = std::max(0, new_top_y);
1251 // scrollDocView(new_top_y);
1256 void BufferView::setCursorFromRow(int row)
1261 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1263 cursor_.reset(buffer_->inset());
1265 buffer_->text().setCursor(cursor_, 0, 0);
1267 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1271 void BufferView::gotoLabel(docstring const & label)
1273 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1274 vector<docstring> labels;
1275 it->getLabelList(*buffer_, labels);
1276 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1285 TextMetrics const & BufferView::textMetrics(Text const * t) const
1287 return const_cast<BufferView *>(this)->textMetrics(t);
1291 TextMetrics & BufferView::textMetrics(Text const * t)
1293 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1294 if (tmc_it == text_metrics_.end()) {
1295 tmc_it = text_metrics_.insert(
1296 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1298 return tmc_it->second;
1302 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1305 return textMetrics(t).parMetrics(pit);
1309 int BufferView::workHeight() const
1315 void BufferView::setCursor(DocIterator const & dit)
1317 size_t const n = dit.depth();
1318 for (size_t i = 0; i < n; ++i)
1319 dit[i].inset().edit(cursor_, true);
1321 cursor_.setCursor(dit);
1322 cursor_.selection() = false;
1326 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1328 // Would be wrong to delete anything if we have a selection.
1329 if (cur.selection())
1332 bool need_anchor_change = false;
1333 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1334 need_anchor_change);
1336 if (need_anchor_change)
1342 updateLabels(*buffer_);
1344 updateMetrics(false);
1350 bool BufferView::mouseSetCursor(Cursor & cur)
1352 BOOST_ASSERT(&cur.bv() == this);
1354 // this event will clear selection so we save selection for
1355 // persistent selection
1356 cap::saveSelection(cursor());
1358 // Has the cursor just left the inset?
1359 bool badcursor = false;
1360 bool leftinset = (&cursor_.inset() != &cur.inset());
1362 badcursor = notifyCursorLeaves(cursor_, cur);
1364 // do the dEPM magic if needed
1365 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1366 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1367 // the leftinset bool would not be necessary (badcursor instead).
1368 bool update = leftinset;
1369 if (!badcursor && cursor_.inTexted())
1370 update |= checkDepm(cur, cursor_);
1372 // if the cursor was in an empty script inset and the new
1373 // position is in the nucleus of the inset, notifyCursorLeaves
1374 // will kill the script inset itself. So we check all the
1375 // elements of the cursor to make sure that they are correct.
1376 // For an example, see bug 2933:
1377 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1378 // The code below could maybe be moved to a DocIterator method.
1379 //lyxerr << "cur before " << cur <<std::endl;
1380 DocIterator dit(cur.inset());
1381 dit.push_back(cur.bottom());
1383 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1384 dit.push_back(cur[i]);
1387 //lyxerr << "5 cur after" << dit <<std::endl;
1389 cursor_.setCursor(dit);
1390 cursor_.boundary(cur.boundary());
1391 cursor_.clearSelection();
1397 void BufferView::putSelectionAt(DocIterator const & cur,
1398 int length, bool backwards)
1400 cursor_.clearSelection();
1406 cursor_.pos() += length;
1407 cursor_.setSelection(cursor_, -length);
1409 cursor_.setSelection(cursor_, length);
1414 Cursor & BufferView::cursor()
1420 Cursor const & BufferView::cursor() const
1426 pit_type BufferView::anchor_ref() const
1432 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1434 return metrics_info_;
1438 // FIXME: We should split-up updateMetrics() for the singlepar case.
1439 void BufferView::updateMetrics(bool singlepar)
1441 Text & buftext = buffer_->text();
1442 TextMetrics & tm = textMetrics(&buftext);
1443 pit_type size = int(buftext.paragraphs().size());
1445 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1446 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1451 // Clear out the position cache in case of full screen redraw,
1452 coord_cache_.clear();
1454 // Clear out paragraph metrics to avoid having invalid metrics
1455 // in the cache from paragraphs not relayouted below
1459 // If the paragraph metrics has changed, we can not
1460 // use the singlepar optimisation.
1462 // In Single Paragraph mode, rebreak only
1463 // the (main text, not inset!) paragraph containing the cursor.
1464 // (if this paragraph contains insets etc., rebreaking will
1465 // recursively descend)
1466 && tm.redoParagraph(cursor_.bottom().pit()))
1469 pit_type const pit = anchor_ref_;
1472 size_t const npit = buftext.paragraphs().size();
1474 // Rebreak anchor paragraph.
1476 tm.redoParagraph(pit);
1478 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1480 // Redo paragraphs above anchor if necessary.
1482 while (y1 > 0 && pit1 > 0) {
1483 y1 -= tm.parMetrics(pit1).ascent();
1486 tm.redoParagraph(pit1);
1487 y1 -= tm.parMetrics(pit1).descent();
1491 // Take care of ascent of first line
1492 y1 -= tm.parMetrics(pit1).ascent();
1494 // Normalize anchor for next time
1498 // Grey at the beginning is ugly
1499 if (pit1 == 0 && y1 > 0) {
1505 // Redo paragraphs below the anchor if necessary.
1507 while (y2 < height_ && pit2 < int(npit) - 1) {
1508 y2 += tm.parMetrics(pit2).descent();
1511 tm.redoParagraph(pit2);
1512 y2 += tm.parMetrics(pit2).ascent();
1515 // Take care of descent of last line
1516 y2 += tm.parMetrics(pit2).descent();
1518 // The coordinates of all these paragraphs are correct, cache them
1520 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1521 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1522 ParagraphMetrics const & pm = tm.parMetrics(pit);
1524 parPos[pit] = Point(0, y);
1525 if (singlepar && pit == cursor_.bottom().pit()) {
1526 // In Single Paragraph mode, collect here the
1527 // y1 and y2 of the (one) paragraph the cursor is in
1528 y1 = y - pm.ascent();
1529 y2 = y + pm.descent();
1535 // collect cursor paragraph iter bounds
1536 pit1 = cursor_.bottom().pit();
1537 pit2 = cursor_.bottom().pit();
1540 LYXERR(Debug::DEBUG)
1541 << BOOST_CURRENT_FUNCTION
1544 << " pit1: " << pit1
1545 << " pit2: " << pit2
1546 << " npit: " << npit
1547 << " singlepar: " << singlepar
1551 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1552 singlepar? SingleParUpdate: FullScreenUpdate, size);
1554 if (lyxerr.debugging(Debug::WORKAREA)) {
1555 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1556 coord_cache_.dump();
1561 void BufferView::menuInsertLyXFile(string const & filenm)
1563 BOOST_ASSERT(cursor_.inTexted());
1564 string filename = filenm;
1566 if (filename.empty()) {
1567 // Launch a file browser
1569 string initpath = lyxrc.document_path;
1572 string const trypath = buffer_->filePath();
1573 // If directory is writeable, use this as default.
1574 if (isDirWriteable(FileName(trypath)))
1579 FileDialog fileDlg(_("Select LyX document to insert"),
1581 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1582 make_pair(_("Examples|#E#e"),
1583 from_utf8(addPath(package().system_support().absFilename(),
1586 FileDialog::Result result =
1587 fileDlg.open(from_utf8(initpath),
1588 FileFilterList(_("LyX Documents (*.lyx)")),
1591 if (result.first == FileDialog::Later)
1595 filename = to_utf8(result.second);
1597 // check selected filename
1598 if (filename.empty()) {
1599 // emit message signal.
1600 message(_("Canceled."));
1605 // Get absolute path of file and add ".lyx"
1606 // to the filename if necessary
1607 filename = fileSearch(string(), filename, "lyx").absFilename();
1609 docstring const disp_fn = makeDisplayPath(filename);
1610 // emit message signal.
1611 message(bformat(_("Inserting document %1$s..."), disp_fn));
1614 Buffer buf("", false);
1615 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1616 ErrorList & el = buffer_->errorList("Parse");
1617 // Copy the inserted document error list into the current buffer one.
1618 el = buf.errorList("Parse");
1619 recordUndo(cursor_);
1620 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1621 buf.params().textclass, el);
1622 res = _("Document %1$s inserted.");
1624 res = _("Could not insert document %1$s");
1626 // emit message signal.
1627 message(bformat(res, disp_fn));
1628 buffer_->errors("Parse");