]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
5c545cbcddc603302ed301696f09d3ab738122c7
[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 using namespace std;
52
53 using lyx::pit_type;
54 using lyx::support::bformat;
55 using lyx::support::libFileSearch;
56 using lyx::support::makeDisplayPath;
57 using lyx::support::onlyFilename;
58 using lyx::support::onlyPath;
59 using lyx::support::unlink;
60
61 using std::min;
62 using std::string;
63
64 namespace fs = boost::filesystem;
65
66 extern BufferList bufferlist;
67
68 namespace {
69
70 bool readFile(Buffer * const b, string const & s)
71 {
72         BOOST_ASSERT(b);
73
74         // File information about normal file
75         if (!fs::exists(s)) {
76                 string const file = makeDisplayPath(s, 50);
77                 string text = bformat(_("The specified document\n%1$s"
78                                         "\ncould not be read."), file);
79                 Alert::error(_("Could not read document"), text);
80                 return false;
81         }
82
83         // Check if emergency save file exists and is newer.
84         string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
85
86         if (fs::exists(e) && fs::exists(s)
87             && fs::last_write_time(e) > fs::last_write_time(s))
88         {
89                 string const file = makeDisplayPath(s, 20);
90                 string const text =
91                         bformat(_("An emergency save of the document "
92                                   "%1$s exists.\n\n"
93                                   "Recover emergency save?"), file);
94                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
95                                       _("&Recover"),  _("&Load Original"),
96                                       _("&Cancel")))
97                 {
98                 case 0:
99                         // the file is not saved if we load the emergency file.
100                         b->markDirty();
101                         return b->readFile(e);
102                 case 1:
103                         break;
104                 default:
105                         return false;
106                 }
107         }
108
109         // Now check if autosave file is newer.
110         string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
111
112         if (fs::exists(a) && fs::exists(s)
113             && fs::last_write_time(a) > fs::last_write_time(s))
114         {
115                 string const file = makeDisplayPath(s, 20);
116                 string const text =
117                         bformat(_("The backup of the document "
118                                   "%1$s is newer.\n\nLoad the "
119                                   "backup instead?"), file);
120                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
121                                       _("&Load backup"), _("Load &original"),
122                                       _("&Cancel") ))
123                 {
124                 case 0:
125                         // the file is not saved if we load the autosave file.
126                         b->markDirty();
127                         return b->readFile(a);
128                 case 1:
129                         // Here we delete the autosave
130                         unlink(a);
131                         break;
132                 default:
133                         return false;
134                 }
135         }
136         return b->readFile(s);
137 }
138
139
140 } // namespace anon
141
142
143
144 bool loadLyXFile(Buffer * b, string const & s)
145 {
146         BOOST_ASSERT(b);
147
148         if (fs::is_readable(s)) {
149                 if (readFile(b, s)) {
150                         b->lyxvc().file_found_hook(s);
151                         if (!fs::is_writable(s))
152                                 b->setReadonly(true);
153                         return true;
154                 }
155         } else {
156                 string const file = makeDisplayPath(s, 20);
157                 // Here we probably should run
158                 if (LyXVC::file_not_found_hook(s)) {
159                         string const text =
160                                 bformat(_("Do you want to retrieve the document"
161                                           " %1$s from version control?"), file);
162                         int const ret = Alert::prompt(_("Retrieve from version control?"),
163                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
164
165                         if (ret == 0) {
166                                 // How can we know _how_ to do the checkout?
167                                 // With the current VC support it has to be,
168                                 // a RCS file since CVS do not have special ,v files.
169                                 RCS::retrieve(s);
170                                 return loadLyXFile(b, s);
171                         }
172                 }
173         }
174         return false;
175 }
176
177
178 Buffer * newFile(string const & filename, string const & templatename,
179                  bool const isNamed)
180 {
181         // get a free buffer
182         Buffer * b = bufferlist.newBuffer(filename);
183         BOOST_ASSERT(b);
184
185         string tname;
186         // use defaults.lyx as a default template if it exists.
187         if (templatename.empty())
188                 tname = libFileSearch("templates", "defaults.lyx");
189         else
190                 tname = templatename;
191
192         if (!tname.empty()) {
193                 if (!b->readFile(tname)) {
194                         string const file = makeDisplayPath(tname, 50);
195                         string const text  = bformat(_("The specified document template\n%1$s\ncould not be read."), file);
196                         Alert::error(_("Could not read template"), text);
197                         // no template, start with empty buffer
198                 }
199         }
200
201         if (!isNamed) {
202                 b->setUnnamed();
203                 b->setFileName(filename);
204         }
205
206         b->setReadonly(false);
207         b->fully_loaded(true);
208         b->updateDocLang(b->params().language);
209
210         return b;
211 }
212
213
214 void bufferErrors(Buffer const & buf, TeXErrors const & terr)
215 {
216         TeXErrors::Errors::const_iterator cit = terr.begin();
217         TeXErrors::Errors::const_iterator end = terr.end();
218
219         for (; cit != end; ++cit) {
220                 int id_start = -1;
221                 int pos_start = -1;
222                 int errorrow = cit->error_in_line;
223                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
224                                                        pos_start);
225                 int id_end = -1;
226                 int pos_end = -1;
227                 do {
228                         ++errorrow;
229                         found = buf.texrow().getIdFromRow(errorrow, id_end,
230                                                           pos_end);
231                 } while (found && id_start == id_end && pos_start == pos_end);
232
233                 buf.error(ErrorItem(cit->error_desc, cit->error_text,
234                                     id_start, pos_start, pos_end));
235         }
236 }
237
238
239 void bufferErrors(Buffer const & buf, ErrorList const & el)
240 {
241         for_each(el.begin(), el.end(), bind(ref(buf.error), _1));
242 }
243
244
245 string const bufferFormat(Buffer const & buffer)
246 {
247         if (buffer.isLinuxDoc())
248                 return "linuxdoc";
249         else if (buffer.isDocBook())
250                 return "docbook";
251         else if (buffer.isLiterate())
252                 return "literate";
253         else
254                 return "latex";
255 }
256
257
258 int countWords(DocIterator const & from, DocIterator const & to)
259 {
260         int count = 0;
261         bool inword = false;
262         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
263                 // Copied and adapted from isLetter() in ControlSpellChecker
264                 if (dit.inTexted()
265                     && dit.pos() != dit.lastpos()
266                     && dit.paragraph().isLetter(dit.pos())
267                     && !isDeletedText(dit.paragraph(), dit.pos())) {
268                         if (!inword) {
269                                 ++count;
270                                 inword = true;
271                         }
272                 } else if (inword)
273                         inword = false;
274         }
275
276         return count;
277 }
278
279
280 namespace {
281
282 lyx::depth_type getDepth(DocIterator const & it)
283 {
284         lyx::depth_type depth = 0;
285         for (size_t i = 0 ; i < it.depth() ; ++i)
286                 if (!it[i].inset().inMathed())
287                         depth += it[i].paragraph().getDepth() + 1;
288         // remove 1 since the outer inset does not count
289         return depth - 1;
290 }
291
292 lyx::depth_type getItemDepth(ParIterator const & it)
293 {
294         Paragraph const & par = *it;
295         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
296
297         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
298                 return 0;
299
300         // this will hold the lowest depth encountered up to now.
301         lyx::depth_type min_depth = getDepth(it);
302         ParIterator prev_it = it;
303         while (true) {
304                 if (prev_it.pit())
305                         --prev_it.top().pit();
306                 else {
307                         // start of nested inset: go to outer par
308                         prev_it.pop_back();
309                         if (prev_it.empty()) {
310                                 // start of document: nothing to do
311                                 return 0;
312                         }
313                 }
314
315                 // We search for the first paragraph with same label
316                 // that is not more deeply nested.
317                 Paragraph & prev_par = *prev_it;
318                 lyx::depth_type const prev_depth = getDepth(prev_it);
319                 if (labeltype == prev_par.layout()->labeltype) {
320                         if (prev_depth < min_depth) {
321                                 return prev_par.itemdepth + 1;
322                         }
323                         else if (prev_depth == min_depth) {
324                                 return prev_par.itemdepth;
325                         }
326                 }
327                 min_depth = std::min(min_depth, prev_depth);
328                 // small optimization: if we are at depth 0, we won't
329                 // find anything else
330                 if (prev_depth == 0) {
331                         return 0;
332                 }
333         }
334 }
335
336
337 bool needEnumCounterReset(ParIterator const & it)
338 {
339         Paragraph const & par = *it;
340         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
341         lyx::depth_type const cur_depth = par.getDepth();
342         ParIterator prev_it = it;
343         while (prev_it.pit()) {
344                 --prev_it.top().pit();
345                 Paragraph const & prev_par = *prev_it;
346                 if (prev_par.getDepth() <= cur_depth)
347                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
348         }
349         // start of nested inset: reset
350         return true;
351 }
352
353
354 // set the label of a paragraph. This includes the counters.
355 void setLabel(Buffer const & buf, ParIterator & it)
356 {
357         Paragraph & par = *it;
358         BufferParams const & bufparams = buf.params();
359         LyXTextClass const & textclass = bufparams.getLyXTextClass();
360         LyXLayout_ptr const & layout = par.layout();
361         Counters & counters = textclass.counters();
362
363         if (it.pit() == 0) {
364                 par.params().appendix(par.params().startOfAppendix());
365         } else {
366                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
367                 if (!par.params().appendix() &&
368                     par.params().startOfAppendix()) {
369                         par.params().appendix(true);
370                         textclass.counters().reset();
371                 }
372         }
373
374         // Compute the item depth of the paragraph
375         par.itemdepth = getItemDepth(it);
376
377         // erase what was there before
378         par.params().labelString(string());
379
380         if (layout->margintype == MARGIN_MANUAL) {
381                 if (par.params().labelWidthString().empty())
382                         par.setLabelWidthString(layout->labelstring());
383         } else {
384                 par.setLabelWidthString(string());
385         }
386
387         // is it a layout that has an automatic label?
388         if (layout->labeltype == LABEL_COUNTER) {
389                 if (layout->toclevel <= buf.params().secnumdepth
390                     && (layout->latextype != LATEX_ENVIRONMENT
391                         || isFirstInSequence(it.pit(), it.plist()))) {
392                         counters.step(layout->counter);
393                         string label = expandLabel(buf, layout,
394                                                    par.params().appendix());
395                         par.params().labelString(label);
396                 }
397         } else if (layout->labeltype == LABEL_ITEMIZE) {
398                 // At some point of time we should do something more
399                 // clever here, like:
400                 //   par.params().labelString(
401                 //    bufparams.user_defined_bullet(par.itemdepth).getText());
402                 // for now, use a simple hardcoded label
403                 string itemlabel;
404                 switch (par.itemdepth) {
405                 case 0:
406                         itemlabel = "*";
407                         break;
408                 case 1:
409                         itemlabel = "-";
410                         break;
411                 case 2:
412                         itemlabel = "@";
413                         break;
414                 case 3:
415                         itemlabel = "·";
416                         break;
417                 }
418
419                 par.params().labelString(itemlabel);
420         } else if (layout->labeltype == LABEL_ENUMERATE) {
421                 // FIXME
422                 // Yes I know this is a really, really! bad solution
423                 // (Lgb)
424                 string enumcounter = "enum";
425
426                 switch (par.itemdepth) {
427                 case 2:
428                         enumcounter += 'i';
429                 case 1:
430                         enumcounter += 'i';
431                 case 0:
432                         enumcounter += 'i';
433                         break;
434                 case 3:
435                         enumcounter += "iv";
436                         break;
437                 default:
438                         // not a valid enumdepth...
439                         break;
440                 }
441
442                 // Maybe we have to reset the enumeration counter.
443                 if (needEnumCounterReset(it))
444                         counters.reset(enumcounter);
445
446                 counters.step(enumcounter);
447
448                 string format;
449
450                 switch (par.itemdepth) {
451                 case 0:
452                         format = N_("\\arabic{enumi}.");
453                         break;
454                 case 1:
455                         format = N_("(\\alph{enumii})");
456                         break;
457                 case 2:
458                         format = N_("\\roman{enumiii}.");
459                         break;
460                 case 3:
461                         format = N_("\\Alph{enumiv}.");
462                         break;
463                 default:
464                         // not a valid enumdepth...
465                         break;
466                 }
467
468                 par.params().labelString(counters.counterLabel(buf.B_(format)));
469         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
470                 counters.step("bibitem");
471                 int number = counters.value("bibitem");
472                 if (par.bibitem())
473                         par.bibitem()->setCounter(number);
474                 par.params().labelString(buf.B_(layout->labelstring()));
475                 // In biblio should't be following counters but...
476         } else if (layout->labeltype == LABEL_SENSITIVE) {
477                 // Search for the first float or wrap inset in the iterator
478                 string type;
479                 size_t i = it.depth();
480                 while (i > 0) {
481                         --i;
482                         InsetBase * const in = &it[i].inset();
483                         if (in->lyxCode() == InsetBase::FLOAT_CODE
484                             || in->lyxCode() == InsetBase::WRAP_CODE) {
485                                 type = in->getInsetName();
486                                 break;
487                         }
488                 }
489
490                 string s;
491                 if (!type.empty()) {
492                         Floating const & fl = textclass.floats().getType(type);
493
494                         counters.step(fl.type());
495
496                         // Doesn't work... yet.
497                         s = bformat(_("%1$s #:"), buf.B_(fl.name()));
498                 } else {
499                         // par->SetLayout(0);
500                         s = buf.B_(layout->labelstring());
501                 }
502
503                 par.params().labelString(s);
504         } else if (layout->labeltype == LABEL_NO_LABEL)
505                 par.params().labelString(string());
506         else
507                 par.params().labelString(buf.B_(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         lyx::toc::updateToc(buf);
591 }
592
593
594 string expandLabel(Buffer const & buf,
595         LyXLayout_ptr const & layout, bool appendix)
596 {
597         LyXTextClass const & tclass = buf.params().getLyXTextClass();
598
599         string fmt = buf.B_(appendix ? layout->labelstring_appendix()
600                             : layout->labelstring());
601
602         // handle 'inherited level parts' in 'fmt',
603         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
604         size_t const i = fmt.find('@', 0);
605         if (i != string::npos) {
606                 size_t const j = fmt.find('@', i + 1);
607                 if (j != string::npos) {
608                         string parent(fmt, i + 1, j - i - 1);
609                         string label = expandLabel(buf, tclass[parent], appendix);
610                         fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
611                 }
612         }
613
614         return tclass.counters().counterLabel(fmt);
615 }