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