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 "callback.h" // added for Dispatch functions
25 #include "CoordCache.h"
26 #include "CutAndPaste.h"
28 #include "DispatchResult.h"
29 #include "ErrorList.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
36 #include "InsetIterator.h"
38 #include "LaTeXFeatures.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
52 #include "TextClass.h"
56 #include "WordLangTuple.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"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/Package.h"
75 #include "support/types.h"
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
85 using std::istringstream;
89 using std::mem_fun_ref;
96 using support::addPath;
97 using support::bformat;
98 using support::FileFilterList;
99 using support::FileName;
100 using support::fileSearch;
101 using support::isDirWriteable;
102 using support::isFileReadable;
103 using support::makeDisplayPath;
104 using support::package;
106 namespace Alert = frontend::Alert;
110 /// Return an inset of this class if it exists at the current cursor position
112 T * getInsetByCode(Cursor const & cur, Inset::Code code)
114 DocIterator it = cur;
115 Inset * inset = it.nextInset();
116 if (inset && inset->lyxCode() == code)
117 return static_cast<T*>(inset);
122 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
125 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
126 string const & contents)
128 DocIterator tmpdit = dit;
131 Inset const * inset = tmpdit.nextInset();
133 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
134 && (contents.empty() ||
135 static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
139 tmpdit.forwardInset();
146 /// Looks for next inset with one of the the given code
147 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
151 DocIterator tmpdit = dit;
152 tmpdit.forwardInset();
157 Inset const * inset = tmpdit.nextInset();
159 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
160 contents = static_cast<InsetCommand const *>(inset)->getContents();
164 if (!findNextInset(tmpdit, codes, contents)) {
165 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
167 if (!findNextInset(tmpdit, codes, contents))
178 /// Looks for next inset with the given code
179 void findInset(DocIterator & dit, Inset_code code, bool same_content)
181 findInset(dit, vector<Inset_code>(1, code), same_content);
185 /// Moves cursor to the next inset with one of the given codes.
186 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
189 Cursor tmpcur = bv->cursor();
190 if (!findInset(tmpcur, codes, same_content)) {
191 bv->cursor().message(_("No more insets"));
195 tmpcur.clearSelection();
196 bv->setCursor(tmpcur);
200 /// Moves cursor to the next inset with given code.
201 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
203 gotoInset(bv, vector<Inset_code>(1, code), same_content);
210 BufferView::BufferView(Buffer & buf)
211 : width_(0), height_(0), buffer_(buf), wh_(0),
213 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
214 need_centering_(false), intl_(new Intl), last_inset_(0)
216 xsel_cache_.set = false;
217 intl_->initKeyMapper(lyxrc.use_kbmap);
219 cursor_.push(buffer_.inset());
220 cursor_.resetAnchor();
221 cursor_.setCurrentFont();
223 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
224 graphics::Previews::get().generateBufferPreviews(buffer_);
228 BufferView::~BufferView()
230 // current buffer is going to be switched-off, save cursor pos
231 // Ideally, the whole cursor stack should be saved, but session
232 // currently can only handle bottom (whole document) level pit and pos.
233 // That is to say, if a cursor is in a nested inset, it will be
234 // restore to the left of the top level inset.
235 LyX::ref().session().lastFilePos().save(
236 support::FileName(buffer_.fileName()),
237 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
241 Buffer & BufferView::buffer()
247 Buffer const & BufferView::buffer() const
253 bool BufferView::fitCursor()
255 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
256 frontend::FontMetrics const & fm =
257 theFontMetrics(cursor_.getFont());
258 int const asc = fm.maxAscent();
259 int const des = fm.maxDescent();
260 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
261 if (p.y_ - asc >= 0 && p.y_ + des < height_)
269 bool BufferView::multiParSel()
271 if (!cursor_.selection())
273 bool ret = multiparsel_cache_;
274 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
275 // Either this, or previous selection spans paragraphs
276 return ret || multiparsel_cache_;
280 bool BufferView::update(Update::flags flags)
282 // last_inset_ points to the last visited inset. This pointer may become
283 // invalid because of keyboard editing. Since all such operations
284 // causes screen update(), I reset last_inset_ to avoid such a problem.
286 // This is close to a hot-path.
288 << BOOST_CURRENT_FUNCTION
289 << "[fitcursor = " << (flags & Update::FitCursor)
290 << ", forceupdate = " << (flags & Update::Force)
291 << ", singlepar = " << (flags & Update::SinglePar)
292 << "] buffer: " << &buffer_ << endl;
294 // Update macro store
295 if (!(cursor().inMathed() && cursor().inMacroMode()))
296 buffer_.buildMacros();
298 // Now do the first drawing step if needed. This consists on updating
299 // the CoordCache in updateMetrics().
300 // The second drawing step is done in WorkArea::redraw() if needed.
302 // Case when no explicit update is requested.
304 // no need to redraw anything.
305 metrics_info_.update_strategy = NoScreenUpdate;
309 if (flags == Update::Decoration) {
310 metrics_info_.update_strategy = DecorationUpdate;
314 if (flags == Update::FitCursor
315 || flags == (Update::Decoration | Update::FitCursor)) {
316 bool const fit_cursor = fitCursor();
317 // tell the frontend to update the screen if needed.
319 updateMetrics(false);
322 if (flags & Update::Decoration) {
323 metrics_info_.update_strategy = DecorationUpdate;
326 // no screen update is needed.
327 metrics_info_.update_strategy = NoScreenUpdate;
331 bool full_metrics = flags & Update::Force;
332 if (flags & Update::MultiParSel)
333 full_metrics |= multiParSel();
335 bool const single_par = !full_metrics;
336 updateMetrics(single_par);
338 if (flags & Update::FitCursor) {
339 //FIXME: updateMetrics() does not update paragraph position
340 // This is done at draw() time. So we need a redraw!
343 updateMetrics(false);
345 // The screen has already been updated thanks to the
346 // 'buffer_.changed()' call three line above. So no need
351 // tell the frontend to update the screen.
356 void BufferView::updateScrollbar()
358 Text & t = buffer_.text();
359 TextMetrics & tm = text_metrics_[&t];
361 int const parsize = int(t.paragraphs().size() - 1);
362 if (anchor_ref_ > parsize) {
363 anchor_ref_ = parsize;
368 << BOOST_CURRENT_FUNCTION
369 << " Updating scrollbar: height: " << t.paragraphs().size()
370 << " curr par: " << cursor_.bottom().pit()
371 << " default height " << defaultRowHeight() << endl;
373 // It would be better to fix the scrollbar to understand
374 // values in [0..1] and divide everything by wh
376 // estimated average paragraph height:
380 int h = tm.parMetrics(anchor_ref_).height();
382 // Normalize anchor/offset (MV):
383 while (offset_ref_ > h && anchor_ref_ < parsize) {
386 h = tm.parMetrics(anchor_ref_).height();
388 // Look at paragraph heights on-screen
391 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
394 int const h2 = tm.parMetrics(pit).height();
400 int const hav = sumh / nh;
401 // More realistic average paragraph height
406 scrollbarParameters_.height = (parsize + 1) * wh_;
407 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
408 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
412 ScrollbarParameters const & BufferView::scrollbarParameters() const
414 return scrollbarParameters_;
418 void BufferView::scrollDocView(int value)
420 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
421 << "[ value = " << value << "]" << endl;
423 Text & t = buffer_.text();
424 TextMetrics & tm = text_metrics_[&t];
426 float const bar = value / float(wh_ * t.paragraphs().size());
428 anchor_ref_ = int(bar * t.paragraphs().size());
429 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
430 anchor_ref_ = int(t.paragraphs().size()) - 1;
432 tm.redoParagraph(anchor_ref_);
433 int const h = tm.parMetrics(anchor_ref_).height();
434 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
435 updateMetrics(false);
440 void BufferView::setCursorFromScrollbar()
442 TextMetrics & tm = text_metrics_[&buffer_.text()];
444 int const height = 2 * defaultRowHeight();
445 int const first = height;
446 int const last = height_ - height;
447 Cursor & cur = cursor_;
449 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
452 case bv_funcs::CUR_ABOVE:
453 // We reset the cursor because bv_funcs::status() does not
454 // work when the cursor is within mathed.
455 cur.reset(buffer_.inset());
456 tm.setCursorFromCoordinates(cur, 0, first);
457 cur.clearSelection();
459 case bv_funcs::CUR_BELOW:
460 // We reset the cursor because bv_funcs::status() does not
461 // work when the cursor is within mathed.
462 cur.reset(buffer_.inset());
463 tm.setCursorFromCoordinates(cur, 0, last);
464 cur.clearSelection();
466 case bv_funcs::CUR_INSIDE:
467 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
468 int const newy = min(last, max(y, first));
470 cur.reset(buffer_.inset());
471 tm.setCursorFromCoordinates(cur, 0, newy);
477 Change const BufferView::getCurrentChange() const
479 if (!cursor_.selection())
480 return Change(Change::UNCHANGED);
482 DocIterator dit = cursor_.selectionBegin();
483 return dit.paragraph().lookupChange(dit.pos());
487 void BufferView::saveBookmark(unsigned int idx)
489 // tenatively save bookmark, id and pos will be used to
490 // acturately locate a bookmark in a 'live' lyx session.
491 // pit and pos will be updated with bottom level pit/pos
493 LyX::ref().session().bookmarks().save(
494 FileName(buffer_.fileName()),
495 cursor_.bottom().pit(),
496 cursor_.bottom().pos(),
497 cursor_.paragraph().id(),
502 // emit message signal.
503 message(_("Save bookmark"));
507 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
508 int top_id, pos_type top_pos)
510 bool success = false;
513 cursor_.clearSelection();
515 // if a valid par_id is given, try it first
516 // This is the case for a 'live' bookmark when unique paragraph ID
517 // is used to track bookmarks.
519 ParIterator par = buffer_.getParFromID(top_id);
520 if (par != buffer_.par_iterator_end()) {
521 doc_it = makeDocIterator(par, min(par->size(), top_pos));
522 // Some slices of the iterator may not be
523 // reachable (e.g. closed collapsable inset)
524 // so the dociterator may need to be
525 // shortened. Otherwise, setCursor may crash
526 // lyx when the cursor can not be set to these
528 size_t const n = doc_it.depth();
529 for (size_t i = 0; i < n; ++i)
530 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
538 // if top_id == 0, or searching through top_id failed
539 // This is the case for a 'restored' bookmark when only bottom
540 // (document level) pit was saved. Because of this, bookmark
541 // restoration is inaccurate. If a bookmark was within an inset,
542 // it will be restored to the left of the outmost inset that contains
544 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
545 doc_it = doc_iterator_begin(buffer_.inset());
546 doc_it.pit() = bottom_pit;
547 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
552 // Note: only bottom (document) level pit is set.
554 // set the current font.
555 cursor_.setCurrentFont();
556 // center the screen on this new position.
564 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
566 if (lyxrc.rtl_support) {
567 if (cursor_.real_current_font.isRightToLeft()) {
568 if (intl_->keymap == Intl::PRIMARY)
571 if (intl_->keymap == Intl::SECONDARY)
576 intl_->getTransManager().translateAndInsert(c, t, cur);
580 int BufferView::workWidth() const
586 void BufferView::updateOffsetRef()
588 // No need to update offset_ref_ in this case.
589 if (!need_centering_)
592 // We are not properly started yet, delay until resizing is
597 CursorSlice & bot = cursor_.bottom();
598 TextMetrics & tm = text_metrics_[bot.text()];
599 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
600 Point p = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary());
601 offset_ref_ = p.y_ + pm.ascent() - height_ / 2;
603 need_centering_ = false;
607 void BufferView::center()
609 anchor_ref_ = cursor_.bottom().pit();
610 need_centering_ = true;
614 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
618 Cursor & cur = cursor_;
620 switch (cmd.action) {
623 flag.enabled(!buffer_.undostack().empty());
626 flag.enabled(!buffer_.redostack().empty());
628 case LFUN_FILE_INSERT:
629 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
630 case LFUN_FILE_INSERT_PLAINTEXT:
631 case LFUN_BOOKMARK_SAVE:
632 // FIXME: Actually, these LFUNS should be moved to Text
633 flag.enabled(cur.inTexted());
635 case LFUN_FONT_STATE:
636 case LFUN_LABEL_INSERT:
637 case LFUN_PARAGRAPH_GOTO:
638 // FIXME handle non-trivially
639 case LFUN_OUTLINE_UP:
640 case LFUN_OUTLINE_DOWN:
641 case LFUN_OUTLINE_IN:
642 case LFUN_OUTLINE_OUT:
644 case LFUN_REFERENCE_NEXT:
646 case LFUN_WORD_REPLACE:
649 case LFUN_MARK_TOGGLE:
650 case LFUN_SCREEN_RECENTER:
651 case LFUN_BIBTEX_DATABASE_ADD:
652 case LFUN_BIBTEX_DATABASE_DEL:
653 case LFUN_WORDS_COUNT:
654 case LFUN_NEXT_INSET_TOGGLE:
658 case LFUN_LABEL_GOTO: {
659 flag.enabled(!cmd.argument().empty()
660 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
664 case LFUN_CHANGES_TRACK:
666 flag.setOnOff(buffer_.params().trackChanges);
669 case LFUN_CHANGES_OUTPUT:
671 flag.setOnOff(buffer_.params().outputChanges);
674 case LFUN_CHANGES_MERGE:
675 case LFUN_CHANGE_NEXT:
676 case LFUN_ALL_CHANGES_ACCEPT:
677 case LFUN_ALL_CHANGES_REJECT:
678 // TODO: context-sensitive enabling of LFUNs
679 // In principle, these command should only be enabled if there
680 // is a change in the document. However, without proper
681 // optimizations, this will inevitably result in poor performance.
685 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
686 flag.setOnOff(buffer_.params().compressed);
691 case LFUN_SCREEN_DOWN:
695 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
696 // everywhere else before this can enabled:
697 case LFUN_SCREEN_UP_SELECT:
698 case LFUN_SCREEN_DOWN_SELECT:
710 Update::flags BufferView::dispatch(FuncRequest const & cmd)
712 //lyxerr << BOOST_CURRENT_FUNCTION
713 // << [ cmd = " << cmd << "]" << endl;
715 // Make sure that the cached BufferView is correct.
716 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
717 << " action[" << cmd.action << ']'
718 << " arg[" << to_utf8(cmd.argument()) << ']'
719 << " x[" << cmd.x << ']'
720 << " y[" << cmd.y << ']'
721 << " button[" << cmd.button() << ']'
724 Cursor & cur = cursor_;
725 // Default Update flags.
726 Update::flags updateFlags = Update::Force | Update::FitCursor;
728 switch (cmd.action) {
731 cur.message(_("Undo"));
732 cur.clearSelection();
733 if (!textUndo(*this)) {
734 cur.message(_("No further undo information"));
735 updateFlags = Update::None;
740 cur.message(_("Redo"));
741 cur.clearSelection();
742 if (!textRedo(*this)) {
743 cur.message(_("No further redo information"));
744 updateFlags = Update::None;
748 case LFUN_FILE_INSERT:
750 menuInsertLyXFile(to_utf8(cmd.argument()));
753 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
755 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
758 case LFUN_FILE_INSERT_PLAINTEXT:
760 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
763 case LFUN_FONT_STATE:
764 cur.message(cur.currentState());
767 case LFUN_BOOKMARK_SAVE:
768 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
771 case LFUN_LABEL_GOTO: {
772 docstring label = cmd.argument();
775 getInsetByCode<InsetRef>(cursor_,
778 label = inset->getParam("reference");
779 // persistent=false: use temp_bookmark
789 case LFUN_PARAGRAPH_GOTO: {
790 int const id = convert<int>(to_utf8(cmd.argument()));
792 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
793 b = theBufferList().next(b)) {
795 ParIterator par = b->getParFromID(id);
796 if (par == b->par_iterator_end()) {
798 << "No matching paragraph found! ["
799 << id << "]." << endl;
802 << "Paragraph " << par->id()
803 << " found in buffer `"
804 << b->fileName() << "'." << endl;
808 setCursor(makeDocIterator(par, 0));
810 // Switch to other buffer view and resend cmd
811 theLyXFunc().dispatch(FuncRequest(
812 LFUN_BUFFER_SWITCH, b->fileName()));
813 theLyXFunc().dispatch(cmd);
814 updateFlags = Update::None;
823 case LFUN_OUTLINE_UP:
824 toc::outline(toc::Up, cursor_);
825 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
826 updateLabels(buffer_);
828 case LFUN_OUTLINE_DOWN:
829 toc::outline(toc::Down, cursor_);
830 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
831 updateLabels(buffer_);
833 case LFUN_OUTLINE_IN:
834 toc::outline(toc::In, cursor_);
835 updateLabels(buffer_);
837 case LFUN_OUTLINE_OUT:
838 toc::outline(toc::Out, cursor_);
839 updateLabels(buffer_);
843 gotoInset(this, Inset::NOTE_CODE, false);
846 case LFUN_REFERENCE_NEXT: {
847 vector<Inset_code> tmp;
848 tmp.push_back(Inset::LABEL_CODE);
849 tmp.push_back(Inset::REF_CODE);
850 gotoInset(this, tmp, true);
854 case LFUN_CHANGES_TRACK:
855 buffer_.params().trackChanges = !buffer_.params().trackChanges;
858 case LFUN_CHANGES_OUTPUT:
859 buffer_.params().outputChanges = !buffer_.params().outputChanges;
860 if (buffer_.params().outputChanges) {
861 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
862 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
863 LaTeXFeatures::isAvailable("xcolor");
865 if (!dvipost && !xcolorsoul) {
866 Alert::warning(_("Changes not shown in LaTeX output"),
867 _("Changes will not be highlighted in LaTeX output, "
868 "because neither dvipost nor xcolor/soul are installed.\n"
869 "Please install these packages or redefine "
870 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
871 } else if (!xcolorsoul) {
872 Alert::warning(_("Changes not shown in LaTeX output"),
873 _("Changes will not be highlighted in LaTeX output "
874 "when using pdflatex, because xcolor and soul are not installed.\n"
875 "Please install both packages or redefine "
876 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
881 case LFUN_CHANGE_NEXT:
882 findNextChange(this);
885 case LFUN_CHANGES_MERGE:
886 if (findNextChange(this))
887 showDialog("changes");
890 case LFUN_ALL_CHANGES_ACCEPT:
891 // select complete document
892 cursor_.reset(buffer_.inset());
893 cursor_.selHandle(true);
894 buffer_.text().cursorBottom(cursor_);
895 // accept everything in a single step to support atomic undo
896 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
899 case LFUN_ALL_CHANGES_REJECT:
900 // select complete document
901 cursor_.reset(buffer_.inset());
902 cursor_.selHandle(true);
903 buffer_.text().cursorBottom(cursor_);
904 // reject everything in a single step to support atomic undo
905 // Note: reject does not work recursively; the user may have to repeat the operation
906 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
913 case LFUN_WORD_REPLACE: {
914 bool has_deleted = false;
915 if (cur.selection()) {
916 DocIterator beg = cur.selectionBegin();
917 DocIterator end = cur.selectionEnd();
918 if (beg.pit() == end.pit()) {
919 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
920 if (cur.paragraph().isDeleted(p))
925 replace(this, cmd, has_deleted);
930 cur.clearSelection();
932 cur.message(from_utf8(N_("Mark off")));
936 cur.clearSelection();
939 cur.message(from_utf8(N_("Mark on")));
942 case LFUN_MARK_TOGGLE:
943 cur.clearSelection();
946 cur.message(from_utf8(N_("Mark removed")));
949 cur.message(from_utf8(N_("Mark set")));
954 case LFUN_SCREEN_RECENTER:
958 case LFUN_BIBTEX_DATABASE_ADD: {
959 Cursor tmpcur = cursor_;
960 findInset(tmpcur, Inset::BIBTEX_CODE, false);
961 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
964 if (inset->addDatabase(to_utf8(cmd.argument())))
965 buffer_.updateBibfilesCache();
970 case LFUN_BIBTEX_DATABASE_DEL: {
971 Cursor tmpcur = cursor_;
972 findInset(tmpcur, Inset::BIBTEX_CODE, false);
973 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
976 if (inset->delDatabase(to_utf8(cmd.argument())))
977 buffer_.updateBibfilesCache();
982 case LFUN_WORDS_COUNT: {
983 DocIterator from, to;
984 if (cur.selection()) {
985 from = cur.selectionBegin();
986 to = cur.selectionEnd();
988 from = doc_iterator_begin(buffer_.inset());
989 to = doc_iterator_end(buffer_.inset());
991 int const count = countWords(from, to);
995 message = bformat(_("%1$d words in selection."),
998 message = bformat(_("%1$d words in document."),
1002 if (cur.selection())
1003 message = _("One word in selection.");
1005 message = _("One word in document.");
1008 Alert::information(_("Count words"), message);
1012 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1013 // turn compression on/off
1014 buffer_.params().compressed = !buffer_.params().compressed;
1017 case LFUN_NEXT_INSET_TOGGLE: {
1018 // this is the real function we want to invoke
1019 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1020 // if there is an inset at cursor, see whether it
1022 Inset * inset = cur.nextInset();
1024 if (inset->isActive()) {
1025 Cursor tmpcur = cur;
1026 tmpcur.pushLeft(*inset);
1027 inset->dispatch(tmpcur, tmpcmd);
1028 if (tmpcur.result().dispatched()) {
1031 } else if (inset->editable() == Inset::IS_EDITABLE) {
1032 inset->edit(cur, true);
1035 // if it did not work, try the underlying inset.
1036 if (!cur.result().dispatched())
1037 cur.dispatch(tmpcmd);
1039 if (cur.result().dispatched())
1040 cur.clearSelection();
1045 case LFUN_SCREEN_UP:
1046 case LFUN_SCREEN_DOWN: {
1047 Point p = bv_funcs::getPos(*this, cur, cur.boundary());
1048 if (p.y_ < 0 || p.y_ > height_) {
1049 // The cursor is off-screen so recenter before proceeding.
1051 updateMetrics(false);
1052 //FIXME: updateMetrics() does not update paragraph position
1053 // This is done at draw() time. So we need a redraw!
1055 p = bv_funcs::getPos(*this, cur, cur.boundary());
1057 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1058 cur.reset(buffer_.inset());
1059 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1060 //FIXME: what to do with cur.x_target()?
1062 // The metrics are already up to date. see scroll()
1063 updateFlags = Update::None;
1067 case LFUN_SCREEN_UP_SELECT:
1068 case LFUN_SCREEN_DOWN_SELECT: {
1069 cur.selHandle(true);
1070 size_t initial_depth = cur.depth();
1071 Point const p = bv_funcs::getPos(*this, cur, cur.boundary());
1072 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1073 // FIXME: We need to verify if the cursor stayed within an inset...
1074 //cur.reset(buffer_.inset());
1075 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1077 while (cur.depth() > initial_depth) {
1080 // FIXME: we need to do a redraw again because of the selection
1082 updateFlags = Update::Force | Update::FitCursor;
1087 updateFlags = Update::None;
1094 docstring const BufferView::requestSelection()
1096 Cursor & cur = cursor_;
1098 if (!cur.selection()) {
1099 xsel_cache_.set = false;
1103 if (!xsel_cache_.set ||
1104 cur.top() != xsel_cache_.cursor ||
1105 cur.anchor_.top() != xsel_cache_.anchor)
1107 xsel_cache_.cursor = cur.top();
1108 xsel_cache_.anchor = cur.anchor_.top();
1109 xsel_cache_.set = cur.selection();
1110 return cur.selectionAsString(false);
1116 void BufferView::clearSelection()
1118 cursor_.clearSelection();
1119 // Clear the selection buffer. Otherwise a subsequent
1120 // middle-mouse-button paste would use the selection buffer,
1121 // not the more current external selection.
1122 cap::clearSelection();
1123 xsel_cache_.set = false;
1124 // The buffer did not really change, but this causes the
1125 // redraw we need because we cleared the selection above.
1130 void BufferView::resize(int width, int height)
1132 // Update from work area
1136 updateMetrics(false);
1140 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1142 TextMetrics & tm = text_metrics_[&text];
1143 Inset * inset = tm.checkInsetHit(x, y);
1147 if (!inset->descendable())
1148 // No need to go further down if the inset is not
1152 size_t cell_number = inset->nargs();
1153 // Check all the inner cell.
1154 for (size_t i = 0; i != cell_number; ++i) {
1155 Text const * inner_text = inset->getText(i);
1158 Inset const * inset_deeper =
1159 getCoveringInset(*inner_text, x, y);
1161 return inset_deeper;
1169 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1171 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1173 // This is only called for mouse related events including
1174 // LFUN_FILE_OPEN generated by drag-and-drop.
1175 FuncRequest cmd = cmd0;
1178 cur.push(buffer_.inset());
1179 cur.selection() = cursor_.selection();
1181 // Either the inset under the cursor or the
1182 // surrounding Text will handle this event.
1184 // make sure we stay within the screen...
1185 cmd.y = min(max(cmd.y, -1), height_);
1187 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1189 // Get inset under mouse, if there is one.
1190 Inset const * covering_inset =
1191 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1192 if (covering_inset == last_inset_)
1193 // Same inset, no need to do anything...
1196 bool need_redraw = false;
1197 // const_cast because of setMouseHover().
1198 Inset * inset = const_cast<Inset *>(covering_inset);
1200 // Remove the hint on the last hovered inset (if any).
1201 need_redraw |= last_inset_->setMouseHover(false);
1203 // Highlighted the newly hovered inset (if any).
1204 need_redraw |= inset->setMouseHover(true);
1205 last_inset_ = inset;
1209 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1210 // not expose the button for redraw. We adjust here the metrics dimension
1211 // to enable a full redraw in any case as this is not costly.
1212 TextMetrics & tm = text_metrics_[&buffer_.text()];
1213 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1214 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1215 int y1 = firstpm.second->position() - firstpm.second->ascent();
1216 int y2 = lastpm.second->position() + lastpm.second->descent();
1217 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1218 FullScreenUpdate, buffer_.text().paragraphs().size());
1219 // Reinitialize anchor to first pit.
1220 anchor_ref_ = firstpm.first;
1222 LYXERR(Debug::PAINTING)
1223 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1224 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1225 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1227 // This event (moving without mouse click) is not passed further.
1228 // This should be changed if it is further utilized.
1232 // Build temporary cursor.
1233 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1235 // Put anchor at the same position.
1238 // Try to dispatch to an non-editable inset near this position
1239 // via the temp cursor. If the inset wishes to change the real
1240 // cursor it has to do so explicitly by using
1241 // cur.bv().cursor() = cur; (or similar)
1243 inset->dispatch(cur, cmd);
1246 // Now dispatch to the temporary cursor. If the real cursor should
1247 // be modified, the inset's dispatch has to do so explicitly.
1248 if (!cur.result().dispatched())
1251 //Do we have a selection?
1252 theSelection().haveSelection(cursor().selection());
1254 // Redraw if requested and necessary.
1255 if (cur.result().dispatched() && cur.result().update())
1256 return update(cur.result().update());
1262 void BufferView::scroll(int y)
1271 void BufferView::scrollDown(int offset)
1273 Text * text = &buffer_.text();
1274 TextMetrics & tm = text_metrics_[text];
1275 int ymax = height_ + offset;
1277 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1278 int bottom_pos = last.second->position() + last.second->descent();
1279 if (last.first + 1 == int(text->paragraphs().size())) {
1280 if (bottom_pos <= height_)
1282 offset = min(offset, bottom_pos - height_);
1285 if (bottom_pos > ymax)
1287 tm.newParMetricsDown();
1289 offset_ref_ += offset;
1290 updateMetrics(false);
1295 void BufferView::scrollUp(int offset)
1297 Text * text = &buffer_.text();
1298 TextMetrics & tm = text_metrics_[text];
1299 int ymin = - offset;
1301 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1302 int top_pos = first.second->position() - first.second->ascent();
1303 if (first.first == 0) {
1306 offset = min(offset, - top_pos);
1311 tm.newParMetricsUp();
1313 offset_ref_ -= offset;
1314 updateMetrics(false);
1319 void BufferView::setCursorFromRow(int row)
1324 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1326 cursor_.reset(buffer_.inset());
1328 buffer_.text().setCursor(cursor_, 0, 0);
1330 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1334 void BufferView::gotoLabel(docstring const & label)
1336 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1337 vector<docstring> labels;
1338 it->getLabelList(buffer_, labels);
1339 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1348 TextMetrics const & BufferView::textMetrics(Text const * t) const
1350 return const_cast<BufferView *>(this)->textMetrics(t);
1354 TextMetrics & BufferView::textMetrics(Text const * t)
1356 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1357 if (tmc_it == text_metrics_.end()) {
1358 tmc_it = text_metrics_.insert(
1359 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1361 return tmc_it->second;
1365 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1368 return textMetrics(t).parMetrics(pit);
1372 int BufferView::workHeight() const
1378 void BufferView::setCursor(DocIterator const & dit)
1380 size_t const n = dit.depth();
1381 for (size_t i = 0; i < n; ++i)
1382 dit[i].inset().edit(cursor_, true);
1384 cursor_.setCursor(dit);
1385 cursor_.selection() = false;
1389 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1391 // Would be wrong to delete anything if we have a selection.
1392 if (cur.selection())
1395 bool need_anchor_change = false;
1396 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1397 need_anchor_change);
1399 if (need_anchor_change)
1405 updateLabels(buffer_);
1407 updateMetrics(false);
1413 bool BufferView::mouseSetCursor(Cursor & cur)
1415 BOOST_ASSERT(&cur.bv() == this);
1417 // this event will clear selection so we save selection for
1418 // persistent selection
1419 cap::saveSelection(cursor());
1421 // Has the cursor just left the inset?
1422 bool badcursor = false;
1423 bool leftinset = (&cursor_.inset() != &cur.inset());
1425 badcursor = notifyCursorLeaves(cursor_, cur);
1427 // do the dEPM magic if needed
1428 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1429 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1430 // the leftinset bool would not be necessary (badcursor instead).
1431 bool update = leftinset;
1432 if (!badcursor && cursor_.inTexted())
1433 update |= checkDepm(cur, cursor_);
1435 // if the cursor was in an empty script inset and the new
1436 // position is in the nucleus of the inset, notifyCursorLeaves
1437 // will kill the script inset itself. So we check all the
1438 // elements of the cursor to make sure that they are correct.
1439 // For an example, see bug 2933:
1440 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1441 // The code below could maybe be moved to a DocIterator method.
1442 //lyxerr << "cur before " << cur <<std::endl;
1443 DocIterator dit(cur.inset());
1444 dit.push_back(cur.bottom());
1446 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1447 dit.push_back(cur[i]);
1450 //lyxerr << "5 cur after" << dit <<std::endl;
1452 cursor_.setCursor(dit);
1453 cursor_.boundary(cur.boundary());
1454 cursor_.clearSelection();
1460 void BufferView::putSelectionAt(DocIterator const & cur,
1461 int length, bool backwards)
1463 cursor_.clearSelection();
1469 cursor_.pos() += length;
1470 cursor_.setSelection(cursor_, -length);
1472 cursor_.setSelection(cursor_, length);
1477 Cursor & BufferView::cursor()
1483 Cursor const & BufferView::cursor() const
1489 pit_type BufferView::anchor_ref() const
1495 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1497 return metrics_info_;
1501 bool BufferView::singleParUpdate()
1503 Text & buftext = buffer_.text();
1504 pit_type const bottom_pit = cursor_.bottom().pit();
1505 TextMetrics & tm = textMetrics(&buftext);
1506 int old_height = tm.parMetrics(bottom_pit).height();
1508 // In Single Paragraph mode, rebreak only
1509 // the (main text, not inset!) paragraph containing the cursor.
1510 // (if this paragraph contains insets etc., rebreaking will
1511 // recursively descend)
1512 tm.redoParagraph(bottom_pit);
1513 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1514 if (pm.height() != old_height)
1515 // Paragraph height has changed so we cannot proceed to
1516 // the singlePar optimisation.
1519 int y1 = pm.position() - pm.ascent();
1520 int y2 = pm.position() + pm.descent();
1521 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1522 SingleParUpdate, buftext.paragraphs().size());
1523 LYXERR(Debug::PAINTING)
1524 << BOOST_CURRENT_FUNCTION
1527 << " pit: " << bottom_pit
1534 void BufferView::updateMetrics(bool singlepar)
1536 if (singlepar && singleParUpdate())
1537 // No need to update the full screen metrics.
1540 Text & buftext = buffer_.text();
1541 pit_type const npit = int(buftext.paragraphs().size());
1543 if (anchor_ref_ > int(npit - 1)) {
1544 anchor_ref_ = int(npit - 1);
1548 // Clear out the position cache in case of full screen redraw,
1549 coord_cache_.clear();
1551 // Clear out paragraph metrics to avoid having invalid metrics
1552 // in the cache from paragraphs not relayouted below
1553 // The complete text metrics will be redone.
1554 text_metrics_.clear();
1556 TextMetrics & tm = textMetrics(&buftext);
1558 pit_type const pit = anchor_ref_;
1562 // Rebreak anchor paragraph.
1563 tm.redoParagraph(pit);
1565 // Take care of anchor offset if case a recentering is needed.
1568 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1570 // Redo paragraphs above anchor if necessary.
1572 while (y1 > 0 && pit1 > 0) {
1573 y1 -= tm.parMetrics(pit1).ascent();
1575 tm.redoParagraph(pit1);
1576 y1 -= tm.parMetrics(pit1).descent();
1579 // Take care of ascent of first line
1580 y1 -= tm.parMetrics(pit1).ascent();
1582 // Normalize anchor for next time
1586 // Grey at the beginning is ugly
1587 if (pit1 == 0 && y1 > 0) {
1593 // Redo paragraphs below the anchor if necessary.
1595 while (y2 < height_ && pit2 < int(npit) - 1) {
1596 y2 += tm.parMetrics(pit2).descent();
1598 tm.redoParagraph(pit2);
1599 y2 += tm.parMetrics(pit2).ascent();
1602 // Take care of descent of last line
1603 y2 += tm.parMetrics(pit2).descent();
1605 LYXERR(Debug::PAINTING)
1606 << BOOST_CURRENT_FUNCTION
1609 << " pit1: " << pit1
1610 << " pit2: " << pit2
1611 << " npit: " << npit
1615 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1616 FullScreenUpdate, npit);
1618 if (lyxerr.debugging(Debug::WORKAREA)) {
1619 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1620 coord_cache_.dump();
1625 void BufferView::menuInsertLyXFile(string const & filenm)
1627 BOOST_ASSERT(cursor_.inTexted());
1628 string filename = filenm;
1630 if (filename.empty()) {
1631 // Launch a file browser
1633 string initpath = lyxrc.document_path;
1634 string const trypath = buffer_.filePath();
1635 // If directory is writeable, use this as default.
1636 if (isDirWriteable(FileName(trypath)))
1640 FileDialog fileDlg(_("Select LyX document to insert"),
1642 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1643 make_pair(_("Examples|#E#e"),
1644 from_utf8(addPath(package().system_support().absFilename(),
1647 FileDialog::Result result =
1648 fileDlg.open(from_utf8(initpath),
1649 FileFilterList(_("LyX Documents (*.lyx)")),
1652 if (result.first == FileDialog::Later)
1656 filename = to_utf8(result.second);
1658 // check selected filename
1659 if (filename.empty()) {
1660 // emit message signal.
1661 message(_("Canceled."));
1666 // Get absolute path of file and add ".lyx"
1667 // to the filename if necessary
1668 filename = fileSearch(string(), filename, "lyx").absFilename();
1670 docstring const disp_fn = makeDisplayPath(filename);
1671 // emit message signal.
1672 message(bformat(_("Inserting document %1$s..."), disp_fn));
1675 Buffer buf("", false);
1676 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1677 ErrorList & el = buffer_.errorList("Parse");
1678 // Copy the inserted document error list into the current buffer one.
1679 el = buf.errorList("Parse");
1680 recordUndo(cursor_);
1681 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1682 buf.params().getTextClassPtr(), el);
1683 res = _("Document %1$s inserted.");
1685 res = _("Could not insert document %1$s");
1687 // emit message signal.
1688 message(bformat(res, disp_fn));
1689 buffer_.errors("Parse");
1690 updateMetrics(false);
1694 void BufferView::draw(frontend::Painter & pain)
1696 PainterInfo pi(this, pain);
1697 // Should the whole screen, including insets, be refreshed?
1698 // FIXME: We should also distinguish DecorationUpdate to avoid text
1699 // drawing if possible. This is not possible to do easily right now
1700 // because of the single backing pixmap.
1701 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1703 if (pi.full_repaint)
1704 // Clear background (if not delegated to rows)
1705 pain.fillRectangle(0, metrics_info_.y1, width_,
1706 metrics_info_.y2 - metrics_info_.y1,
1707 buffer_.inset().backgroundColor());
1709 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1710 Text & text = buffer_.text();
1711 TextMetrics const & tm = text_metrics_[&text];
1712 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1713 if (!pi.full_repaint)
1714 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1717 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1719 // and grey out above (should not happen later)
1720 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1721 if (metrics_info_.y1 > 0
1722 && metrics_info_.update_strategy == FullScreenUpdate)
1723 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1725 // and possibly grey out below
1726 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1727 if (metrics_info_.y2 < height_
1728 && metrics_info_.update_strategy == FullScreenUpdate)
1729 pain.fillRectangle(0, metrics_info_.y2, width_,
1730 height_ - metrics_info_.y2, Color::bottomarea);