On 18/05/2012 2:36 a.m., Alex Vergara Gil wrote:

El 15/05/2012 06:23 p.m., Daniel escribió:
Hi,

I am writing my PhD thesis in Lyx and I'm using Jabref to manage my
references
and produce the .bib file. When I compile my file Lyx correctly
produces the
bibliography at the end of the document but the citations are messed
up. I get
things like "l [e,?]" where the citation should go (but the corresponding
reference in the bibliography is there.

Any ideas on how to fix this would be greatly appreciated.

Daniel


Hi Daniel!

I strongly recommend you Andrew Parsloe bib importer to LyX, on which
you can reedit in LyX your bib file erasing all unnecessary characters.
You will found this very useful.

There is also a posibility that your citation style is not what you
espect, you could check that by right clicking the cite itself.

Alex


To make sense of the first suggestion (using LyX to edit bibliography files) I've attached the relevant files to this email (two converters bib2ltx.py, ltx2bib.py, a layout file bibliography.layout and module, and an explanatory document). The converters have been modified since their last airing on this list, in particular in response to problems and suggestions arising from their use by Alex Vergara Gil.

Andrew
#
# ltx2bib.py
#
# author: Andrew Parsloe ([email protected]) 10 May 2012 
#
# Usage: python <path to>ltx2bib.py <file>.tex <file>.bib
#
# Converts a bibliography styled with bibliography.layout
# and exported from LyX to (plain) LaTeX, into a plain-text
# biblatex bib file.

import re, sys

fltx = open(sys.argv[-2], 'r')
fbib = open(sys.argv[-1], 'w')

#Boolean flags
bibtexcmd = False
datatype = False

#functions

def del_last_brace(line):
    'Delete last right brace of line.'
    line = re.sub(r'}\s*\n', '\n', line)
    return line

def de_escape_last_brace(line):
    line = re.sub(r'\\(},|})\s*$', r'\1\n', line)
    return line

#substitutions
def do_BibTeX_cmd_subs(line):
    if line not in '\n':
        #delete \chapter{ or \chapter*{;
        #for right brace see del_last_brace
        line = re.sub(r'\\chapter.*?{', '', line, 1)
        #remove braces from around [...]
        line = re.sub(r'{(\[|\])}', r'\1', line)
        #verbose form to ", \
        line = re.sub(r'\\textquotedbl{}', '"', line)
        line = re.sub(r'\\textbackslash{}', r'\\', line)
        #remove escapes (\) from {, }, #
        line = re.sub(r'\\([{}#])\s*', r'\1', line)
    return line

def do_data_type_subs(line):
    if line not in '\n':
        #remove \item [{ ... }] wrapper
        line = re.sub(r'\\item\s*\[{(.+)}\]', r'\1', line, 1)
        #de-escape immediately following {
        line = re.sub(r'=\s*\\{', r'= {', line, 1)
        #verbose form to ", \
        line = re.sub(r'\\textquotedbl{}', '"', line)
        line = re.sub(r'\\textbackslash{}', r'\\', line)
        #remove { } wrappers from [, ]
        line = re.sub(r'{(\[|\])}', r'\1', line)
        #de-escape # { concatenator
        line = re.sub(r'\\#\s*\\{', r'# {', line)
        #delete
        line = re.sub(r'~\s*$', '', line)
        if re.search(r'\\end{(lyxlist|description|section)}', line):
            line = re.sub(r'\\end{(lyxlist|description|section)}', '', line)
            line = de_escape_last_brace(line)
    return line

#main loop
line0 = ''
for line in fltx:
    #BibTeX commands (chapter or chapter*)
    if re.search(r'(?i)@(preamble|string|comment)\\{', line):
        if line0 not in '\n':
            line0 = del_last_brace(line0)
            fbib.write(line0)
        fbib.write('\n')
        line0 = do_BibTeX_cmd_subs(line)
        bibtexcmd = True

    #concatenation lines (#)
    elif re.match(r'\\chapter.*?{\\#', line):
        if line0 not in '\n':
            line0 = del_last_brace(line0)
            fbib.write(line0)
        line0 = do_BibTeX_cmd_subs(line)
        bibtexcmd = True
        
    #entry types (chapter or chapter*)
    elif re.match(r'\\chapter.*?{', line):
        if line0 not in '\n':
            line0 = del_last_brace(line0)
            fbib.write(line0)
        fbib.write('\n')
        bibtexcmd = False
        #remove \chapter{ or \chapter*{
        line = re.sub(r'\\chapter.*?{', '', line, 1)
        #de-escape opening {
        line = re.sub(r'\\({)\s*', r'\1',line, 1)
        #assume no spillover to next line!
        line0 = del_last_brace(line)
        fbib.write(line0)
        line0 = ''

    #spillover BibTeX command lines
    elif bibtexcmd:
        line = do_BibTeX_cmd_subs(line)
        line = line0[:-1] + line #spillover; delete inner \n
        line = del_last_brace(line)
        fbib.write(line)
        line0 = ''
        bibtexcmd = False

    #data types
    elif re.match(r'\\item\s*\[{', line):
        #de-escape last }; remove trailing whitespace
        line0 = de_escape_last_brace(line0)
        fbib.write(line0)
        datatype = True
        line0 = do_data_type_subs(line)

    elif re.search(r'\\end{(lyxlist|description|section)}', line):
        datatype = False
        if line0 not in '\n':
            line0 = de_escape_last_brace(line0)
            fbib.write(line0)
        line = re.sub(r'\\end{(lyxlist|description|section)}', '', line)
        line0 = de_escape_last_brace(line)

    elif re.match(r'\\begin{(lyxlist|description|section)}', line):
        continue
        
    #spillover data type lines
    elif datatype:
        line = do_data_type_subs(line)
        line = de_escape_last_brace(line)
        line = line0 + line #retains inner \n
        fbib.write(line)
        line0 = ''

    #in case record's final } is in LyX Standard style
    elif re.match(r'\\}\s*$', line):
        fbib.write('}\n')
        line0 = ''

fbib.close()
               



#LyX 2.0 created this file. For more info see http://www.lyx.org/
\lyxformat 413
\begin_document
\begin_header
\textclass scrartcl
\use_default_options true
\maintain_unincluded_children false
\language english
\language_package default
\inputencoding auto
\fontencoding global
\font_roman lmodern
\font_sans lmss
\font_typewriter lmtt
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100

\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize a4paper
\use_geometry true
\use_amsmath 1
\use_esint 1
\use_mhchem 1
\use_mathdots 1
\cite_engine basic
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\use_refstyle 1
\index Index
\shortcut idx
\color #008000
\end_index
\leftmargin 3cm
\rightmargin 3cm
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

\begin_layout Title
Editing & organising bibliographies
\begin_inset Newline newline
\end_inset

 in LyX
\end_layout

\begin_layout Author
Andrew Parsloe
\end_layout

\begin_layout Section*
Introduction
\end_layout

\begin_layout Standard
Is it possible to edit bibliography files in LyX? Yes! LyX has a system
 of converters for converting documents between formats.
 A 
\family typewriter
biblatex
\family default
 bibliography file is a text file (with extension `bib').
 LyX already has plain-text import/export options.
 The thought arises that it should be possible to work on a bibliography
 file in LyX, with all the facilities that makes available, and then export
 the file as plain text, change the extension of the exported file from
 `txt' to `bib' (and perhaps do some other tweaks) and finish with a functioning
 bibliography file to be used by 
\family typewriter
biblatex
\family default
 in the normal way.
 The relation of the LyX file to the bib file would be much like that of
 a LyX file to its pdf, with all the creating and editing done in LyX.
 
\end_layout

\begin_layout Standard
My initial attempts at following through on this idea did, indeed, import
 from and export to text files, but the response of 
\noun on
Alex Vergara Gil
\noun default
 to this work made it clear that when imported into LyX the bibliography
 should display properly as a LyX file, not as a text file.
 On further thought, I realised that what was needed were converters which
 would turn bib files into LaTeX files and vice versa, since LyX already
 knows how to import and export LaTeX.
 But the underlying notion remains the same.
 We work in LyX, just as when creating a pdf, not on the plain-text bib
 file.
 (But whereas the pdf is `prettier' than its LyX file, for bibliographies,
 the LyX file will be `prettier' than the bib file.)
\end_layout

\begin_layout Subsection
LyX version
\end_layout

\begin_layout Standard
The experience of 
\noun on
Alex Vergara Gil
\noun default
 showed that LyX 2.0.0 gave different results with the converters from those
 I obtained using LyX 2.0.3.
 The announcement notices for LyX 2.0.2 and LyX 2.0.3 show significant changes
 were made to the 
\family typewriter
tex2lyx
\family default
 program on those occasions, one of the side-effects being the way lists
 are imported.
 However, 
\noun on
AVG
\noun default
 found a simple edit of the converters solved the problem.
 This is discussed below,
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:LyX-2.0.0-complications"

\end_inset

 shortly.
\end_layout

\begin_layout Subsection
BibTeX or biblatex?
\end_layout

\begin_layout Standard
I did this work with 
\family typewriter
biblatex
\family default
 in mind, since that is the bibliography engine I'm (somewhat) familiar
 with and with which it was intended to work.
 However, some experimenting with the sample BibTeX bibliographies that
 come with the MiKTeX distribution suggested various `tweaks' to the converters.
 BibTeX bibliography files should also now be successfully, imported, displayed
 and exported.
 
\end_layout

\begin_layout Section
bibliography.layout
\end_layout

\begin_layout Standard
The  layout file, 
\family typewriter
bibliography.layout
\family default
,
\begin_inset Foot
status collapsed

\begin_layout Plain Layout
Please note that this layout differs from that presented with the first
 plain-text import/export version of this work.
 I found I had left some `debris' from my experimenting in that layout,
 which didn't affect plain-text functioning but had consequences for LaTeX
 import/export.
\end_layout

\end_inset

 should be placed in one's user layout directory.
\begin_inset Foot
status collapsed

\begin_layout Plain Layout
 On Windows this is something like 
\family typewriter
C:
\backslash
Users
\backslash
<yourname>
\backslash
AppData
\backslash
Roaming
\backslash
LyX2.0
\backslash
layouts
\family default
.
 
\end_layout

\end_inset

 LyX will need to be reconfigured to recognise its presence, closed, then
 restarted.
 Create a new document, then look in 
\family sans
Document \SpecialChar \menuseparator
 Settings \SpecialChar \menuseparator
 Document Class
\family default
 and look down the list of document classes until you find 
\family sans
bibliography
\family default
.
 Select it.
 Now look at the styles available in the style combo-box.
\end_layout

\begin_layout Subsection
Styles and style naming
\end_layout

\begin_layout Standard

\family typewriter
bibliography.layout
\family default
 redefines the sectioning styles 
\family sans
Part
\family default
, 
\family sans
Chapter
\family default
, 
\family sans
Section
\family default
, and 
\family sans
Part*
\family default
 and 
\family sans
Chapter*
\family default
 (some in a major way), as it does the two list environments 
\family sans
Labeling
\family default
 and 
\family sans
Description
\family default
.
 
\end_layout

\begin_layout Standard
It would be better if the style names gave a better indication of their
 function, but there is a conflict here between renaming the styles and
 losing the familiar shortcut keys.
 Of course new shortcuts could be assigned but it seems better not to `use
 up' unassigned key combinations.
 The ideal situation would be to have accurately descriptive names appearing
 in the combo-box as aliases of the styles defined in the layout file using
 their familiar names.
 This would mean the shortcut keys still `did their thing' but the function
 of the styles would be clearer to the user.
 (An enhancement request to this effect has been placed with the LyX 
developers.)
\end_layout

\begin_layout Section
Formats and converters
\begin_inset CommandInset label
LatexCommand label
name "sec:Formats-and-converters"

\end_inset


\end_layout

\begin_layout Standard
The layout file is one main part of this work; the other is the converters,
 to get from 
\family typewriter
.lyx
\family default
 to 
\family typewriter
.bib
\family default
 and vice versa.
 First, we need to define a format -- let's call it 
\family sans
Plain text (bib)
\family default
.
 Go to 
\family sans
Tools \SpecialChar \menuseparator
 Preferences \SpecialChar \menuseparator
 File Handling \SpecialChar \menuseparator
 File Formats
\family default
.
 Click 
\family sans
New
\family default
 and enter 
\series bold
Plain text (bib)
\series default
 in the 
\family sans
Format
\family default
 slot.
 Set (tick) the
\family sans
 Document format
\family default
 and 
\family sans
Show in export menu
\family default
 checkboxes.
 Under 
\family sans
Short Name
\family default
 write 
\series bold
textbib
\series default
; under 
\family sans
Extension
\family default
 write 
\series bold
bib
\series default
.
 A 
\family sans
Viewer
\family default
 is helpful, so select 
\family sans
Custom
\family default
 and in the slot to the right enter the name of your preferred text editor.
 (In the Windows' world, I use 
\family typewriter
notepad++
\family default
.) Possibly you will now need to go to 
\family sans
Tools \SpecialChar \menuseparator
 Preferences \SpecialChar \menuseparator
 Paths
\family default
 and under 
\family sans
PATH prefix:
\family default
 add the path to the folder containing the text editor's binary file (the
 
\family typewriter
.exe
\family default
 file in the Windows' world).
\end_layout

\begin_layout Subsection
Removing the previous converters
\end_layout

\begin_layout Standard
Should you have installed the converters 
\family typewriter
txt2bib.py
\family default
 and 
\family typewriter
bib2lyx.py
\family default
 (from the previous version of this work) for converting between 
\family sans
Plain text
\family default
 and 
\family sans
Plain text (bib)
\family default
, and between 
\family sans
Plain text (bib)
\family default
 and 
\family sans
LyX
\family default
, then these will need to be removed first.
 Go to 
\family sans
Tools \SpecialChar \menuseparator
 Preferences \SpecialChar \menuseparator
 File Handling \SpecialChar \menuseparator
 Converters
\family default
, select each of the converters in turn and click the 
\family sans
Remove
\family default
 button.
\end_layout

\begin_layout Subsection
Exporting a bibliography from LyX: ltx2bib.py
\end_layout

\begin_layout Standard
Place the Python script 
\family typewriter
ltx2bib.py
\family default
 in the 
\family sans
scripts
\family default
 folder in your personal LyX2.0 folder.
\begin_inset Foot
status open

\begin_layout Plain Layout
 In Windows Vista this is 
\family sans
C:/Users/<your name>/AppData/Roaming/LyX2.0/scripts.
\end_layout

\end_inset


\family sans
 
\family default
Now go to 
\family sans
Tools \SpecialChar \menuseparator
 Preferences \SpecialChar \menuseparator
 File Handling \SpecialChar \menuseparator
 Converters
\family default
, select any of the converters listed (it doesn't matter which) and under
 
\family sans
>From format:
\family default
 scroll down to 
\family sans
LaTeX (plain)
\family default
.
 In the 
\family sans
To format:
\family default
 scroll down to 
\family sans
Plain text (bib)
\family default
 -- it should now be present in the list of formats -- and select it.
 Finally, under 
\family sans
Converter
\family default
 write 
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
python <path>ltx2bib.py $$i $$o
\end_layout

\begin_layout Standard
where 
\series bold
<path>
\series default
 is the path to the 
\family sans
scripts 
\family default
folder holding 
\family typewriter
txt2bib.py
\family default
,
\begin_inset Foot
status collapsed

\begin_layout Plain Layout
In Windows, the entry will look something like
\end_layout

\begin_layout LyX-Code
python  C:/Users/<your name>/AppData/Roaming/LyX2.0/scripts/ltx2bib.py $$i
 $$o
\end_layout

\end_inset


\series bold
 
\series default
and click 
\family sans
Add
\family default
 then 
\family sans
Apply
\family default
.
 
\emph on
For Windows users, note that the 
\series bold
\emph default
<path>
\series default
\emph on
 must use the forward slash 
\emph default
/ 
\emph on
rather than the backslash 
\emph default

\backslash
.
\end_layout

\begin_layout Standard
Now when you look in the list under 
\family sans
File \SpecialChar \menuseparator
 Export
\family default
, you should see 
\family sans
Plain text (bib)
\family default
 listed.
 On export, LyX will first export to 
\family sans
LaTeX (plain)
\family default
 and then from 
\family sans
LaTeX (plain)
\family default
 to 
\family sans
Plain text (bib)
\family default
.
\end_layout

\begin_layout Subsection
Importing a bibliography into LyX: bib2ltx.py
\begin_inset CommandInset label
LatexCommand label
name "sub:Importing-a-bibliography"

\end_inset


\end_layout

\begin_layout Standard
In the other direction, 
\emph on
importing
\emph default
 a text-file bibliography into LyX, use the Python script 
\family typewriter
bib2ltx.py
\family default
, which converts from 
\family sans
Plain text (bib)
\family default
 to 
\family sans
LaTeX (plain)
\family default
.
 Place this in the same 
\family sans
scripts
\family default
 folder 
\family typewriter
ltx2bib.py
\family default
 was put.
 Again under 
\family sans
Tools \SpecialChar \menuseparator
 Preferences \SpecialChar \menuseparator
 File Handling \SpecialChar \menuseparator
 Converters
\family default
, select a converter (it doesn't matter which) and under 
\family sans
>From format:
\family default
 scroll down to 
\family sans
Plain text (bib)
\family default
 and select it.
 In the 
\family sans
To format:
\family default
 scroll down to 
\family sans
LaTeX (plain)
\family default
 and select it.
 Finally, under 
\family sans
Converter
\family default
 write, 
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
python <path>bib2ltx.py $$i $$o
\end_layout

\begin_layout Standard
(where <
\series bold
path
\series default
> uses forward slashes / rather than backslashes 
\backslash
) and click 
\family sans
Add
\family default
, then 
\family sans
Save
\family default
.
 
\end_layout

\begin_layout Standard
Now when you look at the list of importable formats under 
\family sans
File \SpecialChar \menuseparator
 Import
\family default
, you should see 
\family sans
Plain text (bib)
\family default
 listed.
 Looking through its converter tree, LyX will first convert from 
\family sans
Plain text (bib)
\family default
 to 
\family sans
LaTeX (plain)
\family default
 and then import from 
\family sans
LaTeX (plain)
\family default
 to 
\family sans
LyX
\family default
.
\end_layout

\begin_layout Subsubsection
Alternative styles
\end_layout

\begin_layout Standard
The style in which the imported records are displayed is a lightly modified
 version of LyX's 
\family sans
Labeling
\family default
 list environment that uses indentation to separate data type from content.
 An alternative format is provided by a modified version of LyX's 
\family sans
Description
\family default
 list environment that uses colour to the same end.
 To import a bibliography in 
\family sans
Description
\family default
 format, use the 
\series bold
-c
\series default
 option (for 
\series bold
c
\series default
olour):
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
python <path>bib2ltx.py -c $$i $$o
\end_layout

\begin_layout Standard
then click the 
\family sans
Modify
\family default
 and 
\family sans
Save
\family default
 (or 
\family sans
Apply
\family default
)
\family sans
 
\family default
buttons.

\family sans
 
\family default
The default (no option specified) is the use of indentation and the 
\family sans
Labeling
\family default
 list environment.
\end_layout

\begin_layout Subsubsection
Keeping introductory material and comments
\end_layout

\begin_layout Standard
An already existing bibliography file may contain introductory remarks and
 various comments between the records.
 When importing it to LyX, you may wish to also import this material.
 This is effected by using the 
\series bold
-k
\series default
 option (for 
\series bold
k
\series default
eep):
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
python <path>bib2ltx.py -k $$i $$o
\end_layout

\begin_layout Standard
(then click the 
\family sans
Modify
\family default
 and 
\family sans
Save
\family default
, or 
\family sans
Apply
\family default
,
\family sans
 
\family default
buttons).
 
\end_layout

\begin_layout Standard
The first line of any such remark or comment is displayed in LyX (prominently)
 in 
\family sans
Part
\family default
 style.
 Generally this will be inappropriate, but it will show up in the 
\family sans
Outline
\family default
 window, and so be easily found even in a large bibliography file; the styling
 can then be changed.
 Note that there is no provision to 
\emph on
export
\emph default
 such comments or introductory remarks.
 It is in the LyX file that they belong; the plain-text bib file is 
\emph on
functional
\emph default
, to be read by 
\family typewriter
biblatex
\family default
 rather than human eyes.
\end_layout

\begin_layout Subsubsection
LyX 2.0.0 complications
\begin_inset CommandInset label
LatexCommand label
name "sub:LyX-2.0.0-complications"

\end_inset


\end_layout

\begin_layout Standard
Between LyX 2.0.0 and LyX 2.0.3 there was a change in the way 
\family typewriter
tex2lyx
\family default
, the program LyX uses to import LaTeX, imported lists into LyX.
 These changes mean the default setting for 
\family typewriter
bib2ltx.py
\family default
 will add extra braces around data types
\family typewriter
 
\family default
in LyX 2.0.0.
 These cause errors when the exported bibliography is used by 
\family typewriter
biblatex
\family default
.
 The solution is to use the 
\series bold
-o
\series default
 (for 
\series bold
o
\series default
lder) option if using LyX 2.0.0.
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
python <path>bib2ltx.py -o $$i $$o
\end_layout

\begin_layout Standard
(The occurrence of the extra braces and the necessary correction were pointed
 out to me by 
\noun on
Alex Vergara Gill
\noun default
.) With precisely which version of LyX the change occurred I don't know,
 so if you are using LyX 2.0.1 or LyX 2.0.2 you may also have to use the 
\series bold
-o
\series default
 option.
\end_layout

\begin_layout Subsubsection
Combining options
\end_layout

\begin_layout Standard
The options can be combined (the order is immaterial):
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
python <path>bib2ltx.py -cko $$i $$o
\end_layout

\begin_layout Section
Entry and data types
\end_layout

\begin_layout Subsection
Entry types
\end_layout

\begin_layout Standard
An entry type is an article or book or booklet or collection or manual or
 report or \SpecialChar \ldots{}
 The possibilities are listed in section
\begin_inset space ~
\end_inset

2.1 of the 
\family typewriter
biblatex
\family default
 manual (for version 1.7 of 
\family typewriter
biblatex
\family default
).
 The entry type provides the leading line of a bibliographic record and
 is always entered in a 
\family typewriter
biblatex
\family default
 bib file with a preceding @: 
\series bold
@book
\series default
, 
\series bold
@report
\series default
, etc.
 These are not case sensitive: 
\series bold
@Book
\series default
,
\series bold
 @Report
\series default
, etc., serve equally well.

\series bold
 
\series default
In 
\family typewriter
bibliography.layout
\family default
 the (heavily redefined) 
\family sans
Chapter
\family default
 style is designed for displaying entry types.
 It prints the line in bold and automatically numbers the entries, which
 can be helpful in a large bibliography.
 Neither the bolding nor the numbers are exported to the plain-text bib
 file.
 Their role is purely cosmetic, aiding the readability of the file in LyX.
 If you don't want numbers in the LyX file, use the starred style, 
\family sans
Chapter*
\family default
.
 The entry-type line is completed by the 
\emph on
key
\emph default
 to the bibliographic record (
\series bold
knuth:ct
\series default
 in this example):
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
@Book{knuth:ct,
\end_layout

\begin_layout Subsection
BibTeX commands
\end_layout

\begin_layout Standard
The initial entries in a bibliography may be 
\family typewriter
BibTeX
\family default
 commands (this is also the case in a 
\family typewriter
biblatex
\family default
 bibliography -- see 
\family typewriter
biblatex-examples.bib
\family default
 in the MiKTeX distribution
\begin_inset Foot
status collapsed

\begin_layout Plain Layout

\size normal
In MiKTeX 2.9 on Windows Vista this is in the folder 
\family typewriter
C:
\backslash
Program Files
\backslash
MiKTeX 2.9
\backslash
doc
\backslash
latex
\backslash
biblatex
\backslash
examples
\end_layout

\end_inset

).
 These also are entered in 
\family sans
Chapter
\family default
 or 
\family sans
Chapter*
\family default
 style.
 In my view it is better to give them the starred (unnumbered) style, to
 distinguish them from the numbered records.
 At present the converters can handle correctly only single-line 
\series bold
@preamble
\series default
 or 
\series bold
@string
\series default
 commands.
\end_layout

\begin_layout Subsection
Data types
\end_layout

\begin_layout Standard
Data types and their contents are lines like 
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
author = {Foo Bar},
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
title = {This is a book title},
\end_layout

\begin_layout Standard
that follow the entry type.
 These are formatted either according to a redefined 
\family sans
Labeling
\family default
 list environment (but still accessible
\family sans
 
\family default
via 
\family sans
Alt+P L
\family default
)
\begin_inset Foot
status collapsed

\begin_layout Plain Layout
That is actually 
\family sans
Alt+
\family default
lower case
\family sans
 P
\family default
 then lower-case 
\family sans
L
\family default
; 
\family sans
P 
\family default
and 
\family sans
L 
\family default
are what is shown on the keys.
\end_layout

\end_inset


\family sans
 
\family default
that uses indentation to distinguish the data type from its contents, or
 a redefined 
\family sans
Description
\family default
 list environment (accessible
\family sans
 
\family default
via 
\family sans
Alt+P D
\family default
) that uses colour.
 In both styles, data-type contents that spill onto more than one line are
 given a hanging indent.
 
\end_layout

\begin_layout Standard
The record is closed by a final 
\series bold
}
\series default
 or 
\series bold
},
\series default
 resting in a line by itself.
 (The importer, Subsection
\begin_inset space ~
\end_inset


\begin_inset CommandInset ref
LatexCommand ref
reference "sub:Importing-a-bibliography"

\end_inset

, depends on this final brace on a line by itself to work correctly.)
\end_layout

\begin_layout Section
Sectioning a bibliography
\begin_inset CommandInset label
LatexCommand label
name "sec:Dividing-a-bibliography"

\end_inset


\end_layout

\begin_layout Standard
The 
\family sans
Part
\family default
 style is used for the headings of major divisions within the bibliography;
 it is numbered with upper-case Roman numerals.
 
\family sans
Part*
\family default
 is used for secondary divisions; it is not numbered.
 In the 
\family sans
Outline 
\family default
window, 
\family sans
Part
\family default
 style is displayed at level 0, as usual, but 
\family sans
Part*
\family default
 style is at level 1, and 
\family sans
Chapter
\family default
 and 
\family sans
Chapter*
\family default
 styles both at level 2.
 This is particular to (or peculiar to) this bibliography layout and different
 from the usual hierarchy, but experimenting with the 
\family typewriter
biblatex-example
\family default
 file that comes with MiKTeX shows the two-level distinction in major divisions
 is useful.
\end_layout

\begin_layout Standard
On export all headings, and any other introductory or inter-record comments
 or instructions, are stripped from the bib file.
 (This is a change from the first plain-text import/export version of this
 work.) The LyX file is the one to be read by humans; the plain-text bib
 file is the one to be read by 
\family typewriter
biblatex
\family default
.
\end_layout

\begin_layout Section
Navigating
\end_layout

\begin_layout Subsection
Outline window
\end_layout

\begin_layout Standard
Getting about the bib file in LyX is no different from getting about any
 other LyX document.
 The 
\family sans
Navigate
\family default
 menu is one place to look, but the most immediate aid is
\family sans
 
\family default
the 
\family sans
Outline
\family default
 window.
 It enables easy navigation throughout the bibliography file.
 
\end_layout

\begin_layout Standard
Its up and down buttons also allow the easy movement of records up and down
 the bibliography, without having to cut and paste.
 (Of course, the reordering of records is reflected in the exported file,
 so this is not entirely a cosmetic effect, but it has no 
\emph on
functional
\emph default
 effect on 
\family typewriter
biblatex
\family default
.) Large blocks of records can also be moved up or down the bibliography
 by judicious insertion of 
\family sans
Part
\family default
 or 
\family sans
Part*
\family default
 headings.
 This way of moving records is safer than cutting and pasting -- one is
 not going to leave a trailing } or other stray character behind.
\end_layout

\begin_layout Subsection
Using cross-reference labels
\end_layout

\begin_layout Standard
Cross-reference labels (
\family sans
Insert \SpecialChar \menuseparator
 Label \SpecialChar \ldots{}

\family default
 or by clicking on the 
\family sans
Insert label
\family default
 icon) provide another navigational aid.
 The recommended way to use labels for cross-reference purposes is to first
 insert a yellow note where you want the label to go, and then insert the
 label in the note.

\family typewriter
 
\family default
A natural value for the label is the bibliographic key for that record.
 This gives a means of jumping to that record from anywhere in the bibliography
 by clicking on the 
\family sans
Insert cross-reference
\family default
 icon, selecting the relevant label and then clicking on the 
\family sans
Go to Label
\family default
 button.
 If a significant number of records are so labelled, then setting the 
\family sans
Sort
\family default
 checkbox of the 
\family sans
Insert cross-reference
\family default
 panel will give a 
\emph on
sorted
\emph default
 list of bibliographic keys.
\end_layout

\begin_layout Standard
Also, you can insert a yellow note with a cross-reference in it in another
 record where it might be appropriate, and again, the right-click context
 menu gives the option of jumping to the label.
 Right-clicking on the label allows a jump back to the cross-reference.
\end_layout

\begin_layout Section
Annotating a bibliography
\end_layout

\begin_layout Standard
Because the LyX and bib files are two different things, it is possible to
 have any number of instructional notes and reminders in the former which
 are 
\emph on
not
\emph default
 exported to the latter -- the export mechanism strips any introductory
 or inter-record material -- and which therefore do not interfere with the
 proper functioning of the bib file.
 
\end_layout

\begin_layout Subsection
Yellow notes
\end_layout

\begin_layout Standard
The particular virtue of LyX's yellow notes (apart from their eye-catching
 colour) is that they can be placed 
\emph on
anywhere
\emph default
 without consequence for the bib file, and, in particular, 
\emph on
anywhere in a record
\emph default
.
 They are not restricted to introductory material or inter-record placement.
 One can write reminders to oneself of things to check, etc., at 
\emph on
exactly
\emph default
 the right place in a record without consequence for 
\family typewriter
biblatex
\family default
 (or 
\family typewriter
BibTeX
\family default
).
 And as noted, they are natural receptacles for labels and cross-references
 to assist navigation about the bibliography.
\end_layout

\begin_layout Standard
In 
\family typewriter
bibliography.layout 
\family default
the styles 
\family sans
Paragraph
\family default
, 
\family sans
Subparagraph, Itemize, Enumerate
\family default
 and 
\family sans
Standard
\family default
 are specifically intended for formatting text in yellow notes.
 These styles have 
\emph on
not
\emph default
 been redefined.
 They are exactly the same as for LaTeX's standard 
\family sans
book
\family default
 class.
\end_layout

\begin_layout Subsection
Another level for the Outline hierarchy
\end_layout

\begin_layout Standard
Another way of drawing attention to a record, or part of a record, in the
 LyX file, without consequence for the bib file, is to add a further level
 of hierarchy to the 
\family sans
Outline
\family default
 window.
 Neither 
\family sans
Labeling
\family default
 nor 
\family sans
Description
\family default
 styles are exhibited in the 
\family sans
Outline
\family default
 window, but it is possible that we might want to draw attention to some
 particular entry in a record -- perhaps something to check or query.
 One way of `drawing attention' is with the little + box in the 
\family sans
Outline
\family default
 window that indicates a lower level of sectioning is available.
 
\end_layout

\begin_layout Standard
To this end the 
\family sans
Section
\family default
 style is redefined to be (nearly) the same as 
\family sans
Description
\family default
.
 The visible difference is that the colours of data type and content are
 swapped, and, since the style is 
\family sans
Section
\family default
, it 
\emph on
does
\emph default
 show up in the 
\family sans
Outline 
\family default
window.
 (I considered similarly redefining 
\family sans
Section*
\family default
 to be nearly the same as 
\family sans
Labeling
\family default
 but there are complications.
 The data-type entry does show up in the 
\family sans
Outline
\family default
 window but it is preceded by the character string 00.00.0000, which is messy.
 It seems better to restrict this additional level of hierarchy only to
 a 
\family sans
Description
\family default
-like 
\family sans
Section
\family default
.) 
\end_layout

\begin_layout Section
Organising bibliographies
\end_layout

\begin_layout Subsection
Branches
\end_layout

\begin_layout Standard
If a number of records are placed into a branch, either collectively or
 record by record, and the branch is deactivated (right-click on the inset's
 label) then 
\emph on
these records are not exported
\emph default
.
 This provides a mechanism for 
\emph on
selectively
\emph default
 exporting records from a LyX bibliography file to a plain text one.
 Multiple branches allow different selections of records to be exported.
 The downside of using branches is that records enclosed in one, whether
 activated or not, no longer respond to the up and down arrow keys at the
 bottom of the 
\family sans
Outline
\family default
 window.
 Pity.
\end_layout

\begin_layout Standard
See also Section
\begin_inset space ~
\end_inset


\begin_inset CommandInset ref
LatexCommand ref
reference "sec:9.2 Using-the-custom-insets"

\end_inset

 for the effects of branches on viewing records with the custom insets that
 come with the module, 
\family typewriter
bibliography.module
\family default
.
\end_layout

\begin_layout Subsection
Master `hub' with child bibliographies
\end_layout

\begin_layout Standard
Pursuing the branches idea further, one might organise 
\emph on
all
\emph default
 one's bibliographies as child documents of a master document which acts
 as a bibliographic `hub'.
 At present, exporting a master document to 
\family sans
Plain text (bib)
\family default
 format does 
\emph on
not
\emph default
 export the child documents.
\end_layout

\begin_layout Section
Shortcut key
\end_layout

\begin_layout Standard
A prominent feature of 
\family typewriter
biblatex
\family default
 bibliographies is the 
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
= {},
\end_layout

\begin_layout Standard
construct.
 It seems worth assigning a shortcut key to this, one that not only inserts
 this combination of symbols but places the cursor between the braces ready
 to enter the data type's content.
 Assigning (for instance) 
\family sans
Ctrl+=
\family default
 to 
\end_layout

\begin_layout LyX-Code
command-sequence self-insert  = {},; char-left; char-left;
\end_layout

\begin_layout Standard
achieves this.
 (Note that there are
\emph on
 two
\emph default
 spaces before the equals sign.) 
\end_layout

\begin_layout Section
Viewing records
\end_layout

\begin_layout Standard
To view the plain text  bibliography, click on the 
\family sans
View other formats
\family default
 button and select 
\family sans
View plain text (bib)
\family default
.
 The bibliography will be displayed in the text editor prescribed in Section
\begin_inset space ~
\end_inset


\begin_inset CommandInset ref
LatexCommand ref
reference "sec:Formats-and-converters"

\end_inset

, in the format in which 
\family typewriter
biblatex
\family default
 will read it.
 All the fancy formatting, yellow notes etc., will be stripped from it.
 Such a view may be helpful while working on the file, but what one generally
 wants to see is how the records will look in a pdf using a proper 
\family typewriter
biblatex
\family default
 style.
\end_layout

\begin_layout Subsection

\family typewriter
biblatex.module
\end_layout

\begin_layout Standard
The module 
\family typewriter
biblatex.module 
\family default
defines two custom insets: 
\family sans
ViewEntriesByKey
\family default
 and 
\family sans
FindAndViewEntries
\family default
.
 These are 
\family typewriter
biblatex
\family default
 (rather than 
\family typewriter
BibTeX
\family default
)
\family typewriter
 
\family default
specific.
 They provide the means for looking at selected records from the 
\emph on
exported
\emph default
 bibliography (the bib file) in their 
\family typewriter
biblatex
\family default
 formatting.
 
\end_layout

\begin_layout Itemize
First, the module needs to be placed in your personal layout folder (where
 
\family typewriter
bibliography .layout
\family default
 was put) and LyX reconfigured so that it is aware of the module's existence.
\end_layout

\begin_layout Itemize
Then you have a choice of adding the module (
\family sans
Document \SpecialChar \menuseparator
 Settings \SpecialChar \menuseparator
 Modules
\family default
) either to the LyX document containing the bibliography, or to a new document.
 The first seems more natural but comes with complications, mentioned below.
 
\end_layout

\begin_layout Itemize
Third, the preamble to the LyX file (
\family sans
Document \SpecialChar \menuseparator
 Settings \SpecialChar \menuseparator
 LaTeX Preamble
\family default
) needs two commands to be entered (note that 
\series bold
numeric
\series default
 here can be replaced by any other 
\family typewriter
biblatex
\family default
 style)
\end_layout

\begin_layout LyX-Code

\family roman
\series bold

\backslash
usepackage[style=numeric]{biblatex}
\end_layout

\begin_layout LyX-Code

\family roman
\series bold

\backslash
addbibresource{<path-to-bib-file><bib-file-name>.bib}
\end_layout

\begin_layout Itemize
As the Wiki notes (in its section on using 
\family typewriter
biblatex
\family default
 with LyX) the <
\series bold
path-to-bib-file>
\series default
 is unnecessary if the bib file is found in the 
\family sans
texmf
\family default
 tree.
 If the bib file is outside the 
\family sans
texmf
\family default
 tree, then the full path is required.
\end_layout

\begin_layout Itemize
In Windows, should the path contain spaces, enclosing it in double quotes
 (the usual cure) will cause the viewer insets of the next section, and
 the general use of the bib file by 
\family typewriter
biblatex
\family default
, to fail.
 What is required is either to change the location of the bib file, or to
 use a `short filename' in place of that part of the path containing spaces.
 In most cases this will mean taking the first six non-space characters,
 adding a tilde and then the digit 1; see 
\family typewriter
http://support.microsoft.com/kb/142982
\family default
.
\begin_inset Foot
status collapsed

\begin_layout Plain Layout
`Windows truncates the file name, if necessary, to six characters and appends
 a tilde (~) and a digit.
 For example, each unique file name created ends with ``~1.'' Duplicate file
 names end with ``~2,'' ``~3,'' and so on.'
\end_layout

\end_inset

 For example, a path containing 
\family typewriter
\SpecialChar \ldots{}
/Test Folder/test.bib
\family default
 when changed to 
\family typewriter
\SpecialChar \ldots{}
/TestFo~1/test.bib
\family default
 should  work.
 (The 
\emph on
length
\emph default
 of the name or path should not be a problem.
 I'm not familiar with what happens in Linux or on the Mac.)
\end_layout

\begin_layout Itemize
Lastly, a yellow note needs to be inserted in the document proper, preferably
 at the start of the LyX file, and inside that the bib file inserted (
\family sans
Insert \SpecialChar \menuseparator
 List/TOC \SpecialChar \menuseparator
 BibTeX Bibliography 
\family default
then
\family sans
 Add 
\family default
and
\family sans
 Browse
\family default
 to the location of the bib file).
 
\end_layout

\begin_layout Subsection
Using the custom insets
\begin_inset CommandInset label
LatexCommand label
name "sec:9.2 Using-the-custom-insets"

\end_inset


\end_layout

\begin_layout Standard
Now we are ready to use the custom insets, available from 
\family sans
Insert \SpecialChar \menuseparator
 Custom Insets
\family default
.
 The problem is that if we use them in the LyX bibliography file as it stands,
 not only will we get the desired records in correctly formatted garb in
 the pdf, but also the entire LyX file will be written to the pdf and formatted
 according to the presriptions of LaTeX's 
\family sans
book
\family default
 class -- the entry type of each record, for instance, will be treated as
 a chapter heading (and for a large bibliography, that is an awful lot of
 chapters).
 Obviously this is not a problem if the module was added to a separate new
 LyX document.
\end_layout

\begin_layout Standard
The key to using these insets while in the LyX file is the use of branches.
 Place the records in the LyX file into a branch (the branch inset itself
 being given the 
\family sans
Standard
\family default
 style).
 
\emph on
Activate 
\emph default
the branch when exporting to the plain text bib
\emph on
 
\emph default
file.
 
\emph on
Deactivate
\emph default
 the branch when using 
\family sans
ViewEntriesByKey
\family default
 or
\emph on
 
\family sans
\emph default
FindAndViewEntries
\family default
.
\begin_inset Foot
status collapsed

\begin_layout Plain Layout
As noted earlier, the downside to putting the records into a branch is that
 the up and down keys in the 
\family sans
Outline
\family default
 window cease to work.
\end_layout

\end_inset

 
\end_layout

\begin_layout Standard

\family sans
ViewEntriesByKey
\family default
 depends on 
\family typewriter
biblatex
\family default
's 
\family sans
category
\family default
 feature, but hides it from the user.
 First, ensure that the bibliography has been exported to its plain text
 format (branch activated) then, with the branch 
\emph on
de
\emph default
activated, enter the bibliographic keys (they are displayed in the 
\family sans
Outline
\family default
 window)
\family sans
 
\family default
of selected records in a comma-separated list into the inset (with the inset
 preferably placed near the head of the file in LyX), and click on LyX's
 
\family sans
View
\family default
 button.
 A pdf will be produced in which only the chosen records are displayed,
 formatted according to their 
\family typewriter
biblatex
\family default
 style prescription (
\family sans
numeric
\family default
 by default).
\end_layout

\begin_layout Standard
The second custom inset, 
\family sans
FindAndViewEntries
\family default
, is simply `fancy dress' around 
\family typewriter
biblatex
\family default
's 
\series bold

\backslash
printbibliography
\series default
 command.
 Anything that can be entered as an argument in that command, can be entered
 in the inset.
 However, it is mainly intended for use with 
\family typewriter
biblatex
\family default
's 
\family sans
keyword
\family default
 facility.
 For instance, typing
\end_layout

\begin_layout LyX-Code

\family roman
\series bold
keyword=foo, keyword=bar, notkeyword=bah
\end_layout

\begin_layout Standard
in the inset and clicking on LyX's 
\family sans
View
\family default
 button
\family sans
 
\family default
(again, with the branch containing the records in LyX deactivated) will
 create a pdf of those records in which the 
\family sans
keywords
\family default
 field contains both 
\series bold
foo
\series default
 and 
\series bold
bar 
\series default
but not 
\series bold
bah
\series default
 (the commas between 
\series bold
keyword=\SpecialChar \ldots{}
, keyword=\SpecialChar \ldots{}
, \SpecialChar \ldots{}

\series default
 are treated as 
\family sans
And 
\family default
rather than 
\family sans
Or
\family default
).
\end_layout

\end_body
\end_document
#% Do not delete the line below; configure depends on this
#  \DeclareLaTeXClass[book]{bibliography}
# Create, edit, organise biblatex bibliography files in LyX
# Andrew Parsloe 18 March 2012

Format 35

Input stdcounters.inc
Input stdtitle.inc
Input stdsections.inc
Input stdlists.inc

DefaultStyle            Standard

DefaultFont
        Family                          Roman
        Series              Medium
        Shape               Up
        Size                Normal
        Color               None
EndFont

#For yellow notes

Style Title
        Category                        Prelims
End

Style Author
        Category                        Prelims
End

Style Date
        Category                        Prelims
End

Style Paragraph
        Category                        Notes
End

Style Subparagraph
        Category                        Notes
End

Style Itemize
        Category                        Notes
End

Style Enumerate
        Category                        Notes
End

Style Standard
        Category                        Notes
        Margin              Static
        LatexType           Paragraph
        LatexName           relax
        ParIndent           ""
        ParSkip             0.4
        Align               Block
        AlignPossible       Block, Left, Right, Center
        LabelType           No_Label
End

Style --Separator--
        Category              MainText
        KeepEmpty             1
        Margin                Dynamic
        LatexType             Paragraph
        LatexName             dummy
        ParIndent             MM
        Align                 Block
        LabelType             Static
        LabelString           "--- Separate Environment ---"
        LabelFont
          Family              Roman
          Series              Medium
          Size                Normal
          Color               Blue
        EndFont
        HTMLLabel             NONE
End

#Primary & secondary divisions of a bibliography

Style Part
        Category                        Divisions
        Margin              Dynamic
        LabelString         "\thepart"
        LabelType           Counter
        TocLevel            0
        LabelCounter        part
        LatexType           Command
        LatexName                       part
        Labelsep            xxx
        NeedProtect         1
        NextNoIndent        1
        ParSkip             0
        TopSep              1
        BottomSep           1
        ParSep              0
        Align               Left
        AlignPossible           Left,Center
        OptionalArgs        0
        Font
          Series            Bold
          Size              Larger
        EndFont
End

Style Part*
        CopyStyle                       Part
        Margin              Static
        LabelType           No_label
        LatexName                       part*
        LabelCounter        ""
        TocLevel            1
        Font
          Series            Bold
          Size              Large
        EndFont
End
        
#Entry types, numbered & unnumbered

Style Chapter
        Category                        EntryTypes
        Margin              Static
        LabelString         "\thechapter."
        LabelType           Counter
        LabelCounter        chapter
        LatexName                       chapter
        TocLevel            2
        NeedProtect         1
        NextNoIndent        0
        ParSkip             0
        TopSep              1
        BottomSep           0
        ParSep              0
        Align               Left
        OptionalArgs        0
        Font
          Series            Bold
          Size              normal
        EndFont
End

Style Chapter*
        CopyStyle                       Chapter
        Margin              static
        LatexName                       chapter*
        LabelType                       No_label
        LabelCounter        ""
        ParSkip                         1
End

#Data types & contents

Style Description
        Category                        DataTypes
        LeftMargin          "MMM"
        ParIndent                       "-MMM"
        NextNoIndent            0
        LabelSep            x
        ParSkip             0
        ItemSep             0
        TopSep              0
        BottomSep           0
        ParSep              0
        Align               Left
        LabelFont
          Series                        Medium
          Color             red
        EndFont
End

Style Labeling
        Category                        DataTypes
        NextNoIndent            0
        LabelSep            x
        LabelString                     "00.00.0000"
        ItemSep             0
        TopSep              0
        BottomSep           0
        ParSep              0
End

#If data types are to appear in Outline window

Style Section
        CopyStyle                       Description
        LatexName                       section
        TocLevel                        3
        Font
          Color                         red
        EndFont
        LabelFont
          Color                         black
        EndFont
End

NoStyle Subsection
NoStyle Subsubsection

#\DeclareLyXModule{Bibliography}
#DescriptionBegin
#Provides two flex insets for viewing biblatex records
#DescriptionEnd
#
#v.1.0 2012-04-07
#Author: Andrew Parsloe <[email protected]>

Format 35

AddToPreamble
        \usepackage{etoolbox}
        \AtEndPreamble{\DeclareBibliographyCategory{bibView}}
        \AtBeginDocument{\nocite{*}}
EndPreamble

#View entries by key
InsetLayout Flex:ViewEntriesByKey
  LyXType                       custom
  LatexType             Command
  LatexName             ViewEntriesByKey
  ContentAsLabel        0
  Decoration            Classic
  Font
        Color                   Black
        Misc                    no_emph
        Shape                   Up
  EndFont
  LabelFont
        Color                   Blue
  EndFont
  LabelString           ViewEntriesByKey
  Multipar                      0
  PassThru                      0
  ResetsFont            1
  Spellcheck            0
  Preamble
    \newcommand{\ViewEntriesByKey}[1]{\addtocategory{bibView}{#1}%
                \printbibliography[category=bibView]}
  EndPreamble
End

#A wrapper for biblatex's \printbibliography command
InsetLayout Flex:FindAndViewEntries
  LyXType                       custom
  LatexType             Command
  LatexName             FindAndViewEntries
  ContentAsLabel        0
  Decoration            Classic
  Font
        Color                   Black
        Misc                    no_emph
        Shape                   Up
  EndFont
  LabelFont
        Color                   Blue
  EndFont
  LabelString           FindAndViewEntries
  Multipar                      0
  PassThru                      0
  ResetsFont            1
  Spellcheck            0
  Preamble
        \newcommand{\FindAndViewEntries}[1]{\printbibliography[#1]}
  EndPreamble
End
#
# bib2ltx.py
#
# author: Andrew Parsloe ([email protected]) 18 May 2012 
#
# Usage: python <path to>bib2ltx.py [options] <file>.bib <file>.tex
#
# Converts a biblatex or BibTeX bib file into a LaTeX file for 
# importing to LyX to be displayed with bibliography.layout. 
#
# Options: -c   displays bib records in a description
#               list environment using colour default
#               is labeling using indentation)
#          -k   keeps introductory and inter-record
#               comments, headings etc.
#          -o   prevents extra braces being inserted when
#               importing in LyX 2.0.0. (Not known whether
#               needed for LyX 2.0.1 or 2.0.2 as yet.)
#          -cko  combines the options

import re, sys

guff0 = 0
liststyle = 'lyxlist'
older = False

opts=sys.argv[1]
if opts.find('-')==0:
    if opts.find('c')>0:
        liststyle = 'description'
    if opts.find('k')>0:
        guff0 = 1
    if opts.find('o')>0:
        older = True
        
guff = guff0

fbib = open(sys.argv[-2],'r')
fltx = open(sys.argv[-1],'w')

preamble='''\\documentclass{bibliography}
\\usepackage[T1]{fontenc}
\\usepackage[latin9]{inputenc}
\\setcounter{secnumdepth}{2}
\\setlength{\\parskip}{\\smallskipamount}
\\setlength{\\parindent}{0pt}

'''
endofrecords = '\n%Keep this comment (formatting purposes)!\n'
chapter = '\n\\chapter{'
chapterstar = '\n\\chapter*{'
item = '\\item[{'
endlyxlist = '\\end{lyxlist}\n\n'

#escape last }
def escape_last_brace(line):
    if line not in '\n':
        line = re.sub(r'(}|},)\s*$', r'\\\1\n', line)
    return line

#list style for displaying records
def startlist(c):
    if c == 'description':
        fltx.write('\\begin{description}\n')
    else:
        fltx.write('\\begin{lyxlist}{00.00.0000}\n')

def endlist(c):
    if c == 'description':
        fltx.write('\\end{description}\n')
    else:
        fltx.write('\\end{lyxlist}\n')
        

fltx.write(preamble)
fltx.write('\\begin{document}\n\n')

line0 = ''
for line in fbib:
    #delete any whitespace at start of lines
    line=re.sub(r'\A\s*', '', line)
    
    #BibTeX commands (including # concatenations)
    if re.match(r'(?i)@(string|preamble|comment)', line) \
    or re.match(r'#', line):
        guff = 0
        fltx.write(chapterstar)
        #\ to \textbackslash
        line = re.sub(r'\\', r'\\textbackslash ',line)
        #escape braces
        line = re.sub(r'([{}])', r'\\\1',line)
        fltx.write(line[:-1]+'}\n')
        guff = guff0
               
    #entry types
    elif re.match(r'@\w*{', line):
        guff = 0
        fltx.write(chapter)
        line = re.sub(r'{', r'\\{', line)
        fltx.write(line[:-1]+'}\n')
        startlist(liststyle)

    #data types
    elif re.match(r'\w+\s*=\s*', line):
        if line0 not in '\n':
            #escape last }
            line0 = escape_last_brace(line0)
            fltx.write(line0)
            line0 = ''
        if older:
            line = re.sub(r'(\w+)', r'\\item [\1]', line, 1)
        else:
            line = re.sub(r'(\w+)', r'\\item [{\1}]', line, 1)
        line = re.sub(r'(\s*=\s*){', r'\1\\{', line, 1)
        # concatenator #
        line0 = re.sub(r'(#\s*{)', r'# \\{', line, 1)
        
    #end of record
    elif re.match(r'(}|},)\s*$', line):
        if line0 != '':
            line0 = escape_last_brace(line0)
            fltx.write(line0)
            line0 = ''
        if older:
            fltx.write('\\item [\}]\n')
        else:
            fltx.write('\\item [{\}}]\n')
        endlist(liststyle)
        guff = guff0 # for inter-record guff
        
    else: 
        #data type contents
        if guff and line not in '\n':
            fltx.write(line+'\n')
        elif line0 not in '\n':
            fltx.write(line0)
            line0 = line

fltx.write(endofrecords)

fltx.write('\n\\end{document}')

fltx.close()

Reply via email to