summaryrefslogtreecommitdiff
path: root/CodeLite/ctags_manager.cpp
blob: 37243d7271cb255ee6b6b49c69a1116bee320cd1 (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
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : ctags_manager.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    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 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "precompiled_header.h"
#include "processreaderthread.h"
#include "cppwordscanner.h"
#include "fileextmanager.h"
#include <algorithm>
#include "file_logger.h"
#include <wx/frame.h>
#include <wx/app.h>
#include "codelite_exports.h"
#include <wx/sizer.h>
#include <wx/log.h>
#include "parse_thread.h"
#include "ctags_manager.h"
#include "named_pipe_client.h"
#include <set>
#include "cl_indexer_request.h"
#include "asyncprocess.h"
#include "clindexerprotocol.h"
#include "cl_indexer_reply.h"
#include <wx/txtstrm.h>
#include <wx/file.h>
#include <algorithm>
#include <wx/progdlg.h>
#include "wx/tokenzr.h"
#include "wx/filename.h"
#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include "cpp_comment_creator.h"
#include "tags_options_data.h"
#include <wx/busyinfo.h>
#include "wx/timer.h"
#include "procutils.h"
#include <sstream>
#include <wx/string.h>
#include <wx/xrc/xmlres.h>
#include <wx/msgdlg.h>
#include "code_completion_api.h"
#include <wx/stdpaths.h>
#include "tags_storage_sqlite3.h"
#include "cl_standard_paths.h"
#include <algorithm>


//#define __PERFORMANCE
#include "performance.h"

#ifdef __WXMSW__
#define PIPE_NAME "\\\\.\\pipe\\codelite_indexer_%s"
#else
#define PIPE_NAME "/tmp/codelite_indexer.%s.sock"
#endif

const wxEventType wxEVT_UPDATE_FILETREE_EVENT = XRCID("update_file_tree_event");
const wxEventType wxEVT_TAGS_DB_UPGRADE       = XRCID("tags_db_upgraded");
const wxEventType wxEVT_TAGS_DB_UPGRADE_INTER = XRCID("tags_db_upgraded_now");

//---------------------------------------------------------------------------
// Misc

static bool isDarkColor(const wxColour& color)
{
    int evg = (color.Red() + color.Green() + color.Blue())/3;
    if (evg < 127)
        return true;
    return false;
}

// Descending sorting function
struct SDescendingSort {
    bool operator()(const TagEntryPtr &rStart, const TagEntryPtr &rEnd) {
        return rStart->GetName().Cmp(rEnd->GetName()) > 0;
    }
};

/// Ascending sorting function
struct SAscendingSort {
    bool operator()(const TagEntryPtr &rStart, const TagEntryPtr &rEnd) {
        return rEnd->GetName().Cmp(rStart->GetName()) > 0;
    }
};

struct tagParseResult {
    TagTreePtr tree;
    std::vector<CommentPtr> *comments;
    wxString fileName;
};

//////////////////////////////////////
// Adapter class to TagsManager
//////////////////////////////////////
static TagsManager* gs_TagsManager = NULL;

void TagsManagerST::Free()
{
    if(gs_TagsManager) {
        delete gs_TagsManager;
    }
    gs_TagsManager = NULL;
}

TagsManager* TagsManagerST::Get()
{
    if(gs_TagsManager == NULL)
        gs_TagsManager = new TagsManager();

    return gs_TagsManager;
}

//------------------------------------------------------------------------------
// CTAGS Manager
//------------------------------------------------------------------------------

BEGIN_EVENT_TABLE(TagsManager, wxEvtHandler)
    EVT_COMMAND(wxID_ANY, wxEVT_PROC_TERMINATED,       TagsManager::OnIndexerTerminated)
END_EVENT_TABLE()

//ToDo: use GetScopesByScopeName method - DRY

TagsManager::TagsManager()
    : wxEvtHandler()
    , m_codeliteIndexerPath(wxT("codelite_indexer"))
    , m_codeliteIndexerProcess (NULL)
    , m_canRestartIndexer      (true)
    , m_lang                   (NULL)
    , m_evtHandler             (NULL)
    , m_encoding               (wxFONTENCODING_DEFAULT)
{

    m_db = new TagsStorageSQLite();
    m_db->SetSingleSearchLimit( MAX_SEARCH_LIMIT );

    // Create databases
    m_ctagsCmd = wxT("  --excmd=pattern --sort=no --fields=aKmSsnit --c-kinds=+p --C++-kinds=+p ");

    // CPP keywords that are usually followed by open brace '('
    m_CppIgnoreKeyWords.insert(wxT("while"));
    m_CppIgnoreKeyWords.insert(wxT("if"));
    m_CppIgnoreKeyWords.insert(wxT("for"));
    m_CppIgnoreKeyWords.insert(wxT("switch"));
}

TagsManager::~TagsManager()
{
    if(m_codeliteIndexerProcess) {

        // Dont kill the indexer process, just terminate the
        // reader-thread (this is done by deleting the indexer object)
        m_canRestartIndexer = false;

#ifndef __WXMSW__
        m_codeliteIndexerProcess->Terminate();
#endif
        delete m_codeliteIndexerProcess;

#ifndef __WXMSW__
        // Clear the socket file
        std::stringstream s;
        s << wxGetProcessId();

        char channel_name[1024];
        memset(channel_name, 0, sizeof(channel_name));
        sprintf(channel_name, PIPE_NAME, s.str().c_str());
        ::unlink( channel_name );
        ::remove( channel_name );
#endif
    }
}

void TagsManager::OpenDatabase(const wxFileName& fileName)
{
    m_dbFile = fileName;
    ITagsStoragePtr db;
    db = m_db;

    bool retagIsRequired = false;
    if(fileName.FileExists() == false) {
        retagIsRequired = true;
    }

    db->OpenDatabase(fileName);
    db->SetEnableCaseInsensitive( !(m_tagsOptions.GetFlags() & CC_IS_CASE_SENSITIVE) );
    db->SetSingleSearchLimit(m_tagsOptions.GetCcNumberOfDisplayItems());

    if (db->GetVersion() != db->GetSchemaVersion()) {
        db->RecreateDatabase();

        // Send event to the main frame notifying it about database recreation
        if( m_evtHandler ) {
            wxCommandEvent event(wxEVT_TAGS_DB_UPGRADE_INTER);
            event.SetEventObject(this);
            m_evtHandler->ProcessEvent( event );
        }
    }

    if(retagIsRequired && m_evtHandler) {
        wxCommandEvent e(wxEVT_COMMAND_MENU_SELECTED, XRCID("retag_workspace"));
        m_evtHandler->AddPendingEvent(e);
    }
}

TagTreePtr TagsManager::ParseSourceFile(const wxFileName& fp, std::vector<CommentPtr> *comments)
{
    wxString tags;

    if ( !m_codeliteIndexerProcess ) {
        return TagTreePtr( NULL );
    }
    SourceToTags(fp, tags);

    int dummy;
    TagTreePtr ttp = TagTreePtr( TreeFromTags(tags, dummy) );

    if ( comments && GetParseComments() ) {
        // parse comments
        GetLanguage()->ParseComments( fp, comments );

    }
    return ttp;
}

TagTreePtr TagsManager::ParseSourceFile2(const wxFileName& fp, const wxString &tags, std::vector<CommentPtr> *comments)
{
    //	return ParseTagsFile(tags, project);
    int count(0);
    TagTreePtr ttp = TagTreePtr( TreeFromTags(tags, count) );

    if (comments && GetParseComments()) {
        // parse comments
        GetLanguage()->ParseComments(fp, comments);
    }
    return ttp;
}

//-----------------------------------------------------------
// Database operations
//-----------------------------------------------------------

void TagsManager::Store(TagTreePtr tree, const wxFileName& path)
{
    GetDatabase()->Store(tree, path);
}

TagTreePtr TagsManager::Load(const wxFileName& fileName, TagEntryPtrVector_t* tags)
{
    TagTreePtr          tree;
    TagEntryPtrVector_t tagsByFile;

    if( tags ) {
        tagsByFile.insert(tagsByFile.end(), tags->begin(), tags->end());

    } else {
        GetDatabase()->SelectTagsByFile(fileName.GetFullPath(), tagsByFile);

    }

    // Load the records and build a language tree
    TagEntry root;
    root.SetName(wxT("<ROOT>"));
    tree.Reset( new TagTree(wxT("<ROOT>"), root) );
    for(size_t i=0; i<tagsByFile.size(); i++) {
        tree->AddEntry( *(tagsByFile.at(i)) );
    }
    return tree;
}

void TagsManager::Delete(const wxFileName& path, const wxString& fileName)
{
    GetDatabase()->DeleteByFileName(path, fileName);
}

//--------------------------------------------------------
// Process Handling of CTAGS
//--------------------------------------------------------

void TagsManager::StartCodeLiteIndexer()
{
    if(!m_canRestartIndexer)
        return;

    // Run ctags process
    wxString cmd;
    wxString ctagsCmd;

    // build the command, we surround ctags name with double quatations
    wxString uid;
    uid << wxGetProcessId();

    if(m_codeliteIndexerPath.FileExists() == false) {
        CL_ERROR(wxT("ERROR: Could not locate indexer: %s"), m_codeliteIndexerPath.GetFullPath().c_str());
        m_codeliteIndexerProcess = NULL;
        return;
    }

    // concatenate the PID to identifies this channel to this instance of codelite
    cmd << wxT("\"") << m_codeliteIndexerPath.GetFullPath() << wxT("\" ") << uid << wxT(" --pid");
    m_codeliteIndexerProcess = CreateAsyncProcess(this, cmd, IProcessCreateDefault, clStandardPaths::Get().GetUserDataDir());
}

void TagsManager::RestartCodeLiteIndexer()
{
    if(m_codeliteIndexerProcess) {
        m_codeliteIndexerProcess->Terminate();
    }

    // no need to call StartCodeLiteIndexer(), since it will be called automatically
    // by the termination handler
}

void TagsManager::SetCodeLiteIndexerPath(const wxString& path)
{
    m_codeliteIndexerPath = path;
}

void TagsManager::OnIndexerTerminated(wxCommandEvent& event)
{
    if(m_codeliteIndexerProcess) {
        delete m_codeliteIndexerProcess;
        m_codeliteIndexerProcess = NULL;
    }
    StartCodeLiteIndexer();
}

//---------------------------------------------------------------------
// Parsing
//---------------------------------------------------------------------
void TagsManager::SourceToTags(const wxFileName& source, wxString& tags)
{
    std::stringstream s;
    s << wxGetProcessId();

    char channel_name[1024];
    memset(channel_name, 0, sizeof(channel_name));
    sprintf(channel_name, PIPE_NAME, s.str().c_str());

    clNamedPipeClient client(channel_name);

    // Build a request for the indexer
    clIndexerRequest req;
    // set the command
    req.setCmd(clIndexerRequest::CLI_PARSE);

    // prepare list of files to be parsed
    std::vector<std::string> files;
    files.push_back(source.GetFullPath().mb_str(wxConvUTF8).data());
    req.setFiles(files);

    // set ctags options to be used
    wxString ctagsCmd;
    ctagsCmd << wxT(" ") << m_tagsOptions.ToString() << wxT(" --excmd=pattern --sort=no --fields=aKmSsnit --c-kinds=+p --C++-kinds=+p ");
    req.setCtagOptions(ctagsCmd.mb_str(wxConvUTF8).data());

    // connect to the indexer
    if (!client.connect()) {
        wxPrintf(wxT("Failed to connect to indexer ID %d!\n"), (int)wxGetProcessId());
        return;
    }

    // send the request
    if ( !clIndexerProtocol::SendRequest(&client, req) ) {
        wxPrintf(wxT("Failed to send request to indexer ID [%d]\n"), (int)wxGetProcessId());
        return;
    }

    // read the reply
    clIndexerReply reply;
    try {
        if (!clIndexerProtocol::ReadReply(&client, reply)) {
            RestartCodeLiteIndexer();
            return;
        }
    } catch (std::bad_alloc &ex) {
        tags.Clear();
        return;
    }

    // convert the data into wxString
    if(m_encoding == wxFONTENCODING_DEFAULT || m_encoding == wxFONTENCODING_SYSTEM)
        tags = wxString(reply.getTags().c_str(), wxConvUTF8);
    else
        tags = wxString(reply.getTags().c_str(), wxCSConv(m_encoding));
    if(tags.empty()) {
        tags = wxString::From8BitData(reply.getTags().c_str());
    }

    AddEnumClassData(tags);

#if 0
    wxFFile fff(clStandardPaths::Get().GetUserDataDir() + wxT("\\tmp_tags"), wxT("w+"));
    if(fff.IsOpened()) {
        fff.Write(tags);
    }
#endif
}

TagTreePtr TagsManager::TreeFromTags(const wxString& tags, int &count)
{
    // Load the records and build a language tree
    TagEntry root;
    root.SetName(wxT("<ROOT>"));

    TagTreePtr tree( new TagTree(wxT("<ROOT>"), root) );

    wxStringTokenizer tkz(tags, wxT("\n"));
    while (tkz.HasMoreTokens()) {
        TagEntry tag;
        wxString line = tkz.NextToken();

        line = line.Trim();
        line = line.Trim(false);
        if (line.IsEmpty())
            continue;

        // Construct the tag from the line
        tag.FromLine(line);

        // Add the tag to the tree, locals are not added to the
        // tree
        count++;
        if ( tag.GetKind() != wxT("local") )
            tree->AddEntry(tag);
    }
    return tree;
}

bool TagsManager::IsValidCtagsFile(const wxFileName &filename) const
{
    bool is_ok(false);
    // Put a request on the parsing thread to update the GUI tree & the database
    wxString filespec = GetCtagsOptions().GetFileSpec();

    // do we support files without an extension?
    if (GetCtagsOptions().GetFlags() & CC_PARSE_EXT_LESS_FILES && filename.GetExt().IsEmpty())
        return true;

    //if the file spec matches the current file, notify ctags
    wxStringTokenizer tkz(filespec, wxT(";"));
    while (tkz.HasMoreTokens()) {
        wxString spec = tkz.NextToken();
        spec.MakeLower();
        wxString lowerName = filename.GetFullName();
        lowerName.MakeLower();
        if (wxMatchWild(spec, lowerName)) {
            is_ok = true;
            break;
        }
    } // while(tkz.HasMoreTokens())
    return is_ok;
}

//-----------------------------------------------------------------------------
// >>>>>>>>>>>>>>>>>>>>> Code Completion API START
//-----------------------------------------------------------------------------

void TagsManager::TagsByScopeAndName(const wxString& scope, const wxString &name, std::vector<TagEntryPtr> &tags, size_t flags)
{
    std::vector<wxString> derivationList;
    // add this scope as well to the derivation list

    wxString _scopeName = DoReplaceMacros( scope );
    derivationList.push_back(_scopeName);
    std::set<wxString> scannedInherits;
    GetDerivationList(_scopeName, NULL, derivationList, scannedInherits);

    // make enough room for max of 500 elements in the vector
    tags.reserve(500);
    wxArrayString scopes;

    for (size_t i=0; i<derivationList.size(); i++) {
        // try the worksapce database for match
        scopes.Add(derivationList.at(i));
    }

    GetDatabase()->GetTagsByScopeAndName(scopes, name, flags & PartialMatch, tags);

    // and finally sort the results
    std::sort(tags.begin(), tags.end(), SAscendingSort());
}

void TagsManager::TagsByScope(const wxString& scope, std::vector<TagEntryPtr> &tags)
{
    std::vector<wxString> derivationList;
    //add this scope as well to the derivation list
    wxString _scopeName = DoReplaceMacros( scope );
    derivationList.push_back(_scopeName);
    std::set<wxString> scannedInherits;
    GetDerivationList(_scopeName, NULL, derivationList, scannedInherits);

    //make enough room for max of 500 elements in the vector
    tags.reserve(500);

    for (size_t i=0; i<derivationList.size(); i++) {
        wxString tmpScope(derivationList.at(i));
        tmpScope = DoReplaceMacros(tmpScope);

        // try the external database for match
        GetDatabase()->GetTagsByScope(derivationList.at(i), tags);
    }

    // and finally sort the results
    std::sort(tags.begin(), tags.end(), SAscendingSort());

}

bool TagsManager::WordCompletionCandidates(const wxFileName &fileName, int lineno, const wxString& expr, const wxString& text, const wxString &word, std::vector<TagEntryPtr> &candidates)
{
    PERF_START("WordCompletionCandidates");

    candidates.clear();
    wxString path, tmp;
    wxString typeName, typeScope;

    //remove the word from the expression
    wxString expression(expr);

    // Trim whitespace from right and left
    static wxString trimString(wxT("!<>=(){};\r\n\t\v "));

    expression.erase(0, expression.find_first_not_of(trimString));
    expression.erase(expression.find_last_not_of(trimString)+1);
    tmp = expression;
    expression.EndsWith(word, &tmp);
    expression = tmp;

    wxString funcSig;
    std::vector<wxString> additionlScopes; //from 'using namespace XXX;' statements

    wxString scope;
    wxString scopeName = GetLanguage()->GetScopeName(text, &additionlScopes);

    if( GetCtagsOptions().GetFlags() &  CC_DEEP_SCAN_USING_NAMESPACE_RESOLVING ) {
        // Do a deep scan for 'using namespace'
        GetLanguage()->SetAdditionalScopes(additionlScopes, fileName.GetFullPath());
        additionlScopes = GetLanguage()->GetAdditionalScopes();
    }

    TagEntryPtr funcTag = FunctionFromFileLine(fileName, lineno);
    if (funcTag) {
        funcSig = funcTag->GetSignature();
    }

    wxString oper;
    wxString tmpExp(expression);
    tmpExp.Trim().Trim(false);

    // Keep 3 vectors of the results
    // we keep 3 vectors so the end user will see the matches
    // by their importance order: locals -> scoped -> globals
    TagEntryPtrVector_t locals;
    TagEntryPtrVector_t scoped;
    TagEntryPtrVector_t globals;

    if ( tmpExp.IsEmpty() ) {
        // Collect all the tags from the current scope, and
        // from the global scope
        wxString curFunctionBody;
        wxString textAfterTokenReplacements;
        int lastFuncLine = funcTag ? funcTag->GetLine() : -1;
        textAfterTokenReplacements = GetLanguage()->ApplyCtagsReplacementTokens(text);
        scope = GetLanguage()->OptimizeScope(textAfterTokenReplacements, lastFuncLine, curFunctionBody);
        std::vector<TagEntryPtr> tmpCandidates;

        // First get the scoped tags
        TagsByScopeAndName(scopeName, word, scoped);
        if(scopeName != wxT("<global>")) {
            // No need to call it twice...
            GetGlobalTags(word, globals);
        }
        // Allways collect the local and the function argument tags
        GetLocalTags(word, scope,   locals, PartialMatch | IgnoreCaseSensitive | ReplaceTokens );
        GetLocalTags(word, funcSig, locals, PartialMatch | IgnoreCaseSensitive);

        for (size_t i=0; i<additionlScopes.size(); i++) {
            TagsByScopeAndName(additionlScopes.at(i), word, scoped);
        }

        // for every vector filter the results
        DoFilterDuplicatesByTagID    (locals, locals);
        DoFilterDuplicatesBySignature(locals, locals);

        DoFilterDuplicatesByTagID    (scoped, scoped);
        DoFilterDuplicatesBySignature(scoped, scoped);

        DoFilterDuplicatesByTagID    (globals, globals);
        DoFilterDuplicatesBySignature(globals, globals);

        // unified the results into a single match
        candidates.insert(candidates.end(), locals.begin(), locals.end());
        candidates.insert(candidates.end(), scoped.begin(), scoped.end());
        candidates.insert(candidates.end(), globals.begin(), globals.end());

    } else if( tmpExp == wxT("::") ) {
        // Global scope only
        // e.g.: ::My <CTRL>+<SPACE>
        // Collect all tags from the global scope which starts with 'My' (i.e. 'word')
        std::vector<TagEntryPtr> tmpCandidates;
        GetGlobalTags     (word, tmpCandidates);
        DoFilterDuplicatesByTagID  (tmpCandidates, candidates);
        DoFilterDuplicatesBySignature(candidates, candidates);

    } else {
        wxString typeName, typeScope, dummy;
        bool res = ProcessExpression(fileName, lineno, expression, text, typeName, typeScope, oper, dummy);
        if (!res) {
            PERF_END();
            return false;
        }

        //get all symbols realted to this scope
        scope = wxT("");
        if (typeScope == wxT("<global>"))
            scope << typeName;
        else
            scope << typeScope << wxT("::") << typeName;

        std::vector<TagEntryPtr> tmpCandidates, tmpCandidates1;
        TagsByScopeAndName(scope, word, tmpCandidates);

        wxString partialName(word);
        partialName.MakeLower();

        if(partialName.IsEmpty() == false) {
            for(size_t i=0; i<tmpCandidates.size(); i++) {
                wxString nm = tmpCandidates[i]->GetName();
                nm.MakeLower();
                if(nm.StartsWith(partialName)) {
                    tmpCandidates1.push_back( tmpCandidates.at(i) );
                }
            }
            DoFilterDuplicatesByTagID(tmpCandidates1, candidates);
            DoFilterDuplicatesBySignature(candidates, candidates);
        } else {
            DoFilterDuplicatesByTagID(tmpCandidates, candidates);
            DoFilterDuplicatesBySignature(candidates, candidates);
        }

        DoSortByVisibility( candidates );
    }

    PERF_END();
    return true;
}

bool TagsManager::AutoCompleteCandidates(const wxFileName &fileName, int lineno, const wxString& expr, const wxString& text, std::vector<TagEntryPtr>& candidates)
{
    PERF_START("AutoCompleteCandidates");

    candidates.clear();
    wxString path;
    wxString typeName, typeScope;

    wxString expression(expr);
    static wxString trimLeftString(wxT("{};\r\n\t\v "));
    static wxString trimRightString(wxT("({};\r\n\t\v "));
    expression.erase(0, expression.find_first_not_of(trimLeftString));
    expression.erase(expression.find_last_not_of(trimRightString)+1);
    wxString oper;
    wxString scopeTeamplateInitList;
    bool     isGlobalScopeOperator(false);

    if( expression == wxT("::") ) {
        // global scope
        isGlobalScopeOperator = true;

    } else {

        PERF_BLOCK("ProcessExpression") {
            bool res = ProcessExpression(fileName, lineno, expression, text, typeName, typeScope, oper, scopeTeamplateInitList);
            if (!res) {
                PERF_END();
                CL_DEBUG(wxT("Failed to resolve %s"), expression.c_str());
                return false;
            }
        }
    }

    // Load all tags from the database that matches typeName & typeScope
    wxString scope;
    if (typeScope == wxT("<global>"))
        scope << typeName;
    else
        scope << typeScope << wxT("::") << typeName;

    //this function will retrieve the ineherited tags as well
    //incase the last operator used was '::', retrieve all kinds of tags. Otherwise (-> , . operators were used)
    //retrieve only the members/prototypes/functions/enums
    wxArrayString filter;

    if ( isGlobalScopeOperator ) {
        // Fetch all tags from the global scope
        GetDatabase()->GetGlobalFunctions(candidates);

        if(candidates.empty() == false)
            std::sort(candidates.begin(), candidates.end(), SAscendingSort());

    } else if (oper == wxT("::")) {

        filter.Add(wxT("namespace"));
        filter.Add(wxT("class"));
        filter.Add(wxT("struct"));
        filter.Add(wxT("prototype"));
        filter.Add(wxT("function"));
        filter.Add(wxT("member"));
        filter.Add(wxT("typedef"));
        filter.Add(wxT("enum"));
        filter.Add(wxT("enumerator"));
        filter.Add(wxT("union"));

        PERF_BLOCK("TagsByScope") {
            TagsByScope(scope, filter, candidates, true);
        }

        //Let's search in typerefs
        if (candidates.empty()) {
            PERF_BLOCK("TagsByTyperef") {
                TagsByTyperef(scope, filter, candidates, true);
            }
        }

    } else {

        filter.Add(wxT("function"));
        filter.Add(wxT("member"));
        filter.Add(wxT("prototype"));
        PERF_BLOCK("TagsByScope") {
            TagsByScope(scope, filter, candidates, true);
        }
    }

    PERF_END();

    DoSortByVisibility( candidates );
    return candidates.empty() == false;
}

void TagsManager::DoFilterDuplicatesBySignature(std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& target)
{
    // filter out all entries with the same signature (we do keep declaration overa an implenetation
    // since usually the declaration contains more useful information)
    std::map<wxString, TagEntryPtr> others, impls;

    for (size_t i=0; i<src.size(); i++) {
        const TagEntryPtr& t = src.at(i);
        if(t->IsMethod()) {
            wxString strippedSignature = NormalizeFunctionSig(t->GetSignature(), 0);
            strippedSignature.Prepend( t->GetName() );

            if(t->IsPrototype()) {
                // keep declaration in the output map
                others[strippedSignature] = t;
            } else {
                // keep the signature in a different map
                impls[strippedSignature] = t;
            }
        } else {
            // keep all other entries
            others[t->GetName()] = t;
        }

    }

    // unified the two multimaps
    std::map<wxString, TagEntryPtr>::iterator iter = impls.begin();
    for(; iter != impls.end(); iter++) {
        if(others.find(iter->first) == others.end()) {
            others[iter->first] = iter->second;
        }
    }

    target.clear();
    // convert the map into vector
    iter = others.begin();
    for(; iter != others.end(); iter++) {
        target.push_back(iter->second);
    }
}

void TagsManager::DoFilterDuplicatesByTagID(std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& target)
{
    std::map<int, TagEntryPtr>      mapTags;
    std::map<wxString, TagEntryPtr> localTags;

    for (size_t i=0; i<src.size(); i++) {
        const TagEntryPtr& t = src.at(i);
        int tagId = t->GetId();
        if(t->GetParent() == wxT("<local>")) {
            if(localTags.find(t->GetName()) == localTags.end()) {
                localTags[t->GetName()] = t;
            }

        } else if(mapTags.find(tagId) == mapTags.end()) {
            mapTags[tagId] = t;

        } else {
            tagId = -1;
        }
    }

    // Add the real entries (fetched from the database)
    std::map<int, TagEntryPtr>::iterator iter = mapTags.begin();
    for(; iter != mapTags.end(); iter++) {
        target.push_back( iter->second );
    }

    // Add the locals (collected from the current scope)
    std::map<wxString, TagEntryPtr>::iterator iter2 = localTags.begin();
    for(; iter2 != localTags.end(); iter2++) {
        target.push_back( iter2->second );
    }
}

void TagsManager::RemoveDuplicatesTips(std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& target)
{
    std::map<wxString, TagEntryPtr> unique_tags;

    for (size_t i=0; i<src.size(); i++) {

        wxString raw_sig ( src.at(i)->GetSignature().Trim().Trim(false) );
        wxString sig;
        if (raw_sig.empty() == false) {
            sig = NormalizeFunctionSig(raw_sig, 0);
        }

        // the signature that we want to keep is one with name & default values, so try and get the maximum out of the
        // function signature
        bool hasDefaultValues = (raw_sig.Find(wxT("=")) != wxNOT_FOUND);

        wxString name = src.at(i)->GetName();
        wxString key = name + sig;

        std::map<wxString, TagEntryPtr>::iterator iter = unique_tags.find(key);
        if (iter == unique_tags.end()) {
            // does not exist
            unique_tags[key] = src.at(i);
        } else {
            // an entry with this key already exist
            if (hasDefaultValues) {
                // this entry has a default values, it means that we probably prefer this signature over the other
                TagEntryPtr t = iter->second;
                t->SetSignature(raw_sig);
                unique_tags[key] = t;
            }
        }
    }

    // conver the map back to std::vector
    std::map<wxString, TagEntryPtr>::iterator iter = unique_tags.begin();
    target.clear();

    for (; iter != unique_tags.end(); iter++) {
        target.push_back(iter->second);
    }
}

void TagsManager::GetGlobalTags(const wxString &name, std::vector<TagEntryPtr> &tags, size_t flags)
{
    // Make enough room for max of 500 elements in the vector
    tags.reserve(500);
    GetDatabase()->GetTagsByScopeAndName(wxT("<global>"), name, flags & PartialMatch, tags);
    std::sort(tags.begin(), tags.end(), SAscendingSort());
}

void TagsManager::GetLocalTags(const wxString &name, const wxString &scope, std::vector<TagEntryPtr> &tags, size_t flags)
{
    //collect tags from the current scope text
    GetLanguage()->GetLocalVariables(scope, tags, name, flags);
}

void TagsManager::GetHoverTip(const wxFileName &fileName, int lineno, const wxString & expr, const wxString &word, const wxString & text, std::vector<wxString> & tips)
{
    wxString path;
    wxString typeName, typeScope, tmp;
    std::vector<TagEntryPtr> tmpCandidates, candidates;

    //remove the word from the expression
    wxString expression(expr);

    // Trim whitespace from right and left
    static wxString trimLeftString(wxT("{};\r\n\t\v "));
    static wxString trimRightString(wxT("({};\r\n\t\v "));
    expression.erase(0, expression.find_first_not_of(trimLeftString));
    expression.erase(expression.find_last_not_of(trimRightString)+1);

    tmp = expression;
    expression.EndsWith(word, &tmp);
    expression = tmp;

    wxString curFunctionBody;
    wxString scope = GetLanguage()->OptimizeScope(text, -1, curFunctionBody);
    wxString scopeName = GetLanguage()->GetScopeName(scope, NULL);
    if (expression.IsEmpty()) {
        //collect all the tags from the current scope, and
        //from the global scope

        GetGlobalTags(word, tmpCandidates, ExactMatch);
        GetLocalTags(word, scope, tmpCandidates, ExactMatch);
        TagsByScopeAndName(scopeName, word, tmpCandidates);
        RemoveDuplicatesTips(tmpCandidates, candidates);

        // we now have a list of tags that matches our word
        TipsFromTags(candidates, word, tips);
    } else {
        wxString typeName, typeScope;
        wxString oper, dummy;
        bool res = ProcessExpression(fileName, lineno, expression, text, typeName, typeScope, oper, dummy);
        if (!res) {
            return;
        }

        //get all symbols realted to this scope
        scope = wxT("");
        if (typeScope == wxT("<global>"))
            scope << typeName;
        else
            scope << typeScope << wxT("::") << typeName;

        std::vector<TagEntryPtr> tmpCandidates;
        TagsByScopeAndName(scope, word, tmpCandidates);
        RemoveDuplicatesTips(tmpCandidates, candidates);

        // we now have a list of tags that matches our word
        TipsFromTags(candidates, word, tips);
    }
}

void TagsManager::FindImplDecl(const wxFileName &fileName,
                               int lineno,
                               const wxString & expr,
                               const wxString &word,
                               const wxString & text,
                               std::vector<TagEntryPtr> &tags,
                               bool imp,
                               bool workspaceOnly)
{
    // Don't attempt to parse non valid ctags file
    if ( !IsValidCtagsFile(fileName) ) {
        return;
    }

    wxString path;
    wxString tmp;
    std::vector<TagEntryPtr> tmpCandidates, candidates;


    //remove the word from the expression
    wxString expression(expr);

    // Trim whitespace from right and left
    static wxString trimString(wxT("(){};\r\n\t\v "));

    expression.erase(0, expression.find_first_not_of(trimString));
    expression.erase(expression.find_last_not_of(trimString)+1);
    tmp = expression;
    expression.EndsWith(word, &tmp);
    expression = tmp;
    expression.Trim().Trim(false);


    wxString scope(text);
    std::vector<wxString> visibleScopes;
    wxString scopeName = GetLanguage()->GetScopeName(scope, &visibleScopes);
    if (expression.IsEmpty() || expression == wxT("::")) {
        expression.Clear();

        // add the current scope to the "visibleScopes" to be tested
        if(scopeName != wxT("<global>")) {
            visibleScopes.push_back(scopeName);
            wxArrayString outerScopes = BreakToOuterScopes(scopeName);
            for(size_t i=0; i<outerScopes.GetCount(); i++)
                visibleScopes.push_back(outerScopes.Item(i));
        }

        // collect tags from all the visible scopes
        for(size_t i=0; i<visibleScopes.size(); i++)
            TagsByScopeAndName(visibleScopes.at(i), word, tmpCandidates, ExactMatch);

        if (tmpCandidates.empty()) {
            // no match in the given scope, try to collect from global scope as well
            GetGlobalTags(word, tmpCandidates, ExactMatch);
        }

        if (!imp) {
            //collect only implementation
            FilterImplementation(tmpCandidates, tags);

        } else {
            FilterDeclarations(tmpCandidates, tags);
        }

        if(tags.empty()) {
            TryFindImplDeclUsingNS(scopeName, word, imp, visibleScopes, tags);
            if(tags.empty())
                TryReducingScopes(scopeName, word, imp, tags);
        }

    } else {
        wxString typeName, typeScope;
        wxString oper, dummy;
        bool res = ProcessExpression(fileName, lineno, expression, text, typeName, typeScope, oper, dummy);
        if (!res) {
            return;
        }
        //get all symbols realted to this scope
        scope = wxT("");
        if (typeScope == wxT("<global>"))
            scope << typeName;
        else
            scope << typeScope << wxT("::") << typeName;

        std::vector<TagEntryPtr> tmpCandidates;
        TagsByScopeAndName(scope, word, tmpCandidates, ExactMatch);

        if (!imp) {
            //collect only implementation
            FilterImplementation(tmpCandidates, tags);
        } else {
            FilterDeclarations(tmpCandidates, tags);
        }

        if(tags.empty()) {
            TryFindImplDeclUsingNS(scope, word, imp, visibleScopes, tags);
            if(tags.empty())
                TryReducingScopes(scope, word, imp, tags);
        }
    }
}

void TagsManager::TryReducingScopes(const wxString& scope, const wxString& word, bool imp, std::vector<TagEntryPtr>& tags)
{
    if(scope == wxT("<global>") || scope.IsEmpty())
        return;

    // if we are here, it means that the the 'word' was not found in the 'scope'
    // and we already tried the 'TryFindImplDeclUsingNS' method.
    // What is left to be done is to reduce the 'scope' until we find a match.
    // Example:
    // OuterScope::Foo::Bar::Method()
    // However the entry in the database is stored only with as 'Bar::Method()'
    // we will reduce the scope and will try the following scopes:
    // Foo::Bar
    // Bar
    std::vector<wxString> visibleScopes;
    wxArrayString scopes = wxStringTokenize(scope, wxT(":"), wxTOKEN_STRTOK);
    for(size_t i=1; i<scopes.GetCount(); i++) {
        wxString newScope;
        for(size_t j=i; j<scopes.GetCount(); j++) {
            newScope << scopes.Item(j) << wxT("::");
        }
        if(newScope.Len() >= 2) {
            newScope.RemoveLast(2);
        }
        visibleScopes.push_back(newScope);
    }
    std::vector<TagEntryPtr> tmpCandidates;
    if(visibleScopes.empty() == false) {
        for(size_t i=0; i<visibleScopes.size(); i++) {
            TagsByScopeAndName(visibleScopes.at(i), word, tmpCandidates, ExactMatch);
        }

        if (!imp) {
            //collect only implementation
            FilterImplementation(tmpCandidates, tags);
        } else {
            FilterDeclarations(tmpCandidates, tags);
        }
    }
}

void TagsManager::TryFindImplDeclUsingNS(const wxString &scope,
        const wxString &word,
        bool imp,
        const std::vector<wxString>& visibleScopes,
        std::vector<TagEntryPtr> &tags)
{
    std::vector<TagEntryPtr> tmpCandidates;
    // if we got here and the tags.empty() is true,
    // there is another option to try:
    // sometimes people tend to write code similar to:
    // using namespace Foo;
    // void Bar::func(){}
    // this will make the entry in the tags database to have a scope of 'Bar' without
    // the Foo scope, however the ProcessExpression() method does take into consideration
    // the 'using namespace' statement, we attempt to fix this here
    if(visibleScopes.empty() == false) {
        tmpCandidates.clear();
        for(size_t i=0; i<visibleScopes.size(); i++) {
            wxString newScope(scope);
            if(newScope.StartsWith(visibleScopes.at(i) + wxT("::"))) {
                newScope.Remove(0, visibleScopes.at(i).Len() + 2);
            }
            TagsByScopeAndName(newScope, word, tmpCandidates, ExactMatch);
        }

        if (!imp) {
            //collect only implementation
            FilterImplementation(tmpCandidates, tags);
        } else {
            FilterDeclarations(tmpCandidates, tags);
        }
    }
}

void TagsManager::FilterImplementation(const std::vector<TagEntryPtr> &src, std::vector<TagEntryPtr> &tags)
{
    //remove all implementations and leave only declarations
    std::map<wxString, TagEntryPtr> tmpMap;
    for (size_t i=0; i<src.size(); i++) {
        TagEntryPtr tag = src.at(i);
        if (tag->GetKind() != wxT("function")) {
            wxString key;
            key << tag->GetFile() << tag->GetLine();
            tmpMap[key] = tag;
        }
    }

    std::map<wxString, TagEntryPtr>::iterator iter = tmpMap.begin();
    for (; iter != tmpMap.end(); iter++) {
        tags.push_back(iter->second);
    }
}

void TagsManager::FilterDeclarations(const std::vector<TagEntryPtr> &src, std::vector<TagEntryPtr> &tags)
{
    std::map<wxString, TagEntryPtr> tmpMap;
    for (size_t i=0; i<src.size(); i++) {
        TagEntryPtr tag = src.at(i);
        if (tag->GetKind() != wxT("prototype")) {
            wxString key;
            key << tag->GetFile() << tag->GetLine();
            tmpMap[key] = tag;
        }
    }
    std::map<wxString, TagEntryPtr>::iterator iter = tmpMap.begin();
    for (; iter != tmpMap.end(); iter++) {
        tags.push_back(iter->second);
    }
}

clCallTipPtr TagsManager::GetFunctionTip(const wxFileName &fileName, int lineno, const wxString &expr, const wxString &text, const wxString &word)
{
    wxString path;
    wxString typeName, typeScope, tmp;
    std::vector<TagEntryPtr> tips;

    // Skip any C++ keywords
    if ( m_CppIgnoreKeyWords.find(word) != m_CppIgnoreKeyWords.end() ) {
        return NULL;
    }

    // Trim whitespace from right and left
    wxString expression(expr);
    static wxString trimLeftString(wxT("{};\r\n\t\v "));
    static wxString trimRightString(wxT("({};\r\n\t\v "));
    expression.erase(0, expression.find_first_not_of(trimLeftString));
    expression.erase(expression.find_last_not_of(trimRightString)+1);

    //remove the last token from the expression
    expression.EndsWith(word, &tmp);
    expression = tmp;
    if (word.IsEmpty()) {
        return NULL;
    }

    CppScanner scanner;
    scanner.SetText(_C(word));
    if (scanner.yylex() != IDENTIFIER) {
        return NULL;
    }

    expression.Trim().Trim(false);
    if (expression.IsEmpty()) {
        DoGetFunctionTipForEmptyExpression(word, text, tips);

        if(tips.empty()) {
            // no luck yet
            // we now try this:
            // Perhaps our "function" is actually a constuctor, e.g.:
            // ClassName cls(
            wxString alteredText ( text );
            alteredText.Append(wxT(";"));
            std::vector<TagEntryPtr> tmpCandidates;
            GetLocalTags(word, text, tmpCandidates, ExactMatch);
            if( tmpCandidates.size() == 1) {
                TagEntryPtr t = tmpCandidates.at(0);
                DoGetFunctionTipForEmptyExpression(t->GetScope(), text, tips);
                
            } else {
                // Stil no luck, try this:
                // Assume that the expression is a code-complete expression (i.e. an expression that ends with -> or .
                // and try to resolve it. If we succeed, we collect only the ctors matches from that list
                TagEntryPtrVector_t matches;
                tmpCandidates.clear();
                if ( AutoCompleteCandidates(fileName, lineno, expr + ".", text, matches) && !matches.empty() ) {
                    std::for_each(matches.begin(), matches.end(), TagEntry::ForEachCopyIfCtor(tmpCandidates) );
                    GetFunctionTipFromTags(tmpCandidates, matches.at(0)->GetScopeName(), tips);
                }
            }
        }
    } else if( expression == wxT("::") ) {
        // Test the global scope
        DoGetFunctionTipForEmptyExpression(word, text, tips, true);

    } else {
        wxString oper, dummy;
        bool res = ProcessExpression(fileName, lineno, expression, text, typeName, typeScope, oper, dummy);
        if (!res) {
            return NULL;
        }

        //load all tags from the database that matches typeName & typeScope
        wxString scope;
        if (typeScope == wxT("<global>"))
            scope << typeName;
        else
            scope << typeScope << wxT("::") << typeName;

        //this function will retrieve the ineherited tags as well
        std::vector<TagEntryPtr> tmpCandidates;
        TagsByScopeAndName(scope, word, tmpCandidates, ExactMatch);
        GetFunctionTipFromTags(tmpCandidates, word, tips);
    }

    // In case the user requested that the function signature will not be formatted
    // respect it and add the 'Tag_No_Signature_Format' flag
    if(GetCtagsOptions().GetFlags() & CC_KEEP_FUNCTION_SIGNATURE_UNFORMATTED) {
        for(size_t i=0; i<tips.size(); i++) {
            tips.at(i)->SetFlags(TagEntry::Tag_No_Signature_Format);
        }
    }

    clCallTipPtr ct( new clCallTip(tips) );
    return ct;
}

//-----------------------------------------------------------------------------
// <<<<<<<<<<<<<<<<<<< Code Completion API END
//-----------------------------------------------------------------------------
void TagsManager::OpenType(std::vector<TagEntryPtr> &tags)
{
    wxArrayString kinds;
    kinds.Add(wxT("class"));
    kinds.Add(wxT("namespace"));
    kinds.Add(wxT("struct"));
    kinds.Add(wxT("union"));
    kinds.Add(wxT("enum"));
    kinds.Add(wxT("typedef"));

    GetDatabase()->GetTagsByKind(kinds, wxT("name"), ITagsStorage::OrderDesc, tags);
}

void TagsManager::FindSymbol(const wxString& name, std::vector<TagEntryPtr> &tags)
{
    // since we dont get a scope, we better user a search that only uses the
    // name (GetTagsByScopeAndName) is optimized to search the global tags table
    GetDatabase()->GetTagsByName(name, tags, true);
}

void TagsManager::DeleteFilesTags(const wxArrayString &files)
{
    std::vector<wxFileName> files_;
    for (size_t i=0; i<files.GetCount(); i++) {
        files_.push_back(files.Item(i));
    }
    DeleteFilesTags(files_);
}

void TagsManager::DeleteFilesTags(const std::vector<wxFileName> &projectFiles)
{
    if (projectFiles.empty()) {
        return;
    }

    // Put a request to the parsing thread to delete the tags for the 'projectFiles'
    ParseRequest *req = new ParseRequest( ParseThreadST::Get()->GetNotifiedWindow() );
    req->setDbFile( GetDatabase()->GetDatabaseFileName().GetFullPath().c_str() );
    req->setType  ( ParseRequest::PR_DELETE_TAGS_OF_FILES );
    req->_workspaceFiles.clear();
    req->_workspaceFiles.reserve( projectFiles.size() );
    for(size_t i=0; i<projectFiles.size(); i++) {
        req->_workspaceFiles.push_back( projectFiles.at(i).GetFullPath().mb_str(wxConvUTF8).data() );
    }
    ParseThreadST::Get()->Add ( req );
}

void TagsManager::RetagFiles(const std::vector<wxFileName> &files, RetagType type, wxEvtHandler *cb)
{
    wxArrayString strFiles;
    // step 1: remove all non-tags files
    for (size_t i=0; i<files.size(); i++) {
        if (!IsValidCtagsFile(files.at(i).GetFullPath())) {
            continue;
        }

        strFiles.Add(files.at(i).GetFullPath());
    }

    // If there are no files to tag - send the 'end' event
    if (strFiles.IsEmpty()) {
        wxFrame *frame = dynamic_cast<wxFrame*>( wxTheApp->GetTopWindow() );
        if (frame) {
            wxCommandEvent retaggingCompletedEvent(wxEVT_PARSE_THREAD_RETAGGING_COMPLETED);
            frame->GetEventHandler()->AddPendingEvent(retaggingCompletedEvent);
        }
        return;
    }

    // step 2: remove all files which do not need retag
    if ( type == Retag_Quick || type == Retag_Quick_No_Scan )
        DoFilterNonNeededFilesForRetaging(strFiles, GetDatabase());

    // If there are no files to tag - send the 'end' event
    if (strFiles.IsEmpty()) {
        wxFrame *frame = dynamic_cast<wxFrame*>( wxTheApp->GetTopWindow() );
        if (frame) {
            wxCommandEvent retaggingCompletedEvent(wxEVT_PARSE_THREAD_RETAGGING_COMPLETED);
            frame->GetEventHandler()->AddPendingEvent(retaggingCompletedEvent);
        }
        return;
    }

    // step 4: Remove tags belonging to these files
    DeleteFilesTags(strFiles);

    // step 5: build the database
    ParseRequest *req = new ParseRequest( ParseThreadST::Get()->GetNotifiedWindow() );
    if ( cb ) {
        req->_evtHandler = cb; // Callback window
    }

    req->setDbFile( GetDatabase()->GetDatabaseFileName().GetFullPath().c_str() );

    req->setType( type == Retag_Quick_No_Scan ? ParseRequest::PR_PARSE_FILE_NO_INCLUDES : ParseRequest::PR_PARSE_AND_STORE );
    req->_workspaceFiles.clear();
    req->_workspaceFiles.reserve( strFiles.size() );
    for(size_t i=0; i<strFiles.GetCount(); i++) {
        req->_workspaceFiles.push_back( strFiles[i].mb_str(wxConvUTF8).data() );
    }
    ParseThreadST::Get()->Add ( req );
}

void TagsManager::FindByNameAndScope(const wxString &name, const wxString &scope, std::vector<TagEntryPtr> &tags)
{
    wxString _name  = DoReplaceMacros(name);
    wxString _scope = DoReplaceMacros(scope);
    DoFindByNameAndScope(_name, _scope, tags);

    // Sort the results base on their name
    std::sort(tags.begin(), tags.end(), SAscendingSort());
}

void TagsManager::FindByPath(const wxString &path, std::vector<TagEntryPtr> &tags)
{
    GetDatabase()->GetTagsByPath(path, tags);
}

void TagsManager::DoFindByNameAndScope(const wxString &name, const wxString &scope, std::vector<TagEntryPtr> &tags)
{
    wxString sql;
    if (scope == wxT("<global>")) {
        // try the workspace database for match
        GetDatabase()->GetTagsByNameAndParent(name, wxT("<global>"), tags);
    } else {
        std::vector<wxString> derivationList;
        derivationList.push_back(scope);
        std::set<wxString> scannedInherits;
        GetDerivationList(scope, NULL, derivationList, scannedInherits);
        wxArrayString paths;
        for (size_t i=0; i<derivationList.size(); i++) {
            wxString path_;
            path_ << derivationList.at(i) << wxT("::") << name ;
            paths.Add(path_);
        }

        // try the workspace database for match
        GetDatabase()->GetTagsByPath(paths, tags);
    }
}

bool TagsManager::IsTypeAndScopeContainer(wxString& typeName, wxString& scope)
{
    wxString cacheKey;
    cacheKey << typeName << wxT("@") << scope;

    //we search the cache first, note that the cache
    //is used only for the external database
    std::map<wxString, bool>::iterator iter = m_typeScopeContainerCache.find(cacheKey);
    if (iter != m_typeScopeContainerCache.end()) {
        return iter->second;
    }

    // replace macros:
    // replace the provided typeName and scope with user defined macros as appeared in the PreprocessorMap
    wxString _typeName = DoReplaceMacros(typeName);
    wxString _scope    = DoReplaceMacros(scope);

    bool res = GetDatabase()->IsTypeAndScopeContainer(_typeName, _scope);
    if(res) {
        typeName = _typeName;
        scope    = _scope;
    }
    return res;
}

bool TagsManager::IsTypeAndScopeExists(wxString &typeName, wxString &scope)
{
    wxString cacheKey;
    cacheKey << typeName << wxT("@") << scope;

    //we search the cache first, note that the cache
    //is used only for the external database
    std::map<wxString, bool>::iterator iter = m_typeScopeCache.find(cacheKey);
    if (iter != m_typeScopeCache.end()) {
        return iter->second;
    }

    // First try the fast query to save some time
    if(GetDatabase()->IsTypeAndScopeExistLimitOne(typeName, scope)) {
        return true;
    }

    // replace macros:
    // replace the provided typeName and scope with user defined macros as appeared in the PreprocessorMap
    typeName = DoReplaceMacros(typeName);
    scope    = DoReplaceMacros(scope);

    return GetDatabase()->IsTypeAndScopeExist(typeName, scope);
}

bool TagsManager::GetDerivationList(const wxString& path, TagEntryPtr derivedClassTag, std::vector<wxString>& derivationList, std::set<wxString>& scannedInherits)
{
    std::vector<TagEntryPtr> tags;
    TagEntryPtr tag;

    wxArrayString kind;
    kind.Add(wxT("class"));
    kind.Add(wxT("struct"));

    GetDatabase()->GetTagsByKindAndPath(kind, path, tags);

    if (tags.size() == 1) {
        tag = tags.at(0);
    } else {
        return false;
    }

    if (tag && tag->IsOk()) {

        // Get the template instantiation list from the child class
        wxArrayString ineheritsList  = tag->GetInheritsAsArrayNoTemplates();

        wxString templateInstantiationLine;
        if(derivedClassTag) {
            wxArrayString p_ineheritsListT = derivedClassTag->GetInheritsAsArrayWithTemplates();
            wxArrayString p_ineheritsList  = derivedClassTag->GetInheritsAsArrayNoTemplates();

            for(size_t i=0; i<p_ineheritsList.GetCount(); i++) {
                if(p_ineheritsList.Item(i) == tag->GetName()) {
                    templateInstantiationLine =  p_ineheritsListT.Item(i);
                    templateInstantiationLine = templateInstantiationLine.AfterFirst(wxT('<'));
                    templateInstantiationLine.Prepend(wxT("<"));
                    break;
                }
            }
        }

        for(size_t i=0; i<ineheritsList.GetCount(); i++) {
            wxString inherits = ineheritsList.Item(i);
            wxString tagName  = tag->GetName();
            wxString tmpInhr  = inherits;

            bool isTempplate = (tag->GetPattern().Find(wxT("template")) != wxNOT_FOUND);
            tagName.MakeLower();
            tmpInhr.MakeLower();

            // Make sure that inherits != the current name or we will end up in an infinite loop
            if(tmpInhr != tagName) {
                wxString possibleScope(wxT("<global>"));

                // if the 'inherits' already contains a scope
                // dont attempt to fix it
                if(inherits.Contains(wxT("::")) == false) {

                    // Correc the type/scope
                    bool testForTemplate = !IsTypeAndScopeExists(inherits, possibleScope);

                    // If the type does not exists, check for templates
                    if( testForTemplate && derivedClassTag && isTempplate ) {
                        TemplateHelper th;

                        // e.g. template<typename T> class MyClass
                        wxArrayString templateArgs = GetLanguage()->DoExtractTemplateDeclarationArgs(tag);
                        th.SetTemplateDeclaration(templateArgs);                // <typename T>
                        th.SetTemplateInstantiation(templateInstantiationLine); // e.g. MyClass<wxString>

                        wxString newType = th.Substitute(inherits);

                        // Locate the new type by name in the database
                        // this is done to make sure that the new type is not a macro...
                        if(!newType.IsEmpty() && newType != inherits) {

                            // check the user defined types for a replcement token
                            wxString replacement = DoReplaceMacros(newType);
                            if(replacement == newType) {
                                // No match was found in the user defined replacements
                                // try the database
                                replacement = DoReplaceMacrosFromDatabase(newType);

                            }
                            inherits = replacement;
                        }
                    }

                    if (possibleScope != wxT("<global>")) {
                        inherits = possibleScope + wxT("::") + inherits;
                    }

                }

                // Make sure that this parent was not scanned already
                if(scannedInherits.find(inherits) == scannedInherits.end()) {
                    scannedInherits.insert(inherits);
                    derivationList.push_back(inherits);
                    GetDerivationList(inherits, tag, derivationList, scannedInherits);
                }
            }
        }
    }
    return true;
}

void TagsManager::TipsFromTags(const std::vector<TagEntryPtr> &tags, const wxString &word, std::vector<wxString> &tips)
{
    bool isDarkBG = isDarkColor(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK));
    wxString retValueColour = "\"BLUE\"";
    if ( isDarkBG ) {
        retValueColour = "\"YELLOW\"";
    }

    for (size_t i=0; i<tags.size(); i++) {
        if (tags.at(i)->GetName() != word)
            continue;

        wxString tip = tags.at(i)->GetPattern();

        //remove the pattern perfix and suffix
        tip = tip.Trim().Trim(false);
        tip = tip.AfterFirst(wxT('^'));
        if (tip.Find(wxT('$')) != wxNOT_FOUND) {
            tip = tip.BeforeLast(wxT('$'));
        } else {
            if (tip.EndsWith(wxT("/"))) {
                tip = tip.BeforeLast(wxT('/'));
            }
        }

        //since the tip is built from the pattern, which is actually a regex expression
        //some characters might be escaped (e.g. '/' will appear as '\/')
        tip.Replace(wxT("\\/"), wxT("/"));

        // Trim whitespace from right and left
        static wxString trimString(wxT("{};\r\n\t\v "));

        tip.erase(0, tip.find_first_not_of(trimString));
        tip.erase(tip.find_last_not_of(trimString)+1);
        tip.Replace(wxT("\t"), wxT(" "));

        // create a proper tooltip from the stripped pattern
        TagEntryPtr t= tags.at(i);
        if (t->IsMethod()) {

            // add return value
            tip.Clear();

            wxString ret_value = GetFunctionReturnValueFromPattern(t);
            if(ret_value.IsEmpty() == false) {
                tip << "<b><color=" << retValueColour << ">" << ret_value << wxT("</color></b> ");
            } else {
                wxString retValue = t->GetReturnValue();
                if(retValue.IsEmpty() == false) {
                    tip << "<b><color=" << retValueColour << ">" << retValue << wxT("</color></b> ");
                }
            }

            // add the scope
            if (!t->IsScopeGlobal()) {
                tip << t->GetScope() << wxT("::");
            }

            // name
            tip << "<b>" << t->GetName() << "</b>";

            // method signature
            tip << NormalizeFunctionSig(t->GetSignature(), Normalize_Func_Name | Normalize_Func_Default_value);
        }

        // remove any extra spaces from the tip
        while (tip.Replace(wxT("  "), wxT(" "))) {}

        // BUG#3082954: limit the size of the 'match pattern' to a reasonable size (200 chars)
        tip = WrapLines(tip);

        if ( !tips.empty() ) {
            tip.Prepend("\n<hr>\n");
        }

        // prepend any comment if exists
        tips.push_back(tip);
    }
}

void TagsManager::GetFunctionTipFromTags(const std::vector<TagEntryPtr> &tags, const wxString &word, std::vector<TagEntryPtr> &tips)
{
    std::map<wxString, TagEntryPtr> tipsMap;
    std::vector<TagEntryPtr> ctor_tags;

    for (size_t i=0; i<tags.size(); i++) {
        if (tags.at(i)->GetName() != word)
            continue;

        TagEntryPtr t;
        TagEntryPtr curtag = tags.at(i);

        // try to replace the current tag with a macro replacement.
        // we dont temper with 'curtag' content since we dont want
        // to modify cached items
        t = curtag->ReplaceSimpleMacro();
        if(!t) {
            t = curtag;
        }

        wxString pat = t->GetPattern();

        if ( t->IsMethod() ) {
            wxString tip;
            tip << wxT("function:") << t->GetSignature();

            // collect each signature only once, we do this by using
            // map
            tipsMap[tip] = t;

        } else if (t->IsClass()) {

            // this tag is a class declaration that matches the word
            // user is probably is typing something like
            // Class *a = new Class(
            // or even Class a = Class(
            // the steps to take from here:
            // - lookup in the tables for tags that matches path of: WordScope::Word::Word and of type prototype/function
            wxString scope;
            if ( t->GetScope().IsEmpty() == false && t->GetScope() != wxT("<global>") ) {
                scope << t->GetScope() << wxT("::");
            }

            scope << t->GetName();
            ctor_tags.clear();
            TagsByScopeAndName(scope, t->GetName(), ctor_tags, ExactMatch);

            for (size_t i=0; i<ctor_tags.size(); i++) {
                TagEntryPtr ctor_tag = ctor_tags.at(i);
                if ( ctor_tag->IsMethod() ) {
                    wxString tip;
                    tip << wxT("function:") << ctor_tag->GetSignature();
                    tipsMap[ctor_tag->GetSignature()] = ctor_tag;
                }
            }

        } else if (t->IsMacro()) {

            wxString tip;
            wxString macroName = t->GetName();
            wxString pattern = t->GetPattern();

            int where = pattern.Find(macroName);
            if (where != wxNOT_FOUND) {
                //remove the #define <name> from the pattern
                pattern = pattern.Mid(where + macroName.Length());
                pattern = pattern.Trim().Trim(false);
                if (pattern.StartsWith(wxT("("))) {
                    //this macro has the form of a function
                    pattern = pattern.BeforeFirst(wxT(')'));
                    pattern.Append(wxT(')'));

                    tip << wxT("macro:") << pattern;

                    //collect each signature only once, we do this by using
                    //map
                    tipsMap[tip] = t;
                }
            }
        }
    }

    for (std::map<wxString, TagEntryPtr>::iterator iter = tipsMap.begin(); iter != tipsMap.end(); iter++) {
        tips.push_back(iter->second);
    }
}

void TagsManager::CloseDatabase()
{
    m_dbFile.Clear();
    m_db = NULL; // Free the current database
    m_db = new TagsStorageSQLite();
    m_db->SetSingleSearchLimit( m_tagsOptions.GetCcNumberOfDisplayItems() );
    m_db->SetUseCache(true);
}

DoxygenComment TagsManager::GenerateDoxygenComment(const wxString &file, const int line, wxChar keyPrefix)
{
    if (GetDatabase()->IsOpen()) {
        std::vector<TagEntryPtr> tags;

        GetDatabase()->GetTagsByFileAndLine(file, line + 1, tags );

        if (tags.empty() || tags.size() > 1)
            return DoxygenComment();

        //create a doxygen comment from the tag
        return DoCreateDoxygenComment(tags.at(0), keyPrefix);
    }
    return DoxygenComment();
}

DoxygenComment TagsManager::DoCreateDoxygenComment(TagEntryPtr tag, wxChar keyPrefix)
{
    CppCommentCreator commentCreator(tag, keyPrefix);
    DoxygenComment dc;
    dc.comment = commentCreator.CreateComment();
    dc.name = tag->GetName();
    return dc;
}

bool TagsManager::GetParseComments()
{
    return m_parseComments;
}

void TagsManager::SetCtagsOptions(const TagsOptionsData &options)
{
    m_tagsOptions = options;
    RestartCodeLiteIndexer();
    m_parseComments = m_tagsOptions.GetFlags() & CC_PARSE_COMMENTS ? true : false;
    ITagsStoragePtr db = GetDatabase();
    if(db) {
        db->SetSingleSearchLimit(m_tagsOptions.GetCcNumberOfDisplayItems());
    }
}

void TagsManager::GenerateSettersGetters(const wxString &scope, const SettersGettersData &data, const std::vector<TagEntryPtr> &tags, wxString &impl, wxString *decl)
{
    wxUnusedVar(scope);
    wxUnusedVar(data);
    wxUnusedVar(tags);
    wxUnusedVar(impl);
    wxUnusedVar(decl);
}

void TagsManager::TagsByScope(const wxString &scopeName, const wxString &kind, std::vector<TagEntryPtr> &tags, bool includeInherits, bool applyLimit)
{
    wxString sql;
    std::vector<wxString> derivationList;
    //add this scope as well to the derivation list
    derivationList.push_back(scopeName);
    std::set<wxString> scannedInherits;
    if (includeInherits) {
        GetDerivationList(scopeName, NULL, derivationList, scannedInherits);
    }

    //make enough room for max of 500 elements in the vector
    tags.reserve(500);
    wxArrayString kinds, scopes;
    kinds.Add(kind);

    for (size_t i=0; i<derivationList.size(); i++) {
        scopes.Add(derivationList.at(i));
    }

    if(applyLimit)
        GetDatabase()->GetTagsByScopesAndKind(scopes, kinds, tags);
    else
        GetDatabase()->GetTagsByScopesAndKindNoLimit(scopes, kinds, tags);
}

wxString TagsManager::GetScopeName(const wxString &scope)
{
    Language *lang = GetLanguage();
    return lang->GetScopeName(scope, NULL);
}

bool TagsManager::ProcessExpression(const wxFileName &filename, int lineno, const wxString &expr, const wxString &scopeText, wxString &typeName, wxString &typeScope, wxString &oper, wxString &scopeTempalteInitiList)
{
    return GetLanguage()->ProcessExpression(expr, scopeText, filename, lineno, typeName, typeScope, oper, scopeTempalteInitiList);
}

bool TagsManager::GetMemberType(const wxString &scope, const wxString &name, wxString &type, wxString &typeScope)
{
    wxString expression(scope);
    expression << wxT("::") << name << wxT(".");
    wxString dummy;
    return GetLanguage()->ProcessExpression(expression, wxEmptyString, wxFileName(), wxNOT_FOUND, type, typeScope, dummy, dummy);
}

void TagsManager::GetFiles(const wxString &partialName, std::vector<FileEntryPtr> &files)
{
    if (GetDatabase()) {
        GetDatabase()->GetFiles(partialName, files);
    }
}

void TagsManager::GetFiles(const wxString &partialName, std::vector<wxFileName> &files)
{
    std::vector<FileEntryPtr> f;
    GetFiles(partialName, f);

    for (size_t i=0; i<f.size(); i++) {
        files.push_back( wxFileName(f.at(i)->GetFile()) );
    }
}

TagEntryPtr TagsManager::FunctionFromFileLine(const wxFileName &fileName, int lineno, bool nextFunction /*false*/)
{
    if (!GetDatabase()) {
        return NULL;
    }

    if (!IsFileCached(fileName.GetFullPath())) {
        CacheFile(fileName.GetFullPath());
    }

    TagEntryPtr foo = NULL;
    for (size_t i=0; i<m_cachedFileFunctionsTags.size(); i++) {
        TagEntryPtr t = m_cachedFileFunctionsTags.at(i);

        if (nextFunction && t->GetLine() > lineno) {
            // keep the last non matched method
            foo = t;
        } else if (t->GetLine() <= lineno) {
            if (nextFunction ) {
                return foo;
            } else {
                return t;
            }
        }
    }
    return NULL;
}

void TagsManager::GetScopesFromFile(const wxFileName &fileName, std::vector< wxString > &scopes)
{
    if (!GetDatabase()) {
        return;
    }

    GetDatabase()->GetScopesFromFileAsc(fileName, scopes);
}

void TagsManager::TagsFromFileAndScope(const wxFileName& fileName, const wxString &scopeName, std::vector< TagEntryPtr > &tags)
{
    if (!GetDatabase()) {
        return;
    }

    wxArrayString kind;
    kind.Add(wxT("function"));
    kind.Add(wxT("prototype"));
    kind.Add(wxT("enum"));

    GetDatabase()->GetTagsByFileScopeAndKind(fileName, scopeName, kind, tags);
    std::sort(tags.begin(), tags.end(), SAscendingSort());
}

bool TagsManager::GetFunctionDetails(const wxFileName &fileName, int lineno, TagEntryPtr &tag, clFunction &func)
{
    tag = FunctionFromFileLine(fileName, lineno);
    if (tag) {
        GetLanguage()->FunctionFromPattern( tag, func );
        return true;
    }
    return false;
}

TagEntryPtr TagsManager::FirstFunctionOfFile(const wxFileName &fileName)
{
    if (!GetDatabase()) {
        return NULL;
    }

    std::vector<TagEntryPtr> tags;
    wxArrayString            kind;
    kind.Add(wxT("function"));
    GetDatabase()->GetTagsByKindAndFile(kind, fileName.GetFullPath(), wxT("line"), ITagsStorage::OrderAsc, tags);

    if ( tags.empty() ) return NULL;
    return tags.at(0);
}

TagEntryPtr TagsManager::FirstScopeOfFile(const wxFileName &fileName)
{
    if (!GetDatabase()) {
        return NULL;
    }
    std::vector<TagEntryPtr> tags;
    wxArrayString            kind;
    kind.Add(wxT("struct"));
    kind.Add(wxT("class"));
    kind.Add(wxT("namespace"));
    GetDatabase()->GetTagsByKindAndFile(kind, fileName.GetFullPath(), wxT("line"), ITagsStorage::OrderAsc, tags);

    if ( tags.empty() ) return NULL;
    return tags.at(0);
}

wxString TagsManager::FormatFunction(TagEntryPtr tag, size_t flags, const wxString &scope)
{
    clFunction foo;
    if (!GetLanguage()->FunctionFromPattern(tag, foo)) {
        return wxEmptyString;
    }

    wxString body;
    // add virtual keyword to declarations only && if the flags is set
    if (foo.m_isVirtual && (flags & FunctionFormat_WithVirtual) && !(flags & FunctionFormat_Impl)) {
        body << wxT("virtual ");
    }

    wxString ret_value = GetFunctionReturnValueFromPattern(tag);
    if(ret_value.IsEmpty() == false) {
        body << ret_value << wxT(" ");

    } else {
        wxString retValue = tag->GetReturnValue();
        if(retValue.IsEmpty() == false) {
            body << retValue << wxT(" ");
        }

    }

    if (flags & FunctionFormat_Impl) {
        if (scope.IsEmpty()) {
            if (tag->GetScope() != wxT("<global>")) {
                body << tag->GetScope() << wxT("::");
            }
        } else {
            body << scope << wxT("::");
        }
    }

    // Build the flags required by the NormalizeFunctionSig() method
    size_t tmpFlags(0);
    if ( flags & FunctionFormat_Impl ) {
        tmpFlags |= Normalize_Func_Name | Normalize_Func_Reverse_Macro;
    } else {
        tmpFlags |= Normalize_Func_Name | Normalize_Func_Reverse_Macro | Normalize_Func_Default_value;
    }

    if(flags & FunctionFormat_Arg_Per_Line)
        tmpFlags |= Normalize_Func_Arg_Per_Line;

    if(flags & FunctionFormat_Arg_Per_Line)
        body << wxT("\n");

    body << tag->GetName();
    if(tag->GetFlags() & TagEntry::Tag_No_Signature_Format) {
        body << tag->GetSignature();

    } else {
        body << NormalizeFunctionSig( tag->GetSignature(), tmpFlags);

    }

    if ( foo.m_isConst ) {
        body << wxT(" const");
    }

    if (!foo.m_throws.empty()) {
        body << wxT(" throw (") << wxString(foo.m_throws.c_str(), wxConvUTF8) << wxT(")");
    }

    if (flags & FunctionFormat_Impl) {
        body << wxT("\n{\n}\n");
    } else {
        body << wxT(";\n");
    }

    // convert \t to spaces
    body.Replace(wxT("\t"), wxT(" "));

    // remove any extra spaces from the tip
    while (body.Replace(wxT("  "), wxT(" "))) {}
    return body;
}

bool TagsManager::IsPureVirtual(TagEntryPtr tag)
{
    clFunction foo;
    if (!GetLanguage()->FunctionFromPattern(tag, foo)) {
        return false;
    }
    return foo.m_isPureVirtual;
}

bool TagsManager::IsVirtual(TagEntryPtr tag)
{
    clFunction foo;
    if (!GetLanguage()->FunctionFromPattern(tag, foo)) {
        return false;
    }
    return foo.m_isVirtual;
}
void TagsManager::SetLanguage(Language *lang)
{
    m_lang = lang;
}

Language* TagsManager::GetLanguage()
{
    if ( !m_lang ) {
        //for backward compatibility allows access to the tags manager using
        //the singleton call
        return LanguageST::Get();
    } else {
        return m_lang;
    }
}

bool TagsManager::ProcessExpression(const wxString &expression, wxString &type, wxString &typeScope)
{
    wxString oper, dummy;
    return ProcessExpression(wxFileName(), wxNOT_FOUND, expression, wxEmptyString, type, typeScope, oper, dummy);
}

void TagsManager::GetClasses(std::vector< TagEntryPtr > &tags, bool onlyWorkspace)
{
    wxArrayString kind;
    kind.Add(wxT("class"));
    kind.Add(wxT("struct"));
    kind.Add(wxT("union"));

    GetDatabase()->GetTagsByKind(kind, wxT("name"), ITagsStorage::OrderAsc, tags);
}

void TagsManager::StripComments(const wxString &text, wxString &stippedText)
{
    CppScanner scanner;
    scanner.SetText( _C(text) );

    bool changedLine = false;
    bool prepLine = false;
    int curline = 0;

    while (true) {
        int type = scanner.yylex();
        if (type == 0) {
            break;
        }

        // eat up all tokens until next line
        if ( prepLine && scanner.lineno() == curline) {
            continue;
        }

        prepLine = false;

        // Get the current line number, it will help us detect preprocessor lines
        changedLine = (scanner.lineno() > curline);
        if (changedLine) {
            stippedText << wxT("\n");
        }

        curline = scanner.lineno();
        if (type == '#') {
            if (changedLine) {
                // We are at the start of a new line
                // consume everything until new line is found or end of text
                prepLine = true;
                continue;
            }
        }
        stippedText << _U( scanner.YYText() ) << wxT(" ");
    }
}

void TagsManager::GetFunctions(std::vector< TagEntryPtr > &tags, const wxString &fileName , bool onlyWorkspace )
{
    wxArrayString kind;
    kind.Add(wxT("function"));
    kind.Add(wxT("prototype"));
    GetDatabase()->GetTagsByKindAndFile(kind, fileName, wxT("name"), ITagsStorage::OrderAsc, tags);
}

void TagsManager::GetAllTagsNames(wxArrayString &tagsList)
{
    size_t kind = GetCtagsOptions().GetCcColourFlags();
    if (kind == CC_COLOUR_ALL) {
        GetDatabase()->GetAllTagsNames(tagsList);
        return;
    }

    wxArrayString kindArr;

    if ( kind & CC_COLOUR_CLASS) {
        kindArr.Add(wxT("class"));
    }
    if ( kind & CC_COLOUR_ENUM) {
        kindArr.Add(wxT("enum"));
    }
    if ( kind & CC_COLOUR_FUNCTION) {
        kindArr.Add(wxT("function"));
    }
    if ( kind & CC_COLOUR_MACRO) {
        kindArr.Add(wxT("macro"));
    }
    if ( kind & CC_COLOUR_NAMESPACE) {
        kindArr.Add(wxT("namespace"));
    }
    if ( kind & CC_COLOUR_PROTOTYPE) {
        kindArr.Add(wxT("prototype"));
    }
    if ( kind & CC_COLOUR_STRUCT) {
        kindArr.Add(wxT("struct"));
    }
    if ( kind & CC_COLOUR_TYPEDEF) {
        kindArr.Add(wxT("typedef"));
    }
    if ( kind & CC_COLOUR_UNION) {
        kindArr.Add(wxT("union"));
    }
    if ( kind & CC_COLOUR_ENUMERATOR) {
        kindArr.Add(wxT("enumerator"));
    }
    if ( kind & CC_COLOUR_VARIABLE) {
        kindArr.Add(wxT("variable"));
    }
    if ( kind & CC_COLOUR_MEMBER) {
        kindArr.Add(wxT("member"));
    }

    if ( kindArr.IsEmpty() ) {
        return;
    }

    GetDatabase()->GetTagsNames(kindArr, tagsList);
}

void TagsManager::TagsByScope(const wxString &scopeName, const wxArrayString &kind, std::vector<TagEntryPtr> &tags, bool include_anon)
{
    wxUnusedVar(include_anon);

    wxArrayString scopes;
    GetScopesByScopeName(scopeName, scopes);
    //make enough room for max of 500 elements in the vector
    tags.reserve(500);
    GetDatabase()->GetTagsByScopesAndKind(scopes, kind, tags);

    // and finally sort the results
    std::sort(tags.begin(), tags.end(), SAscendingSort());
}

void TagsManager::TagsByTyperef(const wxString &scopeName, const wxArrayString &kind, std::vector<TagEntryPtr> &tags, bool include_anon)
{
    wxUnusedVar(include_anon);

    wxArrayString scopes;
    GetScopesByScopeName(scopeName, scopes);
    //make enough room for max of 500 elements in the vector
    tags.reserve(500);

    GetDatabase()->GetTagsByTyperefAndKind(scopes, kind, tags);

    // and finally sort the results
    std::sort(tags.begin(), tags.end(), SAscendingSort());
}

wxString TagsManager::NormalizeFunctionSig(const wxString &sig, size_t flags, std::vector<std::pair<int, int> > *paramLen)
{
    std::map<std::string, std::string> ignoreTokens = GetCtagsOptions().GetTokensMap();
    std::map<std::string, std::string> reverseTokens;

    if(flags & Normalize_Func_Reverse_Macro)
        reverseTokens = GetCtagsOptions().GetTokensReversedMap();

    VariableList li;
    const wxCharBuffer patbuf = _C(sig);

    get_variables(patbuf.data(), li, ignoreTokens, true);

    //construct a function signature from the results
    wxString str_output;
    str_output << wxT("(");

    if (paramLen) {
        paramLen->clear();
    }
    if(flags & Normalize_Func_Arg_Per_Line && li.size()) {
        str_output << wxT("\n    ");
    }

    VariableList::iterator iter = li.begin();
    for ( ; iter != li.end() ; iter++) {
        Variable v = *iter;
        int start_offset = str_output.length();

        //add const qualifier
        if (v.m_isConst) {
            str_output << wxT("const ");
        }

        if ( v.m_isVolatile ) {
            str_output << wxT("volatile ");
        }
        
        // enum as part of the type?
        if ( v.m_enumInTypeDecl ) {
            str_output << "enum ";
        }
        
        //add scope
        if (v.m_typeScope.empty() == false) {
            str_output << _U(v.m_typeScope.c_str()) << wxT("::");
        }
        
        if (v.m_type.empty() == false) {
            if(flags & Normalize_Func_Reverse_Macro) {
                // replace the type if it exists in the map
                std::map<std::string, std::string>::iterator miter = reverseTokens.find(v.m_type);
                if(miter != reverseTokens.end()) {
                    v.m_type = miter->second;
                }
            }
            str_output << _U(v.m_type.c_str());
        }

        if (v.m_templateDecl.empty() == false) {
            str_output << _U(v.m_templateDecl.c_str());
        }

        if (v.m_starAmp.empty() == false) {
            str_output << _U(v.m_starAmp.c_str());
        }

        if (v.m_rightSideConst.empty() == false) {
            str_output << wxT(" ") << _U(v.m_rightSideConst.c_str());
        }
        
        if (v.m_name.empty() == false && (flags & Normalize_Func_Name)) {
            str_output << wxT(" ") << _U(v.m_name.c_str());
            
        } else if ( v.m_isEllipsis ) {
            str_output << wxT(" ...");
        }

        if (v.m_arrayBrackets.empty() == false) {
            str_output << wxT(" ") << _U(v.m_arrayBrackets.c_str());
        }

        if (v.m_defaultValue.empty() == false && (flags & Normalize_Func_Default_value)) {
            str_output << wxT(" = ") << _U(v.m_defaultValue.c_str());
        }

        // keep the length of this argument
        if (paramLen) {
            paramLen->push_back(std::pair<int, int>(start_offset, str_output.length() - start_offset));
        }
        str_output << wxT(", ");
        if(flags & Normalize_Func_Arg_Per_Line && li.size()) {
            str_output << wxT("\n    ");
        }
    }

    if (li.empty() == false) {
        str_output = str_output.BeforeLast(wxT(','));
    }

    str_output << wxT(")");
    return str_output;
}

void TagsManager::GetUnImplementedFunctions(const wxString& scopeName, std::map<wxString, TagEntryPtr>& protos)
{
    //get list of all prototype functions from the database
    std::vector< TagEntryPtr > vproto;
    std::vector< TagEntryPtr > vimpl;

    //currently we want to add implementation only for workspace classes
    TagsByScope(scopeName, wxT("prototype"), vproto, false, false);
    TagsByScope(scopeName, wxT("function"), vimpl, false, false);

    //filter out functions which already has implementation
    for ( size_t i=0; i < vproto.size() ; i++ ) {
        TagEntryPtr tag = vproto.at(i);
        wxString key = tag->GetName();

        //override the scope to be our scope...
        tag->SetScope( scopeName );

        key << NormalizeFunctionSig( tag->GetSignature(), Normalize_Func_Reverse_Macro );
        protos[key] = tag;
    }

    std::map<std::string, std::string> ignoreTokens = GetCtagsOptions().GetTokensMap();

    // remove functions with implementation
    for ( size_t i=0; i < vimpl.size() ; i++ ) {
        TagEntryPtr tag = vimpl.at(i);
        wxString key = tag->GetName();
        key << NormalizeFunctionSig( tag->GetSignature(), Normalize_Func_Reverse_Macro );
        std::map<wxString, TagEntryPtr>::iterator iter = protos.find(key);

        if ( iter != protos.end() ) {
            protos.erase( iter );
        }
    }

    std::map<wxString, TagEntryPtr> tmpMap( protos );
    std::map<wxString, TagEntryPtr>::iterator it = tmpMap.begin();
    protos.clear();

    // collect only non-pure virtual methods
    for (; it != tmpMap.end() ; it++ ) {
        TagEntryPtr tag = it->second;
        clFunction f;
        if ( GetLanguage()->FunctionFromPattern(tag, f) ) {
            if ( !f.m_isPureVirtual ) {
                // incude this function
                protos[it->first] = it->second;
            }
        } else {
            // parsing failed
            protos[it->first] = it->second;
        }
    }
}

void TagsManager::CacheFile(const wxString& fileName)
{
    if (!GetDatabase()) {
        return;
    }

    m_cachedFile = fileName;
    m_cachedFileFunctionsTags.clear();

    wxArrayString kinds;
    kinds.Add(wxT("function"));
    kinds.Add(wxT("prototype"));
    // disable the cache
    GetDatabase()->SetUseCache(false);
    GetDatabase()->GetTagsByKindAndFile(kinds, fileName, wxT("line"), ITagsStorage::OrderDesc, m_cachedFileFunctionsTags);
    // re-enable it
    GetDatabase()->SetUseCache(true);
}

void TagsManager::ClearCachedFile(const wxString &fileName)
{
    if (fileName == m_cachedFile) {
        m_cachedFile.Clear();
        m_cachedFileFunctionsTags.clear();
    }
}

bool TagsManager::IsFileCached(const wxString& fileName) const
{
    return fileName == m_cachedFile;
}

wxString TagsManager::GetCTagsCmd()
{
    wxString cmd;
    wxString ctagsCmd;
    ctagsCmd << m_tagsOptions.ToString() << m_ctagsCmd;

    // build the command, we surround ctags name with double quatations
    cmd << wxT("\"") << m_codeliteIndexerPath.GetFullPath() << wxT("\"") << ctagsCmd;

    return cmd;
}

wxString TagsManager::DoReplaceMacros(wxString name)
{
    // replace macros:
    // replace the provided typeName and scope with user defined macros as appeared in the PreprocessorMap
    wxString _name(name);

    std::map<wxString, wxString> iTokens = GetCtagsOptions().GetTokensWxMap();
    std::map<wxString, wxString>::iterator it = iTokens.end();

    it = iTokens.find(name);
    if (it != iTokens.end()) {
        if (it->second.empty() == false) {
            _name = it->second;
        }
    }
    return _name;
}

void TagsManager::DeleteTagsByFilePrefix(const wxString& dbfileName, const wxString& filePrefix)
{
    ITagsStorage *db = new TagsStorageSQLite();
    db->OpenDatabase(wxFileName(dbfileName));
    db->Begin();

    // delete the tags
    db->DeleteByFilePrefix     (db->GetDatabaseFileName(), filePrefix);

    // deelete the FILES entries
    db->DeleteFromFilesByPrefix(db->GetDatabaseFileName(), filePrefix);
    db->Commit();

    delete db;
}

void TagsManager::UpdateFilesRetagTimestamp(const wxArrayString& files, ITagsStoragePtr db)
{
    db->Begin();
    for (size_t i=0; i<files.GetCount(); i++) {
        db->InsertFileEntry(files.Item(i), (int)time(NULL));
    }
    db->Commit();
}

void TagsManager::FilterNonNeededFilesForRetaging(wxArrayString& strFiles,ITagsStoragePtr db)
{
    std::vector<FileEntryPtr> files_entries;
    db->GetFiles(files_entries);
    std::set<wxString> files_set;

    for (size_t i=0; i<strFiles.GetCount(); i++) {
        files_set.insert(strFiles.Item(i));
    }

    for (size_t i=0; i<files_entries.size(); i++) {
        FileEntryPtr fe = files_entries.at(i);

        // does the file exist in both lists?
        std::set<wxString>::iterator iter = files_set.find(fe->GetFile());
        if ( iter != files_set.end() ) {
            // get the actual modifiaction time of the file from the disk
            struct stat buff;
            int modified(0);

            const wxCharBuffer cname = _C((*iter));
            if (stat(cname.data(), &buff) == 0) {
                modified = (int)buff.st_mtime;
            }

            // if the timestamp from the database < then the actual timestamp, re-tag the file
            if (fe->GetLastRetaggedTimestamp() >= modified) {
                files_set.erase(iter);
            }
        }
    }

    // copy back the files to the array
    std::set<wxString>::iterator iter = files_set.begin();
    strFiles.Clear();
    for (; iter != files_set.end(); iter++ ) {
        strFiles.Add( *iter );
    }
}

void TagsManager::DoFilterNonNeededFilesForRetaging(wxArrayString& strFiles, ITagsStoragePtr db)
{
    FilterNonNeededFilesForRetaging(strFiles, db);
}

wxString TagsManager::GetFunctionReturnValueFromPattern(TagEntryPtr tag)
{
    // evaluate the return value of the tag
    clFunction foo;
    wxString return_value;
    if (GetLanguage()->FunctionFromPattern(tag, foo)) {
        if (foo.m_retrunValusConst.empty() == false) {
            return_value << _U(foo.m_retrunValusConst.c_str()) << wxT(" ");
        }

        if (foo.m_returnValue.m_typeScope.empty() == false) {
            return_value << _U(foo.m_returnValue.m_typeScope.c_str()) << wxT("::");
        }

        if (foo.m_returnValue.m_type.empty() == false) {
            return_value << _U(foo.m_returnValue.m_type.c_str());
            if (foo.m_returnValue.m_templateDecl.empty() == false) {
                return_value << wxT("<") << _U(foo.m_returnValue.m_templateDecl.c_str()) << wxT(">");
            }
            return_value << _U(foo.m_returnValue.m_starAmp.c_str());
            return_value << wxT(" ");
        }

        if ( !foo.m_returnValue.m_rightSideConst.empty() ) {
            return_value << foo.m_returnValue.m_rightSideConst << " ";
        }
    }
    return return_value;
}

void TagsManager::GetTagsByKind(std::vector<TagEntryPtr>& tags, const wxArrayString& kind, const wxString& partName)
{
    wxUnusedVar(partName);
    GetDatabase()->GetTagsByKind(kind, wxEmptyString, ITagsStorage::OrderNone, tags);
}

void TagsManager::GetTagsByKindLimit(std::vector<TagEntryPtr>& tags, const wxArrayString& kind, int limit, const wxString& partName)
{
    GetDatabase()->GetTagsByKindLimit(kind, wxEmptyString, ITagsStorage::OrderNone, limit, partName, tags);
}

void TagsManager::DoGetFunctionTipForEmptyExpression(const wxString& word, const wxString& text, std::vector<TagEntryPtr>& tips, bool globalScopeOnly/* = false*/)
{
    std::vector<TagEntryPtr> candidates;
    std::vector<wxString>    additionlScopes;

    //we are probably examining a global function, or a scope function
    GetGlobalTags(word, candidates, ExactMatch);

    if( !globalScopeOnly ) {
        wxString scopeName = GetLanguage()->GetScopeName(text, &additionlScopes);
        TagsByScopeAndName(scopeName, word, candidates);
        for (size_t i=0; i<additionlScopes.size(); i++) {
            TagsByScopeAndName(additionlScopes.at(i), word, candidates);
        }

    }
    GetFunctionTipFromTags(candidates, word, tips);
}

void TagsManager::GetUnOverridedParentVirtualFunctions(const wxString& scopeName, bool onlyPureVirtual, std::vector<TagEntryPtr> &protos)
{
    std::vector<TagEntryPtr> tags;
    std::map<wxString, TagEntryPtr> parentSignature2tag;
    std::map<wxString, TagEntryPtr> classSignature2tag;

    GetDatabase()->GetTagsByPath(scopeName, tags);
    if(tags.size() != 1) {
        return;
    }

    TagEntryPtr classTag = tags.at(0);
    if(classTag->GetKind() != wxT("class") && classTag->GetKind() != wxT("struct"))
        return;


    // Step 1:
    // ========
    // Compoze a list of all virtual functions from the direct parent(s)
    // class (there could be a multiple inheritance...)
    wxArrayString parents = classTag->GetInheritsAsArrayNoTemplates();
    wxArrayString kind;

    tags.clear();
    kind.Add(wxT("prototype"));
    kind.Add(wxT("function" ));
    for(wxArrayString::size_type i=0; i<parents.GetCount(); i++) {
        GetDatabase()->GetTagsByScopeAndKind(parents.Item(i), kind, tags, false);
    }

    for(wxArrayString::size_type i=0; i<tags.size(); i++) {
        TagEntryPtr t   = tags.at(i);

        // Skip c-tors/d-tors
        if(t->IsDestructor() || t->IsConstructor())
            continue;

        if( onlyPureVirtual ) {

            // Collect only pure virtual methods
            if( IsPureVirtual(t) ) {
                TagEntryPtr t   = tags.at(i);
                wxString    sig = NormalizeFunctionSig(t->GetSignature(), Normalize_Func_Reverse_Macro);
                sig.Prepend(t->GetName());
                parentSignature2tag[sig] = tags.at(i);
            }

        } else {

            // Collect both virtual and pure virtual
            if( IsVirtual(tags.at(i)) || IsPureVirtual(tags.at(i)) ) {
                wxString    sig = NormalizeFunctionSig(t->GetSignature(), Normalize_Func_Reverse_Macro);
                sig.Prepend(t->GetName());
                parentSignature2tag[sig] = tags.at(i);
            }
        }
    }

    // Step 2:
    // ========
    // Collect a list of function prototypes from the class
    tags.clear();
    GetDatabase()->GetTagsByScopeAndKind(scopeName, kind, tags, false);
    for(size_t i=0; i<tags.size(); i++) {
        TagEntryPtr t   = tags.at(i);
        wxString    sig = NormalizeFunctionSig(t->GetSignature(), Normalize_Func_Reverse_Macro);
        sig.Prepend(t->GetName());
        classSignature2tag[sig] = t;
    }

    // Step 3:
    // =======
    // remove any entry from the parent tags which exists in the child tags
    std::map<wxString, TagEntryPtr>::iterator iter = classSignature2tag.begin();
    for(; iter != classSignature2tag.end(); iter++) {
        if(parentSignature2tag.find(iter->first) != parentSignature2tag.end()) {
            // the current signature exists both in the child and the parent,
            // remove it
            parentSignature2tag.erase(iter->first);
        }
    }

    // Step 4:
    // =======
    // parentSignature2tag now contains map of signature/tags of virtual functions which exists
    // in the parent but could not be found in the child
    iter = parentSignature2tag.begin();
    for(; iter != parentSignature2tag.end(); iter++) {
        protos.push_back(iter->second);
    }
}

void TagsManager::ClearTagsCache()
{
    GetDatabase()->ClearCache();
}

void TagsManager::SetProjectPaths(const wxArrayString& paths)
{
    m_projectPaths.Clear();
    m_projectPaths = paths;
}

void TagsManager::GetDereferenceOperator(const wxString& scope, std::vector<TagEntryPtr>& tags)
{
    std::vector<wxString> derivationList;

    //add this scope as well to the derivation list
    wxString _scopeName = DoReplaceMacros( scope );
    derivationList.push_back(_scopeName);
    std::set<wxString> scannedInherits;
    GetDerivationList(_scopeName, NULL, derivationList, scannedInherits);

    //make enough room for max of 500 elements in the vector
    for (size_t i=0; i<derivationList.size(); i++) {
        wxString tmpScope(derivationList.at(i));
        tmpScope = DoReplaceMacros(tmpScope);

        GetDatabase()->GetDereferenceOperator(tmpScope, tags);
        if(tags.size()) {

            // No need to further check
            break;

        }
    }
}

void TagsManager::GetSubscriptOperator(const wxString& scope, std::vector<TagEntryPtr>& tags)
{
    std::vector<wxString> derivationList;

    //add this scope as well to the derivation list
    wxString _scopeName = DoReplaceMacros( scope );
    derivationList.push_back(_scopeName);
    std::set<wxString> scannedInherits;
    GetDerivationList(_scopeName, NULL, derivationList, scannedInherits);

    //make enough room for max of 500 elements in the vector
    for (size_t i=0; i<derivationList.size(); i++) {
        wxString tmpScope(derivationList.at(i));
        tmpScope = DoReplaceMacros(tmpScope);

        GetDatabase()->GetSubscriptOperator(scope, tags);
        if(tags.size()) {

            // No need to further check
            break;

        }
    }
}

void TagsManager::ClearAllCaches()
{
    m_cachedFile.Clear();
    m_cachedFileFunctionsTags.clear();
    GetDatabase()->ClearCache();
}

CppToken TagsManager::FindLocalVariable(const wxFileName& fileName, int pos, int lineNumber, const wxString& word, const wxString& modifiedText)
{
    // Load the file and get a state map + the text from the scanner
    TagEntryPtr    tag   (NULL);
    TextStatesPtr  states(NULL);
    CppWordScanner scanner;

    if(modifiedText.empty() == false) {
        // Parse the modified text
        std::vector<TagEntryPtr> tags;
        DoParseModifiedText(modifiedText, tags);

        // It is safe to assume that the tags are sorted by line number
        // Loop over the tree and search for the a function closest to the given line number
        for(size_t i=0; i<tags.size() && tags[i]->GetLine() <= lineNumber; i++) {
            if(tags[i]->IsFunction()) {
                tag = tags[i];
            }
        }

        // Construct a scanner based on the modified text
        scanner = CppWordScanner(fileName.GetFullPath(), modifiedText.mb_str().data(), 0);
        states = scanner.states();

    } else {
        // get the local by scanning from the current function's
        tag = FunctionFromFileLine(fileName, lineNumber + 1);
        scanner = CppWordScanner(fileName.GetFullPath().mb_str().data());
        states = scanner.states();
    }

    if(!tag || !states)
        return CppToken();

    // Get the line number of the function
    int funcLine = tag->GetLine() - 1;

    // Convert the line number to offset
    int from = states->LineToPos     (funcLine);
    int to   = states->FunctionEndPos(from);

    if(to == wxNOT_FOUND)
        return CppToken();

    // get list of variables from the given scope
    VariableList vars;
    std::map<std::string, std::string> ignoreMap;

    get_variables(states->text.substr(from, to-from).mb_str().data(), vars, ignoreMap, false);
    VariableList::iterator iter = vars.begin();
    bool isLocalVar(false);
    for(; iter != vars.end(); iter++) {
        if(wxString::From8BitData(iter->m_name.c_str()) == word) {
            // our 'word' is indeed a variable
            isLocalVar = true;
            break;
        }
    }

    if (!isLocalVar)
        return CppToken();

    // search for matches in the given range
    CppTokensMap l;
    scanner.Match(word.mb_str().data(), l, from, to);

    std::list<CppToken> tokens;
    l.findTokens(word.mb_str().data(), tokens);
    if (tokens.empty())
        return CppToken();

    // return the first match
    return *tokens.begin();
}

void TagsManager::DoParseModifiedText(const wxString &text, std::vector<TagEntryPtr>& tags)
{
    wxFFile fp;
    wxString fileName = wxFileName::CreateTempFileName(wxT("codelite_mod_file_"), &fp);
    if(fp.IsOpened()) {
        fp.Write(text);
        fp.Close();
        wxString tagsStr;
        SourceToTags(wxFileName(fileName), tagsStr);

        // Create tags from the string
        wxArrayString tagsLines = wxStringTokenize(tagsStr, wxT("\n"), wxTOKEN_STRTOK);
        for(size_t i=0; i<tagsLines.GetCount(); i++) {
            wxString line = tagsLines.Item(i).Trim().Trim(false);
            if (line.IsEmpty())
                continue;

            TagEntryPtr tag(new TagEntry());
            tag->FromLine(line);

            tags.push_back(tag);
        }
        // Delete the modified file
        wxRemoveFile( fileName );
    }
}

bool TagsManager::IsBinaryFile(const wxString& filepath)
{
    // If the file is a C++ file, avoid testing the content return false based on the extension
    FileExtManager::FileType type = FileExtManager::GetType(filepath);
    if(type == FileExtManager::TypeHeader || type == FileExtManager::TypeSourceC || type == FileExtManager::TypeSourceCpp)
        return false;

    // examine the file based on the content of the first 4K (max) bytes
    FILE *fp = fopen(filepath.To8BitData(), "rb");
    if(fp) {

        char      buffer[1];
        int       textLen(0);
        const int maxTextToExamine(4096);

        // examine up to maxTextToExamine first chars in the file and search for '\0'
        while( fread(buffer, sizeof(char), sizeof(buffer), fp) == 1 && textLen < maxTextToExamine) {
            textLen++;
            // if we found a NULL, return true
            if(buffer[0] == 0) {
                fclose(fp);
                return true;
            }
        }

        fclose(fp);
        return false;
    }

    // if we could not open it, return true
    return true;
}

wxString TagsManager::WrapLines(const wxString& str)
{
    wxString wrappedString;

    int curLineBytes(0);
    wxString::const_iterator iter = str.begin();
    for(; iter != str.end(); iter++) {
        if(*iter == wxT('\t')) {
            wrappedString << wxT(" ");

        } else if(*iter == wxT('\n')) {
            wrappedString << wxT("\n");
            curLineBytes = 0;

        } else if(*iter == wxT('\r')) {
            // Skip it

        } else {
            wrappedString << *iter;
        }
        curLineBytes++;

        if(curLineBytes == MAX_TIP_LINE_SIZE) {

            // Wrap the lines
            if(wrappedString.IsEmpty() == false && wrappedString.Last() != wxT('\n')) {
                wrappedString << wxT("\n");

            }
            curLineBytes = 0;
        }
    }
    return wrappedString;
}

void TagsManager::GetVariables(const std::string& in, VariableList& li, const std::map<std::string, std::string>& ignoreMap, bool isUsedWithinFunc)
{
    get_variables(in, li, ignoreMap, isUsedWithinFunc);
}

void TagsManager::SetEncoding(const wxFontEncoding& encoding)
{
    m_encoding = encoding;
}

wxArrayString TagsManager::BreakToOuterScopes(const wxString& scope)
{
    wxArrayString outerScopes;
    wxArrayString scopes = wxStringTokenize(scope, wxT(":"), wxTOKEN_STRTOK);
    for(size_t i=1; i<scopes.GetCount(); i++) {
        wxString newScope;
        for(size_t j=0; j<i; j++) {
            newScope << scopes.Item(j) << wxT("::");
        }
        if(newScope.Len() >= 2) {
            newScope.RemoveLast(2);
        }
        outerScopes.Add(newScope);
    }
    return outerScopes;
}

ITagsStoragePtr TagsManager::GetDatabase()
{
    return m_db;
}

void TagsManager::GetTagsByName(const wxString& prefix, std::vector<TagEntryPtr>& tags)
{
    GetDatabase()->GetTagsByName(prefix, tags);
}

wxString TagsManager::DoReplaceMacrosFromDatabase(const wxString& name)
{
    std::set<wxString> scannedMacros;
    wxString newName = name;
    while ( true ) {
        std::vector<TagEntryPtr> tmpTags;
        TagEntryPtr matchedTag = GetDatabase()->GetTagsByNameLimitOne(newName);
        if(matchedTag && matchedTag->IsMacro() && scannedMacros.find(matchedTag->GetName()) == scannedMacros.end() )  {
            TagEntryPtr realTag = matchedTag->ReplaceSimpleMacro();
            if(realTag) {

                newName = realTag->GetName();
                scannedMacros.insert(newName);
                continue;

            } else {
                break;
            }
        } else {
            break;
        }
    }
    return newName;
}

void TagsManager::GetTagsByPartialName(const wxString& partialName, std::vector<TagEntryPtr>& tags)
{
    GetDatabase()->GetTagsByPartName(partialName, tags);
}

bool TagsManager::AreTheSame(const TagEntryPtrVector_t& v1, const TagEntryPtrVector_t& v2) const
{
    // Assuming that v1 and v2 are sorted!
    if( v1.size() != v2.size() )
        return false;
    for(size_t i=0; i<v1.size(); i++) {
        if( v1.at(i)->CompareDisplayString(v2.at(i)) != 0 )
            return false;
    }
    return true;
}

bool TagsManager::InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent, int visibility)
{
    return GetLanguage()->InsertFunctionDecl(clsname, functionDecl, sourceContent, visibility);
}

void TagsManager::InsertFunctionImpl(const wxString& clsname, const wxString& functionImpl, const wxString& filename, wxString& sourceContent, int& insertedLine)
{
    return GetLanguage()->InsertFunctionImpl(clsname, functionImpl, filename, sourceContent, insertedLine);
}

void TagsManager::DoSortByVisibility(TagEntryPtrVector_t& tags)
{
    TagEntryPtrVector_t publicTags, privateTags, protectedTags;
    for(size_t i=0; i<tags.size(); ++i) {

        TagEntryPtr tag = tags.at(i);
        wxString access = tag->GetAccess();

        if( access == "private" ) {
            privateTags.push_back( tag );

        } else if ( access == "protected" ) {
            protectedTags.push_back( tag );

        } else if ( access == "public" ) {
            publicTags.push_back( tag );

        } else {
            // assume private
            privateTags.push_back( tag );
        }

    }

    std::sort(privateTags.begin(),   privateTags.end(), SAscendingSort());
    std::sort(publicTags.begin(),    publicTags.end(), SAscendingSort());
    std::sort(protectedTags.begin(), protectedTags.end(), SAscendingSort());
    tags.clear();
    tags.insert(tags.end(), publicTags.begin(),    publicTags.end());
    tags.insert(tags.end(), protectedTags.begin(), protectedTags.end());
    tags.insert(tags.end(), privateTags.begin(),   privateTags.end());
}

void TagsManager::AddEnumClassData(wxString& tags)
{
    //Add tisInEnumNamespace flag for enums. For declaration "enum class ..." (C++11)
    size_t startIndex = tags.find(TagEntry::KIND_ENUM + wxT(" "), 0);
    while (startIndex != (size_t)wxNOT_FOUND) {
        size_t patternEndIndex = tags.find(wxT("$/"), startIndex);
        wxString pattern = tags.substr(startIndex, patternEndIndex - startIndex);
        if (pattern.Contains(TagEntry::KIND_CLASS)) {

            wxString enumName = pattern.AfterLast(wxT(' '));

            //Get namespace
            wxString enumNamespace = wxT("");
            size_t endIndex = tags.find(wxT("\n"), startIndex);
            wxString line = tags.substr(startIndex, endIndex - startIndex);
            size_t namespaceStartIndex = line.find(TagEntry::KIND_NAMESPACE, 0);
            if (namespaceStartIndex != (size_t)wxNOT_FOUND) {
                size_t namespaceNameStartIndex = line.find(wxT(":"), namespaceStartIndex);
                if (namespaceNameStartIndex != (size_t)wxNOT_FOUND) {
                    namespaceNameStartIndex++;
                    size_t namespaceNameEndIndex = line.find_first_of(wxT("\t\r"), namespaceNameStartIndex);
                    enumNamespace = line.substr(namespaceNameStartIndex, namespaceNameEndIndex - namespaceNameStartIndex);
                }
            }

            wxString fullName = enumNamespace.IsEmpty() ? enumName : enumNamespace + wxT("::") + enumName;
            wxString parametersFrom = TagEntry::KIND_ENUM + wxT(":") + fullName + wxT("\r");
            wxString parametersTo = TagEntry::KIND_ENUM + wxT(":") + fullName + wxT("\tisInEnumNamespace:1") + wxT("\r");
            size_t lengthBefore = tags.Length();
            tags.Replace(parametersFrom, parametersTo, true);
            startIndex += tags.Length() - lengthBefore;
        }

        startIndex += TagEntry::KIND_ENUM.Length();
        startIndex = tags.find(TagEntry::KIND_ENUM + wxT(" "), startIndex);
    }
}

void TagsManager::GetScopesByScopeName(const wxString &scopeName, wxArrayString & scopes)
{
    std::vector<wxString> derivationList;

    //add this scope as well to the derivation list
    wxString _scopeName = DoReplaceMacros( scopeName );
    derivationList.push_back(_scopeName);
    std::set<wxString> scannedInherits;
    GetDerivationList(_scopeName, NULL, derivationList, scannedInherits);

    for (size_t i=0; i<derivationList.size(); i++) {
        wxString tmpScope(derivationList.at(i));
        tmpScope = DoReplaceMacros(tmpScope);
        scopes.Add(tmpScope);
    }
}

void TagsManager::InsertForwardDeclaration(const wxString& classname, const wxString& fileContent, wxString& lineToAdd, int& line, const wxString& impExpMacro)
{
    lineToAdd << "class ";
    if ( !impExpMacro.IsEmpty() ) {
        lineToAdd << impExpMacro << " ";
    }
    lineToAdd << classname << ";";
    line = GetLanguage()->GetBestLineForForwardDecl(fileContent);
}

void TagsManager::GetVariables(const wxFileName& filename, wxArrayString& locals)
{
    wxFFile fp(filename.GetFullPath(), "rb");
    if ( !fp.IsOpened() )
        return;
        
    wxString content;
    fp.ReadAll( &content );
    fp.Close();
    
    VariableList li;
    std::map<std::string, std::string> ignoreMap;
    wxCharBuffer cb = content.mb_str(wxConvUTF8);
    get_variables(cb.data(), li, ignoreMap, false);
    
    VariableList::iterator iter = li.begin();
    for(; iter != li.end(); ++iter ) {
        locals.Add(iter->m_name);
    }
}

void TagsManager::GetFilesForCC(const wxString& userTyped, wxArrayString& matches)
{
    GetDatabase()->GetFilesForCC(userTyped, matches);
}