]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
Embedding: saving inzip name to .lyx file so that embedded files can always be found...
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
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 "InsetList.h"
25 #include "InsetIterator.h"
26 #include "Language.h"
27 #include "LaTeX.h"
28 #include "Layout.h"
29 #include "LayoutPtr.h"
30 #include "LyX.h"
31 #include "TextClass.h"
32 #include "TextClassList.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphList.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "TexRow.h"
39 #include "Text.h"
40 #include "TocBackend.h"
41
42 #include "frontends/alert.h"
43
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
46
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/filetools.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58
59 namespace Alert = frontend::Alert;
60
61
62 Buffer * checkAndLoadLyXFile(FileName const & filename)
63 {
64         // File already open?
65         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
66         if (checkBuffer) {
67                 if (checkBuffer->isClean())
68                         return checkBuffer;
69                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
70                 docstring text = bformat(_(
71                                 "The document %1$s is already loaded and has unsaved changes.\n"
72                                 "Do you want to abandon your changes and reload the version on disk?"), file);
73                 if (Alert::prompt(_("Reload saved document?"),
74                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
75                         return checkBuffer;
76
77                 // FIXME: should be LFUN_REVERT
78                 theBufferList().release(checkBuffer);
79                 // Load it again.
80                 return checkAndLoadLyXFile(filename);
81         }
82
83         if (filename.isReadableFile()) {
84                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
85                 if (!b)
86                         // Buffer creation is not possible.
87                         return 0;
88                 if (!b->loadLyXFile(filename)) {
89                         theBufferList().release(b);
90                         return 0;
91                 }
92                 return b;
93         }
94
95         docstring text = bformat(_("The document %1$s does not yet "
96                 "exist.\n\nDo you want to create a new document?"),
97                 from_utf8(filename.absFilename()));
98         if (!Alert::prompt(_("Create new document?"),
99                         text, 0, 1, _("&Create"), _("Cancel")))
100                 return newFile(filename.absFilename(), string(), true);
101
102         return 0;
103 }
104
105
106 // FIXME newFile() should probably be a member method of Application...
107 Buffer * newFile(string const & filename, string const & templatename,
108                  bool const isNamed)
109 {
110         // get a free buffer
111         Buffer * b = theBufferList().newBuffer(filename);
112         if (!b)
113                 // Buffer creation is not possible.
114                 return 0;
115
116         FileName tname;
117         // use defaults.lyx as a default template if it exists.
118         if (templatename.empty())
119                 tname = libFileSearch("templates", "defaults.lyx");
120         else
121                 tname = makeAbsPath(templatename);
122
123         if (!tname.empty()) {
124                 if (!b->readFile(tname)) {
125                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
126                         docstring const text  = bformat(
127                                 _("The specified document template\n%1$s\ncould not be read."),
128                                 file);
129                         Alert::error(_("Could not read template"), text);
130                         theBufferList().release(b);
131                         return 0;
132                 }
133         }
134
135         if (!isNamed) {
136                 b->setUnnamed();
137                 b->setFileName(filename);
138         }
139
140         b->setReadonly(false);
141         b->setFullyLoaded(true);
142
143         return b;
144 }
145
146
147 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
148 {
149         static int newfile_number;
150
151         string document_path = path.absFilename();
152         string filename = addName(document_path,
153                 "newfile" + convert<string>(++newfile_number) + ".lyx");
154         while (theBufferList().exists(filename)
155                 || FileName(filename).isReadableFile()) {
156                 ++newfile_number;
157                 filename = addName(document_path,
158                         "newfile" +     convert<string>(newfile_number) + ".lyx");
159         }
160         return newFile(filename, templatename, false);
161 }
162
163
164 int countWords(DocIterator const & from, DocIterator const & to)
165 {
166         int count = 0;
167         bool inword = false;
168         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
169                 // Copied and adapted from isLetter() in ControlSpellChecker
170                 if (dit.inTexted()
171                     && dit.pos() != dit.lastpos()
172                     && dit.paragraph().isLetter(dit.pos())
173                     && !dit.paragraph().isDeleted(dit.pos())) {
174                         if (!inword) {
175                                 ++count;
176                                 inword = true;
177                         }
178                 } else if (inword)
179                         inword = false;
180         }
181
182         return count;
183 }
184
185
186 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
187 {
188         int chars = 0;
189         int blanks = 0;
190         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
191                 if (dit.inTexted()
192                     && dit.pos() != dit.lastpos()
193                     && !dit.paragraph().isDeleted(dit.pos())) {
194                         if (dit.paragraph().isInset(dit.pos())) {
195                                 if (dit.paragraph().getInset(dit.pos())->isLetter())
196                                         ++chars;
197                                 else if (dit.paragraph().getInset(dit.pos())->isSpace() && with_blanks)
198                                         ++blanks;
199                         } else {
200                                 char_type const c = dit.paragraph().getChar(dit.pos());
201                                 if (isPrintableNonspace(c))
202                                         ++chars;
203                                 else if (isSpace(c) && with_blanks)
204                                         ++blanks;
205                         }
206                 }
207         }
208
209         return chars + blanks;
210 }
211
212
213 namespace {
214
215 depth_type getDepth(DocIterator const & it)
216 {
217         depth_type depth = 0;
218         for (size_t i = 0 ; i < it.depth() ; ++i)
219                 if (!it[i].inset().inMathed())
220                         depth += it[i].paragraph().getDepth() + 1;
221         // remove 1 since the outer inset does not count
222         return depth - 1;
223 }
224
225 depth_type getItemDepth(ParIterator const & it)
226 {
227         Paragraph const & par = *it;
228         LabelType const labeltype = par.layout()->labeltype;
229
230         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
231                 return 0;
232
233         // this will hold the lowest depth encountered up to now.
234         depth_type min_depth = getDepth(it);
235         ParIterator prev_it = it;
236         while (true) {
237                 if (prev_it.pit())
238                         --prev_it.top().pit();
239                 else {
240                         // start of nested inset: go to outer par
241                         prev_it.pop_back();
242                         if (prev_it.empty()) {
243                                 // start of document: nothing to do
244                                 return 0;
245                         }
246                 }
247
248                 // We search for the first paragraph with same label
249                 // that is not more deeply nested.
250                 Paragraph & prev_par = *prev_it;
251                 depth_type const prev_depth = getDepth(prev_it);
252                 if (labeltype == prev_par.layout()->labeltype) {
253                         if (prev_depth < min_depth)
254                                 return prev_par.itemdepth + 1;
255                         if (prev_depth == min_depth)
256                                 return prev_par.itemdepth;
257                 }
258                 min_depth = min(min_depth, prev_depth);
259                 // small optimization: if we are at depth 0, we won't
260                 // find anything else
261                 if (prev_depth == 0)
262                         return 0;
263         }
264 }
265
266
267 bool needEnumCounterReset(ParIterator const & it)
268 {
269         Paragraph const & par = *it;
270         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
271         depth_type const cur_depth = par.getDepth();
272         ParIterator prev_it = it;
273         while (prev_it.pit()) {
274                 --prev_it.top().pit();
275                 Paragraph const & prev_par = *prev_it;
276                 if (prev_par.getDepth() <= cur_depth)
277                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
278         }
279         // start of nested inset: reset
280         return true;
281 }
282
283
284 // set the label of a paragraph. This includes the counters.
285 void setLabel(Buffer const & buf, ParIterator & it)
286 {
287         TextClass const & textclass = buf.params().getTextClass();
288         Paragraph & par = it.paragraph();
289         LayoutPtr const & layout = par.layout();
290         Counters & counters = textclass.counters();
291
292         if (par.params().startOfAppendix()) {
293                 // FIXME: only the counter corresponding to toplevel
294                 // sectionning should be reset
295                 counters.reset();
296                 counters.appendix(true);
297         }
298         par.params().appendix(counters.appendix());
299
300         // Compute the item depth of the paragraph
301         par.itemdepth = getItemDepth(it);
302
303         if (layout->margintype == MARGIN_MANUAL) {
304                 if (par.params().labelWidthString().empty())
305                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
306         } else {
307                 par.params().labelWidthString(docstring());
308         }
309
310         switch(layout->labeltype) {
311         case LABEL_COUNTER:
312                 if (layout->toclevel <= buf.params().secnumdepth
313                     && (layout->latextype != LATEX_ENVIRONMENT
314                         || isFirstInSequence(it.pit(), it.plist()))) {
315                         counters.step(layout->counter);
316                         par.params().labelString(
317                                 par.expandLabel(layout, buf.params()));
318                 } else
319                         par.params().labelString(docstring());
320                 break;
321
322         case LABEL_ITEMIZE: {
323                 // At some point of time we should do something more
324                 // clever here, like:
325                 //   par.params().labelString(
326                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
327                 // for now, use a simple hardcoded label
328                 docstring itemlabel;
329                 switch (par.itemdepth) {
330                 case 0:
331                         itemlabel = char_type(0x2022);
332                         break;
333                 case 1:
334                         itemlabel = char_type(0x2013);
335                         break;
336                 case 2:
337                         itemlabel = char_type(0x2217);
338                         break;
339                 case 3:
340                         itemlabel = char_type(0x2219); // or 0x00b7
341                         break;
342                 }
343                 par.params().labelString(itemlabel);
344                 break;
345         }
346
347         case LABEL_ENUMERATE: {
348                 // FIXME: Yes I know this is a really, really! bad solution
349                 // (Lgb)
350                 docstring enumcounter = from_ascii("enum");
351
352                 switch (par.itemdepth) {
353                 case 2:
354                         enumcounter += 'i';
355                 case 1:
356                         enumcounter += 'i';
357                 case 0:
358                         enumcounter += 'i';
359                         break;
360                 case 3:
361                         enumcounter += "iv";
362                         break;
363                 default:
364                         // not a valid enumdepth...
365                         break;
366                 }
367
368                 // Maybe we have to reset the enumeration counter.
369                 if (needEnumCounterReset(it))
370                         counters.reset(enumcounter);
371
372                 counters.step(enumcounter);
373
374                 string format;
375
376                 switch (par.itemdepth) {
377                 case 0:
378                         format = N_("\\arabic{enumi}.");
379                         break;
380                 case 1:
381                         format = N_("(\\alph{enumii})");
382                         break;
383                 case 2:
384                         format = N_("\\roman{enumiii}.");
385                         break;
386                 case 3:
387                         format = N_("\\Alph{enumiv}.");
388                         break;
389                 default:
390                         // not a valid enumdepth...
391                         break;
392                 }
393
394                 par.params().labelString(counters.counterLabel(
395                         par.translateIfPossible(from_ascii(format), buf.params())));
396
397                 break;
398         }
399
400         case LABEL_SENSITIVE: {
401                 string const & type = counters.current_float();
402                 docstring full_label;
403                 if (type.empty())
404                         full_label = buf.B_("Senseless!!! ");
405                 else {
406                         docstring name = buf.B_(textclass.floats().getType(type).name());
407                         if (counters.hasCounter(from_utf8(type))) {
408                                 counters.step(from_utf8(type));
409                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
410                                                      name, 
411                                                      counters.theCounter(from_utf8(type)));
412                         } else
413                                 full_label = bformat(from_ascii("%1$s #:"), name);      
414                 }
415                 par.params().labelString(full_label);   
416                 break;
417         }
418
419         case LABEL_NO_LABEL:
420                 par.params().labelString(docstring());
421                 break;
422
423         case LABEL_MANUAL:
424         case LABEL_TOP_ENVIRONMENT:
425         case LABEL_CENTERED_TOP_ENVIRONMENT:
426         case LABEL_STATIC:      
427         case LABEL_BIBLIO:
428                 par.params().labelString(
429                         par.translateIfPossible(layout->labelstring(), 
430                                                 buf.params()));
431                 break;
432         }
433 }
434
435 } // anon namespace
436
437 void updateLabels(Buffer const & buf, ParIterator & parit)
438 {
439         BOOST_ASSERT(parit.pit() == 0);
440
441         // set the position of the text in the buffer to be able
442         // to resolve macros in it. This has nothing to do with
443         // labels, but by putting it here we avoid implementing
444         // a whole bunch of traversal routines just for this call.
445         parit.text()->setMacrocontextPosition(parit);
446
447         depth_type maxdepth = 0;
448         pit_type const lastpit = parit.lastpit();
449         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
450                 // reduce depth if necessary
451                 parit->params().depth(min(parit->params().depth(), maxdepth));
452                 maxdepth = parit->getMaxDepthAfter();
453
454                 // set the counter for this paragraph
455                 setLabel(buf, parit);
456
457                 // Now the insets
458                 InsetList::const_iterator iit = parit->insetList().begin();
459                 InsetList::const_iterator end = parit->insetList().end();
460                 for (; iit != end; ++iit) {
461                         parit.pos() = iit->pos;
462                         iit->inset->updateLabels(buf, parit);
463                 }
464         }
465         
466 }
467
468
469 // FIXME: buf should should be const because updateLabels() modifies
470 // the contents of the paragraphs.
471 void updateLabels(Buffer const & buf, bool childonly)
472 {
473         Buffer const * const master = buf.masterBuffer();
474         // Use the master text class also for child documents
475         TextClass const & textclass = master->params().getTextClass();
476
477         if (!childonly) {
478                 // If this is a child document start with the master
479                 if (master != &buf) {
480                         updateLabels(*master);
481                         return;
482                 }
483
484                 // start over the counters
485                 textclass.counters().reset();
486         }
487
488         Buffer & cbuf = const_cast<Buffer &>(buf);
489
490         if (buf.text().empty()) {
491                 // FIXME: we don't call continue with updateLabels()
492                 // here because it crashes on newly created documents.
493                 // But the TocBackend needs to be initialised
494                 // nonetheless so we update the tocBackend manually.
495                 cbuf.tocBackend().update();
496                 return;
497         }
498
499         // do the real work
500         ParIterator parit = par_iterator_begin(buf.inset());
501         updateLabels(buf, parit);
502
503         cbuf.tocBackend().update();
504         if (!childonly)
505                 cbuf.structureChanged();
506 }
507
508
509 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
510 {
511         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
512                 Buffer const * master = buffer.masterBuffer();
513                 master->tocBackend().updateItem(par_it);
514                 master->structureChanged();
515         }
516 }
517
518
519 } // namespace lyx