]> git.lyx.org Git - lyx.git/blob - src/buffer.C
move some selection related stuff over to textcursor.C
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "buffer_funcs.h"
15 #include "bufferlist.h"
16 #include "LyXAction.h"
17 #include "lyxrc.h"
18 #include "lyxlex.h"
19 #include "tex-strings.h"
20 #include "layout.h"
21 #include "bufferview_funcs.h"
22 #include "lyxfont.h"
23 #include "version.h"
24 #include "LaTeX.h"
25 #include "Chktex.h"
26 #include "debug.h"
27 #include "LaTeXFeatures.h"
28 #include "lyxtext.h"
29 #include "gettext.h"
30 #include "language.h"
31 #include "exporter.h"
32 #include "errorlist.h"
33 #include "Lsstream.h"
34 #include "format.h"
35 #include "BufferView.h"
36 #include "ParagraphParameters.h"
37 #include "iterators.h"
38 #include "lyxtextclasslist.h"
39 #include "sgml.h"
40 #include "paragraph_funcs.h"
41 #include "messages.h"
42 #include "author.h"
43
44 #include "frontends/LyXView.h"
45
46 #include "mathed/formulamacro.h"
47 #include "mathed/formula.h"
48
49 #include "insets/insetbibitem.h"
50 #include "insets/insetbibtex.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insettext.h"
53
54 #include "frontends/Dialogs.h"
55 #include "frontends/Alert.h"
56
57 #include "graphics/Previews.h"
58
59 #include "support/textutils.h"
60 #include "support/filetools.h"
61 #include "support/path.h"
62 #include "support/os.h"
63 #include "support/tostr.h"
64 #include "support/lyxlib.h"
65 #include "support/FileInfo.h"
66 #include "support/lyxmanip.h"
67 #include "support/lyxtime.h"
68
69 #include <boost/bind.hpp>
70 #include <boost/tuple/tuple.hpp>
71
72 #include <fstream>
73 #include <iomanip>
74 #include <map>
75 #include <stack>
76 #include <list>
77 #include <algorithm>
78
79 #include <cstdlib>
80 #include <cmath>
81 #include <unistd.h>
82 #include <sys/types.h>
83 #include <utime.h>
84
85 #ifdef HAVE_LOCALE
86 #include <locale>
87 #endif
88
89 #ifndef CXX_GLOBAL_CSTD
90 using std::pow;
91 #endif
92
93 using std::ostream;
94 using std::ofstream;
95 using std::ifstream;
96 using std::fstream;
97 using std::ios;
98 using std::setw;
99 using std::endl;
100 using std::pair;
101 using std::make_pair;
102 using std::vector;
103 using std::map;
104 using std::stack;
105 using std::list;
106 using std::for_each;
107
108 using lyx::pos_type;
109 using lyx::textclass_type;
110
111 // all these externs should eventually be removed.
112 extern BufferList bufferlist;
113
114 namespace {
115
116 const int LYX_FORMAT = 224;
117
118 } // namespace anon
119
120 Buffer::Buffer(string const & file, bool ronly)
121         : niceFile(true), lyx_clean(true), bak_clean(true),
122           unnamed(false), read_only(ronly),
123           filename_(file), users(0)
124 {
125         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
126         filepath_ = OnlyPath(file);
127         lyxvc.buffer(this);
128         if (read_only || lyxrc.use_tempdir) {
129                 tmppath = CreateBufferTmpDir();
130         } else {
131                 tmppath.erase();
132         }
133
134         // set initial author
135         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
136 }
137
138
139 Buffer::~Buffer()
140 {
141         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142         // here the buffer should take care that it is
143         // saved properly, before it goes into the void.
144
145         // make sure that views using this buffer
146         // forgets it.
147         if (users)
148                 users->buffer(0);
149
150         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
151                 Alert::warning(_("Could not remove temporary directory"),
152                         bformat(_("Could not remove the temporary directory %1$s"), tmppath));
153         }
154
155         paragraphs.clear();
156
157         // Remove any previewed LaTeX snippets assocoated with this buffer.
158         grfx::Previews::get().removeLoader(this);
159 }
160
161
162 string const Buffer::getLatexName(bool no_path) const
163 {
164         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
165         return no_path ? OnlyFilename(name) : name;
166 }
167
168
169 pair<Buffer::LogType, string> const Buffer::getLogName() const
170 {
171         string const filename = getLatexName(false);
172
173         if (filename.empty())
174                 return make_pair(Buffer::latexlog, string());
175
176         string path = OnlyPath(filename);
177
178         if (lyxrc.use_tempdir || !IsDirWriteable(path))
179                 path = tmppath;
180
181         string const fname = AddName(path,
182                                      OnlyFilename(ChangeExtension(filename,
183                                                                   ".log")));
184         string const bname =
185                 AddName(path, OnlyFilename(
186                         ChangeExtension(filename,
187                                         formats.extension("literate") + ".out")));
188
189         // If no Latex log or Build log is newer, show Build log
190
191         FileInfo const f_fi(fname);
192         FileInfo const b_fi(bname);
193
194         if (b_fi.exist() &&
195             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
196                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
197                 return make_pair(Buffer::buildlog, bname);
198         }
199         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
200         return make_pair(Buffer::latexlog, fname);
201 }
202
203
204 void Buffer::setReadonly(bool flag)
205 {
206         if (read_only != flag) {
207                 read_only = flag;
208                 updateTitles();
209                 if (users)
210                         users->owner()->getDialogs().updateBufferDependent(false);
211         }
212 }
213
214
215 AuthorList & Buffer::authors()
216 {
217         return params.authorlist;
218 }
219
220
221 /// Update window titles of all users
222 // Should work on a list
223 void Buffer::updateTitles() const
224 {
225         if (users)
226                 users->owner()->updateWindowTitle();
227 }
228
229
230 /// Reset autosave timer of all users
231 // Should work on a list
232 void Buffer::resetAutosaveTimers() const
233 {
234         if (users)
235                 users->owner()->resetAutosaveTimer();
236 }
237
238
239 void Buffer::setFileName(string const & newfile)
240 {
241         filename_ = MakeAbsPath(newfile);
242         filepath_ = OnlyPath(filename_);
243         setReadonly(IsFileWriteable(filename_) == 0);
244         updateTitles();
245 }
246
247
248 // We'll remove this later. (Lgb)
249 namespace {
250
251 void unknownClass(string const & unknown)
252 {
253         Alert::warning(_("Unknown document class"),
254                 bformat(_("Using the default document class, because the "
255                         " class %1$s is unknown."), unknown));
256 }
257
258 } // anon
259
260 int Buffer::readHeader(LyXLex & lex)
261 {
262         int unknown_tokens = 0;
263
264         while (lex.isOK()) {
265                 lex.nextToken();
266                 string const token = lex.getString();
267
268                 if (token.empty())
269                         continue;
270
271                 if (token == "\\end_header")
272                         break;
273
274                 lyxerr[Debug::PARSER] << "Handling header token: `"
275                                       << token << '\'' << endl;
276
277
278                 string unknown = params.readToken(lex, token);
279                 if (!unknown.empty()) {
280                         if (unknown[0] != '\\') {
281                                 unknownClass(unknown);
282                         } else {
283                                 ++unknown_tokens;
284                                 string const s = bformat(_("Unknown token: "
285                                                            "%1$s %2$s\n"), 
286                                                          token, 
287                                                          lex.getString());
288                                 parseError(ErrorItem(_("Header error"), s, 
289                                                      -1, 0, 0));
290                         }
291                 }
292         }
293         return unknown_tokens;
294 }
295
296
297 // candidate for move to BufferView
298 // (at least some parts in the beginning of the func)
299 //
300 // Uwe C. Schroeder
301 // changed to be public and have one parameter
302 // if par = 0 normal behavior
303 // else insert behavior
304 // Returns false if "\the_end" is not read (Asger)
305 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
306 {
307         Paragraph::depth_type depth = 0;
308         bool the_end_read = false;
309
310         if (paragraphs.empty()) {
311                 readHeader(lex);
312                 if (!params.getLyXTextClass().load()) {
313                         string theclass = params.getLyXTextClass().name();
314                         Alert::error(_("Can't load document class"), bformat(
315                                         "Using the default document class, because the "
316                                         " class %1$s could not be loaded.", theclass));
317                         params.textclass = 0;
318                 }
319         } else {
320                 // We are inserting into an existing document
321                 users->text->breakParagraph(paragraphs);
322
323                 // We don't want to adopt the parameters from the
324                 // document we insert, so read them into a temporary buffer
325                 // and then discard it
326
327                 Buffer tmpbuf("", false);
328                 tmpbuf.readHeader(lex);
329         }
330
331         while (lex.isOK()) {
332                 lex.nextToken();
333                 string const token = lex.getString();
334
335                 if (token.empty())
336                         continue;
337
338                 lyxerr[Debug::PARSER] << "Handling token: `"
339                                       << token << '\'' << endl;
340
341                 if (token == "\\the_end") {
342                         the_end_read = true;
343                         continue;
344                 }
345
346                 readParagraph(lex, token, paragraphs, pit, depth);
347         }
348
349         return the_end_read;
350 }
351
352
353 int Buffer::readParagraph(LyXLex & lex, string const & token,
354                           ParagraphList & pars, ParagraphList::iterator & pit,
355                           Paragraph::depth_type & depth)
356 {
357         static Change current_change;
358         int unknown = 0;
359
360         if (token == "\\layout") {
361                 lex.pushToken(token);
362
363                 Paragraph par;
364                 par.params().depth(depth);
365                 if (params.tracking_changes)
366                         par.trackChanges();
367                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
368                 par.setFont(0, f);
369
370                 // insert after
371                 if (pit != pars.end())
372                         ++pit;
373
374                 pit = pars.insert(pit, par);
375
376                 // FIXME: goddamn InsetTabular makes us pass a Buffer
377                 // not BufferParams
378                 ::readParagraph(*this, *pit, lex);
379
380         } else if (token == "\\begin_deeper") {
381                 ++depth;
382         } else if (token == "\\end_deeper") {
383                 if (!depth) {
384                         lex.printError("\\end_deeper: " "depth is already null");
385                 } else {
386                         --depth;
387                 }
388         } else {
389                 ++unknown;
390         }
391         return unknown;
392 }
393
394
395 // needed to insert the selection
396 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
397                                  LyXFont const & fn,string const & str)
398 {
399         LyXLayout_ptr const & layout = par->layout();
400
401         LyXFont font = fn;
402
403         par->checkInsertChar(font);
404         // insert the string, don't insert doublespace
405         bool space_inserted = true;
406         bool autobreakrows = !par->inInset() ||
407                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
408         for(string::const_iterator cit = str.begin();
409             cit != str.end(); ++cit) {
410                 if (*cit == '\n') {
411                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
412                                 breakParagraph(params, paragraphs, par, pos,
413                                                layout->isEnvironment());
414                                 ++par;
415                                 pos = 0;
416                                 space_inserted = true;
417                         } else {
418                                 continue;
419                         }
420                         // do not insert consecutive spaces if !free_spacing
421                 } else if ((*cit == ' ' || *cit == '\t') &&
422                            space_inserted && !par->isFreeSpacing()) {
423                         continue;
424                 } else if (*cit == '\t') {
425                         if (!par->isFreeSpacing()) {
426                                 // tabs are like spaces here
427                                 par->insertChar(pos, ' ', font);
428                                 ++pos;
429                                 space_inserted = true;
430                         } else {
431                                 const pos_type nb = 8 - pos % 8;
432                                 for (pos_type a = 0; a < nb ; ++a) {
433                                         par->insertChar(pos, ' ', font);
434                                         ++pos;
435                                 }
436                                 space_inserted = true;
437                         }
438                 } else if (!IsPrintable(*cit)) {
439                         // Ignore unprintables
440                         continue;
441                 } else {
442                         // just insert the character
443                         par->insertChar(pos, *cit, font);
444                         ++pos;
445                         space_inserted = (*cit == ' ');
446                 }
447
448         }
449 }
450
451
452 bool Buffer::readFile(LyXLex & lex, string const & filename)
453 {
454         bool ret = readFile(lex, filename, paragraphs.begin());
455
456         // After we have read a file, we must ensure that the buffer
457         // language is set and used in the gui.
458         // If you know of a better place to put this, please tell me. (Lgb)
459         updateDocLang(params.language);
460
461         return ret;
462 }
463
464
465 // FIXME: all the below Alerts should give the filename..
466 bool Buffer::readFile(LyXLex & lex, string const & filename,
467                       ParagraphList::iterator pit)
468 {
469         if (!lex.isOK()) {
470                 Alert::error(_("Document could not be read"),
471                         _("The specified document could not be read."));
472                 return false;
473         }
474
475         lex.next();
476         string const token(lex.getString());
477
478         if (!lex.isOK()) {
479                 Alert::error(_("Document could not be read"),
480                         _("The specified document could not be read."));
481                 return false;
482         }
483
484         // the first token _must_ be...
485         if (token != "\\lyxformat") {
486                 Alert::error(_("Document format failure"),
487                         _("The specified document is not a LyX document."));
488                 return false;
489         }
490
491         lex.eatLine();
492         string tmp_format = lex.getString();
493         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
494         // if present remove ".," from string.
495         string::size_type dot = tmp_format.find_first_of(".,");
496         //lyxerr << "           dot found at " << dot << endl;
497         if (dot != string::npos)
498                         tmp_format.erase(dot, 1);
499         file_format = strToInt(tmp_format);
500         //lyxerr << "format: " << file_format << endl;
501         if (file_format == LYX_FORMAT) {
502                 // current format
503         } else if (file_format > LYX_FORMAT) {
504                 Alert::warning(_("Document format failure"),
505                         _("This document was created with a newer version of "
506                         "LyX. This is likely to cause problems."));
507         } else if (file_format < LYX_FORMAT) {
508                 // old formats
509                 if (file_format < 200) {
510                         Alert::error(_("Document format failure"),
511                                 _("This LyX document is too old to be read "
512                                 "by this version of LyX. Try LyX 0.10."));
513                         return false;
514                 } else if (!filename.empty()) {
515                         string command =
516                                 LibFileSearch("lyx2lyx", "lyx2lyx");
517                         if (command.empty()) {
518                                 Alert::error(_("Conversion script not found"),
519                                         _("The document is from an earlier version "
520                                           "of LyX, but the conversion script lyx2lyx "
521                                           "could not be found."));
522                                 return false;
523                         }
524                         command += " -t"
525                                 +tostr(LYX_FORMAT) + ' '
526                                 + QuoteName(filename);
527                         lyxerr[Debug::INFO] << "Running '"
528                                             << command << '\''
529                                             << endl;
530                         cmd_ret const ret = RunCommand(command);
531                         if (ret.first) {
532                                 Alert::error(_("Conversion script failed"),
533                                         _("The document is from an earlier version "
534                                           "of LyX, but the lyx2lyx script failed "
535                                           "to convert it."));
536                                 return false;
537                         }
538                         istringstream is(STRCONV(ret.second));
539                         LyXLex tmplex(0, 0);
540                         tmplex.setStream(is);
541                         return readFile(tmplex, string(), pit);
542                 } else {
543                         // This code is reached if lyx2lyx failed (for
544                         // some reason) to change the file format of
545                         // the file.
546                         lyx::Assert(false);
547                         return false;
548                 }
549         }
550         bool the_end = readBody(lex, pit);
551         params.setPaperStuff();
552
553         if (!the_end) {
554                 Alert::error(_("Document format failure"),
555                         _("The document ended unexpectedly, which means "
556                           "that it is probably corrupted."));
557         }
558         return true;
559 }
560
561
562 // Should probably be moved to somewhere else: BufferView? LyXView?
563 bool Buffer::save() const
564 {
565         // We don't need autosaves in the immediate future. (Asger)
566         resetAutosaveTimers();
567
568         // make a backup
569         string s;
570         if (lyxrc.make_backup) {
571                 s = fileName() + '~';
572                 if (!lyxrc.backupdir_path.empty())
573                         s = AddName(lyxrc.backupdir_path,
574                                     subst(os::slashify_path(s),'/','!'));
575
576                 // Rename is the wrong way of making a backup,
577                 // this is the correct way.
578                 /* truss cp fil fil2:
579                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
580                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
581                    open("LyXVC.lyx", O_RDONLY)                     = 3
582                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
583                    fstat(4, 0xEFFFF508)                            = 0
584                    fstat(3, 0xEFFFF508)                            = 0
585                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
586                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
587                    read(3, 0xEFFFD4A0, 8192)                       = 0
588                    close(4)                                        = 0
589                    close(3)                                        = 0
590                    chmod("LyXVC3.lyx", 0100644)                    = 0
591                    lseek(0, 0, SEEK_CUR)                           = 46440
592                    _exit(0)
593                 */
594
595                 // Should probably have some more error checking here.
596                 // Doing it this way, also makes the inodes stay the same.
597                 // This is still not a very good solution, in particular we
598                 // might loose the owner of the backup.
599                 FileInfo finfo(fileName());
600                 if (finfo.exist()) {
601                         mode_t fmode = finfo.getMode();
602                         struct utimbuf times = {
603                                 finfo.getAccessTime(),
604                                 finfo.getModificationTime() };
605
606                         ifstream ifs(fileName().c_str());
607                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
608                         if (ifs && ofs) {
609                                 ofs << ifs.rdbuf();
610                                 ifs.close();
611                                 ofs.close();
612                                 ::chmod(s.c_str(), fmode);
613
614                                 if (::utime(s.c_str(), &times)) {
615                                         lyxerr << "utime error." << endl;
616                                 }
617                         } else {
618                                 lyxerr << "LyX was not able to make "
619                                         "backup copy. Beware." << endl;
620                         }
621                 }
622         }
623
624         if (writeFile(fileName())) {
625                 markClean();
626                 removeAutosaveFile(fileName());
627         } else {
628                 // Saving failed, so backup is not backup
629                 if (lyxrc.make_backup) {
630                         lyx::rename(s, fileName());
631                 }
632                 return false;
633         }
634         return true;
635 }
636
637
638 bool Buffer::writeFile(string const & fname) const
639 {
640         if (read_only && (fname == fileName())) {
641                 return false;
642         }
643
644         FileInfo finfo(fname);
645         if (finfo.exist() && !finfo.writable()) {
646                 return false;
647         }
648
649         ofstream ofs(fname.c_str());
650         if (!ofs) {
651                 return false;
652         }
653
654 #ifdef HAVE_LOCALE
655         // Use the standard "C" locale for file output.
656         ofs.imbue(std::locale::classic());
657 #endif
658
659         // The top of the file should not be written by params.
660
661         // write out a comment in the top of the file
662         ofs << '#' << lyx_docversion
663             << " created this file. For more info see http://www.lyx.org/\n"
664             << "\\lyxformat " << LYX_FORMAT << "\n";
665
666         // now write out the buffer paramters.
667         params.writeFile(ofs);
668
669         ofs << "\\end_header\n";
670
671         Paragraph::depth_type depth = 0;
672
673         // this will write out all the paragraphs
674         // using recursive descent.
675         ParagraphList::const_iterator pit = paragraphs.begin();
676         ParagraphList::const_iterator pend = paragraphs.end();
677         for (; pit != pend; ++pit)
678                 pit->write(this, ofs, params, depth);
679
680         // Write marker that shows file is complete
681         ofs << "\n\\the_end" << endl;
682
683         ofs.close();
684
685         // how to check if close went ok?
686         // Following is an attempt... (BE 20001011)
687
688         // good() returns false if any error occured, including some
689         //        formatting error.
690         // bad()  returns true if something bad happened in the buffer,
691         //        which should include file system full errors.
692
693         bool status = true;
694         if (!ofs.good()) {
695                 status = false;
696 #if 0
697                 if (ofs.bad()) {
698                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
699                 } else {
700                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
701                                << endl;
702                 }
703 #endif
704         }
705
706         return status;
707 }
708
709
710 namespace {
711
712 pair<int, string> const addDepth(int depth, int ldepth)
713 {
714         int d = depth * 2;
715         if (ldepth > depth)
716                 d += (ldepth - depth) * 2;
717         return make_pair(d, string(d, ' '));
718 }
719
720 }
721
722
723 string const Buffer::asciiParagraph(Paragraph const & par,
724                                     unsigned int linelen,
725                                     bool noparbreak) const
726 {
727         ostringstream buffer;
728         int ltype = 0;
729         Paragraph::depth_type ltype_depth = 0;
730         bool ref_printed = false;
731         Paragraph::depth_type depth = par.params().depth();
732
733         // First write the layout
734         string const & tmp = par.layout()->name();
735         if (compare_no_case(tmp, "itemize") == 0) {
736                 ltype = 1;
737                 ltype_depth = depth + 1;
738         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
739                 ltype = 2;
740                 ltype_depth = depth + 1;
741         } else if (contains(ascii_lowercase(tmp), "ection")) {
742                 ltype = 3;
743                 ltype_depth = depth + 1;
744         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
745                 ltype = 4;
746                 ltype_depth = depth + 1;
747         } else if (compare_ascii_no_case(tmp, "description") == 0) {
748                 ltype = 5;
749                 ltype_depth = depth + 1;
750         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
751                 ltype = 6;
752                 ltype_depth = 0;
753         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
754                 ltype = 7;
755                 ltype_depth = 0;
756         } else {
757                 ltype = 0;
758                 ltype_depth = 0;
759         }
760
761         /* maybe some vertical spaces */
762
763         /* the labelwidthstring used in lists */
764
765         /* some lines? */
766
767         /* some pagebreaks? */
768
769         /* noindent ? */
770
771         /* what about the alignment */
772
773         // linelen <= 0 is special and means we don't have paragraph breaks
774
775         string::size_type currlinelen = 0;
776
777         if (!noparbreak) {
778                 if (linelen > 0)
779                         buffer << "\n\n";
780
781                 buffer << string(depth * 2, ' ');
782                 currlinelen += depth * 2;
783
784                 //--
785                 // we should probably change to the paragraph language in the
786                 // gettext here (if possible) so that strings are outputted in
787                 // the correct language! (20012712 Jug)
788                 //--
789                 switch (ltype) {
790                 case 0: // Standard
791                 case 4: // (Sub)Paragraph
792                 case 5: // Description
793                         break;
794                 case 6: // Abstract
795                         if (linelen > 0) {
796                                 buffer << _("Abstract") << "\n\n";
797                                 currlinelen = 0;
798                         } else {
799                                 string const abst = _("Abstract: ");
800                                 buffer << abst;
801                                 currlinelen += abst.length();
802                         }
803                         break;
804                 case 7: // Bibliography
805                         if (!ref_printed) {
806                                 if (linelen > 0) {
807                                         buffer << _("References") << "\n\n";
808                                         currlinelen = 0;
809                                 } else {
810                                         string const refs = _("References: ");
811                                         buffer << refs;
812                                         currlinelen += refs.length();
813                                 }
814
815                                 ref_printed = true;
816                         }
817                         break;
818                 default:
819                 {
820                         string const parlab = par.params().labelString();
821                         buffer << parlab << ' ';
822                         currlinelen += parlab.length() + 1;
823                 }
824                 break;
825
826                 }
827         }
828
829         if (!currlinelen) {
830                 pair<int, string> p = addDepth(depth, ltype_depth);
831                 buffer << p.second;
832                 currlinelen += p.first;
833         }
834
835         // this is to change the linebreak to do it by word a bit more
836         // intelligent hopefully! (only in the case where we have a
837         // max linelength!) (Jug)
838
839         string word;
840
841         for (pos_type i = 0; i < par.size(); ++i) {
842                 char c = par.getUChar(params, i);
843                 switch (c) {
844                 case Paragraph::META_INSET:
845                 {
846                         Inset const * inset = par.getInset(i);
847                         if (inset) {
848                                 if (linelen > 0) {
849                                         buffer << word;
850                                         currlinelen += word.length();
851                                         word.erase();
852                                 }
853                                 if (inset->ascii(this, buffer, linelen)) {
854                                         // to be sure it breaks paragraph
855                                         currlinelen += linelen;
856                                 }
857                         }
858                 }
859                 break;
860
861                 default:
862                         if (c == ' ') {
863                                 if (linelen > 0 &&
864                                     currlinelen + word.length() > linelen - 10) {
865                                         buffer << "\n";
866                                         pair<int, string> p = addDepth(depth, ltype_depth);
867                                         buffer << p.second;
868                                         currlinelen = p.first;
869                                 }
870
871                                 buffer << word << ' ';
872                                 currlinelen += word.length() + 1;
873                                 word.erase();
874
875                         } else {
876                                 if (c != '\0') {
877                                         word += c;
878                                 } else {
879                                         lyxerr[Debug::INFO] <<
880                                                 "writeAsciiFile: NULL char in structure." << endl;
881                                 }
882                                 if ((linelen > 0) &&
883                                         (currlinelen + word.length()) > linelen)
884                                 {
885                                         buffer << "\n";
886
887                                         pair<int, string> p =
888                                                 addDepth(depth, ltype_depth);
889                                         buffer << p.second;
890                                         currlinelen = p.first;
891                                 }
892                         }
893                         break;
894                 }
895         }
896         buffer << word;
897         return STRCONV(buffer.str());
898 }
899
900
901 void Buffer::writeFileAscii(string const & fname, int linelen)
902 {
903         ofstream ofs(fname.c_str());
904         if (!ofs) {
905                 string const file = MakeDisplayPath(fname, 50);
906                 string text = bformat(_("Could not save the document\n%1$s."), file);
907                 Alert::error(_("Could not save document"), text);
908                 return;
909         }
910         writeFileAscii(ofs, linelen);
911 }
912
913
914 void Buffer::writeFileAscii(ostream & os, int linelen)
915 {
916         ParagraphList::iterator beg = paragraphs.begin();
917         ParagraphList::iterator end = paragraphs.end();
918         ParagraphList::iterator it = beg;
919         for (; it != end; ++it) {
920                 os << asciiParagraph(*it, linelen, it == beg);
921         }
922         os << "\n";
923 }
924
925
926
927 void Buffer::makeLaTeXFile(string const & fname,
928                            string const & original_path,
929                            LatexRunParams const & runparams,
930                            bool only_body, bool only_preamble)
931 {
932         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
933
934         ofstream ofs(fname.c_str());
935         if (!ofs) {
936                 string const file = MakeDisplayPath(fname, 50);
937                 string text = bformat(_("Could not open the specified document\n%1$s."),
938                         file);
939                 Alert::error(_("Could not open file"), text);
940                 return;
941         }
942
943         makeLaTeXFile(ofs, original_path,
944                       runparams, only_body, only_preamble);
945
946         ofs.close();
947         if (ofs.fail()) {
948                 lyxerr << "File was not closed properly." << endl;
949         }
950 }
951
952
953 void Buffer::makeLaTeXFile(ostream & os,
954                            string const & original_path,
955                            LatexRunParams const & runparams_in,
956                            bool only_body, bool only_preamble)
957 {
958         LatexRunParams runparams = runparams_in;
959         niceFile = runparams.nice; // this will be used by Insetincludes.
960
961         // validate the buffer.
962         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
963         LaTeXFeatures features(params);
964         validate(features);
965         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
966
967         texrow.reset();
968         // The starting paragraph of the coming rows is the
969         // first paragraph of the document. (Asger)
970         texrow.start(paragraphs.begin()->id(), 0);
971
972         if (!only_body && runparams.nice) {
973                 os << "%% " << lyx_docversion << " created this file.  "
974                         "For more info, see http://www.lyx.org/.\n"
975                         "%% Do not edit unless you really know what "
976                         "you are doing.\n";
977                 texrow.newline();
978                 texrow.newline();
979         }
980         lyxerr[Debug::INFO] << "lyx header finished" << endl;
981         // There are a few differences between nice LaTeX and usual files:
982         // usual is \batchmode and has a
983         // special input@path to allow the including of figures
984         // with either \input or \includegraphics (what figinsets do).
985         // input@path is set when the actual parameter
986         // original_path is set. This is done for usual tex-file, but not
987         // for nice-latex-file. (Matthias 250696)
988         if (!only_body) {
989                 if (!runparams.nice) {
990                         // code for usual, NOT nice-latex-file
991                         os << "\\batchmode\n"; // changed
992                         // from \nonstopmode
993                         texrow.newline();
994                 }
995                 if (!original_path.empty()) {
996                         string inputpath = os::external_path(original_path);
997                         subst(inputpath, "~", "\\string~");
998                         os << "\\makeatletter\n"
999                             << "\\def\\input@path{{"
1000                             << inputpath << "/}}\n"
1001                             << "\\makeatother\n";
1002                         texrow.newline();
1003                         texrow.newline();
1004                         texrow.newline();
1005                 }
1006
1007                 // Write the preamble
1008                 runparams.use_babel = params.writeLaTeX(os, features, texrow);
1009
1010                 if (only_preamble)
1011                         return;
1012
1013                 // make the body.
1014                 os << "\\begin{document}\n";
1015                 texrow.newline();
1016         } // only_body
1017         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1018
1019         if (!lyxrc.language_auto_begin) {
1020                 os << subst(lyxrc.language_command_begin, "$$lang",
1021                              params.language->babel())
1022                     << endl;
1023                 texrow.newline();
1024         }
1025
1026         latexParagraphs(this, paragraphs, os, texrow, runparams);
1027
1028         // add this just in case after all the paragraphs
1029         os << endl;
1030         texrow.newline();
1031
1032         if (!lyxrc.language_auto_end) {
1033                 os << subst(lyxrc.language_command_end, "$$lang",
1034                              params.language->babel())
1035                     << endl;
1036                 texrow.newline();
1037         }
1038
1039         if (!only_body) {
1040                 os << "\\end{document}\n";
1041                 texrow.newline();
1042
1043                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1044         } else {
1045                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1046                                      << endl;
1047         }
1048
1049         // Just to be sure. (Asger)
1050         texrow.newline();
1051
1052         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1053         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1054                             << '.' << endl;
1055
1056         // we want this to be true outside previews (for insetexternal)
1057         niceFile = true;
1058 }
1059
1060
1061 bool Buffer::isLatex() const
1062 {
1063         return params.getLyXTextClass().outputType() == LATEX;
1064 }
1065
1066
1067 bool Buffer::isLinuxDoc() const
1068 {
1069         return params.getLyXTextClass().outputType() == LINUXDOC;
1070 }
1071
1072
1073 bool Buffer::isLiterate() const
1074 {
1075         return params.getLyXTextClass().outputType() == LITERATE;
1076 }
1077
1078
1079 bool Buffer::isDocBook() const
1080 {
1081         return params.getLyXTextClass().outputType() == DOCBOOK;
1082 }
1083
1084
1085 bool Buffer::isSGML() const
1086 {
1087         LyXTextClass const & tclass = params.getLyXTextClass();
1088
1089         return tclass.outputType() == LINUXDOC ||
1090                tclass.outputType() == DOCBOOK;
1091 }
1092
1093
1094 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1095 {
1096         ofstream ofs(fname.c_str());
1097
1098         if (!ofs) {
1099                 string const file = MakeDisplayPath(fname, 50);
1100                 string text = bformat(_("Could not save the specified document\n%1$s.\n"),
1101                         file);
1102                 Alert::error(_("Could not save document"), text);
1103                 return;
1104         }
1105
1106         niceFile = nice; // this will be used by included files.
1107
1108         LaTeXFeatures features(params);
1109
1110         validate(features);
1111
1112         texrow.reset();
1113
1114         LyXTextClass const & tclass = params.getLyXTextClass();
1115
1116         string top_element = tclass.latexname();
1117
1118         if (!body_only) {
1119                 ofs << "<!doctype linuxdoc system";
1120
1121                 string preamble = params.preamble;
1122                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1123                          : fname;
1124                 preamble += features.getIncludedFiles(name);
1125                 preamble += features.getLyXSGMLEntities();
1126
1127                 if (!preamble.empty()) {
1128                         ofs << " [ " << preamble << " ]";
1129                 }
1130                 ofs << ">\n\n";
1131
1132                 if (params.options.empty())
1133                         sgml::openTag(ofs, 0, false, top_element);
1134                 else {
1135                         string top = top_element;
1136                         top += ' ';
1137                         top += params.options;
1138                         sgml::openTag(ofs, 0, false, top);
1139                 }
1140         }
1141
1142         ofs << "<!-- "  << lyx_docversion
1143             << " created this file. For more info see http://www.lyx.org/"
1144             << " -->\n";
1145
1146         Paragraph::depth_type depth = 0; // paragraph depth
1147         string item_name;
1148         vector<string> environment_stack(5);
1149
1150         ParagraphList::iterator pit = paragraphs.begin();
1151         ParagraphList::iterator pend = paragraphs.end();
1152         for (; pit != pend; ++pit) {
1153                 LyXLayout_ptr const & style = pit->layout();
1154                 // treat <toc> as a special case for compatibility with old code
1155                 if (pit->isInset(0)) {
1156                         Inset * inset = pit->getInset(0);
1157                         Inset::Code lyx_code = inset->lyxCode();
1158                         if (lyx_code == Inset::TOC_CODE) {
1159                                 string const temp = "toc";
1160                                 sgml::openTag(ofs, depth, false, temp);
1161                                 continue;
1162                         }
1163                 }
1164
1165                 // environment tag closing
1166                 for (; depth > pit->params().depth(); --depth) {
1167                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1168                         environment_stack[depth].erase();
1169                 }
1170
1171                 // write opening SGML tags
1172                 switch (style->latextype) {
1173                 case LATEX_PARAGRAPH:
1174                         if (depth == pit->params().depth()
1175                            && !environment_stack[depth].empty()) {
1176                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1177                                 environment_stack[depth].erase();
1178                                 if (depth)
1179                                         --depth;
1180                                 else
1181                                         ofs << "</p>";
1182                         }
1183                         sgml::openTag(ofs, depth, false, style->latexname());
1184                         break;
1185
1186                 case LATEX_COMMAND:
1187                         if (depth != 0)
1188                                 parseError(ErrorItem(_("Error:"), _("Wrong depth for LatexType Command.\n"), pit->id(), 0, pit->size()));
1189
1190                         if (!environment_stack[depth].empty()) {
1191                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1192                                 ofs << "</p>";
1193                         }
1194
1195                         environment_stack[depth].erase();
1196                         sgml::openTag(ofs, depth, false, style->latexname());
1197                         break;
1198
1199                 case LATEX_ENVIRONMENT:
1200                 case LATEX_ITEM_ENVIRONMENT:
1201                 case LATEX_BIB_ENVIRONMENT:
1202                 {
1203                         string const & latexname = style->latexname();
1204
1205                         if (depth == pit->params().depth()
1206                             && environment_stack[depth] != latexname) {
1207                                 sgml::closeTag(ofs, depth, false,
1208                                              environment_stack[depth]);
1209                                 environment_stack[depth].erase();
1210                         }
1211                         if (depth < pit->params().depth()) {
1212                                depth = pit->params().depth();
1213                                environment_stack[depth].erase();
1214                         }
1215                         if (environment_stack[depth] != latexname) {
1216                                 if (depth == 0) {
1217                                         sgml::openTag(ofs, depth, false, "p");
1218                                 }
1219                                 sgml::openTag(ofs, depth, false, latexname);
1220
1221                                 if (environment_stack.size() == depth + 1)
1222                                         environment_stack.push_back("!-- --");
1223                                 environment_stack[depth] = latexname;
1224                         }
1225
1226                         if (style->latexparam() == "CDATA")
1227                                 ofs << "<![CDATA[";
1228
1229                         if (style->latextype == LATEX_ENVIRONMENT) break;
1230
1231                         if (style->labeltype == LABEL_MANUAL)
1232                                 item_name = "tag";
1233                         else
1234                                 item_name = "item";
1235
1236                         sgml::openTag(ofs, depth + 1, false, item_name);
1237                 }
1238                 break;
1239
1240                 default:
1241                         sgml::openTag(ofs, depth, false, style->latexname());
1242                         break;
1243                 }
1244
1245                 simpleLinuxDocOnePar(ofs, pit, depth);
1246
1247                 ofs << "\n";
1248                 // write closing SGML tags
1249                 switch (style->latextype) {
1250                 case LATEX_COMMAND:
1251                         break;
1252                 case LATEX_ENVIRONMENT:
1253                 case LATEX_ITEM_ENVIRONMENT:
1254                 case LATEX_BIB_ENVIRONMENT:
1255                         if (style->latexparam() == "CDATA")
1256                                 ofs << "]]>";
1257                         break;
1258                 default:
1259                         sgml::closeTag(ofs, depth, false, style->latexname());
1260                         break;
1261                 }
1262         }
1263
1264         // Close open tags
1265         for (int i = depth; i >= 0; --i)
1266                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1267
1268         if (!body_only) {
1269                 ofs << "\n\n";
1270                 sgml::closeTag(ofs, 0, false, top_element);
1271         }
1272
1273         ofs.close();
1274         // How to check for successful close
1275
1276         // we want this to be true outside previews (for insetexternal)
1277         niceFile = true;
1278 }
1279
1280
1281 // checks, if newcol chars should be put into this line
1282 // writes newline, if necessary.
1283 namespace {
1284
1285 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1286                           string::size_type newcol)
1287 {
1288         colcount += newcol;
1289         if (colcount > lyxrc.ascii_linelen) {
1290                 os << "\n";
1291                 colcount = newcol; // assume write after this call
1292         }
1293 }
1294
1295 enum PAR_TAG {
1296         NONE=0,
1297         TT = 1,
1298         SF = 2,
1299         BF = 4,
1300         IT = 8,
1301         SL = 16,
1302         EM = 32
1303 };
1304
1305
1306 string tag_name(PAR_TAG const & pt) {
1307         switch (pt) {
1308         case NONE: return "!-- --";
1309         case TT: return "tt";
1310         case SF: return "sf";
1311         case BF: return "bf";
1312         case IT: return "it";
1313         case SL: return "sl";
1314         case EM: return "em";
1315         }
1316         return "";
1317 }
1318
1319
1320 inline
1321 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1322 {
1323         p1 = static_cast<PAR_TAG>(p1 | p2);
1324 }
1325
1326
1327 inline
1328 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1329 {
1330         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1331 }
1332
1333 } // anon
1334
1335
1336 // Handle internal paragraph parsing -- layout already processed.
1337 void Buffer::simpleLinuxDocOnePar(ostream & os,
1338         ParagraphList::iterator par,
1339         Paragraph::depth_type /*depth*/) const
1340 {
1341         LyXLayout_ptr const & style = par->layout();
1342
1343         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1344
1345         // gets paragraph main font
1346         LyXFont font_old;
1347         bool desc_on;
1348         if (style->labeltype == LABEL_MANUAL) {
1349                 font_old = style->labelfont;
1350                 desc_on = true;
1351         } else {
1352                 font_old = style->font;
1353                 desc_on = false;
1354         }
1355
1356         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1357         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1358         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1359         bool is_em = false;
1360
1361         stack<PAR_TAG> tag_state;
1362         // parsing main loop
1363         for (pos_type i = 0; i < par->size(); ++i) {
1364
1365                 PAR_TAG tag_close = NONE;
1366                 list < PAR_TAG > tag_open;
1367
1368                 LyXFont const font = par->getFont(params, i, outerFont(par, paragraphs));
1369
1370                 if (font_old.family() != font.family()) {
1371                         switch (family_type) {
1372                         case LyXFont::SANS_FAMILY:
1373                                 tag_close |= SF;
1374                                 break;
1375                         case LyXFont::TYPEWRITER_FAMILY:
1376                                 tag_close |= TT;
1377                                 break;
1378                         default:
1379                                 break;
1380                         }
1381
1382                         family_type = font.family();
1383
1384                         switch (family_type) {
1385                         case LyXFont::SANS_FAMILY:
1386                                 tag_open.push_back(SF);
1387                                 break;
1388                         case LyXFont::TYPEWRITER_FAMILY:
1389                                 tag_open.push_back(TT);
1390                                 break;
1391                         default:
1392                                 break;
1393                         }
1394                 }
1395
1396                 if (font_old.series() != font.series()) {
1397                         switch (series_type) {
1398                         case LyXFont::BOLD_SERIES:
1399                                 tag_close |= BF;
1400                                 break;
1401                         default:
1402                                 break;
1403                         }
1404
1405                         series_type = font.series();
1406
1407                         switch (series_type) {
1408                         case LyXFont::BOLD_SERIES:
1409                                 tag_open.push_back(BF);
1410                                 break;
1411                         default:
1412                                 break;
1413                         }
1414
1415                 }
1416
1417                 if (font_old.shape() != font.shape()) {
1418                         switch (shape_type) {
1419                         case LyXFont::ITALIC_SHAPE:
1420                                 tag_close |= IT;
1421                                 break;
1422                         case LyXFont::SLANTED_SHAPE:
1423                                 tag_close |= SL;
1424                                 break;
1425                         default:
1426                                 break;
1427                         }
1428
1429                         shape_type = font.shape();
1430
1431                         switch (shape_type) {
1432                         case LyXFont::ITALIC_SHAPE:
1433                                 tag_open.push_back(IT);
1434                                 break;
1435                         case LyXFont::SLANTED_SHAPE:
1436                                 tag_open.push_back(SL);
1437                                 break;
1438                         default:
1439                                 break;
1440                         }
1441                 }
1442                 // handle <em> tag
1443                 if (font_old.emph() != font.emph()) {
1444                         if (font.emph() == LyXFont::ON) {
1445                                 tag_open.push_back(EM);
1446                                 is_em = true;
1447                         }
1448                         else if (is_em) {
1449                                 tag_close |= EM;
1450                                 is_em = false;
1451                         }
1452                 }
1453
1454                 list < PAR_TAG > temp;
1455                 while (!tag_state.empty() && tag_close) {
1456                         PAR_TAG k =  tag_state.top();
1457                         tag_state.pop();
1458                         os << "</" << tag_name(k) << '>';
1459                         if (tag_close & k)
1460                                 reset(tag_close,k);
1461                         else
1462                                 temp.push_back(k);
1463                 }
1464
1465                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1466                     j != temp.end(); ++j) {
1467                         tag_state.push(*j);
1468                         os << '<' << tag_name(*j) << '>';
1469                 }
1470
1471                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1472                     j != tag_open.end(); ++j) {
1473                         tag_state.push(*j);
1474                         os << '<' << tag_name(*j) << '>';
1475                 }
1476
1477                 char c = par->getChar(i);
1478
1479                 if (c == Paragraph::META_INSET) {
1480                         Inset * inset = par->getInset(i);
1481                         inset->linuxdoc(this, os);
1482                         font_old = font;
1483                         continue;
1484                 }
1485
1486                 if (style->latexparam() == "CDATA") {
1487                         // "TeX"-Mode on == > SGML-Mode on.
1488                         if (c != '\0')
1489                                 os << c;
1490                         ++char_line_count;
1491                 } else {
1492                         bool ws;
1493                         string str;
1494                         boost::tie(ws, str) = sgml::escapeChar(c);
1495                         if (ws && !par->isFreeSpacing()) {
1496                                 // in freespacing mode, spaces are
1497                                 // non-breaking characters
1498                                 if (desc_on) {// if char is ' ' then...
1499
1500                                         ++char_line_count;
1501                                         sgmlLineBreak(os, char_line_count, 6);
1502                                         os << "</tag>";
1503                                         desc_on = false;
1504                                 } else  {
1505                                         sgmlLineBreak(os, char_line_count, 1);
1506                                         os << c;
1507                                 }
1508                         } else {
1509                                 os << str;
1510                                 char_line_count += str.length();
1511                         }
1512                 }
1513                 font_old = font;
1514         }
1515
1516         while (!tag_state.empty()) {
1517                 os << "</" << tag_name(tag_state.top()) << '>';
1518                 tag_state.pop();
1519         }
1520
1521         // resets description flag correctly
1522         if (desc_on) {
1523                 // <tag> not closed...
1524                 sgmlLineBreak(os, char_line_count, 6);
1525                 os << "</tag>";
1526         }
1527 }
1528
1529
1530 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1531 {
1532         ofstream ofs(fname.c_str());
1533         if (!ofs) {
1534                 string const file = MakeDisplayPath(fname, 50);
1535                 string text = bformat(_("Could not save the specified document\n%1$s.\n"),
1536                         file);
1537                 Alert::error(_("Could not save document"), text);
1538                 return;
1539         }
1540
1541         niceFile = nice; // this will be used by Insetincludes.
1542
1543         LaTeXFeatures features(params);
1544         validate(features);
1545
1546         texrow.reset();
1547
1548         LyXTextClass const & tclass = params.getLyXTextClass();
1549         string top_element = tclass.latexname();
1550
1551         if (!only_body) {
1552                 ofs << "<!DOCTYPE " << top_element
1553                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1554
1555                 string preamble = params.preamble;
1556                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1557                          : fname;
1558                 preamble += features.getIncludedFiles(name);
1559                 preamble += features.getLyXSGMLEntities();
1560
1561                 if (!preamble.empty()) {
1562                         ofs << "\n [ " << preamble << " ]";
1563                 }
1564                 ofs << ">\n\n";
1565         }
1566
1567         string top = top_element;
1568         top += " lang=\"";
1569         top += params.language->code();
1570         top += '"';
1571
1572         if (!params.options.empty()) {
1573                 top += ' ';
1574                 top += params.options;
1575         }
1576         sgml::openTag(ofs, 0, false, top);
1577
1578         ofs << "<!-- DocBook file was created by " << lyx_docversion
1579             << "\n  See http://www.lyx.org/ for more information -->\n";
1580
1581         vector<string> environment_stack(10);
1582         vector<string> environment_inner(10);
1583         vector<string> command_stack(10);
1584
1585         bool command_flag = false;
1586         Paragraph::depth_type command_depth = 0;
1587         Paragraph::depth_type command_base = 0;
1588         Paragraph::depth_type cmd_depth = 0;
1589         Paragraph::depth_type depth = 0; // paragraph depth
1590
1591         string item_name;
1592         string command_name;
1593
1594         ParagraphList::iterator par = paragraphs.begin();
1595         ParagraphList::iterator pend = paragraphs.end();
1596
1597         for (; par != pend; ++par) {
1598                 string sgmlparam;
1599                 string c_depth;
1600                 string c_params;
1601                 int desc_on = 0; // description mode
1602
1603                 LyXLayout_ptr const & style = par->layout();
1604
1605                 // environment tag closing
1606                 for (; depth > par->params().depth(); --depth) {
1607                         if (environment_inner[depth] != "!-- --" && !environment_inner[depth].empty()) {
1608                                 item_name = "listitem";
1609                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1610                                 if (environment_inner[depth] == "varlistentry")
1611                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1612                         }
1613                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1614                         environment_stack[depth].erase();
1615                         environment_inner[depth].erase();
1616                 }
1617
1618                 if (depth == par->params().depth()
1619                    && environment_stack[depth] != style->latexname()
1620                    && !environment_stack[depth].empty()) {
1621                         if (environment_inner[depth] != "!-- --") {
1622                                 item_name= "listitem";
1623                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1624                                 if (environment_inner[depth] == "varlistentry")
1625                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1626                         }
1627
1628                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1629
1630                         environment_stack[depth].erase();
1631                         environment_inner[depth].erase();
1632                 }
1633
1634                 // Write opening SGML tags.
1635                 switch (style->latextype) {
1636                 case LATEX_PARAGRAPH:
1637                         sgml::openTag(ofs, depth + command_depth,
1638                                     false, style->latexname());
1639                         break;
1640
1641                 case LATEX_COMMAND:
1642                         if (depth != 0)
1643                                 parseError(ErrorItem(_("Error"), _("Wrong depth for LatexType Command."), par->id(), 0, par->size()));
1644
1645                         command_name = style->latexname();
1646
1647                         sgmlparam = style->latexparam();
1648                         c_params = split(sgmlparam, c_depth,'|');
1649
1650                         cmd_depth = lyx::atoi(c_depth);
1651
1652                         if (command_flag) {
1653                                 if (cmd_depth < command_base) {
1654                                         for (Paragraph::depth_type j = command_depth;
1655                                              j >= command_base; --j) {
1656                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1657                                                 ofs << endl;
1658                                         }
1659                                         command_depth = command_base = cmd_depth;
1660                                 } else if (cmd_depth <= command_depth) {
1661                                         for (int j = command_depth;
1662                                              j >= int(cmd_depth); --j) {
1663                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1664                                                 ofs << endl;
1665                                         }
1666                                         command_depth = cmd_depth;
1667                                 } else
1668                                         command_depth = cmd_depth;
1669                         } else {
1670                                 command_depth = command_base = cmd_depth;
1671                                 command_flag = true;
1672                         }
1673                         if (command_stack.size() == command_depth + 1)
1674                                 command_stack.push_back(string());
1675                         command_stack[command_depth] = command_name;
1676
1677                         // treat label as a special case for
1678                         // more WYSIWYM handling.
1679                         // This is a hack while paragraphs can't have
1680                         // attributes, like id in this case.
1681                         if (par->isInset(0)) {
1682                                 Inset * inset = par->getInset(0);
1683                                 Inset::Code lyx_code = inset->lyxCode();
1684                                 if (lyx_code == Inset::LABEL_CODE) {
1685                                         command_name += " id=\"";
1686                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1687                                         command_name += '"';
1688                                         desc_on = 3;
1689                                 }
1690                         }
1691
1692                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1693
1694                         item_name = c_params.empty() ? "title" : c_params;
1695                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1696                         break;
1697
1698                 case LATEX_ENVIRONMENT:
1699                 case LATEX_ITEM_ENVIRONMENT:
1700                         if (depth < par->params().depth()) {
1701                                 depth = par->params().depth();
1702                                 environment_stack[depth].erase();
1703                         }
1704
1705                         if (environment_stack[depth] != style->latexname()) {
1706                                 if (environment_stack.size() == depth + 1) {
1707                                         environment_stack.push_back("!-- --");
1708                                         environment_inner.push_back("!-- --");
1709                                 }
1710                                 environment_stack[depth] = style->latexname();
1711                                 environment_inner[depth] = "!-- --";
1712                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1713                         } else {
1714                                 if (environment_inner[depth] != "!-- --") {
1715                                         item_name= "listitem";
1716                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1717                                         if (environment_inner[depth] == "varlistentry")
1718                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1719                                 }
1720                         }
1721
1722                         if (style->latextype == LATEX_ENVIRONMENT) {
1723                                 if (!style->latexparam().empty()) {
1724                                         if (style->latexparam() == "CDATA")
1725                                                 ofs << "<![CDATA[";
1726                                         else
1727                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1728                                 }
1729                                 break;
1730                         }
1731
1732                         desc_on = (style->labeltype == LABEL_MANUAL);
1733
1734                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1735                         sgml::openTag(ofs, depth + 1 + command_depth,
1736                                     false, environment_inner[depth]);
1737
1738                         item_name = desc_on ? "term" : "para";
1739                         sgml::openTag(ofs, depth + 1 + command_depth,
1740                                     false, item_name);
1741                         break;
1742                 default:
1743                         sgml::openTag(ofs, depth + command_depth,
1744                                     false, style->latexname());
1745                         break;
1746                 }
1747
1748                 simpleDocBookOnePar(ofs, par, desc_on,
1749                                     depth + 1 + command_depth);
1750
1751                 string end_tag;
1752                 // write closing SGML tags
1753                 switch (style->latextype) {
1754                 case LATEX_COMMAND:
1755                         end_tag = c_params.empty() ? "title" : c_params;
1756                         sgml::closeTag(ofs, depth + command_depth,
1757                                      false, end_tag);
1758                         break;
1759                 case LATEX_ENVIRONMENT:
1760                         if (!style->latexparam().empty()) {
1761                                 if (style->latexparam() == "CDATA")
1762                                         ofs << "]]>";
1763                                 else
1764                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1765                         }
1766                         break;
1767                 case LATEX_ITEM_ENVIRONMENT:
1768                         if (desc_on == 1) break;
1769                         end_tag = "para";
1770                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1771                         break;
1772                 case LATEX_PARAGRAPH:
1773                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1774                         break;
1775                 default:
1776                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1777                         break;
1778                 }
1779         }
1780
1781         // Close open tags
1782         for (int d = depth; d >= 0; --d) {
1783                 if (!environment_stack[depth].empty()) {
1784                         if (environment_inner[depth] != "!-- --") {
1785                                 item_name = "listitem";
1786                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1787                                if (environment_inner[depth] == "varlistentry")
1788                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1789                         }
1790
1791                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1792                 }
1793         }
1794
1795         for (int j = command_depth; j >= 0 ; --j)
1796                 if (!command_stack[j].empty()) {
1797                         sgml::closeTag(ofs, j, false, command_stack[j]);
1798                         ofs << endl;
1799                 }
1800
1801         ofs << "\n\n";
1802         sgml::closeTag(ofs, 0, false, top_element);
1803
1804         ofs.close();
1805         // How to check for successful close
1806
1807         // we want this to be true outside previews (for insetexternal)
1808         niceFile = true;
1809 }
1810
1811
1812 void Buffer::simpleDocBookOnePar(ostream & os,
1813                                  ParagraphList::iterator par, int & desc_on,
1814                                  Paragraph::depth_type depth) const
1815 {
1816         bool emph_flag = false;
1817
1818         LyXLayout_ptr const & style = par->layout();
1819
1820         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1821
1822         int char_line_count = depth;
1823         //if (!style.free_spacing)
1824         //      os << string(depth,' ');
1825
1826         // parsing main loop
1827         for (pos_type i = 0; i < par->size(); ++i) {
1828                 LyXFont font = par->getFont(params, i, outerFont(par, paragraphs));
1829
1830                 // handle <emphasis> tag
1831                 if (font_old.emph() != font.emph()) {
1832                         if (font.emph() == LyXFont::ON) {
1833                                 if (style->latexparam() == "CDATA")
1834                                         os << "]]>";
1835                                 os << "<emphasis>";
1836                                 if (style->latexparam() == "CDATA")
1837                                         os << "<![CDATA[";
1838                                 emph_flag = true;
1839                         } else if (i) {
1840                                 if (style->latexparam() == "CDATA")
1841                                         os << "]]>";
1842                                 os << "</emphasis>";
1843                                 if (style->latexparam() == "CDATA")
1844                                         os << "<![CDATA[";
1845                                 emph_flag = false;
1846                         }
1847                 }
1848
1849
1850                 if (par->isInset(i)) {
1851                         Inset * inset = par->getInset(i);
1852                         // don't print the inset in position 0 if desc_on == 3 (label)
1853                         if (i || desc_on != 3) {
1854                                 if (style->latexparam() == "CDATA")
1855                                         os << "]]>";
1856                                 inset->docbook(this, os, false);
1857                                 if (style->latexparam() == "CDATA")
1858                                         os << "<![CDATA[";
1859                         }
1860                 } else {
1861                         char c = par->getChar(i);
1862                         bool ws;
1863                         string str;
1864                         boost::tie(ws, str) = sgml::escapeChar(c);
1865
1866                         if (style->pass_thru) {
1867                                 os << c;
1868                         } else if (par->isFreeSpacing() || c != ' ') {
1869                                         os << str;
1870                         } else if (desc_on == 1) {
1871                                 ++char_line_count;
1872                                 os << "\n</term><listitem><para>";
1873                                 desc_on = 2;
1874                         } else {
1875                                 os << ' ';
1876                         }
1877                 }
1878                 font_old = font;
1879         }
1880
1881         if (emph_flag) {
1882                 if (style->latexparam() == "CDATA")
1883                         os << "]]>";
1884                 os << "</emphasis>";
1885                 if (style->latexparam() == "CDATA")
1886                         os << "<![CDATA[";
1887         }
1888
1889         // resets description flag correctly
1890         if (desc_on == 1) {
1891                 // <term> not closed...
1892                 os << "</term>\n<listitem><para>&nbsp;</para>";
1893         }
1894         if (style->free_spacing)
1895                 os << '\n';
1896 }
1897
1898
1899 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1900 // Other flags: -wall -v0 -x
1901 int Buffer::runChktex()
1902 {
1903         if (!users->text) return 0;
1904
1905         users->owner()->busy(true);
1906
1907         // get LaTeX-Filename
1908         string const name = getLatexName();
1909         string path = filePath();
1910
1911         string const org_path = path;
1912         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1913                 path = tmppath;
1914         }
1915
1916         Path p(path); // path to LaTeX file
1917         users->owner()->message(_("Running chktex..."));
1918
1919         // Generate the LaTeX file if neccessary
1920         LatexRunParams runparams;
1921         runparams.flavor = LatexRunParams::LATEX;
1922         runparams.nice = false;
1923         makeLaTeXFile(name, org_path, runparams);
1924
1925         TeXErrors terr;
1926         Chktex chktex(lyxrc.chktex_command, name, filePath());
1927         int res = chktex.run(terr); // run chktex
1928
1929         if (res == -1) {
1930                 Alert::error(_("chktex failure"),
1931                              _("Could not run chktex successfully."));
1932         } else if (res > 0) {
1933                 // Insert all errors as errors boxes
1934                 parseErrors(*this, terr);
1935         }
1936
1937         users->owner()->busy(false);
1938
1939         return res;
1940 }
1941
1942
1943 void Buffer::validate(LaTeXFeatures & features) const
1944 {
1945         LyXTextClass const & tclass = params.getLyXTextClass();
1946
1947         if (params.tracking_changes) {
1948                 features.require("dvipost");
1949                 features.require("color");
1950         }
1951
1952         // AMS Style is at document level
1953         if (params.use_amsmath == BufferParams::AMS_ON
1954             || tclass.provides(LyXTextClass::amsmath))
1955                 features.require("amsmath");
1956
1957         for_each(paragraphs.begin(), paragraphs.end(),
1958                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1959
1960         // the bullet shapes are buffer level not paragraph level
1961         // so they are tested here
1962         for (int i = 0; i < 4; ++i) {
1963                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1964                         int const font = params.user_defined_bullets[i].getFont();
1965                         if (font == 0) {
1966                                 int const c = params
1967                                         .user_defined_bullets[i]
1968                                         .getCharacter();
1969                                 if (c == 16
1970                                    || c == 17
1971                                    || c == 25
1972                                    || c == 26
1973                                    || c == 31) {
1974                                         features.require("latexsym");
1975                                 }
1976                         } else if (font == 1) {
1977                                 features.require("amssymb");
1978                         } else if ((font >= 2 && font <= 5)) {
1979                                 features.require("pifont");
1980                         }
1981                 }
1982         }
1983
1984         if (lyxerr.debugging(Debug::LATEX)) {
1985                 features.showStruct();
1986         }
1987 }
1988
1989
1990 void Buffer::getLabelList(std::vector<string> & list) const
1991 {
1992         /// if this is a child document and the parent is already loaded
1993         /// Use the parent's list instead  [ale990407]
1994         if (!params.parentname.empty()
1995             && bufferlist.exists(params.parentname)) {
1996                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
1997                 if (tmp) {
1998                         tmp->getLabelList(list);
1999                         return;
2000                 }
2001         }
2002
2003         for (inset_iterator it = inset_const_iterator_begin();
2004              it != inset_const_iterator_end(); ++it) {
2005                 it->getLabelList(list);
2006         }
2007 }
2008
2009
2010 // This is also a buffer property (ale)
2011 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2012 {
2013         /// if this is a child document and the parent is already loaded
2014         /// use the parent's list instead  [ale990412]
2015         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2016                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2017                 if (tmp) {
2018                         tmp->fillWithBibKeys(keys);
2019                         return;
2020                 }
2021         }
2022
2023         for (inset_iterator it = inset_const_iterator_begin();
2024                 it != inset_const_iterator_end(); ++it) {
2025                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2026                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2027                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2028                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2029                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2030                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2031                         string const key = bib.getContents();
2032                         string const opt = bib.getOptions();
2033                         string const ref; // = pit->asString(this, false);
2034                         string const info = opt + "TheBibliographyRef" + ref;
2035                         keys.push_back(pair<string, string>(key, info));
2036                 }
2037         }
2038 }
2039
2040
2041 bool Buffer::isDepClean(string const & name) const
2042 {
2043         DepClean::const_iterator it = dep_clean_.find(name);
2044         if (it == dep_clean_.end())
2045                 return true;
2046         return it->second;
2047 }
2048
2049
2050 void Buffer::markDepClean(string const & name)
2051 {
2052         dep_clean_[name] = true;
2053 }
2054
2055
2056 bool Buffer::dispatch(string const & command, bool * result)
2057 {
2058         // Split command string into command and argument
2059         string cmd;
2060         string line = ltrim(command);
2061         string const arg = trim(split(line, cmd, ' '));
2062
2063         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2064 }
2065
2066
2067 bool Buffer::dispatch(int action, string const & argument, bool * result)
2068 {
2069         bool dispatched = true;
2070
2071         switch (action) {
2072                 case LFUN_EXPORT: {
2073                         bool const tmp = Exporter::Export(this, argument, false);
2074                         if (result)
2075                                 *result = tmp;
2076                         break;
2077                 }
2078
2079                 default:
2080                         dispatched = false;
2081         }
2082         return dispatched;
2083 }
2084
2085
2086 void Buffer::resizeInsets(BufferView * bv)
2087 {
2088         /// then remove all LyXText in text-insets
2089         for_each(paragraphs.begin(), paragraphs.end(),
2090                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2091 }
2092
2093
2094 void Buffer::redraw()
2095 {
2096 #warning repaint needed here, or do you mean update() ?
2097         users->repaint();
2098         users->fitCursor();
2099 }
2100
2101
2102 void Buffer::changeLanguage(Language const * from, Language const * to)
2103 {
2104         lyxerr << "Changing Language!" << endl;
2105
2106         // Take care of l10n/i18n
2107         updateDocLang(to);
2108
2109         ParIterator end = par_iterator_end();
2110         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2111                 it->changeLanguage(params, from, to);
2112 }
2113
2114
2115 void Buffer::updateDocLang(Language const * nlang)
2116 {
2117         messages_.reset(new Messages(nlang->code()));
2118 }
2119
2120
2121 bool Buffer::isMultiLingual()
2122 {
2123         ParIterator end = par_iterator_end();
2124         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2125                 if (it->isMultiLingual(params))
2126                         return true;
2127
2128         return false;
2129 }
2130
2131
2132 void Buffer::inset_iterator::setParagraph()
2133 {
2134         while (pit != pend) {
2135                 it = pit->insetlist.begin();
2136                 if (it != pit->insetlist.end())
2137                         return;
2138                 ++pit;
2139         }
2140 }
2141
2142
2143 Inset * Buffer::getInsetFromID(int id_arg) const
2144 {
2145         for (inset_iterator it = inset_const_iterator_begin();
2146                  it != inset_const_iterator_end(); ++it)
2147         {
2148                 if (it->id() == id_arg)
2149                         return &(*it);
2150                 Inset * in = it->getInsetFromID(id_arg);
2151                 if (in)
2152                         return in;
2153         }
2154         return 0;
2155 }
2156
2157
2158 ParIterator Buffer::getParFromID(int id) const
2159 {
2160 #warning FIXME: const correctness! (Andre)
2161         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
2162         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
2163
2164 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2165         if (id < 0) {
2166                 // John says this is called with id == -1 from undo
2167                 lyxerr << "getParFromID(), id: " << id << endl;
2168                 return end;
2169         }
2170
2171         for (; it != end; ++it)
2172                 if (it->id() == id)
2173                         return it;
2174
2175         return end;
2176 }
2177
2178
2179 bool Buffer::hasParWithID(int id) const
2180 {
2181         ParConstIterator it = par_iterator_begin();
2182         ParConstIterator end = par_iterator_end();
2183
2184         if (id < 0) {
2185                 // John says this is called with id == -1 from undo
2186                 lyxerr << "hasParWithID(), id: " << id << endl;
2187                 return 0;
2188         }
2189
2190         for (; it != end; ++it)
2191                 if (it->id() == id)
2192                         return true;
2193
2194         return false;
2195 }
2196
2197
2198 ParIterator Buffer::par_iterator_begin()
2199 {
2200         return ParIterator(paragraphs.begin(), paragraphs);
2201 }
2202
2203
2204 ParIterator Buffer::par_iterator_end()
2205 {
2206         return ParIterator(paragraphs.end(), paragraphs);
2207 }
2208
2209 ParConstIterator Buffer::par_iterator_begin() const
2210 {
2211         return ParConstIterator(const_cast<ParagraphList&>(paragraphs).begin(), paragraphs);
2212 }
2213
2214
2215 ParConstIterator Buffer::par_iterator_end() const
2216 {
2217         return ParConstIterator(const_cast<ParagraphList&>(paragraphs).end(), paragraphs);
2218 }
2219
2220
2221
2222 void Buffer::addUser(BufferView * u)
2223 {
2224         users = u;
2225 }
2226
2227
2228 void Buffer::delUser(BufferView *)
2229 {
2230         users = 0;
2231 }
2232
2233
2234 Language const * Buffer::getLanguage() const
2235 {
2236         return params.language;
2237 }
2238
2239
2240 string const Buffer::B_(string const & l10n) const
2241 {
2242         if (messages_.get()) {
2243                 return messages_->get(l10n);
2244         }
2245
2246         return _(l10n);
2247 }
2248
2249
2250 bool Buffer::isClean() const
2251 {
2252         return lyx_clean;
2253 }
2254
2255
2256 bool Buffer::isBakClean() const
2257 {
2258         return bak_clean;
2259 }
2260
2261
2262 void Buffer::markClean() const
2263 {
2264         if (!lyx_clean) {
2265                 lyx_clean = true;
2266                 updateTitles();
2267         }
2268         // if the .lyx file has been saved, we don't need an
2269         // autosave
2270         bak_clean = true;
2271 }
2272
2273
2274 void Buffer::markBakClean()
2275 {
2276         bak_clean = true;
2277 }
2278
2279
2280 void Buffer::setUnnamed(bool flag)
2281 {
2282         unnamed = flag;
2283 }
2284
2285
2286 bool Buffer::isUnnamed()
2287 {
2288         return unnamed;
2289 }
2290
2291
2292 void Buffer::markDirty()
2293 {
2294         if (lyx_clean) {
2295                 lyx_clean = false;
2296                 updateTitles();
2297         }
2298         bak_clean = false;
2299
2300         DepClean::iterator it = dep_clean_.begin();
2301         DepClean::const_iterator const end = dep_clean_.end();
2302
2303         for (; it != end; ++it) {
2304                 it->second = false;
2305         }
2306 }
2307
2308
2309 string const & Buffer::fileName() const
2310 {
2311         return filename_;
2312 }
2313
2314
2315 string const & Buffer::filePath() const
2316 {
2317         return filepath_;
2318 }
2319
2320
2321 bool Buffer::isReadonly() const
2322 {
2323         return read_only;
2324 }
2325
2326
2327 BufferView * Buffer::getUser() const
2328 {
2329         return users;
2330 }
2331
2332
2333 void Buffer::setParentName(string const & name)
2334 {
2335         params.parentname = name;
2336 }
2337
2338
2339 Buffer::inset_iterator::inset_iterator()
2340         : pit(), pend()
2341 {}
2342
2343
2344 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2345         : pit(p), pend(e)
2346 {
2347         setParagraph();
2348 }
2349
2350
2351 Buffer::inset_iterator Buffer::inset_iterator_begin()
2352 {
2353         return inset_iterator(paragraphs.begin(), paragraphs.end());
2354 }
2355
2356
2357 Buffer::inset_iterator Buffer::inset_iterator_end()
2358 {
2359         return inset_iterator(paragraphs.end(), paragraphs.end());
2360 }
2361
2362
2363 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
2364 {
2365         return inset_iterator(const_cast<ParagraphList&>(paragraphs).begin(),
2366                               const_cast<ParagraphList&>(paragraphs).end());
2367 }
2368
2369
2370 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
2371 {
2372         return inset_iterator(const_cast<ParagraphList&>(paragraphs).end(),
2373                               const_cast<ParagraphList&>(paragraphs).end());
2374 }
2375
2376
2377 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2378 {
2379         if (pit != pend) {
2380                 ++it;
2381                 if (it == pit->insetlist.end()) {
2382                         ++pit;
2383                         setParagraph();
2384                 }
2385         }
2386         return *this;
2387 }
2388
2389
2390 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2391 {
2392         inset_iterator tmp = *this;
2393         ++*this;
2394         return tmp;
2395 }
2396
2397
2398 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2399 {
2400         return *it->inset;
2401 }
2402
2403
2404 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2405 {
2406         return it->inset;
2407 }
2408
2409
2410 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2411 {
2412         return pit;
2413 }
2414
2415
2416 lyx::pos_type Buffer::inset_iterator::getPos() const
2417 {
2418         return it->pos;
2419 }
2420
2421
2422 bool operator==(Buffer::inset_iterator const & iter1,
2423                 Buffer::inset_iterator const & iter2)
2424 {
2425         return iter1.pit == iter2.pit
2426                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2427 }
2428
2429
2430 bool operator!=(Buffer::inset_iterator const & iter1,
2431                 Buffer::inset_iterator const & iter2)
2432 {
2433         return !(iter1 == iter2);
2434 }