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