]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
do not create invalid .lyx files when importing \i{}, \j{}, \l{} or \L{}.
[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 "TocBackend.h"
36 #include "vc-backend.h"
37
38 #include "frontends/Alert.h"
39
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
42
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
46
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
49
50
51 namespace lyx {
52
53 using namespace std;
54
55 using support::bformat;
56 using support::FileName;
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, FileName const & s)
72 {
73         BOOST_ASSERT(b);
74
75         // File information about normal file
76         if (!fs::exists(s.toFilesystemEncoding())) {
77                 docstring const file = makeDisplayPath(s.absFilename(), 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         FileName const e(s.absFilename() + ".emergency");
86
87         if (fs::exists(e.toFilesystemEncoding()) &&
88             fs::exists(s.toFilesystemEncoding()) &&
89             fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
90         {
91                 docstring const file = makeDisplayPath(s.absFilename(), 20);
92                 docstring const text =
93                         bformat(_("An emergency save of the document "
94                                   "%1$s exists.\n\n"
95                                                "Recover emergency save?"), file);
96                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
97                                       _("&Recover"),  _("&Load Original"),
98                                       _("&Cancel")))
99                 {
100                 case 0:
101                         // the file is not saved if we load the emergency file.
102                         b->markDirty();
103                         return b->readFile(e.absFilename());
104                 case 1:
105                         break;
106                 default:
107                         return false;
108                 }
109         }
110
111         // Now check if autosave file is newer.
112         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
113
114         if (fs::exists(a.toFilesystemEncoding()) &&
115             fs::exists(s.toFilesystemEncoding()) &&
116             fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
117         {
118                 docstring const file = makeDisplayPath(s.absFilename(), 20);
119                 docstring const text =
120                         bformat(_("The backup of the document "
121                                   "%1$s is newer.\n\nLoad the "
122                                                "backup instead?"), file);
123                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
124                                       _("&Load backup"), _("Load &original"),
125                                       _("&Cancel") ))
126                 {
127                 case 0:
128                         // the file is not saved if we load the autosave file.
129                         b->markDirty();
130                         return b->readFile(a.absFilename());
131                 case 1:
132                         // Here we delete the autosave
133                         unlink(a);
134                         break;
135                 default:
136                         return false;
137                 }
138         }
139         return b->readFile(s.absFilename());
140 }
141
142
143 } // namespace anon
144
145
146
147 bool loadLyXFile(Buffer * b, FileName const & s)
148 {
149         BOOST_ASSERT(b);
150
151         if (fs::is_readable(s.toFilesystemEncoding())) {
152                 if (readFile(b, s)) {
153                         b->lyxvc().file_found_hook(s);
154                         if (!fs::is_writable(s.toFilesystemEncoding()))
155                                 b->setReadonly(true);
156                         return true;
157                 }
158         } else {
159                 docstring const file = makeDisplayPath(s.absFilename(), 20);
160                 // Here we probably should run
161                 if (LyXVC::file_not_found_hook(s)) {
162                         docstring const text =
163                                 bformat(_("Do you want to retrieve the document"
164                                                        " %1$s from version control?"), file);
165                         int const ret = Alert::prompt(_("Retrieve from version control?"),
166                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
167
168                         if (ret == 0) {
169                                 // How can we know _how_ to do the checkout?
170                                 // With the current VC support it has to be,
171                                 // a RCS file since CVS do not have special ,v files.
172                                 RCS::retrieve(s);
173                                 return loadLyXFile(b, s);
174                         }
175                 }
176         }
177         return false;
178 }
179
180 // FIXME newFile() should probably be a member method of Application...
181 Buffer * newFile(string const & filename, string const & templatename,
182                  bool const isNamed)
183 {
184         // get a free buffer
185         Buffer * b = theBufferList().newBuffer(filename);
186         BOOST_ASSERT(b);
187
188         string tname;
189         // use defaults.lyx as a default template if it exists.
190         if (templatename.empty())
191                 tname = libFileSearch("templates", "defaults.lyx").absFilename();
192         else
193                 tname = templatename;
194
195         if (!tname.empty()) {
196                 if (!b->readFile(tname)) {
197                         docstring const file = makeDisplayPath(tname, 50);
198                         docstring const text  = bformat(
199                                 _("The specified document template\n%1$s\ncould not be read."),
200                                 file);
201                         Alert::error(_("Could not read template"), text);
202                         theBufferList().release(b);
203                         return 0;
204                 }
205         }
206
207         if (!isNamed) {
208                 b->setUnnamed();
209                 b->setFileName(filename);
210         }
211
212         b->setReadonly(false);
213         b->fully_loaded(true);
214         b->updateDocLang(b->params().language);
215
216         return b;
217 }
218
219
220 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
221                                   ErrorList & errorList)
222 {
223         TeXErrors::Errors::const_iterator cit = terr.begin();
224         TeXErrors::Errors::const_iterator end = terr.end();
225
226         for (; cit != end; ++cit) {
227                 int id_start = -1;
228                 int pos_start = -1;
229                 int errorrow = cit->error_in_line;
230                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
231                                                        pos_start);
232                 int id_end = -1;
233                 int pos_end = -1;
234                 do {
235                         ++errorrow;
236                         found = buf.texrow().getIdFromRow(errorrow, id_end,
237                                                           pos_end);
238                 } while (found && id_start == id_end && pos_start == pos_end);
239
240                 errorList.push_back(ErrorItem(cit->error_desc,
241                         cit->error_text, id_start, pos_start, pos_end));
242         }
243 }
244
245
246 string const bufferFormat(Buffer const & buffer)
247 {
248         if (buffer.isDocBook())
249                 return "docbook";
250         else if (buffer.isLiterate())
251                 return "literate";
252         else
253                 return "latex";
254 }
255
256
257 int countWords(DocIterator const & from, DocIterator const & to)
258 {
259         int count = 0;
260         bool inword = false;
261         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
262                 // Copied and adapted from isLetter() in ControlSpellChecker
263                 if (dit.inTexted()
264                     && dit.pos() != dit.lastpos()
265                     && dit.paragraph().isLetter(dit.pos())
266                     && !dit.paragraph().isDeleted(dit.pos())) {
267                         if (!inword) {
268                                 ++count;
269                                 inword = true;
270                         }
271                 } else if (inword)
272                         inword = false;
273         }
274
275         return count;
276 }
277
278
279 namespace {
280
281 depth_type getDepth(DocIterator const & it)
282 {
283         depth_type depth = 0;
284         for (size_t i = 0 ; i < it.depth() ; ++i)
285                 if (!it[i].inset().inMathed())
286                         depth += it[i].paragraph().getDepth() + 1;
287         // remove 1 since the outer inset does not count
288         return depth - 1;
289 }
290
291 depth_type getItemDepth(ParIterator const & it)
292 {
293         Paragraph const & par = *it;
294         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
295
296         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
297                 return 0;
298
299         // this will hold the lowest depth encountered up to now.
300         depth_type min_depth = getDepth(it);
301         ParIterator prev_it = it;
302         while (true) {
303                 if (prev_it.pit())
304                         --prev_it.top().pit();
305                 else {
306                         // start of nested inset: go to outer par
307                         prev_it.pop_back();
308                         if (prev_it.empty()) {
309                                 // start of document: nothing to do
310                                 return 0;
311                         }
312                 }
313
314                 // We search for the first paragraph with same label
315                 // that is not more deeply nested.
316                 Paragraph & prev_par = *prev_it;
317                 depth_type const prev_depth = getDepth(prev_it);
318                 if (labeltype == prev_par.layout()->labeltype) {
319                         if (prev_depth < min_depth) {
320                                 return prev_par.itemdepth + 1;
321                         }
322                         else if (prev_depth == min_depth) {
323                                 return prev_par.itemdepth;
324                         }
325                 }
326                 min_depth = std::min(min_depth, prev_depth);
327                 // small optimization: if we are at depth 0, we won't
328                 // find anything else
329                 if (prev_depth == 0) {
330                         return 0;
331                 }
332         }
333 }
334
335
336 bool needEnumCounterReset(ParIterator const & it)
337 {
338         Paragraph const & par = *it;
339         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
340         depth_type const cur_depth = par.getDepth();
341         ParIterator prev_it = it;
342         while (prev_it.pit()) {
343                 --prev_it.top().pit();
344                 Paragraph const & prev_par = *prev_it;
345                 if (prev_par.getDepth() <= cur_depth)
346                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
347         }
348         // start of nested inset: reset
349         return true;
350 }
351
352
353 // set the label of a paragraph. This includes the counters.
354 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
355 {
356         Paragraph & par = *it;
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(buf.translateLabel(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                 //    buf.params().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                 par.params().labelString(buf.translateLabel(layout->labelstring()));
472                 // In biblio should't be following counters but...
473         } else if (layout->labeltype == LABEL_SENSITIVE) {
474                 // Search for the first float or wrap inset in the iterator
475                 docstring type;
476                 size_t i = it.depth();
477                 while (i > 0) {
478                         --i;
479                         InsetBase * const in = &it[i].inset();
480                         if (in->lyxCode() == InsetBase::FLOAT_CODE
481                             || in->lyxCode() == InsetBase::WRAP_CODE) {
482                                 type = in->getInsetName();
483                                 break;
484                         }
485                 }
486
487                 docstring s;
488                 if (!type.empty()) {
489                         Floating const & fl = textclass.floats().getType(to_ascii(type));
490                         // FIXME UNICODE
491                         counters.step(from_ascii(fl.type()));
492
493                         // Doesn't work... yet.
494                         s = bformat(_("%1$s #:"), buf.B_(fl.name()));
495                 } else {
496                         // par->SetLayout(0);
497                         s = buf.translateLabel(layout->labelstring());
498                 }
499
500                 par.params().labelString(s);
501         } else if (layout->labeltype == LABEL_NO_LABEL)
502                 par.params().labelString(docstring());
503         else
504                 par.params().labelString(buf.translateLabel(layout->labelstring()));
505 }
506
507 } // anon namespace
508
509
510 bool updateCurrentLabel(Buffer const & buf,
511         ParIterator & it)
512 {
513     if (it == par_iterator_end(buf.inset()))
514         return false;
515
516 //      if (it.lastpit == 0 && LyXText::isMainText(buf))
517 //              return false;
518
519         switch (it->layout()->labeltype) {
520
521         case LABEL_NO_LABEL:
522         case LABEL_MANUAL:
523         case LABEL_BIBLIO:
524         case LABEL_TOP_ENVIRONMENT:
525         case LABEL_CENTERED_TOP_ENVIRONMENT:
526         case LABEL_STATIC:
527         case LABEL_ITEMIZE:
528                 setLabel(buf, it, buf.params().getLyXTextClass());
529                 return true;
530
531         case LABEL_SENSITIVE:
532         case LABEL_COUNTER:
533         // do more things with enumerate later
534         case LABEL_ENUMERATE:
535                 return false;
536         }
537
538         // This is dead code which get rid of a warning:
539         return true;
540 }
541
542
543 void updateLabels(Buffer const & buf,
544         ParIterator & from, ParIterator & to, bool childonly)
545 {
546         for (ParIterator it = from; it != to; ++it) {
547                 if (it.pit() > it.lastpit())
548                         return;
549                 if (!updateCurrentLabel (buf, it)) {
550                         updateLabels(buf, childonly);
551                         return;
552                 }
553         }
554 }
555
556
557 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
558 {
559         if (updateCurrentLabel(buf, iter))
560                 return;
561
562         updateLabels(buf, childonly);
563 }
564
565
566 void updateLabels(Buffer const & buf, bool childonly)
567 {
568         // Use the master text class also for child documents
569         LyXTextClass const & textclass = buf.params().getLyXTextClass();
570
571         if (!childonly) {
572                 // If this is a child document start with the master
573                 Buffer const * const master = buf.getMasterBuffer();
574                 if (master != &buf) {
575                         updateLabels(*master);
576                         return;
577                 }
578
579                 // start over the counters
580                 textclass.counters().reset();
581         }
582
583         ParIterator const end = par_iterator_end(buf.inset());
584
585         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
586                 // reduce depth if necessary
587                 if (it.pit()) {
588                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
589                         it->params().depth(min(it->params().depth(),
590                                                prevpar.getMaxDepthAfter()));
591                 } else
592                         it->params().depth(0);
593
594                 // set the counter for this paragraph
595                 setLabel(buf, it, textclass);
596
597                 // Now included docs
598                 InsetList::const_iterator iit = it->insetlist.begin();
599                 InsetList::const_iterator end = it->insetlist.end();
600                 for (; iit != end; ++iit) {
601                         if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
602                                 static_cast<InsetInclude const *>(iit->inset)
603                                         ->updateLabels(buf);
604                 }
605         }
606
607         const_cast<Buffer &>(buf).tocBackend().update();
608 }
609
610
611 docstring expandLabel(Buffer const & buf,
612                       LyXLayout_ptr const & layout, bool appendix)
613 {
614         LyXTextClass const & tclass = buf.params().getLyXTextClass();
615
616         docstring fmt = buf.translateLabel(appendix ?
617                         layout->labelstring_appendix() :
618                         layout->labelstring());
619
620         // handle 'inherited level parts' in 'fmt',
621         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
622         size_t const i = fmt.find('@', 0);
623         if (i != docstring::npos) {
624                 size_t const j = fmt.find('@', i + 1);
625                 if (j != docstring::npos) {
626                         docstring parent(fmt, i + 1, j - i - 1);
627                         // FIXME UNICODE
628                         docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
629                         fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
630                 }
631         }
632
633         return tclass.counters().counterLabel(fmt);
634 }
635
636
637 } // namespace lyx