]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
* Painter.h:
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "buffer.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "dociterator.h"
20 #include "counters.h"
21 #include "errorlist.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "gettext.h"
25 #include "language.h"
26 #include "LaTeX.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
33 #include "lyxvc.h"
34 #include "texrow.h"
35 #include "vc-backend.h"
36 #include "toc.h"
37
38 #include "frontends/Alert.h"
39
40 #include "insets/insetbibitem.h"
41
42 #include "support/filetools.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
45
46 #include <iostream>
47
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
50
51
52 namespace lyx {
53
54 using namespace std;
55
56 using support::bformat;
57 using support::libFileSearch;
58 using support::makeDisplayPath;
59 using support::onlyFilename;
60 using support::onlyPath;
61 using support::unlink;
62
63 using std::min;
64 using std::string;
65
66 namespace Alert = frontend::Alert;
67 namespace fs = boost::filesystem;
68
69 namespace {
70
71 bool readFile(Buffer * const b, string const & s)
72 {
73         BOOST_ASSERT(b);
74
75         // File information about normal file
76         if (!fs::exists(s)) {
77                 docstring const file = makeDisplayPath(s, 50);
78                 docstring text = bformat(_("The specified document\n%1$s"
79                                                      "\ncould not be read."), file);
80                 Alert::error(_("Could not read document"), text);
81                 return false;
82         }
83
84         // Check if emergency save file exists and is newer.
85         string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
86
87         if (fs::exists(e) && fs::exists(s)
88             && fs::last_write_time(e) > fs::last_write_time(s))
89         {
90                 docstring const file = makeDisplayPath(s, 20);
91                 docstring const text =
92                         bformat(_("An emergency save of the document "
93                                   "%1$s exists.\n\n"
94                                                "Recover emergency save?"), file);
95                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
96                                       _("&Recover"),  _("&Load Original"),
97                                       _("&Cancel")))
98                 {
99                 case 0:
100                         // the file is not saved if we load the emergency file.
101                         b->markDirty();
102                         return b->readFile(e);
103                 case 1:
104                         break;
105                 default:
106                         return false;
107                 }
108         }
109
110         // Now check if autosave file is newer.
111         string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
112
113         if (fs::exists(a) && fs::exists(s)
114             && fs::last_write_time(a) > fs::last_write_time(s))
115         {
116                 docstring const file = makeDisplayPath(s, 20);
117                 docstring const text =
118                         bformat(_("The backup of the document "
119                                   "%1$s is newer.\n\nLoad the "
120                                                "backup instead?"), file);
121                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
122                                       _("&Load backup"), _("Load &original"),
123                                       _("&Cancel") ))
124                 {
125                 case 0:
126                         // the file is not saved if we load the autosave file.
127                         b->markDirty();
128                         return b->readFile(a);
129                 case 1:
130                         // Here we delete the autosave
131                         unlink(a);
132                         break;
133                 default:
134                         return false;
135                 }
136         }
137         return b->readFile(s);
138 }
139
140
141 } // namespace anon
142
143
144
145 bool loadLyXFile(Buffer * b, string const & s)
146 {
147         BOOST_ASSERT(b);
148
149         if (fs::is_readable(s)) {
150                 if (readFile(b, s)) {
151                         b->lyxvc().file_found_hook(s);
152                         if (!fs::is_writable(s))
153                                 b->setReadonly(true);
154                         return true;
155                 }
156         } else {
157                 docstring const file = makeDisplayPath(s, 20);
158                 // Here we probably should run
159                 if (LyXVC::file_not_found_hook(s)) {
160                         docstring const text =
161                                 bformat(_("Do you want to retrieve the document"
162                                                        " %1$s from version control?"), file);
163                         int const ret = Alert::prompt(_("Retrieve from version control?"),
164                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
165
166                         if (ret == 0) {
167                                 // How can we know _how_ to do the checkout?
168                                 // With the current VC support it has to be,
169                                 // a RCS file since CVS do not have special ,v files.
170                                 RCS::retrieve(s);
171                                 return loadLyXFile(b, s);
172                         }
173                 }
174         }
175         return false;
176 }
177
178 // FIXME newFile() should probably be a member method of Application...
179 Buffer * newFile(string const & filename, string const & templatename,
180                  bool const isNamed)
181 {
182         // get a free buffer
183         Buffer * b = theBufferList().newBuffer(filename);
184         BOOST_ASSERT(b);
185
186         string tname;
187         // use defaults.lyx as a default template if it exists.
188         if (templatename.empty())
189                 tname = libFileSearch("templates", "defaults.lyx");
190         else
191                 tname = templatename;
192
193         if (!tname.empty()) {
194                 if (!b->readFile(tname)) {
195                         docstring const file = makeDisplayPath(tname, 50);
196                         docstring const text  = bformat(
197                                 _("The specified document template\n%1$s\ncould not be read."),
198                                 file);
199                         Alert::error(_("Could not read template"), text);
200                         theBufferList().release(b);
201                         return 0;
202                 }
203         }
204
205         if (!isNamed) {
206                 b->setUnnamed();
207                 b->setFileName(filename);
208         }
209
210         b->setReadonly(false);
211         b->fully_loaded(true);
212         b->updateDocLang(b->params().language);
213
214         return b;
215 }
216
217
218 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
219                                   ErrorList & errorList)
220 {
221         TeXErrors::Errors::const_iterator cit = terr.begin();
222         TeXErrors::Errors::const_iterator end = terr.end();
223
224         for (; cit != end; ++cit) {
225                 int id_start = -1;
226                 int pos_start = -1;
227                 int errorrow = cit->error_in_line;
228                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
229                                                        pos_start);
230                 int id_end = -1;
231                 int pos_end = -1;
232                 do {
233                         ++errorrow;
234                         found = buf.texrow().getIdFromRow(errorrow, id_end,
235                                                           pos_end);
236                 } while (found && id_start == id_end && pos_start == pos_end);
237
238                 errorList.push_back(ErrorItem(from_utf8(cit->error_desc),
239                         from_utf8(cit->error_text), id_start, pos_start, pos_end));
240         }
241 }
242
243
244 string const bufferFormat(Buffer const & buffer)
245 {
246         if (buffer.isDocBook())
247                 return "docbook";
248         else if (buffer.isLiterate())
249                 return "literate";
250         else
251                 return "latex";
252 }
253
254
255 int countWords(DocIterator const & from, DocIterator const & to)
256 {
257         int count = 0;
258         bool inword = false;
259         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
260                 // Copied and adapted from isLetter() in ControlSpellChecker
261                 if (dit.inTexted()
262                     && dit.pos() != dit.lastpos()
263                     && dit.paragraph().isLetter(dit.pos())
264                     && !dit.paragraph().isDeleted(dit.pos())) {
265                         if (!inword) {
266                                 ++count;
267                                 inword = true;
268                         }
269                 } else if (inword)
270                         inword = false;
271         }
272
273         return count;
274 }
275
276
277 namespace {
278
279 depth_type getDepth(DocIterator const & it)
280 {
281         depth_type depth = 0;
282         for (size_t i = 0 ; i < it.depth() ; ++i)
283                 if (!it[i].inset().inMathed())
284                         depth += it[i].paragraph().getDepth() + 1;
285         // remove 1 since the outer inset does not count
286         return depth - 1;
287 }
288
289 depth_type getItemDepth(ParIterator const & it)
290 {
291         Paragraph const & par = *it;
292         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
293
294         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
295                 return 0;
296
297         // this will hold the lowest depth encountered up to now.
298         depth_type min_depth = getDepth(it);
299         ParIterator prev_it = it;
300         while (true) {
301                 if (prev_it.pit())
302                         --prev_it.top().pit();
303                 else {
304                         // start of nested inset: go to outer par
305                         prev_it.pop_back();
306                         if (prev_it.empty()) {
307                                 // start of document: nothing to do
308                                 return 0;
309                         }
310                 }
311
312                 // We search for the first paragraph with same label
313                 // that is not more deeply nested.
314                 Paragraph & prev_par = *prev_it;
315                 depth_type const prev_depth = getDepth(prev_it);
316                 if (labeltype == prev_par.layout()->labeltype) {
317                         if (prev_depth < min_depth) {
318                                 return prev_par.itemdepth + 1;
319                         }
320                         else if (prev_depth == min_depth) {
321                                 return prev_par.itemdepth;
322                         }
323                 }
324                 min_depth = std::min(min_depth, prev_depth);
325                 // small optimization: if we are at depth 0, we won't
326                 // find anything else
327                 if (prev_depth == 0) {
328                         return 0;
329                 }
330         }
331 }
332
333
334 bool needEnumCounterReset(ParIterator const & it)
335 {
336         Paragraph const & par = *it;
337         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
338         depth_type const cur_depth = par.getDepth();
339         ParIterator prev_it = it;
340         while (prev_it.pit()) {
341                 --prev_it.top().pit();
342                 Paragraph const & prev_par = *prev_it;
343                 if (prev_par.getDepth() <= cur_depth)
344                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
345         }
346         // start of nested inset: reset
347         return true;
348 }
349
350
351 // set the label of a paragraph. This includes the counters.
352 void setLabel(Buffer const & buf, ParIterator & it)
353 {
354         Paragraph & par = *it;
355         BufferParams const & bufparams = buf.params();
356         LyXTextClass const & textclass = bufparams.getLyXTextClass();
357         LyXLayout_ptr const & layout = par.layout();
358         Counters & counters = textclass.counters();
359
360         if (it.pit() == 0) {
361                 par.params().appendix(par.params().startOfAppendix());
362         } else {
363                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
364                 if (!par.params().appendix() &&
365                     par.params().startOfAppendix()) {
366                         par.params().appendix(true);
367                         textclass.counters().reset();
368                 }
369         }
370
371         // Compute the item depth of the paragraph
372         par.itemdepth = getItemDepth(it);
373
374         // erase what was there before
375         par.params().labelString(docstring());
376
377         if (layout->margintype == MARGIN_MANUAL) {
378                 if (par.params().labelWidthString().empty())
379                         par.setLabelWidthString(layout->labelstring());
380         } else {
381                 par.setLabelWidthString(docstring());
382         }
383
384         // is it a layout that has an automatic label?
385         if (layout->labeltype == LABEL_COUNTER) {
386                 if (layout->toclevel <= buf.params().secnumdepth
387                     && (layout->latextype != LATEX_ENVIRONMENT
388                         || isFirstInSequence(it.pit(), it.plist()))) {
389                         counters.step(layout->counter);
390                         docstring label = expandLabel(buf, layout,
391                                                       par.params().appendix());
392                         par.params().labelString(label);
393                 }
394         } else if (layout->labeltype == LABEL_ITEMIZE) {
395                 // At some point of time we should do something more
396                 // clever here, like:
397                 //   par.params().labelString(
398                 //    bufparams.user_defined_bullet(par.itemdepth).getText());
399                 // for now, use a simple hardcoded label
400                 docstring itemlabel;
401                 switch (par.itemdepth) {
402                 case 0:
403                         itemlabel = char_type(0x2022);
404                         break;
405                 case 1:
406                         itemlabel = char_type(0x2013);
407                         break;
408                 case 2:
409                         itemlabel = char_type(0x2217);
410                         break;
411                 case 3:
412                         itemlabel += char_type(0x2219); // or 0x00b7
413                         break;
414                 }
415
416                 par.params().labelString(itemlabel);
417         } else if (layout->labeltype == LABEL_ENUMERATE) {
418                 // FIXME
419                 // Yes I know this is a really, really! bad solution
420                 // (Lgb)
421                 docstring enumcounter = from_ascii("enum");
422
423                 switch (par.itemdepth) {
424                 case 2:
425                         enumcounter += 'i';
426                 case 1:
427                         enumcounter += 'i';
428                 case 0:
429                         enumcounter += 'i';
430                         break;
431                 case 3:
432                         enumcounter += "iv";
433                         break;
434                 default:
435                         // not a valid enumdepth...
436                         break;
437                 }
438
439                 // Maybe we have to reset the enumeration counter.
440                 if (needEnumCounterReset(it))
441                         counters.reset(enumcounter);
442
443                 counters.step(enumcounter);
444
445                 string format;
446
447                 switch (par.itemdepth) {
448                 case 0:
449                         format = N_("\\arabic{enumi}.");
450                         break;
451                 case 1:
452                         format = N_("(\\alph{enumii})");
453                         break;
454                 case 2:
455                         format = N_("\\roman{enumiii}.");
456                         break;
457                 case 3:
458                         format = N_("\\Alph{enumiv}.");
459                         break;
460                 default:
461                         // not a valid enumdepth...
462                         break;
463                 }
464
465                 par.params().labelString(counters.counterLabel(buf.B_(format)));
466         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
467                 counters.step(from_ascii("bibitem"));
468                 int number = counters.value(from_ascii("bibitem"));
469                 if (par.bibitem())
470                         par.bibitem()->setCounter(number);
471                 // FIXME UNICODE
472                 par.params().labelString(buf.B_(to_ascii(layout->labelstring())));
473                 // In biblio should't be following counters but...
474         } else if (layout->labeltype == LABEL_SENSITIVE) {
475                 // Search for the first float or wrap inset in the iterator
476                 docstring type;
477                 size_t i = it.depth();
478                 while (i > 0) {
479                         --i;
480                         InsetBase * const in = &it[i].inset();
481                         if (in->lyxCode() == InsetBase::FLOAT_CODE
482                             || in->lyxCode() == InsetBase::WRAP_CODE) {
483                                 type = in->getInsetName();
484                                 break;
485                         }
486                 }
487
488                 docstring s;
489                 if (!type.empty()) {
490                         Floating const & fl = textclass.floats().getType(to_ascii(type));
491                         // FIXME UNICODE
492                         counters.step(from_ascii(fl.type()));
493
494                         // Doesn't work... yet.
495                         s = bformat(_("%1$s #:"), buf.B_(fl.name()));
496                 } else {
497                         // par->SetLayout(0);
498                         // FIXME UNICODE
499                         s = buf.B_(to_ascii(layout->labelstring()));
500                 }
501
502                 par.params().labelString(s);
503         } else if (layout->labeltype == LABEL_NO_LABEL)
504                 par.params().labelString(docstring());
505         else
506                 // FIXME UNICODE
507                 par.params().labelString(buf.B_(to_ascii(layout->labelstring())));
508 }
509
510 } // anon namespace
511
512
513 bool updateCurrentLabel(Buffer const & buf,
514         ParIterator & it)
515 {
516     if (it == par_iterator_end(buf.inset()))
517         return false;
518
519 //      if (it.lastpit == 0 && LyXText::isMainText())
520 //              return false;
521
522         switch (it->layout()->labeltype) {
523
524         case LABEL_NO_LABEL:
525         case LABEL_MANUAL:
526         case LABEL_BIBLIO:
527         case LABEL_TOP_ENVIRONMENT:
528         case LABEL_CENTERED_TOP_ENVIRONMENT:
529         case LABEL_STATIC:
530         case LABEL_ITEMIZE:
531                 setLabel(buf, it);
532                 return true;
533
534         case LABEL_SENSITIVE:
535         case LABEL_COUNTER:
536         // do more things with enumerate later
537         case LABEL_ENUMERATE:
538                 return false;
539         }
540
541         // This is dead code which get rid of a warning:
542         return true;
543 }
544
545
546 void updateLabels(Buffer const & buf,
547         ParIterator & from, ParIterator & to)
548 {
549         for (ParIterator it = from; it != to; ++it) {
550                 if (it.pit() > it.lastpit())
551                         return;
552                 if (!updateCurrentLabel (buf, it)) {
553                         updateLabels(buf);
554                         return;
555                 }
556         }
557 }
558
559
560 void updateLabels(Buffer const & buf,
561         ParIterator & iter)
562 {
563         if (updateCurrentLabel(buf, iter))
564                 return;
565
566         updateLabels(buf);
567 }
568
569
570 void updateLabels(Buffer const & buf)
571 {
572         // start over the counters
573         buf.params().getLyXTextClass().counters().reset();
574
575         ParIterator const end = par_iterator_end(buf.inset());
576
577         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
578                 // reduce depth if necessary
579                 if (it.pit()) {
580                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
581                         it->params().depth(min(it->params().depth(),
582                                                prevpar.getMaxDepthAfter()));
583                 } else
584                         it->params().depth(0);
585
586                 // set the counter for this paragraph
587                 setLabel(buf, it);
588         }
589
590         toc::updateToc(buf);
591 }
592
593
594 docstring expandLabel(Buffer const & buf,
595                       LyXLayout_ptr const & layout, bool appendix)
596 {
597         LyXTextClass const & tclass = buf.params().getLyXTextClass();
598
599         // FIXME UNICODE
600         docstring fmt = buf.B_(to_ascii(appendix ? layout->labelstring_appendix()
601                                              : layout->labelstring()));
602
603         // handle 'inherited level parts' in 'fmt',
604         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
605         size_t const i = fmt.find('@', 0);
606         if (i != docstring::npos) {
607                 size_t const j = fmt.find('@', i + 1);
608                 if (j != docstring::npos) {
609                         docstring parent(fmt, i + 1, j - i - 1);
610                         // FIXME UNICODE
611                         docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
612                         fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
613                 }
614         }
615
616         return tclass.counters().counterLabel(fmt);
617 }
618
619
620 } // namespace lyx