summaryrefslogtreecommitdiffstats
path: root/gettext-tools/src/its.c
blob: 394b5f06dc11c72f71c2d1cdb68bee649df03550 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
/* Internationalization Tag Set (ITS) handling
   Copyright (C) 2015 Free Software Foundation, Inc.

   This file was written by Daiki Ueno <ueno@gnu.org>, 2015.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

/* Specification.  */
#include "its.h"

#include <assert.h>
#include <errno.h>
#include "error.h"
#include "gettext.h"
#include "hash.h"
#include <stdint.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xmlwriter.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <stdlib.h>
#include "trim.h"
#include "xalloc.h"
#include "xvasprintf.h"

#define _(str) gettext (str)

/* The Internationalization Tag Set (ITS) 2.0 standard is available at:
   http://www.w3.org/TR/its20/

   This implementation supports only a few data categories, useful for
   gettext-based projects.  Other data categories can be added by
   extending the its_rule_class_ty class and registering it in
   init_classes().

   The message extraction is performed in three steps.  In the first
   step, its_rule_list_apply() assigns values to nodes in an XML
   document.  In the second step, its_rule_list_extract_nodes() marks
   translatable nodes.  In the final step,
   its_rule_list_extract_text() extracts text contents from the marked
   nodes.

   The values assigned to a node are represented as an array of
   key-value pairs, where both keys and values are string.  The array
   is stored in node->_private.  To retrieve the values for a node,
   use its_rule_list_eval().  */

#define ITS_NS "http://www.w3.org/2005/11/its"
#define XML_NS "http://www.w3.org/XML/1998/namespace"
#define GT_NS "https://www.gnu.org/s/gettext/ns/its/extensions/1.0"

struct its_value_ty
{
  char *name;
  char *value;
};

struct its_value_list_ty
{
  struct its_value_ty *items;
  size_t nitems;
  size_t nitems_max;
};

static void
its_value_list_append (struct its_value_list_ty *values,
                       const char *name,
                       const char *value)
{
  struct its_value_ty _value;

  _value.name = xstrdup (name);
  _value.value = xstrdup (value);

  if (values->nitems == values->nitems_max)
    {
      values->nitems_max = 2 * values->nitems_max + 1;
      values->items =
        xrealloc (values->items,
                  sizeof (struct its_value_ty) * values->nitems_max);
    }
  memcpy (&values->items[values->nitems++], &_value,
          sizeof (struct its_value_ty));
}

static const char *
its_value_list_get_value (struct its_value_list_ty *values,
                          const char *name)
{
  size_t i;

  for (i = 0; i < values->nitems; i++)
    {
      struct its_value_ty *value = &values->items[i];
      if (strcmp (value->name, name) == 0)
        return value->value;
    }
  return NULL;
}

static void
its_value_list_set_value (struct its_value_list_ty *values,
                          const char *name,
                          const char *value)
{
  size_t i;

  for (i = 0; i < values->nitems; i++)
    {
      struct its_value_ty *_value = &values->items[i];
      if (strcmp (_value->name, name) == 0)
        {
          free (_value->value);
          _value->value = xstrdup (value);
          break;
        }
    }

  if (i == values->nitems)
    its_value_list_append (values, name, value);
}

static void
its_value_list_merge (struct its_value_list_ty *values,
                      struct its_value_list_ty *other)
{
  size_t i;

  for (i = 0; i < other->nitems; i++)
    {
      struct its_value_ty *other_value = &other->items[i];
      size_t j;

      for (j = 0; j < values->nitems; j++)
        {
          struct its_value_ty *value = &values->items[j];

          if (strcmp (value->name, other_value->name) == 0
              && strcmp (value->value, other_value->value) != 0)
            {
              free (value->value);
              value->value = xstrdup (other_value->value);
              break;
            }
        }

      if (j == values->nitems)
        its_value_list_append (values, other_value->name, other_value->value);
    }
}

static void
its_value_list_destroy (struct its_value_list_ty *values)
{
  size_t i;

  for (i = 0; i < values->nitems; i++)
    {
      free (values->items[i].name);
      free (values->items[i].value);
    }
  free (values->items);
}

struct its_pool_ty
{
  struct its_value_list_ty *items;
  size_t nitems;
  size_t nitems_max;
};

static struct its_value_list_ty *
its_pool_alloc_value_list (struct its_pool_ty *pool)
{
  struct its_value_list_ty *values;

  if (pool->nitems == pool->nitems_max)
    {
      pool->nitems_max = 2 * pool->nitems_max + 1;
      pool->items =
        xrealloc (pool->items,
                  sizeof (struct its_value_list_ty) * pool->nitems_max);
    }

  values = &pool->items[pool->nitems++];
  memset (values, 0, sizeof (struct its_value_list_ty));
  return values;
}

static const char *
its_pool_get_value_for_node (struct its_pool_ty *pool, xmlNode *node,
                              const char *name)
{
  intptr_t index = (intptr_t) node->_private;
  if (index > 0)
    {
      struct its_value_list_ty *values;

      assert (index <= pool->nitems);
      values = &pool->items[index - 1];

      return its_value_list_get_value (values, name);
    }
  return NULL;
}

static void
its_pool_destroy (struct its_pool_ty *pool)
{
  size_t i;

  for (i = 0; i < pool->nitems; i++)
    its_value_list_destroy (&pool->items[i]);
  free (pool->items);
}

struct its_rule_list_ty
{
  struct its_rule_ty **items;
  size_t nitems;
  size_t nitems_max;

  struct its_pool_ty pool;
};

struct its_node_list_ty
{
  xmlNode **items;
  size_t nitems;
  size_t nitems_max;
};

static void
its_node_list_append (struct its_node_list_ty *nodes,
                      xmlNode *node)
{
  if (nodes->nitems == nodes->nitems_max)
    {
      nodes->nitems_max = 2 * nodes->nitems_max + 1;
      nodes->items =
        xrealloc (nodes->items, sizeof (xmlNode *) * nodes->nitems_max);
    }
  nodes->items[nodes->nitems++] = node;
}

/* Base class representing an ITS rule in global definition.  */
struct its_rule_class_ty
{
  /* How many bytes to malloc for an instance of this class.  */
  size_t size;

  /* What to do immediately after the instance is malloc()ed.  */
  void (*constructor) (struct its_rule_ty *pop, xmlNode *node);

  /* What to do immediately before the instance is free()ed.  */
  void (*destructor) (struct its_rule_ty *pop);

  /* How to apply the rule to all elements in DOC.  */
  void (* apply) (struct its_rule_ty *pop, struct its_pool_ty *pool,
                  xmlDoc *doc);

  /* How to evaluate the value of NODE according to the rule.  */
  struct its_value_list_ty *(* eval) (struct its_rule_ty *pop,
                                      struct its_pool_ty *pool, xmlNode *node);
};

#define ITS_RULE_TY                             \
  struct its_rule_class_ty *methods;            \
  char *selector;                               \
  struct its_value_list_ty values;              \
  xmlNs **namespaces;

struct its_rule_ty
{
  ITS_RULE_TY
};

static hash_table classes;

static void
its_rule_destructor (struct its_rule_ty *pop)
{
  free (pop->selector);
  its_value_list_destroy (&pop->values);
  if (pop->namespaces)
    {
      size_t i;
      for (i = 0; pop->namespaces[i] != NULL; i++)
        xmlFreeNs (pop->namespaces[i]);
      free (pop->namespaces);
    }
}

static void
its_rule_apply (struct its_rule_ty *rule, struct its_pool_ty *pool, xmlDoc *doc)
{
  xmlXPathContext *context;
  xmlXPathObject *object;
  size_t i;

  if (!rule->selector)
    {
      error (0, 0, _("selector is not specified"));
      return;
    }

  context = xmlXPathNewContext (doc);
  if (!context)
    {
      error (0, 0, _("cannot create XPath context"));
      return;
    }

  if (rule->namespaces)
    {
      size_t i;
      for (i = 0; rule->namespaces[i] != NULL; i++)
        {
          xmlNs *ns = rule->namespaces[i];
          xmlXPathRegisterNs (context, ns->prefix, ns->href);
        }
    }

  object = xmlXPathEval (BAD_CAST rule->selector, context);
  if (!object)
    {
      xmlXPathFreeContext (context);
      error (0, 0, _("cannot evaluate XPath expression: %s"), rule->selector);
      return;
    }

  if (object->nodesetval)
    {
      xmlNodeSet *nodes = object->nodesetval;
      for (i = 0; i < nodes->nodeNr; i++)
        {
          xmlNode *node = nodes->nodeTab[i];
          struct its_value_list_ty *values;

          /* We can't store VALUES in NODE, since the address can
             change when realloc()ed.  */
          intptr_t index = (intptr_t) node->_private;

          assert (index <= pool->nitems);
          if (index > 0)
            values = &pool->items[index - 1];
          else
            {
              values = its_pool_alloc_value_list (pool);
              node->_private = (void *) pool->nitems;
            }

          its_value_list_merge (values, &rule->values);
        }
    }

  xmlXPathFreeObject (object);
  xmlXPathFreeContext (context);
}

static char *
_its_get_attribute (xmlNode *node, const char *attr, const char *namespace)
{
  xmlChar *value;
  char *result;

  value = xmlGetNsProp (node, BAD_CAST attr, BAD_CAST namespace);

  result = xstrdup ((const char *) value);
  xmlFree (value);

  return result;
}

static char *
normalize_whitespace (const char *text, enum its_whitespace_type_ty whitespace)
{
  switch (whitespace)
    {
    case ITS_WHITESPACE_PRESERVE:
      return xstrdup (text);

    case ITS_WHITESPACE_TRIM:
      return trim (text);

    default:
      /* Normalize whitespaces within the text, but not at the beginning
         nor the end of the text.  */
      {
        char *result, *p, *end;

        result = xstrdup (text);
        end = result + strlen (result);
        for (p = result; *p != '\0';)
          {
            size_t len = strspn (p, " \t\n");
            if (len > 0)
              {
                *p = ' ';
                memmove (p + 1, p + len, end - (p + len));
                end -= len - 1;
                *end = '\0';
                p++;
              }
            p += strcspn (p, " \t\n");
          }
        return result;
      }
    }
}

static char *
_its_encode_special_chars (const char *content, bool is_attribute)
{
  const char *str;
  size_t amount = 0;
  char *result, *p;

  for (str = content; *str != '\0'; str++)
    {
      switch (*str)
        {
        case '&':
          amount += sizeof ("&amp;");
          break;
        case '<':
          amount += sizeof ("&lt;");
          break;
        case '>':
          amount += sizeof ("&gt;");
          break;
        case '"':
          if (is_attribute)
            amount += sizeof ("&quot;");
          else
            amount += 1;
          break;
        default:
          amount += 1;
          break;
        }
    }

  result = XNMALLOC (amount + 1, char);
  *result = '\0';
  p = result;
  for (str = content; *str != '\0'; str++)
    {
      switch (*str)
        {
        case '&':
          p = stpcpy (p, "&amp;");
          break;
        case '<':
          p = stpcpy (p, "&lt;");
          break;
        case '>':
          p = stpcpy (p, "&gt;");
          break;
        case '"':
          if (is_attribute)
            p = stpcpy (p, "&quot;");
          else
            *p++ = '"';
          break;
        default:
          *p++ = *str;
          break;
        }
    }
  *p = '\0';
  return result;
}

static char *
_its_collect_text_content (xmlNode *node,
                           enum its_whitespace_type_ty whitespace,
                           bool no_escape)
{
  char *buffer = NULL;
  size_t bufmax = 0;
  size_t bufpos = 0;
  xmlNode *n;

  for (n = node->children; n; n = n->next)
    {
      char *content = NULL;

      switch (n->type)
        {
        case XML_TEXT_NODE:
        case XML_CDATA_SECTION_NODE:
          {
            xmlChar *xcontent = xmlNodeGetContent (n);
            char *econtent;
            const char *ccontent;

            /* We can't expect xmlTextWriterWriteString() encode
               special characters as we write text outside of the
               element.  */
            if (no_escape)
              econtent = xstrdup ((const char *) xcontent);
            else
              econtent =
                _its_encode_special_chars ((const char *) xcontent,
                                           node->type == XML_ATTRIBUTE_NODE);
            xmlFree (xcontent);

            /* Skip whitespaces at the beginning of the text, if this
               is the first node.  */
            ccontent = econtent;
            if (whitespace == ITS_WHITESPACE_NORMALIZE && !n->prev)
              ccontent = ccontent + strspn (ccontent, " \t\n");
            content =
              normalize_whitespace (ccontent, whitespace);
            free (econtent);

            /* Skip whitespaces at the end of the text, if this
               is the last node.  */
            if (whitespace == ITS_WHITESPACE_NORMALIZE && !n->next)
              {
                char *p = content + strlen (content);
                for (; p > content; p--)
                  {
                    int c = *(p - 1);
                    if (!(c == ' ' || c == '\t' || c == '\n'))
                      {
                        *p = '\0';
                        break;
                      }
                  }
              }
          }
          break;

        case XML_ELEMENT_NODE:
          {
            xmlOutputBuffer *buffer = xmlAllocOutputBuffer (NULL);
            xmlTextWriter *writer = xmlNewTextWriter (buffer);
            char *p = _its_collect_text_content (n, whitespace,
                                                 no_escape);
            const char *ccontent;

            xmlTextWriterStartElement (writer, BAD_CAST n->name);
            if (n->properties)
              {
                xmlAttr *attr = n->properties;
                for (; attr; attr = attr->next)
                  {
                    xmlChar *prop = xmlGetProp (n, attr->name);
                    xmlTextWriterWriteAttribute (writer,
                                                 attr->name,
                                                 prop);
                    xmlFree (prop);
                  }
              }
            if (*p != '\0')
              xmlTextWriterWriteRaw (writer, BAD_CAST p);
            xmlTextWriterEndElement (writer);
            ccontent = (const char *) xmlOutputBufferGetContent (buffer);
            content = normalize_whitespace (ccontent, whitespace);
            xmlFreeTextWriter (writer);
            free (p);
          }
          break;

        case XML_ENTITY_REF_NODE:
          content = xasprintf ("&%s;", (const char *) n->name);
          break;

        default:
          break;
        }

      if (content != NULL)
        {
          size_t length = strlen (content);

          if (bufpos + length + 1 >= bufmax)
            {
              bufmax = 2 * bufmax + length + 1;
              buffer = xrealloc (buffer, bufmax);
            }
          strcpy (&buffer[bufpos], content);
          bufpos += length;
        }
      free (content);
    }

  if (buffer == NULL)
    buffer = xstrdup ("");
  return buffer;
}

static void
_its_error_missing_attribute (xmlNode *node, const char *attribute)
{
  error (0, 0, _("\"%s\" node does not contain \"%s\""),
         node->name, attribute);
}

/* Implementation of Translate data category.  */
static void
its_translate_rule_constructor (struct its_rule_ty *pop, xmlNode *node)
{
  char *prop;

  if (!xmlHasProp (node, BAD_CAST "selector"))
    {
      _its_error_missing_attribute (node, "selector");
      return;
    }

  if (!xmlHasProp (node, BAD_CAST "translate"))
    {
      _its_error_missing_attribute (node, "translate");
      return;
    }

  prop = _its_get_attribute (node, "selector", NULL);
  if (prop)
    pop->selector = prop;

  prop = _its_get_attribute (node, "translate", NULL);
  its_value_list_append (&pop->values, "translate", prop);
  free (prop);
}

struct its_value_list_ty *
its_translate_rule_eval (struct its_rule_ty *pop, struct its_pool_ty *pool,
                         xmlNode *node)
{
  struct its_value_list_ty *result;

  result = XCALLOC (1, struct its_value_list_ty);

  switch (node->type)
    {
    case XML_ATTRIBUTE_NODE:
      /* Attribute nodes don't inherit from the parent elements.  */
      {
        const char *value =
          its_pool_get_value_for_node (pool, node, "translate");
        if (value != NULL)
          {
            its_value_list_set_value (result, "translate", value);
            return result;
          }

        /* The default value is translate="no".  */
        its_value_list_append (result, "translate", "no");
      }
      break;

    case XML_ELEMENT_NODE:
      /* Inherit from the parent elements.  */
      {
        const char *value;

        /* A local attribute overrides the global rule.  */
        if (xmlHasNsProp (node, BAD_CAST "translate", BAD_CAST ITS_NS))
          {
            char *prop;

            prop = _its_get_attribute (node, "translate", ITS_NS);
            its_value_list_append (result, "translate", prop);
            free (prop);
            return result;
          }

        /* Check value for the current node.  */
        value = its_pool_get_value_for_node (pool, node, "translate");
        if (value != NULL)
          {
            its_value_list_set_value (result, "translate", value);
            return result;
          }

        /* Recursively check value for the parent node.  */
        if (node->parent == NULL
            || node->parent->type != XML_ELEMENT_NODE)
          /* The default value is translate="yes".  */
          its_value_list_append (result, "translate", "yes");
        else
          {
            struct its_value_list_ty *values;

            values = its_translate_rule_eval (pop, pool, node->parent);
            its_value_list_merge (result, values);
            its_value_list_destroy (values);
            free (values);
          }
      }
      break;

    default:
      break;
    }

  return result;
}

static struct its_rule_class_ty its_translate_rule_class =
  {
    sizeof (struct its_rule_ty),
    its_translate_rule_constructor,
    its_rule_destructor,
    its_rule_apply,
    its_translate_rule_eval,
  };

/* Implementation of Localization Note data category.  */
static void
its_localization_note_rule_constructor (struct its_rule_ty *pop, xmlNode *node)
{
  char *prop;
  xmlNode *n;

  if (!xmlHasProp (node, BAD_CAST "selector"))
    {
      _its_error_missing_attribute (node, "selector");
      return;
    }

  if (!xmlHasProp (node, BAD_CAST "locNoteType"))
    {
      _its_error_missing_attribute (node, "locNoteType");
      return;
    }

  prop = _its_get_attribute (node, "selector", NULL);
  if (prop)
    pop->selector = prop;

  for (n = node->children; n; n = n->next)
    {
      if (n->type == XML_ELEMENT_NODE
          && xmlStrEqual (n->name, BAD_CAST "locNote")
          && xmlStrEqual (n->ns->href, BAD_CAST ITS_NS))
        break;
    }

  prop = _its_get_attribute (node, "locNoteType", NULL);
  if (prop)
    its_value_list_append (&pop->values, "locNoteType", prop);
  free (prop);

  if (n)
    {
      /* FIXME: Respect space attribute.  */
      char *content = _its_collect_text_content (n, ITS_WHITESPACE_NORMALIZE,
                                                 false);
      its_value_list_append (&pop->values, "locNote", content);
      free (content);
    }
  else if (xmlHasProp (node, BAD_CAST "locNotePointer"))
    {
      prop = _its_get_attribute (node, "locNotePointer", NULL);
      its_value_list_append (&pop->values, "locNotePointer", prop);
      free (prop);
    }
  /* FIXME: locNoteRef and locNoteRefPointer */
}

struct its_value_list_ty *
its_localization_note_rule_eval (struct its_rule_ty *pop,
                                 struct its_pool_ty *pool,
                                 xmlNode *node)
{
  struct its_value_list_ty *result;

  result = XCALLOC (1, struct its_value_list_ty);

  switch (node->type)
    {
    case XML_ATTRIBUTE_NODE:
      /* Attribute nodes don't inherit from the parent elements.  */
      {
        const char *value;

        value = its_pool_get_value_for_node (pool, node, "locNoteType");
        if (value != NULL)
          its_value_list_set_value (result, "locNoteType", value);

        value = its_pool_get_value_for_node (pool, node, "locNote");
        if (value != NULL)
          {
            its_value_list_set_value (result, "locNote", value);
            return result;
          }

        value = its_pool_get_value_for_node (pool, node, "locNotePointer");
        if (value != NULL)
          {
            its_value_list_set_value (result, "locNotePointer", value);
            return result;
          }
      }
      break;

    case XML_ELEMENT_NODE:
      /* Inherit from the parent elements.  */
      {
        const char *value;

        /* Local attributes overrides the global rule.  */
        if (xmlHasNsProp (node, BAD_CAST "locNote", BAD_CAST ITS_NS)
            || xmlHasNsProp (node, BAD_CAST "locNoteRef", BAD_CAST ITS_NS)
            || xmlHasNsProp (node, BAD_CAST "locNoteType", BAD_CAST ITS_NS))
          {
            char *prop;

            if (xmlHasNsProp (node, BAD_CAST "locNote", BAD_CAST ITS_NS))
              {
                prop = _its_get_attribute (node, "locNote", ITS_NS);
                its_value_list_append (result, "locNote", prop);
                free (prop);
              }

            /* FIXME: locNoteRef */

            if (xmlHasNsProp (node, BAD_CAST "locNoteType", BAD_CAST ITS_NS))
              {
                prop = _its_get_attribute (node, "locNoteType", ITS_NS);
                its_value_list_append (result, "locNoteType", prop);
                free (prop);
              }

            return result;
          }

        /* Check value for the current node.  */
        value = its_pool_get_value_for_node (pool, node, "locNoteType");
        if (value != NULL)
          its_value_list_set_value (result, "locNoteType", value);

        value = its_pool_get_value_for_node (pool, node, "locNote");
        if (value != NULL)
          {
            its_value_list_set_value (result, "locNote", value);
            return result;
          }

        value = its_pool_get_value_for_node (pool, node, "locNotePointer");
        if (value != NULL)
          {
            its_value_list_set_value (result, "locNotePointer", value);
            return result;
          }

        /* Recursively check value for the parent node.  */
        if (node->parent == NULL
            || node->parent->type != XML_ELEMENT_NODE)
          return result;
        else
          {
            struct its_value_list_ty *values;

            values = its_localization_note_rule_eval (pop, pool, node->parent);
            its_value_list_merge (result, values);
            its_value_list_destroy (values);
            free (values);
          }
      }
      break;

    default:
      break;
    }

  /* The default value is None.  */
  return result;
}

static struct its_rule_class_ty its_localization_note_rule_class =
  {
    sizeof (struct its_rule_ty),
    its_localization_note_rule_constructor,
    its_rule_destructor,
    its_rule_apply,
    its_localization_note_rule_eval,
  };

/* Implementation of Element Within Text data category.  */
static void
its_element_within_text_rule_constructor (struct its_rule_ty *pop,
                                          xmlNode *node)
{
  char *prop;

  if (!xmlHasProp (node, BAD_CAST "selector"))
    {
      _its_error_missing_attribute (node, "selector");
      return;
    }

  if (!xmlHasProp (node, BAD_CAST "withinText"))
    {
      _its_error_missing_attribute (node, "withinText");
      return;
    }

  prop = _its_get_attribute (node, "selector", NULL);
  if (prop)
    pop->selector = prop;

  prop = _its_get_attribute (node, "withinText", NULL);
  its_value_list_append (&pop->values, "withinText", prop);
  free (prop);
}

struct its_value_list_ty *
its_element_within_text_rule_eval (struct its_rule_ty *pop,
                                   struct its_pool_ty *pool,
                                   xmlNode *node)
{
  struct its_value_list_ty *result;
  const char *value;

  result = XCALLOC (1, struct its_value_list_ty);

  if (node->type != XML_ELEMENT_NODE)
    return result;

  /* A local attribute overrides the global rule.  */
  if (xmlHasNsProp (node, BAD_CAST "withinText", BAD_CAST ITS_NS))
    {
      char *prop;

      prop = _its_get_attribute (node, "withinText", ITS_NS);
      its_value_list_append (result, "withinText", prop);
      free (prop);
      return result;
    }

  /* Doesn't inherit from the parent elements, and the default value
     is None.  */
  value = its_pool_get_value_for_node (pool, node, "withinText");
  if (value != NULL)
    its_value_list_set_value (result, "withinText", value);

  return result;
}

static struct its_rule_class_ty its_element_within_text_rule_class =
  {
    sizeof (struct its_rule_ty),
    its_element_within_text_rule_constructor,
    its_rule_destructor,
    its_rule_apply,
    its_element_within_text_rule_eval,
  };

/* Implementation of Preserve Space data category.  */
static void
its_preserve_space_rule_constructor (struct its_rule_ty *pop,
                                     xmlNode *node)
{
  char *prop;

  if (!xmlHasProp (node, BAD_CAST "selector"))
    {
      _its_error_missing_attribute (node, "selector");
      return;
    }

  if (!xmlHasProp (node, BAD_CAST "space"))
    {
      _its_error_missing_attribute (node, "space");
      return;
    }

  prop = _its_get_attribute (node, "selector", NULL);
  if (prop)
    pop->selector = prop;

  prop = _its_get_attribute (node, "space", NULL);
  if (prop
      && !(strcmp (prop, "preserve") ==0 
           || strcmp (prop, "default") == 0
           /* gettext extension: remove leading/trailing whitespaces only.  */
           || (node->ns && xmlStrEqual (node->ns->href, BAD_CAST GT_NS)
               && strcmp (prop, "trim") == 0)))
    {
      error (0, 0, _("invalid attribute value \"%s\" for \"%s\""),
             prop, "space");
      free (prop);
      return;
    }

  its_value_list_append (&pop->values, "space", prop);
  free (prop);
}

struct its_value_list_ty *
its_preserve_space_rule_eval (struct its_rule_ty *pop,
                              struct its_pool_ty *pool,
                              xmlNode *node)
{
  struct its_value_list_ty *result;
  struct its_value_list_ty *values;
  const char *value;

  result = XCALLOC (1, struct its_value_list_ty);

  if (node->type != XML_ELEMENT_NODE)
    return result;

  /* A local attribute overrides the global rule.  */
  if (xmlHasNsProp (node, BAD_CAST "space", BAD_CAST XML_NS))
    {
      char *prop;

      prop = _its_get_attribute (node, "space", XML_NS);
      its_value_list_append (result, "space", prop);
      free (prop);
      return result;
    }

  /* Check value for the current node.  */
  value = its_pool_get_value_for_node (pool, node, "space");
  if (value != NULL)
    {
      its_value_list_set_value (result, "space", value);
      return result;
    }

  if (node->parent == NULL
      || node->parent->type != XML_ELEMENT_NODE)
    {
      /* The default value is space="default".  */
      its_value_list_append (result, "space", "default");
      return result;
    }

  /* Recursively check value for the parent node.  */
  values = its_preserve_space_rule_eval (pop, pool, node->parent);
  its_value_list_merge (result, values);
  its_value_list_destroy (values);
  free (values);

  return result;
}

static struct its_rule_class_ty its_preserve_space_rule_class =
  {
    sizeof (struct its_rule_ty),
    its_preserve_space_rule_constructor,
    its_rule_destructor,
    its_rule_apply,
    its_preserve_space_rule_eval,
  };

/* Implementation of Context data category.  */
static void
its_extension_context_rule_constructor (struct its_rule_ty *pop, xmlNode *node)
{
  char *prop;

  if (!xmlHasProp (node, BAD_CAST "selector"))
    {
      _its_error_missing_attribute (node, "selector");
      return;
    }

  if (!xmlHasProp (node, BAD_CAST "contextPointer"))
    {
      _its_error_missing_attribute (node, "contextPointer");
      return;
    }

  prop = _its_get_attribute (node, "selector", NULL);
  if (prop)
    pop->selector = prop;

  prop = _its_get_attribute (node, "contextPointer", NULL);
  its_value_list_append (&pop->values, "contextPointer", prop);
  free (prop);

  if (xmlHasProp (node, BAD_CAST "textPointer"))
    {
      prop = _its_get_attribute (node, "textPointer", NULL);
      its_value_list_append (&pop->values, "textPointer", prop);
      free (prop);
    }
}

struct its_value_list_ty *
its_extension_context_rule_eval (struct its_rule_ty *pop,
                                 struct its_pool_ty *pool,
                                 xmlNode *node)
{
  struct its_value_list_ty *result;
  const char *value;

  result = XCALLOC (1, struct its_value_list_ty);

  /* Doesn't inherit from the parent elements, and the default value
     is None.  */
  value = its_pool_get_value_for_node (pool, node, "contextPointer");
  if (value != NULL)
    its_value_list_set_value (result, "contextPointer", value);

  value = its_pool_get_value_for_node (pool, node, "textPointer");
  if (value != NULL)
    its_value_list_set_value (result, "textPointer", value);

  return result;
}

static struct its_rule_class_ty its_extension_context_rule_class =
  {
    sizeof (struct its_rule_ty),
    its_extension_context_rule_constructor,
    its_rule_destructor,
    its_rule_apply,
    its_extension_context_rule_eval,
  };

/* Implementation of Escape Special Characters data category.  */
static void
its_extension_escape_rule_constructor (struct its_rule_ty *pop, xmlNode *node)
{
  char *prop;

  if (!xmlHasProp (node, BAD_CAST "selector"))
    {
      _its_error_missing_attribute (node, "selector");
      return;
    }

  if (!xmlHasProp (node, BAD_CAST "escape"))
    {
      _its_error_missing_attribute (node, "escape");
      return;
    }

  prop = _its_get_attribute (node, "selector", NULL);
  if (prop)
    pop->selector = prop;

  prop = _its_get_attribute (node, "escape", NULL);
  its_value_list_append (&pop->values, "escape", prop);
  free (prop);
}

struct its_value_list_ty *
its_extension_escape_rule_eval (struct its_rule_ty *pop,
                                struct its_pool_ty *pool,
                                xmlNode *node)
{
  struct its_value_list_ty *result;

  result = XCALLOC (1, struct its_value_list_ty);

  switch (node->type)
    {
    case XML_ATTRIBUTE_NODE:
      /* Attribute nodes don't inherit from the parent elements.  */
      {
        const char *value =
          its_pool_get_value_for_node (pool, node, "escape");
        if (value != NULL)
          {
            its_value_list_set_value (result, "escape", value);
            return result;
          }
      }
      break;

    case XML_ELEMENT_NODE:
      /* Inherit from the parent elements.  */
      {
        const char *value;

        /* Check value for the current node.  */
        value = its_pool_get_value_for_node (pool, node, "escape");
        if (value != NULL)
          {
            its_value_list_set_value (result, "escape", value);
            return result;
          }

        /* Recursively check value for the parent node.  */
        if (node->parent != NULL
            && node->parent->type == XML_ELEMENT_NODE)
          {
            struct its_value_list_ty *values;

            values = its_extension_escape_rule_eval (pop, pool, node->parent);
            its_value_list_merge (result, values);
            its_value_list_destroy (values);
            free (values);
          }
      }
      break;

    default:
      break;
    }

  return result;
}

static struct its_rule_class_ty its_extension_escape_rule_class =
  {
    sizeof (struct its_rule_ty),
    its_extension_escape_rule_constructor,
    its_rule_destructor,
    its_rule_apply,
    its_extension_escape_rule_eval,
  };

static struct its_rule_ty *
its_rule_alloc (struct its_rule_class_ty *method_table, xmlNode *node)
{
  struct its_rule_ty *pop;

  pop = (struct its_rule_ty *) xcalloc (1, method_table->size);
  pop->methods = method_table;
  if (method_table->constructor)
    method_table->constructor (pop, node);
  return pop;
}

static struct its_rule_ty *
its_rule_parse (xmlDoc *doc, xmlNode *node)
{
  const char *name = (const char *) node->name;
  void *value;

  if (hash_find_entry (&classes, name, strlen (name), &value) == 0)
    {
      struct its_rule_ty *result;
      xmlNs **namespaces;

      result = its_rule_alloc ((struct its_rule_class_ty *) value, node);
      namespaces = xmlGetNsList (doc, node);
      if (namespaces)
        {
          size_t i;
          for (i = 0; namespaces[i] != NULL; i++)
            ;
          result->namespaces = XCALLOC (i + 1, xmlNs *);
          for (i = 0; namespaces[i] != NULL; i++)
            result->namespaces[i] = xmlCopyNamespace (namespaces[i]);
        }
      xmlFree (namespaces);
      return result;
    }

  return NULL;
}

static void
its_rule_destroy (struct its_rule_ty *pop)
{
  if (pop->methods->destructor)
    pop->methods->destructor (pop);
}

static void
init_classes (void)
{
#define ADD_RULE_CLASS(n, c) \
  hash_insert_entry (&classes, n, strlen (n), &c);

  ADD_RULE_CLASS ("translateRule", its_translate_rule_class);
  ADD_RULE_CLASS ("locNoteRule", its_localization_note_rule_class);
  ADD_RULE_CLASS ("withinTextRule", its_element_within_text_rule_class);
  ADD_RULE_CLASS ("preserveSpaceRule", its_preserve_space_rule_class);
  ADD_RULE_CLASS ("contextRule", its_extension_context_rule_class);
  ADD_RULE_CLASS ("escapeRule", its_extension_escape_rule_class);

#undef ADD_RULE_CLASS
}

struct its_rule_list_ty *
its_rule_list_alloc (void)
{
  struct its_rule_list_ty *result;

  if (classes.table == NULL)
    {
      hash_init (&classes, 10);
      init_classes ();
    }

  result = XCALLOC (1, struct its_rule_list_ty);
  return result;
}

void
its_rule_list_free (struct its_rule_list_ty *rules)
{
  size_t i;

  for (i = 0; i < rules->nitems; i++)
    {
      its_rule_destroy (rules->items[i]);
      free (rules->items[i]);
    }
  free (rules->items);
  its_pool_destroy (&rules->pool);
}

static bool
its_rule_list_add_from_doc (struct its_rule_list_ty *rules,
                            xmlDoc *doc)
{
  xmlNode *root, *node;

  root = xmlDocGetRootElement (doc);
  if (!(xmlStrEqual (root->name, BAD_CAST "rules")
        && xmlStrEqual (root->ns->href, BAD_CAST ITS_NS)))
    {
      error (0, 0, _("the root element is not \"rules\""
                     " under namespace %s"),
             ITS_NS);
      xmlFreeDoc (doc);
      return false;
    }

  for (node = root->children; node; node = node->next)
    {
      struct its_rule_ty *rule;

      rule = its_rule_parse (doc, node);
      if (!rule)
        continue;

      if (rules->nitems == rules->nitems_max)
        {
          rules->nitems_max = 2 * rules->nitems_max + 1;
          rules->items =
            xrealloc (rules->items,
                      sizeof (struct its_rule_ty *) * rules->nitems_max);
        }
      rules->items[rules->nitems++] = rule;
    }

  return true;
}

bool
its_rule_list_add_from_file (struct its_rule_list_ty *rules,
                             const char *filename)
{
  xmlDoc *doc;
  bool result;

  doc = xmlReadFile (filename, "utf-8",
                     XML_PARSE_NONET
                     | XML_PARSE_NOWARNING
                     | XML_PARSE_NOBLANKS
                     | XML_PARSE_NOERROR);
  if (doc == NULL)
    {
      xmlError *err = xmlGetLastError ();
      error (0, 0, _("cannot read %s: %s"), filename, err->message);
      return false;
    }

  result = its_rule_list_add_from_doc (rules, doc);
  xmlFreeDoc (doc);
  return result;
}

bool
its_rule_list_add_from_string (struct its_rule_list_ty *rules,
                               const char *rule)
{
  xmlDoc *doc;
  bool result;

  doc = xmlReadMemory (rule, strlen (rule),
                       "(internal)",
                       NULL,
                       XML_PARSE_NONET
                       | XML_PARSE_NOWARNING
                       | XML_PARSE_NOBLANKS
                       | XML_PARSE_NOERROR);
  if (doc == NULL)
    {
      xmlError *err = xmlGetLastError ();
      error (0, 0, _("cannot read %s: %s"), "(internal)", err->message);
      return false;
    }

  result = its_rule_list_add_from_doc (rules, doc);
  xmlFreeDoc (doc);
  return result;
}

static void
its_rule_list_apply (struct its_rule_list_ty *rules, xmlDoc *doc)
{
  size_t i;

  for (i = 0; i < rules->nitems; i++)
    {
      struct its_rule_ty *rule = rules->items[i];
      rule->methods->apply (rule, &rules->pool, doc);
    }
}

static struct its_value_list_ty *
its_rule_list_eval (its_rule_list_ty *rules, xmlNode *node)
{
  struct its_value_list_ty *result;
  size_t i;

  result = XCALLOC (1, struct its_value_list_ty);
  for (i = 0; i < rules->nitems; i++)
    {
      struct its_rule_ty *rule = rules->items[i];
      struct its_value_list_ty *values;

      values = rule->methods->eval (rule, &rules->pool, node);
      its_value_list_merge (result, values);
      its_value_list_destroy (values);
      free (values);
    }

  return result;
}

static bool
its_rule_list_is_translatable (its_rule_list_ty *rules,
                               xmlNode *node,
                               int depth)
{
  struct its_value_list_ty *values;
  const char *value;
  xmlNode *n;

  if (node->type != XML_ELEMENT_NODE
      && node->type != XML_ATTRIBUTE_NODE)
    return false;

  values = its_rule_list_eval (rules, node);

  /* Check if NODE has translate="yes".  */
  value = its_value_list_get_value (values, "translate");
  if (!(value && strcmp (value, "yes") == 0))
    {
      its_value_list_destroy (values);
      free (values);
      return false;
    }

  /* Check if NODE has withinText="yes", if NODE is not top-level.  */
  if (depth > 0)
    {
      value = its_value_list_get_value (values, "withinText");
      if (!(value && strcmp (value, "yes") == 0))
        {
          its_value_list_destroy (values);
          free (values);
          return false;
        }
    }

  its_value_list_destroy (values);
  free (values);

  for (n = node->children; n; n = n->next)
    {
      switch (n->type)
        {
        case XML_ELEMENT_NODE:
          if (!its_rule_list_is_translatable (rules, n, depth + 1))
            return false;
          break;

        case XML_TEXT_NODE:
        case XML_ENTITY_REF_NODE:
          break;

        default:
          return false;
        }
    }

  return true;
}

static void
its_rule_list_extract_nodes (its_rule_list_ty *rules,
                             struct its_node_list_ty *nodes,
                             xmlNode *node)
{
  if (node->type == XML_ELEMENT_NODE)
    {
      xmlNode *n;

      if (node->properties)
        {
          xmlAttr *attr = node->properties;
          for (; attr; attr = attr->next)
            {
              xmlNode *n = (xmlNode *) attr;
              if (its_rule_list_is_translatable (rules, n, 0))
                its_node_list_append (nodes, n);
            }
        }

      if (its_rule_list_is_translatable (rules, node, 0))
        its_node_list_append (nodes, node);
      else
        {
          for (n = node->children; n; n = n->next)
            its_rule_list_extract_nodes (rules, nodes, n);
        }
    }
}

static char *
_its_get_content (struct its_rule_list_ty *rules, xmlNode *node,
                  const char *pointer,
                  enum its_whitespace_type_ty whitespace,
                  bool no_escape)
{
  xmlXPathContext *context;
  xmlXPathObject *object;
  size_t i;
  char *result = NULL;

  context = xmlXPathNewContext (node->doc);
  if (!context)
    {
      error (0, 0, _("cannot create XPath context"));
      return NULL;
    }

  for (i = 0; i < rules->nitems; i++)
    {
      struct its_rule_ty *rule = rules->items[i];
      if (rule->namespaces)
        {
          size_t i;
          for (i = 0; rule->namespaces[i] != NULL; i++)
            {
              xmlNs *ns = rule->namespaces[i];
              xmlXPathRegisterNs (context, ns->prefix, ns->href);
            }
        }
    }

  xmlXPathSetContextNode (node, context);
  object = xmlXPathEvalExpression (BAD_CAST pointer, context);
  if (!object)
    {
      xmlXPathFreeContext (context);
      error (0, 0, _("cannot evaluate XPath location path: %s"),
             pointer);
      return NULL;
    }

  switch (object->type)
    {
    case XPATH_NODESET:
      {
        xmlNodeSet *nodes = object->nodesetval;
        string_list_ty sl;
        size_t i;

        string_list_init (&sl);
        for (i = 0; i < nodes->nodeNr; i++)
          {
            char *content = _its_collect_text_content (nodes->nodeTab[i],
                                                       whitespace,
                                                       no_escape);
            string_list_append (&sl, content);
            free (content);
          }
        result = string_list_concat (&sl);
        string_list_destroy (&sl);
      }
      break;

    case XPATH_STRING:
      result = xstrdup ((const char *) object->stringval);
      break;

    default:
      break;
    }

  xmlXPathFreeObject (object);
  xmlXPathFreeContext (context);

  return result;
}

static void
_its_comment_append (string_list_ty *comments, const char *data)
{
  /* Split multiline comment into lines, and remove leading and trailing
     whitespace.  */
  char *copy = xstrdup (data);
  char *p;
  char *q;

  for (p = copy; (q = strchr (p, '\n')) != NULL; p = q + 1)
    {
      while (p[0] == ' ' || p[0] == '\t')
        p++;
      while (q > p && (q[-1] == ' ' || q[-1] == '\t'))
        q--;
      *q = '\0';
      string_list_append (comments, p);
    }
  q = p + strlen (p);
  while (p[0] == ' ' || p[0] == '\t')
    p++;
  while (q > p && (q[-1] == ' ' || q[-1] == '\t'))
    q--;
  *q = '\0';
  string_list_append (comments, p);
  free (copy);
}

static void
its_rule_list_extract_text (its_rule_list_ty *rules,
                            xmlNode *node,
                            const char *logical_filename,
                            flag_context_list_table_ty *flag_table,
                            message_list_ty *mlp,
                            its_extract_callback_ty callback)
{
  if (node->type == XML_ELEMENT_NODE
      || node->type == XML_ATTRIBUTE_NODE)
    {
      struct its_value_list_ty *values;
      const char *value;
      char *msgid = NULL, *msgctxt = NULL, *comment = NULL;
      enum its_whitespace_type_ty whitespace;
      bool no_escape;
      
      values = its_rule_list_eval (rules, node);

      value = its_value_list_get_value (values, "locNote");
      if (value)
        comment = xstrdup (value);
      else
        {
          value = its_value_list_get_value (values, "locNotePointer");
          if (value)
            comment = _its_get_content (rules, node, value, ITS_WHITESPACE_TRIM,
                                        false);
        }

      if (comment != NULL && *comment != '\0')
        {
          string_list_ty comments;
          char *tmp;

          string_list_init (&comments);
          _its_comment_append (&comments, comment);
          tmp = string_list_join (&comments, "\n", '\0', false);
          free (comment);
          comment = tmp;
        }
      else
        /* Extract comments preceding the node.  */
        {
          xmlNode *sibling;
          string_list_ty comments;

          string_list_init (&comments);
          for (sibling = node->prev; sibling; sibling = sibling->prev)
            if (sibling->type != XML_COMMENT_NODE || sibling->prev == NULL)
              break;
          if (sibling)
            {
              if (sibling->type != XML_COMMENT_NODE)
                sibling = sibling->next;
              for (; sibling && sibling->type == XML_COMMENT_NODE;
                   sibling = sibling->next)
                {
                  xmlChar *content = xmlNodeGetContent (sibling);
                  _its_comment_append (&comments, (const char *) content);
                  xmlFree (content);
                }
              free (comment);
              comment = string_list_join (&comments, "\n", '\0', false);
              string_list_destroy (&comments);
            }
        }
      
      value = its_value_list_get_value (values, "space");
      if (value && strcmp (value, "preserve") == 0)
        whitespace = ITS_WHITESPACE_PRESERVE;
      else if (value && strcmp (value, "trim") == 0)
        whitespace = ITS_WHITESPACE_TRIM;
      else
        whitespace = ITS_WHITESPACE_NORMALIZE;

      value = its_value_list_get_value (values, "escape");
      no_escape = value != NULL && strcmp (value, "no") == 0;

      value = its_value_list_get_value (values, "contextPointer");
      if (value)
        msgctxt = _its_get_content (rules, node, value, ITS_WHITESPACE_PRESERVE,
                                    no_escape);

      value = its_value_list_get_value (values, "textPointer");
      if (value)
        msgid = _its_get_content (rules, node, value, ITS_WHITESPACE_PRESERVE,
                                  no_escape);
      its_value_list_destroy (values);
      free (values);

      if (msgid == NULL)
        msgid = _its_collect_text_content (node, whitespace, no_escape);
      if (*msgid != '\0')
        {
          lex_pos_ty pos;
          char *marker;

          pos.file_name = xstrdup (logical_filename);
          pos.line_number = xmlGetLineNo (node);

          if (node->type == XML_ELEMENT_NODE)
            {
              assert (node->parent);
              marker = xasprintf ("%s/%s", node->parent->name, node->name);
            }
          else
            {
              assert (node->parent && node->parent->parent);
              marker = xasprintf ("%s/%s@%s",
                                  node->parent->parent->name,
                                  node->parent->name,
                                  node->name);
            }

          if (msgctxt != NULL && *msgctxt == '\0')
            {
              free (msgctxt);
              msgctxt = NULL;
            }

          callback (mlp, msgctxt, msgid, &pos, comment, marker, whitespace);
          free (marker);
        }
      free (msgctxt);
      free (msgid);
      free (comment);
    }
}

void
its_rule_list_extract (its_rule_list_ty *rules,
                       FILE *fp, const char *real_filename,
                       const char *logical_filename,
                       flag_context_list_table_ty *flag_table,
                       msgdomain_list_ty *mdlp,
                       its_extract_callback_ty callback)
{
  xmlDoc *doc;
  struct its_node_list_ty nodes;
  size_t i;

  doc = xmlReadFd (fileno (fp), logical_filename, NULL,
                   XML_PARSE_NONET
                   | XML_PARSE_NOWARNING
                   | XML_PARSE_NOBLANKS
                   | XML_PARSE_NOERROR);
  if (doc == NULL)
    {
      xmlError *err = xmlGetLastError ();
      error (0, 0, _("cannot read %s: %s"), logical_filename, err->message);
      return;
    }

  its_rule_list_apply (rules, doc);

  memset (&nodes, 0, sizeof (struct its_node_list_ty));
  its_rule_list_extract_nodes (rules,
                               &nodes,
                               xmlDocGetRootElement (doc));

  for (i = 0; i < nodes.nitems; i++)
    its_rule_list_extract_text (rules, nodes.items[i],
                                logical_filename,
                                flag_table,
                                mdlp->item[0]->messages,
                                callback);

  free (nodes.items);
  xmlFreeDoc (doc);
}

struct its_merge_context_ty
{
  its_rule_list_ty *rules;
  xmlDoc *doc;
  struct its_node_list_ty nodes;
};

static void
its_merge_context_merge_node (struct its_merge_context_ty *context,
                              xmlNode *node,
                              const char *language,
                              message_list_ty *mlp)
{
  if (node->type == XML_ELEMENT_NODE)
    {
      struct its_value_list_ty *values;
      const char *value;
      char *msgid = NULL, *msgctxt = NULL;
      enum its_whitespace_type_ty whitespace;
      bool no_escape;

      values = its_rule_list_eval (context->rules, node);

      value = its_value_list_get_value (values, "space");
      if (value && strcmp (value, "preserve") == 0)
        whitespace = ITS_WHITESPACE_PRESERVE;
      else if (value && strcmp (value, "trim") == 0)
        whitespace = ITS_WHITESPACE_TRIM;
      else
        whitespace = ITS_WHITESPACE_NORMALIZE;

      value = its_value_list_get_value (values, "escape");
      no_escape = value != NULL && strcmp (value, "no") == 0;

      value = its_value_list_get_value (values, "contextPointer");
      if (value)
        msgctxt = _its_get_content (context->rules, node, value,
                                    ITS_WHITESPACE_PRESERVE, no_escape);

      value = its_value_list_get_value (values, "textPointer");
      if (value)
        msgid = _its_get_content (context->rules, node, value,
                                  ITS_WHITESPACE_PRESERVE, no_escape);
      its_value_list_destroy (values);
      free (values);

      if (msgid == NULL)
        msgid = _its_collect_text_content (node, whitespace, no_escape);
      if (*msgid != '\0')
        {
          message_ty *mp;

          mp = message_list_search (mlp, msgctxt, msgid);
          if (mp && *mp->msgstr != '\0')
            {
              xmlNode *translated;

              translated = xmlNewNode (node->ns, node->name);
              xmlSetProp (translated, BAD_CAST "xml:lang", BAD_CAST language);

              xmlNodeAddContent (translated, BAD_CAST mp->msgstr);
              xmlAddNextSibling (node, translated);
            }
        }
      free (msgctxt);
      free (msgid);
    }
}

void
its_merge_context_merge (its_merge_context_ty *context,
                         const char *language,
                         message_list_ty *mlp)
{
  size_t i;

  for (i = 0; i < context->nodes.nitems; i++)
    its_merge_context_merge_node (context, context->nodes.items[i],
                                  language,
                                  mlp);
}

struct its_merge_context_ty *
its_merge_context_alloc (its_rule_list_ty *rules,
                         const char *filename)
{
  xmlDoc *doc;
  struct its_merge_context_ty *result;

  doc = xmlReadFile (filename, NULL,
                     XML_PARSE_NONET
                     | XML_PARSE_NOWARNING
                     | XML_PARSE_NOBLANKS
                     | XML_PARSE_NOERROR);
  if (doc == NULL)
    {
      xmlError *err = xmlGetLastError ();
      error (0, 0, _("cannot read %s: %s"), filename, err->message);
      return NULL;
    }

  its_rule_list_apply (rules, doc);

  result = XMALLOC (struct its_merge_context_ty);
  result->rules = rules;
  result->doc = doc;

  /* Collect translatable nodes.  */
  memset (&result->nodes, 0, sizeof (struct its_node_list_ty));
  its_rule_list_extract_nodes (result->rules,
                               &result->nodes,
                               xmlDocGetRootElement (result->doc));

  return result;
}

void
its_merge_context_write (struct its_merge_context_ty *context,
                         FILE *fp)
{
  xmlDocFormatDump (fp, context->doc, 1);
}

void
its_merge_context_free (struct its_merge_context_ty *context)
{
  xmlFreeDoc (context->doc);
  free (context->nodes.items);
  free (context);
}