]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Update it.po
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <list>
24 #include <set>
25 #include <string>
26 #include <vector>
27
28
29 namespace lyx {
30
31 class BiblioInfo;
32 class BufferParams;
33 class BufferSet;
34 class DispatchResult;
35 class DocIterator;
36 class docstring_list;
37 class ErrorItem;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetRef;
43 class InsetLabel;
44 class Font;
45 class Format;
46 class Lexer;
47 class LyXRC;
48 class Text;
49 class LyXVC;
50 class LaTeXFeatures;
51 class Language;
52 class MacroData;
53 class MacroNameSet;
54 class MacroSet;
55 class OutputParams;
56 class Paragraph;
57 class ParConstIterator;
58 class ParIterator;
59 class ParagraphList;
60 class TeXErrors;
61 class TexRow;
62 class TocBackend;
63 class Undo;
64 class WordLangTuple;
65
66 namespace frontend {
67 class GuiBufferDelegate;
68 class WorkAreaManager;
69 }
70
71 namespace support {
72 class FileName;
73 class FileNameList;
74 }
75
76 /** The buffer object.
77  * This is the buffer object. It contains all the informations about
78  * a document loaded into LyX.
79  * The buffer object owns the Text (wrapped in an InsetText), which
80  * contains the individual paragraphs of the document.
81  *
82  *
83  * I am not sure if the class is complete or
84  * minimal, probably not.
85  * \author Lars Gullik Bjønnes
86  */
87 class Buffer {
88 public:
89         /// What type of log will \c getLogName() return?
90         enum LogType {
91                 latexlog, ///< LaTeX log
92                 buildlog  ///< Literate build log
93         };
94
95         /// Result of \c readFile()
96         enum ReadStatus {
97                 failure, ///< The file could not be read
98                 success, ///< The file could not be read
99                 wrongversion ///< The version of the file does not match ours
100         };
101
102
103         /// Method to check if a file is externally modified, used by
104         /// isExternallyModified()
105         /**
106          * timestamp is fast but inaccurate. For example, the granularity
107          * of timestamp on a FAT filesystem is 2 second. Also, various operations
108          * may touch the timestamp of a file even when its content is unchanged.
109          *
110          * checksum is accurate but slow, which can be a problem when it is
111          * frequently used, or used for a large file on a slow (network) file
112          * system.
113          *
114          * FIXME: replace this method with support/FileMonitor.
115          */
116         enum CheckMethod {
117                 checksum_method,  ///< Use file checksum
118                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
119         };
120
121         ///
122         enum UpdateScope {
123                 UpdateMaster,
124                 UpdateChildOnly
125         };
126
127         /// Constructor
128         explicit Buffer(std::string const & file, bool b = false);
129
130         /// Destructor
131         ~Buffer();
132
133         /** High-level interface to buffer functionality.
134             This function parses a command string and executes it.
135         */
136         void dispatch(std::string const & command, DispatchResult & result);
137
138         /// Maybe we know the function already by number...
139         void dispatch(FuncRequest const & func, DispatchResult & result);
140
141         /// Can this function be exectued?
142         /// \return true if we made a decision
143         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
144
145         /// read a new document from a string
146         bool readString(std::string const &);
147         /// load a new file
148         bool readFile(support::FileName const & filename);
149
150         /// read the header, returns number of unknown tokens
151         int readHeader(Lexer & lex);
152
153         /** Reads a file without header.
154             \param par if != 0 insert the file.
155             \return \c true if file is not completely read.
156         */
157         bool readDocument(Lexer &);
158
159         ///
160         DocIterator getParFromID(int id) const;
161         /// do we have a paragraph with this id?
162         bool hasParWithID(int id) const;
163
164         ///
165         frontend::WorkAreaManager & workAreaManager() const;
166
167         /** Save file.
168             Takes care of auto-save files and backup file if requested.
169             Returns \c true if the save is successful, \c false otherwise.
170         */
171         bool save() const;
172
173         /// Write document to stream. Returns \c false if unsuccesful.
174         bool write(std::ostream &) const;
175         /// save emergency file
176         /// \return a status message towards the user.
177         docstring emergencyWrite();
178         /// Write file. Returns \c false if unsuccesful.
179         bool writeFile(support::FileName const &) const;
180
181         /// Loads LyX file \c filename into buffer, *  and \return success
182         bool loadLyXFile(support::FileName const & s);
183
184         /// Fill in the ErrorList with the TeXErrors
185         void bufferErrors(TeXErrors const &, ErrorList &) const;
186
187         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
188         bool makeLaTeXFile(support::FileName const & filename,
189                            std::string const & original_path,
190                            OutputParams const &,
191                            bool output_preamble = true,
192                            bool output_body = true) const;
193         /** Export the buffer to LaTeX.
194             If \p os is a file stream, and params().inputenc is "auto" or
195             "default", and the buffer contains text in different languages
196             with more than one encoding, then this method will change the
197             encoding associated to \p os. Therefore you must not call this
198             method with a string stream if the output is supposed to go to a
199             file. \code
200             ofdocstream ofs;
201             ofs.open("test.tex");
202             writeLaTeXSource(ofs, ...);
203             ofs.close();
204             \endcode is NOT equivalent to \code
205             odocstringstream oss;
206             writeLaTeXSource(oss, ...);
207             ofdocstream ofs;
208             ofs.open("test.tex");
209             ofs << oss.str();
210             ofs.close();
211             \endcode
212          */
213         void writeLaTeXSource(odocstream & os,
214                            std::string const & original_path,
215                            OutputParams const &,
216                            bool output_preamble = true,
217                            bool output_body = true) const;
218         ///
219         void makeDocBookFile(support::FileName const & filename,
220                              OutputParams const & runparams_in,
221                              bool only_body = false) const;
222         ///
223         void writeDocBookSource(odocstream & os, std::string const & filename,
224                              OutputParams const & runparams_in,
225                              bool only_body = false) const;
226         ///
227         void makeLyXHTMLFile(support::FileName const & filename,
228                              OutputParams const & runparams_in,
229                              bool only_body = false) const;
230         ///
231         void writeLyXHTMLSource(odocstream & os,
232                              OutputParams const & runparams_in,
233                              bool only_body = false) const;
234         /// returns the main language for the buffer (document)
235         Language const * language() const;
236         /// get l10n translated to the buffers language
237         docstring const B_(std::string const & l10n) const;
238
239         ///
240         int runChktex();
241         /// return true if the main lyx file does not need saving
242         bool isClean() const;
243         ///
244         bool isBakClean() const;
245         ///
246         bool isDepClean(std::string const & name) const;
247
248         /// whether or not disk file has been externally modified
249         bool isExternallyModified(CheckMethod method) const;
250
251         /// save timestamp and checksum of the given file.
252         void saveCheckSum(support::FileName const & file) const;
253
254         /// mark the main lyx file as not needing saving
255         void markClean() const;
256
257         ///
258         void markBakClean() const;
259
260         ///
261         void markDepClean(std::string const & name);
262
263         ///
264         void setUnnamed(bool flag = true);
265
266         /// Whether or not a filename has been assigned to this buffer
267         bool isUnnamed() const;
268
269         /// Whether or not this buffer is internal.
270         ///
271         /// An internal buffer does not contain a real document, but some auxiliary text segment.
272         /// It is not associated with a filename, it is never saved, thus it does not need to be
273         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
274         bool isInternal() const;
275
276         /// Mark this buffer as dirty.
277         void markDirty();
278
279         /// Returns the buffer's filename. It is always an absolute path.
280         support::FileName fileName() const;
281
282         /// Returns the buffer's filename. It is always an absolute path.
283         std::string absFileName() const;
284
285         /// Returns the the path where the buffer lives.
286         /// It is always an absolute path.
287         std::string filePath() const;
288
289         /** A transformed version of the file name, adequate for LaTeX.
290             \param no_path optional if \c true then the path is stripped.
291         */
292         std::string latexName(bool no_path = true) const;
293
294         /// Get the name and type of the log.
295         std::string logName(LogType * type = 0) const;
296
297         /// Change name of buffer. Updates "read-only" flag.
298         void setFileName(std::string const & newfile);
299
300         /// Set document's parent Buffer.
301         void setParent(Buffer const *);
302         Buffer const * parent() const;
303
304         // Collect all relative buffer
305         std::vector<Buffer const *> allRelatives() const;
306
307         /** Get the document's master (or \c this if this is not a
308             child document)
309          */
310         Buffer const * masterBuffer() const;
311
312         /// \return true if \p child is a child of this \c Buffer.
313         bool isChild(Buffer * child) const;
314         
315         /// return a vector with all children (and grandchildren)
316         std::vector<Buffer *> getChildren(bool grand_children = true) const;
317
318         /// Is buffer read-only?
319         bool isReadonly() const;
320
321         /// Set buffer read-only flag
322         void setReadonly(bool flag = true);
323
324         /// returns \c true if the buffer contains a LaTeX document
325         bool isLatex() const;
326         /// returns \c true if the buffer contains a DocBook document
327         bool isDocBook() const;
328         /// returns \c true if the buffer contains a Wed document
329         bool isLiterate() const;
330
331         /** Validate a buffer for LaTeX.
332             This validates the buffer, and returns a struct for use by
333             #makeLaTeX# and others. Its main use is to figure out what
334             commands and packages need to be included in the LaTeX file.
335             It (should) also check that the needed constructs are there
336             (i.e. that the \refs points to coresponding \labels). It
337             should perhaps inset "error" insets to help the user correct
338             obvious mistakes.
339         */
340         void validate(LaTeXFeatures &) const;
341
342         /// Update the cache with all bibfiles in use (including bibfiles
343         /// of loaded child documents).
344         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
345         ///
346         void invalidateBibinfoCache();
347         /// Return the cache with all bibfiles in use (including bibfiles
348         /// of loaded child documents).
349         support::FileNameList const & 
350                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
351         /// \return the bibliography information for this buffer's master,
352         /// or just for it, if it isn't a child.
353         BiblioInfo const & masterBibInfo() const;
354         /// \return the bibliography information for this buffer ONLY.
355         BiblioInfo const & localBibInfo() const;
356         ///
357         void getLabelList(std::vector<docstring> &) const;
358
359         ///
360         void changeLanguage(Language const * from, Language const * to);
361
362         ///
363         bool isMultiLingual() const;
364
365         ///
366         BufferParams & params();
367         BufferParams const & params() const;
368
369         /** The list of paragraphs.
370             This is a linked list of paragraph, this list holds the
371             whole contents of the document.
372          */
373         ParagraphList & paragraphs();
374         ParagraphList const & paragraphs() const;
375
376         /// LyX version control object.
377         LyXVC & lyxvc();
378         LyXVC const & lyxvc() const;
379
380         /// Where to put temporary files.
381         std::string const temppath() const;
382
383         /// Used when typesetting to place errorboxes.
384         TexRow const & texrow() const;
385         TexRow & texrow();
386
387         ///
388         ParIterator par_iterator_begin();
389         ///
390         ParConstIterator par_iterator_begin() const;
391         ///
392         ParIterator par_iterator_end();
393         ///
394         ParConstIterator par_iterator_end() const;
395
396         // Position of the child buffer where it appears first in the master.
397         DocIterator firstChildPosition(Buffer const * child);
398
399         /** \returns true only when the file is fully loaded.
400          *  Used to prevent the premature generation of previews
401          *  and by the citation inset.
402          */
403         bool isFullyLoaded() const;
404         /// Set by buffer_funcs' newFile.
405         void setFullyLoaded(bool);
406
407         /// Our main text (inside the top InsetText)
408         Text & text() const;
409
410         /// Our top InsetText
411         Inset & inset() const;
412
413         //
414         // Macro handling
415         //
416         /// Collect macro definitions in paragraphs
417         void updateMacros() const;
418         /// Iterate through the whole buffer and try to resolve macros
419         void updateMacroInstances() const;
420
421         /// List macro names of this buffer, the parent and the children
422         void listMacroNames(MacroNameSet & macros) const;
423         /// Collect macros of the parent and its children in front of this buffer.
424         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
425
426         /// Return macro defined before pos (or in the master buffer)
427         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
428         /// Return macro defined anywhere in the buffer (or in the master buffer)
429         MacroData const * getMacro(docstring const & name, bool global = true) const;
430         /// Return macro defined before the inclusion of the child
431         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
432
433         /// Collect user macro names at loading time
434         typedef std::set<docstring> UserMacroSet;
435         UserMacroSet usermacros;
436
437         /// Replace the inset contents for insets which InsetCode is equal
438         /// to the passed \p inset_code.
439         void changeRefsIfUnique(docstring const & from, docstring const & to,
440                 InsetCode code);
441
442         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
443         /// including preamble
444         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
445                 bool full_source) const;
446
447         /// Access to error list.
448         /// This method is used only for GUI visualisation of Buffer related
449         /// errors (like parsing or LateX compilation). This method is const
450         /// because modifying the returned ErrorList does not touch the document
451         /// contents.
452         ErrorList & errorList(std::string const & type) const;
453
454         /// The Toc backend.
455         /// This is useful only for screen visualisation of the Buffer. This
456         /// method is const because modifying this backend does not touch
457         /// the document contents.
458         TocBackend & tocBackend() const;
459
460         ///
461         Undo & undo();
462
463         /// This function is called when the buffer is changed.
464         void changed() const;
465         ///
466         void updateTocItem(std::string const &, DocIterator const &) const;
467         /// This function is called when the buffer structure is changed.
468         void structureChanged() const;
469         /// This function is called when some parsing error shows up.
470         void errors(std::string const & err, bool from_master = false) const;
471         /// This function is called when the buffer busy status change.
472         void setBusy(bool on) const;
473         /// This function is called when the buffer readonly status change.
474         void setReadOnly(bool on) const;
475         /// Update window titles of all users.
476         void updateTitles() const;
477         /// Reset autosave timers for all users.
478         void resetAutosaveTimers() const;
479         ///
480         void message(docstring const & msg) const;
481
482         ///
483         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
484         ///
485         bool hasGuiDelegate() const;
486
487         ///
488         void autoSave() const;
489         ///
490         void removeAutosaveFile() const;
491         ///
492         void moveAutosaveFile(support::FileName const & old) const;
493         ///
494         support::FileName getAutosaveFilename() const;
495
496         /// return the format of the buffer on a string
497         std::string bufferFormat() const;
498         /// return the default output format of the current backend
499         std::string getDefaultOutputFormat() const;
500
501         ///
502         bool doExport(std::string const & format, bool put_in_tempdir,
503                 std::string & result_file) const;
504         ///
505         bool doExport(std::string const & format, bool put_in_tempdir) const;
506         ///
507         bool preview(std::string const & format) const;
508         ///
509         bool isExportable(std::string const & format) const;
510         ///
511         std::vector<Format const *> exportableFormats(bool only_viewable) const;
512
513         ///
514         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
515         References & references(docstring const & label);
516         References const & references(docstring const & label) const;
517         void clearReferenceCache() const;
518         void setInsetLabel(docstring const & label, InsetLabel const * il);
519         InsetLabel const * insetLabel(docstring const & label) const;
520
521         /// return a list of all used branches (also in children)
522         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
523
524         /// sets the buffer_ member for every inset in this buffer.
525         // FIXME This really shouldn't be needed, but at the moment it's not
526         // clear how to do it just for the individual pieces we need.
527         void setBuffersForInsets() const;
528         ///
529         void updateLabels(UpdateScope = UpdateMaster) const;
530         ///
531         void updateLabels(ParIterator & parit) const;
532
533         /// Spellcheck starting from \p from.
534         /// \p from initial position, will then points to the next misspelled
535         ///    word.
536         /// \p to will points to the end of the next misspelled word.
537         /// \p word_lang will contain the found misspelled word.
538         /// \return progress if a new word was found.
539         int spellCheck(DocIterator & from, DocIterator & to,
540                 WordLangTuple & word_lang, docstring_list & suggestions) const;
541
542 private:
543         /// search for macro in local (buffer) table or in children
544         MacroData const * getBufferMacro(docstring const & name,
545                                          DocIterator const & pos) const;
546         /** Update macro table starting with position of it
547             \param it in some text inset
548         */
549         void updateMacros(DocIterator & it,
550                                      DocIterator & scope) const;
551         ///
552         void setLabel(ParIterator & it) const;
553         ///
554         void collectRelatives(BufferSet & bufs) const;
555
556         ///
557         bool readFileHelper(support::FileName const & s);
558         ///
559         std::vector<std::string> backends() const;
560         /** Inserts a file into a document
561             \return \c false if method fails.
562         */
563         ReadStatus readFile(Lexer &, support::FileName const & filename,
564                             bool fromString = false);
565
566         /** If we have branches that use the file suffix
567             feature, return the file name with suffix appended.
568         */
569         support::FileName exportFileName() const;
570
571         /// Use the Pimpl idiom to hide the internals.
572         class Impl;
573         /// The pointer never changes although *pimpl_'s contents may.
574         Impl * const d;
575
576         frontend::GuiBufferDelegate * gui_;
577
578         /// This function is called when the buffer structure is changed.
579         Signal structureChanged_;
580         /// This function is called when some parsing error shows up.
581         //Signal errors(std::string const &) = 0;
582         /// This function is called when some message shows up.
583         //Signal message(docstring const &) = 0;
584         /// This function is called when the buffer busy status change.
585         //Signal setBusy(bool) = 0;
586         /// Reset autosave timers for all users.
587         Signal resetAutosaveTimers_;
588 };
589
590
591 } // namespace lyx
592
593 #endif