]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
move the catInit call around
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetOptArg.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "InsetList.h"
30 #include "Intl.h"
31 #include "Lexer.h"
32 #include "lyxfind.h"
33 #include "LyXRC.h"
34 #include "MetricsInfo.h"
35 #include "output_docbook.h"
36 #include "output_latex.h"
37 #include "OutputParams.h"
38 #include "output_plaintext.h"
39 #include "paragraph_funcs.h"
40 #include "Paragraph.h"
41 #include "ParagraphParameters.h"
42 #include "ParIterator.h"
43 #include "Row.h"
44 #include "sgml.h"
45 #include "TexRow.h"
46 #include "TextClass.h"
47 #include "Text.h"
48 #include "TextMetrics.h"
49 #include "TocBackend.h"
50
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
53
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57
58 #include <boost/bind.hpp>
59 #include "support/lassert.h"
60
61 using namespace std;
62 using namespace lyx::support;
63
64 using boost::bind;
65 using boost::ref;
66
67 namespace lyx {
68
69 using graphics::PreviewLoader;
70
71
72 /////////////////////////////////////////////////////////////////////
73
74 InsetText::InsetText(Buffer const & buf)
75         : drawFrame_(false), frame_color_(Color_insetframe)
76 {
77         setBuffer(const_cast<Buffer &>(buf));
78         initParagraphs();
79 }
80
81
82 InsetText::InsetText(InsetText const & in)
83         : Inset(in), text_()
84 {
85         text_.autoBreakRows_ = in.text_.autoBreakRows_;
86         drawFrame_ = in.drawFrame_;
87         frame_color_ = in.frame_color_;
88         text_.paragraphs() = in.text_.paragraphs();
89         setParagraphOwner();
90 }
91
92
93 void InsetText::setBuffer(Buffer & buf)
94 {
95         ParagraphList::iterator end = paragraphs().end();
96         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
97                 it->setBuffer(buf);
98         Inset::setBuffer(buf);
99 }
100
101
102 void InsetText::initParagraphs()
103 {
104         LASSERT(paragraphs().empty(), /**/);
105         paragraphs().push_back(Paragraph());
106         Paragraph & ourpar = paragraphs().back();
107         ourpar.setInsetOwner(this);
108         ourpar.setDefaultLayout(buffer_->params().documentClass());
109 }
110
111
112 void InsetText::setParagraphOwner()
113 {
114         for_each(paragraphs().begin(), paragraphs().end(),
115                  bind(&Paragraph::setInsetOwner, _1, this));
116 }
117
118
119 void InsetText::clear()
120 {
121         ParagraphList & pars = paragraphs();
122         LASSERT(!pars.empty(), /**/);
123
124         // This is a gross hack...
125         Layout const & old_layout = pars.begin()->layout();
126
127         pars.clear();
128         pars.push_back(Paragraph());
129         pars.begin()->setInsetOwner(this);
130         pars.begin()->setLayout(old_layout);
131 }
132
133
134 Dimension const InsetText::dimension(BufferView const & bv) const
135 {
136         TextMetrics const & tm = bv.textMetrics(&text_);
137         Dimension dim = tm.dimension();
138         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
139         dim.des += TEXT_TO_INSET_OFFSET;
140         dim.asc += TEXT_TO_INSET_OFFSET;
141         return dim;
142 }
143
144
145 void InsetText::write(ostream & os) const
146 {
147         os << "Text\n";
148         text_.write(buffer(), os);
149 }
150
151
152 void InsetText::read(Lexer & lex)
153 {
154         clear();
155
156         // delete the initial paragraph
157         Paragraph oldpar = *paragraphs().begin();
158         paragraphs().clear();
159         ErrorList errorList;
160         lex.setContext("InsetText::read");
161         bool res = text_.read(buffer(), lex, errorList, this);
162
163         if (!res)
164                 lex.printError("Missing \\end_inset at this point. ");
165
166         // sanity check
167         // ensure we have at least one paragraph.
168         if (paragraphs().empty())
169                 paragraphs().push_back(oldpar);
170 }
171
172
173 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
174 {
175         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
176
177         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
178
179         // Hand font through to contained lyxtext:
180         tm.font_.fontInfo() = mi.base.font;
181         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
182         if (hasFixedWidth())
183                 tm.metrics(mi, dim, mi.base.textwidth);
184         else
185                 tm.metrics(mi, dim);
186         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
187         dim.asc += TEXT_TO_INSET_OFFSET;
188         dim.des += TEXT_TO_INSET_OFFSET;
189         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
190 }
191
192
193 void InsetText::draw(PainterInfo & pi, int x, int y) const
194 {
195         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
196
197         if (drawFrame_ || pi.full_repaint) {
198                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
199                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
200                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
201                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
202                 if (pi.full_repaint)
203                         pi.pain.fillRectangle(xframe, yframe, w, h,
204                                 pi.backgroundColor(this));
205
206                 if (drawFrame_)
207                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
208         }
209         ColorCode const old_color = pi.background_color;
210         pi.background_color = pi.backgroundColor(this, false);
211
212         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
213
214         pi.background_color = old_color;
215 }
216
217
218 docstring InsetText::editMessage() const
219 {
220         return _("Opened Text Inset");
221 }
222
223
224 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
225 {
226         pit_type const pit = front ? 0 : paragraphs().size() - 1;
227         pos_type pos = front ? 0 : paragraphs().back().size();
228
229         // if visual information is not to be ignored, move to extreme right/left
230         if (entry_from != ENTRY_DIRECTION_IGNORE) {
231                 Cursor temp_cur = cur;
232                 temp_cur.pit() = pit;
233                 temp_cur.pos() = pos;
234                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
235                 pos = temp_cur.pos();
236         }
237
238         text_.setCursor(cur.top(), pit, pos);
239         cur.clearSelection();
240         cur.finishUndo();
241 }
242
243
244 Inset * InsetText::editXY(Cursor & cur, int x, int y)
245 {
246         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
247 }
248
249
250 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
251 {
252         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
253                 << " [ cmd.action = " << cmd.action << ']');
254         text_.dispatch(cur, cmd);
255 }
256
257
258 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
259         FuncStatus & status) const
260 {
261         switch (cmd.action) {
262         case LFUN_LAYOUT:
263                 status.setEnabled(!forcePlainLayout());
264                 return true;
265
266         case LFUN_LAYOUT_PARAGRAPH:
267         case LFUN_PARAGRAPH_PARAMS:
268         case LFUN_PARAGRAPH_PARAMS_APPLY:
269         case LFUN_PARAGRAPH_SPACING:
270         case LFUN_PARAGRAPH_UPDATE:
271                 status.setEnabled(allowParagraphCustomization());
272                 return true;
273         default:
274                 return text_.getStatus(cur, cmd, status);
275         }
276 }
277
278
279 void InsetText::setChange(Change const & change)
280 {
281         ParagraphList::iterator pit = paragraphs().begin();
282         ParagraphList::iterator end = paragraphs().end();
283         for (; pit != end; ++pit) {
284                 pit->setChange(change);
285         }
286 }
287
288
289 void InsetText::acceptChanges(BufferParams const & bparams)
290 {
291         text_.acceptChanges(bparams);
292 }
293
294
295 void InsetText::rejectChanges(BufferParams const & bparams)
296 {
297         text_.rejectChanges(bparams);
298 }
299
300
301 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
302 {
303         TexRow texrow;
304         latexParagraphs(buffer(), text_, os, texrow, runparams);
305         return texrow.rows();
306 }
307
308
309 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
310 {
311         ParagraphList::const_iterator beg = paragraphs().begin();
312         ParagraphList::const_iterator end = paragraphs().end();
313         ParagraphList::const_iterator it = beg;
314         bool ref_printed = false;
315         int len = 0;
316         for (; it != end; ++it) {
317                 if (it != beg) {
318                         os << '\n';
319                         if (runparams.linelen > 0)
320                                 os << '\n';
321                 }
322                 odocstringstream oss;
323                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
324                 docstring const str = oss.str();
325                 os << str;
326                 // FIXME: len is not computed fully correctly; in principle,
327                 // we have to count the characters after the last '\n'
328                 len = str.size();
329         }
330
331         return len;
332 }
333
334
335 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
336 {
337         docbookParagraphs(paragraphs(), buffer(), os, runparams);
338         return 0;
339 }
340
341
342 void InsetText::validate(LaTeXFeatures & features) const
343 {
344         for_each(paragraphs().begin(), paragraphs().end(),
345                  bind(&Paragraph::validate, _1, ref(features)));
346 }
347
348
349 void InsetText::cursorPos(BufferView const & bv,
350                 CursorSlice const & sl, bool boundary, int & x, int & y) const
351 {
352         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
353         y = bv.textMetrics(&text_).cursorY(sl, boundary);
354 }
355
356
357 bool InsetText::showInsetDialog(BufferView *) const
358 {
359         return false;
360 }
361
362
363 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
364 {
365         clear();
366         Paragraph & first = paragraphs().front();
367         for (unsigned int i = 0; i < data.length(); ++i)
368                 first.insertChar(i, data[i], font, trackChanges);
369 }
370
371
372 void InsetText::setAutoBreakRows(bool flag)
373 {
374         if (flag == text_.autoBreakRows_)
375                 return;
376
377         text_.autoBreakRows_ = flag;
378         if (flag)
379                 return;
380
381         // remove previously existing newlines
382         ParagraphList::iterator it = paragraphs().begin();
383         ParagraphList::iterator end = paragraphs().end();
384         for (; it != end; ++it)
385                 for (int i = 0; i < it->size(); ++i)
386                         if (it->isNewline(i))
387                                 // do not track the change, because the user
388                                 // is not allowed to revert/reject it
389                                 it->eraseChar(i, false);
390 }
391
392
393 void InsetText::setDrawFrame(bool flag)
394 {
395         drawFrame_ = flag;
396 }
397
398
399 ColorCode InsetText::frameColor() const
400 {
401         return frame_color_;
402 }
403
404
405 void InsetText::setFrameColor(ColorCode col)
406 {
407         frame_color_ = col;
408 }
409
410
411 void InsetText::appendParagraphs(ParagraphList & plist)
412 {
413         // There is little we can do here to keep track of changes.
414         // As of 2006/10/20, appendParagraphs is used exclusively by
415         // LyXTabular::setMultiColumn. In this context, the paragraph break
416         // is lost irreversibly and the appended text doesn't really change
417
418         ParagraphList & pl = paragraphs();
419
420         ParagraphList::iterator pit = plist.begin();
421         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
422         ++pit;
423         mergeParagraph(buffer().params(), pl,
424                        distance(pl.begin(), ins) - 1);
425
426         for_each(pit, plist.end(),
427                  bind(&ParagraphList::push_back, ref(pl), _1));
428 }
429
430
431 void InsetText::addPreview(PreviewLoader & loader) const
432 {
433         ParagraphList::const_iterator pit = paragraphs().begin();
434         ParagraphList::const_iterator pend = paragraphs().end();
435
436         for (; pit != pend; ++pit) {
437                 InsetList::const_iterator it  = pit->insetList().begin();
438                 InsetList::const_iterator end = pit->insetList().end();
439                 for (; it != end; ++it)
440                         it->inset->addPreview(loader);
441         }
442 }
443
444
445 ParagraphList const & InsetText::paragraphs() const
446 {
447         return text_.paragraphs();
448 }
449
450
451 ParagraphList & InsetText::paragraphs()
452 {
453         return text_.paragraphs();
454 }
455
456
457 void InsetText::updateLabels(ParIterator const & it)
458 {
459         ParIterator it2 = it;
460         it2.forwardPos();
461         LASSERT(&it2.inset() == this && it2.pit() == 0, /**/);
462         if (producesOutput())
463                 lyx::updateLabels(buffer(), it2);
464         else {
465                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
466                 Counters const savecnt = tclass.counters();
467                 lyx::updateLabels(buffer(), it2);
468                 tclass.counters() = savecnt;
469         }
470 }
471
472
473 void InsetText::addToToc(DocIterator const & cdit)
474 {
475         DocIterator dit = cdit;
476         dit.push_back(CursorSlice(*this));
477         Toc & toc = buffer().tocBackend().toc("tableofcontents");
478
479         BufferParams const & bufparams = buffer_->params();
480         const int min_toclevel = bufparams.documentClass().min_toclevel();
481
482         // For each paragraph, traverse its insets and let them add
483         // their toc items
484         ParagraphList & pars = paragraphs();
485         pit_type pend = paragraphs().size();
486         for (pit_type pit = 0; pit != pend; ++pit) {
487                 Paragraph const & par = pars[pit];
488                 dit.pit() = pit;
489                 // the string that goes to the toc (could be the optarg)
490                 docstring tocstring;
491                 InsetList::const_iterator it  = par.insetList().begin();
492                 InsetList::const_iterator end = par.insetList().end();
493                 for (; it != end; ++it) {
494                         Inset & inset = *it->inset;
495                         dit.pos() = it->pos;
496                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
497                         inset.addToToc(dit);
498                         switch (inset.lyxCode()) {
499                         case OPTARG_CODE: {
500                                 if (!tocstring.empty())
501                                         break;
502                                 dit.pos() = 0;
503                                 Paragraph const & insetpar =
504                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
505                                 if (!par.labelString().empty())
506                                         tocstring = par.labelString() + ' ';
507                                 tocstring += insetpar.asString(AS_STR_INSETS);
508                                 break;
509                         }
510                         default:
511                                 break;
512                         }
513                 }
514                 /// now the toc entry for the paragraph
515                 int const toclevel = par.layout().toclevel;
516                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
517                         dit.pos() = 0;
518                         // insert this into the table of contents
519                         if (tocstring.empty())
520                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
521                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
522                 }
523                 
524                 // And now the list of changes.
525                 par.addChangesToToc(dit, buffer());
526         }
527 }
528
529
530 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
531 {
532         if (cur.buffer().isClean())
533                 return Inset::notifyCursorLeaves(old, cur);
534         
535         // find text inset in old cursor
536         Cursor insetCur = old;
537         int scriptSlice = insetCur.find(this);
538         LASSERT(scriptSlice != -1, /**/);
539         insetCur.cutOff(scriptSlice);
540         LASSERT(&insetCur.inset() == this, /**/);
541         
542         // update the old paragraph's words
543         insetCur.paragraph().updateWords(insetCur.top());
544         
545         return Inset::notifyCursorLeaves(old, cur);
546 }
547
548
549 bool InsetText::completionSupported(Cursor const & cur) const
550 {
551         Cursor const & bvCur = cur.bv().cursor();
552         if (&bvCur.inset() != this)
553                 return false;
554         return text_.completionSupported(cur);
555 }
556
557
558 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
559 {
560         return completionSupported(cur);
561 }
562
563
564 bool InsetText::automaticInlineCompletion() const
565 {
566         return lyxrc.completion_inline_text;
567 }
568
569
570 bool InsetText::automaticPopupCompletion() const
571 {
572         return lyxrc.completion_popup_text;
573 }
574
575
576 bool InsetText::showCompletionCursor() const
577 {
578         return lyxrc.completion_cursor_text;
579 }
580
581
582 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
583 {
584         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
585 }
586
587
588 docstring InsetText::completionPrefix(Cursor const & cur) const
589 {
590         if (!completionSupported(cur))
591                 return docstring();
592         return text_.completionPrefix(cur);
593 }
594
595
596 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
597         bool finished)
598 {
599         if (!completionSupported(cur))
600                 return false;
601
602         return text_.insertCompletion(cur, s, finished);
603 }
604
605
606 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
607         Dimension & dim) const
608 {
609         TextMetrics const & tm = cur.bv().textMetrics(&text_);
610         tm.completionPosAndDim(cur, x, y, dim);
611 }
612
613
614 docstring InsetText::contextMenu(BufferView const &, int, int) const
615 {
616         return from_ascii("context-edit");
617 }
618
619
620 } // namespace lyx