Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

""" 

LaTeX printing support 

 

In order to support latex formatting, an object should define a 

special method ``_latex_(self)`` that returns a string, which will be typeset 

in a mathematical mode (the exact mode depends on circumstances). 

 

AUTHORS: 

 

- William Stein: original implementation 

- Joel B. Mohler: latex_variable_name() drastic rewrite and many doc-tests 

""" 

 

#***************************************************************************** 

# Copyright (C) 2005 William Stein <wstein@gmail.com> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# as published by the Free Software Foundation; either version 2 of 

# the License, or (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import print_function, absolute_import 

from six import iteritems, integer_types 

 

from sage.cpython.string import str_to_bytes 

 

EMBEDDED_MODE = False 

 

COMMON_HEADER = \ 

r'''\usepackage{amsmath} 

\usepackage{amssymb} 

\usepackage{amsfonts} 

\usepackage{graphicx} 

\usepackage{mathrsfs} 

\pagestyle{empty} 

\usepackage[utf8]{inputenc} 

\usepackage[T1]{fontenc} 

''' 

 

LATEX_HEADER = ( 

r'''\documentclass{article} 

''' + COMMON_HEADER + 

r'''\oddsidemargin 0.0in 

\evensidemargin 0.0in 

\textwidth 6.45in 

\topmargin 0.0in 

\headheight 0.0in 

\headsep 0.0in 

\textheight 9.0in 

''') 

 

SLIDE_HEADER = ( 

r'''\documentclass[a0,8pt]{beamer} 

''' + COMMON_HEADER + 

r'''\textwidth=1.1\textwidth 

\textheight=2\textheight 

''') 

 

import sys 

import shutil, re 

import os.path 

import random 

import subprocess 

import types 

 

from sage.misc.temporary_file import tmp_dir 

from . import sage_eval 

from sage.misc.sage_ostools import have_program 

from sage.misc.cachefunc import cached_function, cached_method 

 

@cached_function 

def have_latex(): 

""" 

Return ``True`` if this computer has the program ``latex``. 

 

If this computer doesn't have LaTeX installed, you may obtain it 

from http://ctan.org/. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import have_latex 

sage: have_latex() # random 

True 

""" 

return have_program('latex') 

 

 

@cached_function 

def have_pdflatex(): 

""" 

Return ``True`` if this computer has the program ``pdflatex``. 

 

If this computer doesn't have pdflatex installed, you may obtain it 

from http://ctan.org/. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import have_pdflatex 

sage: have_pdflatex() # random 

True 

""" 

return have_program('pdflatex') 

 

 

@cached_function 

def have_xelatex(): 

""" 

Return ``True`` if this computer has the program ``xelatex``. 

 

If this computer doesn't have xelatex installed, you may obtain it 

from http://ctan.org/. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import have_xelatex 

sage: have_xelatex() # random 

True 

""" 

return have_program('xelatex') 

 

 

@cached_function 

def have_dvipng(): 

""" 

Return ``True`` if this computer has the program ``dvipng``. 

 

If this computer doesn't have dvipng installed, you may obtain it 

from http://sourceforge.net/projects/dvipng/ 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import have_dvipng 

sage: have_dvipng() # random 

True 

""" 

return have_program('dvipng') 

 

 

@cached_function 

def have_convert(): 

""" 

Return ``True`` if this computer has the program ``convert``. 

 

If this computer doesn't have convert installed, you may obtain it 

(along with the rest of the ImageMagick suite) from 

http://www.imagemagick.org 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import have_convert 

sage: have_convert() # random 

True 

""" 

return have_program('convert') 

 

 

def list_function(x): 

r""" 

Returns the LaTeX code for a list ``x``. 

 

INPUT: ``x`` - a list 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import list_function 

sage: list_function([1,2,3]) 

'\\left[1, 2, 3\\right]' 

sage: latex([1,2,3]) # indirect doctest 

\left[1, 2, 3\right] 

sage: latex([Matrix(ZZ,3,range(9)), Matrix(ZZ,3,range(9))]) # indirect doctest 

\left[\left(\begin{array}{rrr} 

0 & 1 & 2 \\ 

3 & 4 & 5 \\ 

6 & 7 & 8 

\end{array}\right), \left(\begin{array}{rrr} 

0 & 1 & 2 \\ 

3 & 4 & 5 \\ 

6 & 7 & 8 

\end{array}\right)\right] 

""" 

return "\\left[" + ", ".join([latex(v) for v in x]) + "\\right]" 

 

 

def tuple_function(x, combine_all=False): 

r""" 

Returns the LaTeX code for a tuple ``x``. 

 

INPUT: 

 

- ``x`` -- a tuple 

 

- ``combine_all`` -- boolean (Default: ``False``) If ``combine_all`` is 

``True``, then it does not return a tuple and instead returns a string 

with all the elements separated by a single space. It does not collapse 

tuples which are inside tuples. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import tuple_function 

sage: tuple_function((1,2,3)) 

'\\left(1, 2, 3\\right)' 

 

Check that :trac:`11775` is fixed:: 

 

sage: tuple_function((1,2,3), combine_all=True) 

'1 2 3' 

sage: tuple_function(((1,2),3), combine_all=True) 

'\\left(1, 2\\right) 3' 

""" 

if combine_all: 

return " ".join([latex(v) for v in x]) 

return "\\left(" + ", ".join([latex(v) for v in x]) + "\\right)" 

 

 

def bool_function(x): 

r""" 

Returns the LaTeX code for a boolean ``x``. 

 

INPUT: 

 

- ``x`` -- boolean 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import bool_function 

sage: print(bool_function(2==3)) 

\mathrm{False} 

sage: print(bool_function(3==(2+1))) 

\mathrm{True} 

""" 

return r"\mathrm{%s}" % bool(x) 

 

def builtin_constant_function(x): 

r""" 

Returns the LaTeX code for a builtin constant ``x``. 

 

INPUT: 

 

- ``x`` -- builtin constant 

 

.. SEEALSO:: Python built-in Constants http://docs.python.org/library/constants.html 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import builtin_constant_function 

sage: builtin_constant_function(True) 

'\\mbox{\\rm True}' 

sage: builtin_constant_function(None) 

'\\mbox{\\rm None}' 

sage: builtin_constant_function(NotImplemented) 

'\\mbox{\\rm NotImplemented}' 

sage: builtin_constant_function(Ellipsis) 

'\\mbox{\\rm Ellipsis}' 

 

TESTS:: 

 

sage: sage.misc.latex.EMBEDDED_MODE = True 

sage: builtin_constant_function(True) 

'{\\rm True}' 

sage: sage.misc.latex.EMBEDDED_MODE = False 

""" 

if EMBEDDED_MODE: 

return "{\\rm %s}"%x 

return "\mbox{\\rm %s}"%x 

 

def None_function(x): 

r""" 

Returns the LaTeX code for ``None``. 

 

INPUT: 

 

- ``x`` -- ``None`` 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import None_function 

sage: print(None_function(None)) 

\mathrm{None} 

""" 

assert x is None 

return r"\mathrm{None}" 

 

 

def str_function(x): 

r""" 

Return a LaTeX representation of the string ``x``. 

 

The main purpose of this function is to generate LaTeX representation for 

classes that do not provide a customized method. 

 

If ``x`` contains only digits with, possibly, a single decimal point and/or 

a sign in front, it is considered to be its own representation. Otherwise 

each line of ``x`` is wrapped in a ``\texttt`` command and these lines are 

assembled in a left-justified array. This gives to complicated strings the 

closest look to their "terminal representation". 

 

.. WARNING:: 

 

Such wrappers **cannot** be used as arguments of LaTeX 

commands or in command definitions. If this causes you any problems, 

they probably can be solved by implementing a suitable ``_latex_`` 

method for an appropriate class. 

 

INPUT: 

 

- ``x`` -- a string. 

 

OUTPUT: 

 

A string 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import str_function 

sage: str_function('34') 

'34' 

sage: str_function('34.5') 

'34.5' 

sage: str_function('-34.5') 

'-34.5' 

sage: str_function('+34.5') 

'+34.5' 

sage: str_function('hello_world') 

'\\text{\\texttt{hello{\\char`\\_}world}}' 

sage: str_function('-1.00000?') # trac 12178 

'-1.00000?' 

""" 

# Check if x is just a number with a possible sign, and/or decimal 

# point, and/or ends with "?" 

if re.match(r'(\+|-)?[0-9]*\.?[0-9]*\??$', x): 

return x 

# Deal with special characters 

char_wrapper = r"{\char`\%s}" 

x = "".join(char_wrapper % c if c in "#$%&\^_{}~" else c for c in x) 

# Avoid grouping spaces into one 

x = x.replace(" ", "{ }") 

# And dashes too, since it causes issues for the command line... 

x = x.replace("-", "{-}") 

# Make it work in math mode, but look like typewriter 

line_wrapper = r"\text{\texttt{%s}}" 

x = "\\\\\n".join(line_wrapper % line for line in x.split("\n")) 

# Preserve line breaks 

if "\n" in x: 

x = "\\begin{array}{l}\n%s\n\\end{array}" % x 

return x 

 

 

def dict_function(x): 

r""" 

Returns the LaTeX code for a dictionary ``x``. 

 

INPUT: 

 

- ``x`` -- a dictionary 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import dict_function 

sage: x,y,z = var('x,y,z') 

sage: print(dict_function({x/2: y^2})) 

\left\{\frac{1}{2} \, x : y^{2}\right\} 

sage: d = {(1,2,x^2): [sin(z^2), y/2]} 

sage: latex(d) 

\left\{\left(1, 2, x^{2}\right) : 

\left[\sin\left(z^{2}\right), \frac{1}{2} \, y\right]\right\} 

""" 

return "".join([r"\left\{", 

", ".join(r"%s : %s" % (latex(key), latex(value)) 

for key, value in iteritems(x)), 

r"\right\}"]) 

 

# One can add to the latex_table in order to install latexing 

# functionality for other types. (Suggested by Robert Kerns of Enthought.) 

 

def float_function(x): 

r""" 

Returns the LaTeX code for a python float ``x``. 

 

INPUT: 

 

- ``x`` -- a python float 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import float_function 

sage: float_function(float(3.14)) 

3.14 

sage: float_function(float(1e-10)) 

1 \times 10^{-10} 

sage: float_function(float(2e10)) 

20000000000.0 

 

TESTS: 

 

Check that :trac:`7356` is fixed:: 

 

sage: latex(float(2e-13)) 

2 \times 10^{-13} 

""" 

from sage.all import RDF 

return latex(RDF(x)) 

 

 

latex_table = {type(None): None_function, 

bool: bool_function, 

dict: dict_function, 

float: float_function, 

list: list_function, 

str: str_function, 

tuple: tuple_function, 

type(NotImplemented): builtin_constant_function, 

type(Ellipsis): builtin_constant_function} 

 

for t in integer_types: 

latex_table[t] = str 

 

 

class LatexExpr(str): 

r""" 

A class for LaTeX expressions. 

 

Normally, objects of this class are created by a :func:`latex` call. It is 

also possible to generate :class:`LatexExpr` directly from a string, which 

must contain valid LaTeX code for typesetting in math mode (without dollar 

signs). In the Sage notebook, use :func:`pretty_print` or the "Typeset" 

checkbox to actually see the typeset LaTeX code; alternatively, from 

either the command-line or the notebook, use the :func:`view` function. 

 

INPUT: 

 

- ``str`` -- a string with valid math mode LaTeX code (or something 

which can be converted to such a string). 

 

OUTPUT: 

 

- :class:`LatexExpr` wrapping the string representation of the input. 

 

EXAMPLES:: 

 

sage: latex(x^20 + 1) 

x^{20} + 1 

sage: LatexExpr(r"\frac{x^2 + 1}{x - 2}") 

\frac{x^2 + 1}{x - 2} 

 

``LatexExpr`` simply converts to string without doing anything 

extra, it does *not* call :func:`latex`:: 

 

sage: latex(ZZ) 

\Bold{Z} 

sage: LatexExpr(ZZ) 

Integer Ring 

 

The result of :func:`latex` is of type ``LatexExpr``:: 

 

sage: L = latex(x^20 + 1) 

sage: L 

x^{20} + 1 

sage: type(L) 

<class 'sage.misc.latex.LatexExpr'> 

 

A ``LatexExpr`` can be converted to a plain string:: 

 

sage: str(latex(x^20 + 1)) 

'x^{20} + 1' 

""" 

def __add__(self, other): 

r""" 

Add a LatexExpr and another LatexExpr (or a string). 

 

EXAMPLES:: 

 

sage: o = LatexExpr(r"\Delta\neq") + LatexExpr(r"\frac{x}{2}"); o 

\Delta\neq \frac{x}{2} 

sage: type(o) 

<class 'sage.misc.latex.LatexExpr'> 

sage: o = LatexExpr(r"\Delta\neq") + r"\frac{x}{2}"; o 

\Delta\neq \frac{x}{2} 

sage: type(o) 

<class 'sage.misc.latex.LatexExpr'> 

 

We add extra space only if it wasn't there yet:: 

 

sage: LatexExpr("foo ") + LatexExpr("bar") 

foo bar 

sage: LatexExpr("foo") + LatexExpr(" bar") 

foo bar 

sage: str(LatexExpr("") + LatexExpr("bar")) 

'bar' 

sage: str(LatexExpr("foo") + LatexExpr("")) 

'foo' 

""" 

left = str(self) 

right = str(other) 

# Add a space if self ends with a non-space and other starts 

# with a non-space 

try: 

if left[-1] != ' ' and right[0] != ' ': 

left += ' ' 

except IndexError: 

pass 

return LatexExpr(left + right) 

 

def __radd__(self, other): 

r""" 

Add a string and a LatexExpr. 

 

EXAMPLES:: 

 

sage: o = "a =" + LatexExpr("b") 

sage: o 

a = b 

sage: type(o) 

<class 'sage.misc.latex.LatexExpr'> 

""" 

return LatexExpr(other) + self 

 

def __repr__(self): 

""" 

Return a string representation of ``self``. 

 

EXAMPLES:: 

 

sage: LatexExpr("abc").__repr__() 

'abc' 

""" 

return str(self) 

 

def _latex_(self): 

""" 

Return a LaTeX representation of ``self``. 

 

EXAMPLES:: 

 

sage: latex(LatexExpr("abc")) # indirect doctest 

abc 

""" 

return str(self) 

 

def has_latex_attr(x): 

""" 

Return ``True`` if ``x`` has a ``_latex_`` attribute, except if ``x`` 

is a ``type``, in which case return ``False``. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import has_latex_attr 

sage: has_latex_attr(identity_matrix(3)) 

True 

sage: has_latex_attr("abc") # strings have no _latex_ method 

False 

 

Types inherit the ``_latex_`` method of the class to which they refer, 

but calling it is broken:: 

 

sage: T = type(identity_matrix(3)); T 

<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'> 

sage: hasattr(T, '_latex_') 

True 

sage: T._latex_() 

Traceback (most recent call last): 

... 

TypeError: descriptor '_latex_' of 'sage.matrix.matrix0.Matrix' object needs an argument 

sage: has_latex_attr(T) 

False 

""" 

return hasattr(x, '_latex_') and not isinstance(x, type) 

 

from sage.structure.sage_object import SageObject 

 

class _Latex_prefs_object(SageObject): 

""" 

An object that holds LaTeX global preferences. 

""" 

def __init__(self, bb=False, delimiters=["(", ")"], 

matrix_column_alignment="r"): 

""" 

Define an object that holds LaTeX global preferences. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import _Latex_prefs_object 

sage: latex_prefs = _Latex_prefs_object() 

sage: TestSuite(latex_prefs).run(skip ="_test_pickling") 

""" 

self._option = {} 

self._option["blackboard_bold"] = bb 

self._option["matrix_delimiters"] = list(delimiters) 

self._option["vector_delimiters"] = list(delimiters) 

self._option["matrix_column_alignment"] = matrix_column_alignment 

self._option["macros"] = "" 

self._option["preamble"] = "" 

self._option["engine"] = "pdflatex" 

self._option["engine_name"] = "LaTeX" 

self._option["mathjax_avoid"] = [] 

 

_Latex_prefs = _Latex_prefs_object() 

 

############################################################## 

# The Latex class is used to make slides and LaTeX output in 

# the Sage Notebook 

######################################### 

 

def latex_extra_preamble(): 

r""" 

Return the string containing the user-configured preamble, 

``sage_latex_macros``, and any user-configured macros. This is 

used in the :meth:`~Latex.eval` method for the :class:`Latex` 

class, and in :func:`_latex_file_`; it follows either 

``LATEX_HEADER`` or ``SLIDE_HEADER`` (defined at the top of this 

file) which is a string containing the documentclass and standard 

usepackage commands. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_extra_preamble 

sage: print(latex_extra_preamble()) 

... 

<BLANKLINE> 

\newcommand{\ZZ}{\Bold{Z}} 

\newcommand{\NN}{\Bold{N}} 

\newcommand{\RR}{\Bold{R}} 

\newcommand{\CC}{\Bold{C}} 

\newcommand{\QQ}{\Bold{Q}} 

\newcommand{\QQbar}{\overline{\QQ}} 

\newcommand{\GF}[1]{\Bold{F}_{#1}} 

\newcommand{\Zp}[1]{\ZZ_{#1}} 

\newcommand{\Qp}[1]{\QQ_{#1}} 

\newcommand{\Zmod}[1]{\ZZ/#1\ZZ} 

\newcommand{\CDF}{\Bold{C}} 

\newcommand{\CIF}{\Bold{C}} 

\newcommand{\CLF}{\Bold{C}} 

\newcommand{\RDF}{\Bold{R}} 

\newcommand{\RIF}{\Bold{I} \Bold{R}} 

\newcommand{\RLF}{\Bold{R}} 

\newcommand{\Bold}[1]{\mathbf{#1}} 

<BLANKLINE> 

""" 

from sage.misc.latex_macros import sage_latex_macros 

return "\n".join([_Latex_prefs._option['preamble'], 

"\n".join(sage_latex_macros()), 

_Latex_prefs._option['macros']]) 

 

def _run_latex_(filename, debug=False, density=150, engine=None, png=False, do_in_background=False): 

""" 

This runs LaTeX on the TeX file "filename.tex". It produces files 

"filename.dvi" (or "filename.pdf"` if engine is either ``pdflatex`` 

or ``xelatex``) and if ``png`` is ``True``, "filename.png". If ``png`` 

is ``True`` and dvipng can't convert the dvi file to png (because of 

postscript specials or other issues), then dvips is called, and the 

PS file is converted to a png file. 

 

INPUT: 

 

- ``filename`` -- string: file to process, including full path 

 

- ``debug`` -- bool (optional, default ``False``): whether to print 

verbose debugging output 

 

- ``density`` -- integer (optional, default 150): how big output 

image is. 

 

- ``engine`` -- string: latex engine to use. 

 

- ``png`` -- bool (optional, default ``False``): whether to produce a 

png file. 

 

- ``do_in_background`` -- bool (optional, default ``False``). Unused, 

kept for backwards compatibility. 

 

OUTPUT: 

 

A string which could be a string starting with 'Error' (if 

there was a problem), or it could be 'pdf' or 'dvi'. If 

engine is latex or ``None``, then a dvi file is created, but if there 

appear to be problems with it (because of PS special commands, for 

example), then a pdf file is created instead. The function 

returns 'dvi' or 'pdf' to indicate which type of file is created. 

(Detecting problems requires that dvipng be installed; if it is 

not, then the dvi file is not checked for problems and 'dvi' is 

returned.) If engine is pdflatex or xelatex and there are no errors, then 

'pdf' is returned. 

 

.. WARNING:: 

 

If ``png`` is ``True``, then when using latex (the default), you 

must have 'dvipng' (or 'dvips' and 'convert') installed on your 

operating system, or this command won't work. When using 

pdflatex or xelatex, you must have 'convert' installed. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import _run_latex_, _latex_file_ 

sage: file = os.path.join(SAGE_TMP, "temp.tex") 

sage: O = open(file, 'w') 

sage: _ = O.write(_latex_file_([ZZ['x'], RR])); O.close() 

sage: _run_latex_(file) # random - depends on whether latex is installed 

'dvi' 

""" 

if engine is None: 

engine = _Latex_prefs._option["engine"] 

 

if not engine or engine == "latex": 

if not have_latex(): 

print("Error: LaTeX does not seem to be installed. Download it from") 

print("ctan.org and try again.") 

return "Error" 

command = "latex" 

# 'suffix' is used in the 'convert' command list 

suffix = "ps" 

return_suffix = "dvi" 

elif engine == "pdflatex": 

if not have_pdflatex(): 

print("Error: PDFLaTeX does not seem to be installed. Download it from") 

print("ctan.org and try again.") 

return "Error" 

command = "pdflatex" 

suffix = "pdf" 

return_suffix = "pdf" 

elif engine == "xelatex": 

if not have_xelatex(): 

print("Error: XeLaTeX does not seem to be installed. Download it from") 

print("ctan.org and try again.") 

return "Error" 

command = "xelatex" 

suffix = "pdf" 

return_suffix = "pdf" 

else: 

raise ValueError("Unsupported LaTeX engine.") 

 

# if png output + latex, check to see if dvipng or convert is installed. 

if png: 

if (not engine or engine == "latex") and not (have_dvipng() or have_convert()): 

print() 

print("Error: neither dvipng nor convert (from the ImageMagick suite)") 

print("appear to be installed. Displaying LaTeX, PDFLaTeX output") 

print("requires at least one of these programs, so please install") 

print("and try again.") 

print() 

print("Go to http://sourceforge.net/projects/dvipng/ and") 

print("http://www.imagemagick.org to download these programs.") 

return "Error" 

# if png output + pdflatex, check to see if convert is installed. 

elif engine == "pdflatex" and not have_convert(): 

print() 

print("Error: convert (from the ImageMagick suite) does not") 

print("appear to be installed. Displaying PDFLaTeX output") 

print("requires this program, so please install and try again.") 

print() 

print("Go to http://www.imagemagick.org to download it.") 

return "Error" 

elif engine == "xelatex" and not have_convert(): 

print() 

print("Error: convert (from the ImageMagick suite) does not") 

print("appear to be installed. Displaying XeLaTeX output") 

print("requires this program, so please install and try again.") 

print() 

print("Go to http://www.imagemagick.org to download it.") 

return "Error" 

# check_validity: check to see if the dvi file is okay by trying 

# to convert to a png file. if this fails, return_suffix will be 

# set to "pdf". return_suffix is the return value for this 

# function. 

# 

# thus if not png output, check validity of dvi output if dvipng 

# or convert is installed. 

else: 

check_validity = have_dvipng() 

# set up filenames, other strings: 

base, filename = os.path.split(filename) 

filename = os.path.splitext(filename)[0] # get rid of extension 

if len(filename.split()) > 1: 

raise ValueError("filename must contain no spaces") 

if not debug: 

redirect = subprocess.PIPE 

else: 

redirect = None 

# if do_in_background: 

# background = ' &' 

# else: 

# background = '' 

 

# Define the commands to be used: 

lt = ['sage-native-execute', command, r'\nonstopmode', r'\input{' + filename + '.tex}'] 

# dvipng is run with the 'picky' option: this means that if 

# there are warnings, no png file is created. 

dvipng = ['sage-native-execute', 'dvipng', '--picky', '-q', '-T', 'tight', 

'-D', str(density), filename + '.dvi', '-o', filename + '.png'] 

 

dvips = ['sage-native-execute', 'dvips', filename + '.dvi'] 

 

ps2pdf = ['sage-native-execute', 'ps2pdf', filename + '.ps'] 

 

# We seem to need a larger size when using convert compared to 

# when using dvipng: 

density = int(1.4 * density / 1.3) 

convert = ['sage-native-execute', 'convert', '-density', 

'{0}x{0}'.format(density), '-trim', filename + '.' + suffix, 

filename + '.png'] 

 

e = False # it is possible to get through the following commands 

# without running a program, so in that case we force error 

 

# our standard way of calling programs here; change this if we want 

# finer-grained analysis of the return code. Think of the output as 

# a boolean: "the command exited normally" 

subpcall = lambda x: not subprocess.call(x, stdout=redirect, 

stderr=redirect, cwd=base) 

if engine == "pdflatex" or engine == "xelatex": 

if debug: 

print(lt) 

if png: 

print(convert) 

e = subpcall(lt) 

if png: 

e = e and subpcall(convert) 

else: # latex 

if (png or check_validity): 

if have_dvipng(): 

if debug: 

print(lt) 

print(dvipng) 

e = subpcall(lt) and subpcall(dvipng) 

dvipng_error = not os.path.exists(os.path.join(base, filename + '.png')) 

# If there is no png file, then either the latex 

# process failed or dvipng failed. Assume that dvipng 

# failed, and try running dvips and convert. (If the 

# latex process failed, then dvips and convert will 

# fail also, so we'll still catch the error.) 

if dvipng_error: 

if png: 

if have_convert(): 

if debug: 

print("'dvipng' failed; trying 'convert' instead...") 

print(dvips) 

print(convert) 

e = subpcall(dvips) and subpcall(convert) 

else: 

print("Error: 'dvipng' failed and 'convert' is not installed.") 

return "Error: dvipng failed." 

else: # not png, i.e., check_validity 

return_suffix = "pdf" 

if debug: 

print("bad dvi file; running dvips and ps2pdf instead...") 

print(dvips) 

print(ps2pdf) 

e = subpcall(dvips) and subpcall(ps2pdf) 

if not e: # error running dvips and/or ps2pdf 

pdflt = lt[:] 

pdflt[1] = 'pdflatex' 

if debug: 

print("error running dvips and ps2pdf; trying pdflatex instead...") 

print(pdflt) 

e = subpcall(pdflt) 

else: # don't have dvipng, so must have convert. run latex, dvips, convert. 

if debug: 

print(lt) 

print(dvips) 

print(convert) 

e = subpcall(lt) and subpcall(dvips) and subpcall(convert) 

if not e: 

print("An error occurred.") 

try: 

print(open(base + '/' + filename + '.log').read()) 

except IOError: 

pass 

return "Error latexing slide." 

return return_suffix 

 

class LatexCall: 

""" 

Typeset Sage objects via a ``__call__`` method to this class, 

typically by calling those objects' ``_latex_`` methods. The 

class :class:`Latex` inherits from this. This class is used in 

:mod:`~sage.misc.latex_macros`, while functions from 

:mod:`~sage.misc.latex_macros` are used in :class:`Latex`, so this 

is here primarily to avoid circular imports. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import LatexCall 

sage: LatexCall()(ZZ) 

\Bold{Z} 

sage: LatexCall().__call__(ZZ) 

\Bold{Z} 

 

This returns an instance of the class :class:`LatexExpr`:: 

 

sage: type(LatexCall()(ZZ)) 

<class 'sage.misc.latex.LatexExpr'> 

""" 

def __call__(self, x, combine_all=False): 

r""" 

Return a :class:`LatexExpr` built out of the argument ``x``. 

 

INPUT: 

 

- ``x`` -- a Sage object 

 

- ``combine_all`` -- boolean (Default: ``False``) If ``combine_all`` 

is ``True`` and the input is a tuple, then it does not return a 

tuple and instead returns a string with all the elements separated by 

a single space. 

 

OUTPUT: 

 

A :class:`LatexExpr` built from ``x`` 

 

EXAMPLES:: 

 

sage: latex(Integer(3)) # indirect doctest 

3 

sage: latex(1==0) 

\mathrm{False} 

sage: print(latex([x,2])) 

\left[x, 2\right] 

 

Check that :trac:`11775` is fixed:: 

 

sage: latex((x,2), combine_all=True) 

x 2 

""" 

if has_latex_attr(x): 

return LatexExpr(x._latex_()) 

try: 

f = latex_table[type(x)] 

if isinstance(x, tuple): 

return LatexExpr(f(x, combine_all=combine_all)) 

return LatexExpr(f(x)) 

except KeyError: 

return LatexExpr(str_function(str(x))) 

 

 

class Latex(LatexCall): 

r"""nodetex 

Enter, e.g., 

 

:: 

 

%latex 

The equation $y^2 = x^3 + x$ defines an elliptic curve. 

We have $2006 = \sage{factor(2006)}$. 

 

in an input cell in the notebook to get a typeset version. Use 

``%latex_debug`` to get debugging output. 

 

Use ``latex(...)`` to typeset a Sage object. Use :class:`LatexExpr` 

to typeset LaTeX code that you create by hand. 

 

Use ``%slide`` instead to typeset slides. 

 

.. WARNING:: 

 

You must have dvipng (or dvips and convert) installed 

on your operating system, or this command won't work. 

 

EXAMPLES:: 

 

sage: latex(x^20 + 1) 

x^{20} + 1 

sage: latex(FiniteField(25,'a')) 

\Bold{F}_{5^{2}} 

sage: latex("hello") 

\text{\texttt{hello}} 

sage: LatexExpr(r"\frac{x^2 - 1}{x + 1} = x - 1") 

\frac{x^2 - 1}{x + 1} = x - 1 

 

LaTeX expressions can be added; note that a space is automatically 

inserted:: 

 

sage: LatexExpr(r"y \neq") + latex(x^20 + 1) 

y \neq x^{20} + 1 

""" 

def __init__(self, debug=False, slide=False, density=150, pdflatex=None, engine=None): 

""" 

Initialize the latex builder. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import Latex 

sage: l = Latex() 

sage: TestSuite(l).run(skip ="_test_pickling") 

""" 

self.__debug = debug 

self.__slide = slide 

self.__pdflatex = pdflatex 

self.__engine = engine 

self.__density = density 

 

def _relation_symbols(self): 

""" 

Returns a dictionary whose keys are attributes of the 

:mod:`operator` module and whose values are the corresponding 

LaTeX expressions. 

 

EXAMPLES:: 

 

sage: import operator 

sage: latex._relation_symbols()[operator.ge] 

' \\geq ' 

""" 

import operator 

return {operator.lt:' < ', operator.le:' \\leq ', 

operator.eq:' = ', operator.ne:' \\neq ', 

operator.ge:' \\geq ', operator.gt:' > '} 

 

def _latex_preparse(self, s, locals): 

r""" 

Replace instances of ``'\sage{x}'`` in ``s`` with the LaTeX version of 

``x`` in the running session. 

 

EXAMPLES:: 

 

sage: s = 2 

sage: sage.misc.latex.Latex()._latex_preparse(r'\sage{s}', locals()) 

'2' 

""" 

i0 = -1 

while True: 

i = s.find('\\sage{') 

if i == -1 or i == i0: 

return s 

i0 = i 

t = s[i+6:] 

j = t.find('}') 

if j == -1: 

return s 

 

var = t[:j] 

try: 

k = str(latex(sage_eval.sage_eval(var, locals))) 

except Exception as msg: 

print(msg) 

k = '\\mbox{\\rm [%s undefined]}'%var 

s = s[:i] + k + t[j+1:] 

 

def eval(self, x, globals, strip=False, filename=None, debug=None, 

density=None, pdflatex=None, engine=None, locals={}): 

r""" 

Compile the formatted tex given by ``x`` as a png and writes the 

output file to the directory given by ``filename``. 

 

INPUT: 

 

- ``globals`` -- a globals dictionary 

 

- ``x`` -- string to evaluate. 

 

- ``strip`` -- ignored 

 

- ``filename`` -- output filename 

 

- ``debug`` -- whether to print verbose debugging 

output 

 

- ``density`` -- how big output image is. 

 

- ``pdflatex`` -- whether to use pdflatex. This is deprecated. Use 

``engine`` option instead. 

 

- ``engine`` -- latex engine to use. Currently latex, pdflatex, and 

xelatex are supported. 

 

- ``locals`` - extra local variables used when 

evaluating Sage code in ``x``. 

 

.. WARNING:: 

 

When using latex (the default), you must have 'dvipng' (or 

'dvips' and 'convert') installed on your operating system, 

or this command will not work. When using pdflatex or xelatex, you 

must have 'convert' installed. 

 

OUTPUT: 

 

If it compiled successfully, this returns an empty string ``''``, 

otherwise it returns ``None``. 

 

EXAMPLES:: 

 

sage: fn = tmp_filename() 

sage: latex.eval("$\\ZZ[x]$", locals(), filename=fn) # not tested 

'' 

sage: latex.eval("\ThisIsAnInvalidCommand", {}) # optional -- ImageMagick 

An error occurred... 

No pages of output... 

""" 

MACROS = latex_extra_preamble() 

 

if density is None: 

density = self.__density 

if filename is None: 

filename = 'sage%s' % random.randint(1, 100) # to defeat browser caches 

else: 

filename = os.path.splitext(filename)[0] # get rid of extension 

base = tmp_dir() 

orig_base, filename = os.path.split(os.path.abspath(filename)) 

if len(filename.split()) > 1: 

raise ValueError("filename must contain no spaces") 

if debug is None: 

debug = self.__debug 

x = self._latex_preparse(x, locals) 

O = open(os.path.join(base, filename + ".tex"), 'w') 

if self.__slide: 

O.write(SLIDE_HEADER) 

O.write(MACROS) 

O.write('\\begin{document}\n\n') 

else: 

O.write(LATEX_HEADER) 

O.write(MACROS) 

O.write('\\begin{document}\n') 

 

O.write(str_to_bytes(x, encoding='utf-8')) 

if self.__slide: 

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

else: 

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

 

O.close() 

if engine is None: 

if self.__engine is None: 

engine = _Latex_prefs._option["engine"] 

else: 

engine = self.__engine 

e = _run_latex_(os.path.join(base, filename + ".tex"), debug=debug, 

density=density, engine=engine, png=True) 

if e.find("Error") == -1: 

shutil.copy(os.path.join(base, filename + ".png"), 

os.path.join(orig_base, filename + ".png")) 

shutil.rmtree(base) 

return '' 

else: 

return 

 

def blackboard_bold(self, t = None): 

r"""nodetex 

Controls whether Sage uses blackboard bold or ordinary bold 

face for typesetting ZZ, RR, etc. 

 

INPUT: 

 

- ``t`` -- boolean or ``None`` 

 

OUTPUT: 

 

If ``t`` is ``None``, return the current setting (``True`` or 

``False``). 

 

If ``t`` is ``True``, use blackboard bold (``\mathbb``); otherwise use 

boldface (``\mathbf``). 

 

EXAMPLES:: 

 

sage: latex.blackboard_bold() 

False 

sage: latex.blackboard_bold(True) 

sage: latex.blackboard_bold() 

True 

sage: latex.blackboard_bold(False) 

""" 

if t is None: 

return _Latex_prefs._option["blackboard_bold"] 

from .latex_macros import sage_configurable_latex_macros 

global sage_configurable_latex_macros 

old = _Latex_prefs._option["blackboard_bold"] 

_Latex_prefs._option["blackboard_bold"] = bool(t) 

if bool(old) != bool(t): 

if old: 

old_macro = "\\newcommand{\\Bold}[1]{\\mathbb{#1}}" 

else: 

old_macro = "\\newcommand{\\Bold}[1]{\\mathbf{#1}}" 

if bool(t): 

macro = "\\newcommand{\\Bold}[1]{\\mathbb{#1}}" 

else: 

macro = "\\newcommand{\\Bold}[1]{\\mathbf{#1}}" 

sage_configurable_latex_macros.remove(old_macro) 

sage_configurable_latex_macros.append(macro) 

 

def matrix_delimiters(self, left=None, right=None): 

r"""nodetex 

Change the left and right delimiters for the LaTeX representation 

of matrices 

 

INPUT: 

 

- ``left``, ``right`` - strings or ``None`` 

 

If both ``left`` and ``right`` are ``None``, then return the 

current delimiters. Otherwise, set the left and/or right 

delimiters, whichever are specified. 

 

Good choices for ``left`` and ``right`` are any delimiters which 

LaTeX understands and knows how to resize; some examples are: 

 

- parentheses: '(', ')' 

- brackets: '[', ']' 

- braces: '\\{', '\\}' 

- vertical lines: '|' 

- angle brackets: '\\langle', '\\rangle' 

 

.. NOTE:: 

 

Putting aside aesthetics, you may combine these in any way 

imaginable; for example, you could set ``left`` to be a 

right-hand bracket ']' and ``right`` to be a right-hand 

brace '\\}', and it will be typeset correctly. 

 

EXAMPLES:: 

 

sage: a = matrix(1, 1, [17]) 

sage: latex(a) 

\left(\begin{array}{r} 

17 

\end{array}\right) 

sage: latex.matrix_delimiters("[", "]") 

sage: latex(a) 

\left[\begin{array}{r} 

17 

\end{array}\right] 

sage: latex.matrix_delimiters(left="\\{") 

sage: latex(a) 

\left\{\begin{array}{r} 

17 

\end{array}\right] 

sage: latex.matrix_delimiters() 

['\\{', ']'] 

 

Restore defaults:: 

 

sage: latex.matrix_delimiters("(", ")") 

""" 

if left is None and right is None: 

return _Latex_prefs._option['matrix_delimiters'] 

else: 

if left is not None: 

_Latex_prefs._option['matrix_delimiters'][0] = left 

if right is not None: 

_Latex_prefs._option['matrix_delimiters'][1] = right 

 

def vector_delimiters(self, left=None, right=None): 

r"""nodetex 

Change the left and right delimiters for the LaTeX representation 

of vectors 

 

INPUT: 

 

- ``left``, ``right`` -- strings or ``None`` 

 

If both ``left`` and ``right`` are ``None``, then return the 

current delimiters. Otherwise, set the left and/or right 

delimiters, whichever are specified. 

 

Good choices for ``left`` and ``right`` are any delimiters which 

LaTeX understands and knows how to resize; some examples are: 

 

- parentheses: '(', ')' 

- brackets: '[', ']' 

- braces: '\\{', '\\}' 

- vertical lines: '|' 

- angle brackets: '\\langle', '\\rangle' 

 

.. NOTE:: 

 

Putting aside aesthetics, you may combine these in any way 

imaginable; for example, you could set ``left`` to be a 

right-hand bracket ']' and ``right`` to be a right-hand 

brace '\\}', and it will be typeset correctly. 

 

EXAMPLES:: 

 

sage: a = vector(QQ, [1,2,3]) 

sage: latex(a) 

\left(1,\,2,\,3\right) 

sage: latex.vector_delimiters("[", "]") 

sage: latex(a) 

\left[1,\,2,\,3\right] 

sage: latex.vector_delimiters(right="\\}") 

sage: latex(a) 

\left[1,\,2,\,3\right\} 

sage: latex.vector_delimiters() 

['[', '\\}'] 

 

Restore defaults:: 

 

sage: latex.vector_delimiters("(", ")") 

""" 

if left is None and right is None: 

return _Latex_prefs._option['vector_delimiters'] 

else: 

if left is not None: 

_Latex_prefs._option['vector_delimiters'][0] = left 

if right is not None: 

_Latex_prefs._option['vector_delimiters'][1] = right 

 

def matrix_column_alignment(self, align=None): 

r"""nodetex 

Changes the column-alignment of the LaTeX representation of 

matrices. 

 

INPUT: 

 

- ``align`` - a string (``'r'`` for right, ``'c'`` for center, 

``'l'`` for left) or ``None``. 

 

OUTPUT: 

 

If ``align`` is ``None``, then returns the current 

alignment-string. Otherwise, set this alignment. 

 

The input ``align`` can be any string which the LaTeX 

``array``-environment understands as a parameter for 

aligning a column. 

 

EXAMPLES:: 

 

sage: a = matrix(1, 1, [42]) 

sage: latex(a) 

\left(\begin{array}{r} 

42 

\end{array}\right) 

sage: latex.matrix_column_alignment('c') 

sage: latex(a) 

\left(\begin{array}{c} 

42 

\end{array}\right) 

sage: latex.matrix_column_alignment('l') 

sage: latex(a) 

\left(\begin{array}{l} 

42 

\end{array}\right) 

 

Restore defaults:: 

 

sage: latex.matrix_column_alignment('r') 

""" 

if align is None: 

return _Latex_prefs._option['matrix_column_alignment'] 

else: 

_Latex_prefs._option['matrix_column_alignment'] = align 

 

@cached_method 

def has_file(self, file_name): 

""" 

INPUT: 

 

- ``file_name`` -- a string 

 

Tests whether the local LaTeX installation includes ``file_name``. 

 

EXAMPLES:: 

 

sage: latex.has_file("article.cls") # optional - latex 

True 

sage: latex.has_file("some_inexistent_file.sty") 

False 

""" 

assert isinstance(file_name, str) 

from subprocess import call, PIPE 

try: 

retcode = call("kpsewhich %s"%file_name, shell=True, stdout=PIPE, stderr=PIPE) 

return (retcode == 0) 

except OSError: 

return False 

 

@cached_method 

def check_file(self, file_name, more_info = ""): 

""" 

INPUT: 

 

- ``file_name`` -- a string 

 

- ``more_info`` -- a string (default: "") 

 

Emit a warning if the local LaTeX installation does not 

include ``file_name``. The string ``more_info`` is appended 

to the warning message. The warning is only emitted the first 

time this method is called. 

 

EXAMPLES:: 

 

sage: latex.check_file("article.cls") # optional - latex 

sage: latex.check_file("some_inexistent_file.sty") 

Warning: `some_inexistent_file.sty` is not part of this computer's TeX installation. 

sage: latex.check_file("some_inexistent_file.sty") 

sage: latex.check_file("some_inexistent_file.sty", "This file is required for blah. It can be downloaded from: http://blah.org/") 

Warning: `some_inexistent_file.sty` is not part of this computer's TeX installation. 

This file is required for blah. It can be downloaded from: http://blah.org/ 

 

This test checks that the bug in :trac:`9091` is fixed:: 

 

sage: latex.check_file("article.cls", "The article class is really critical.") # optional - latex 

""" 

assert isinstance(file_name, str) 

if not self.has_file(file_name): 

print(""" 

Warning: `{}` is not part of this computer's TeX installation.""".format(file_name)) 

if more_info: 

print(more_info) 

 

 

def extra_macros(self, macros=None): 

r"""nodetex 

String containing extra LaTeX macros to use with %latex, 

%html, and %mathjax. 

 

INPUT: 

 

- ``macros`` -- string (default: ``None``) 

 

If ``macros`` is ``None``, return the current string. Otherwise, 

set it to ``macros``. If you want to *append* to the string 

of macros instead of replacing it, use 

:meth:`latex.add_macro <Latex.add_macro>`. 

 

EXAMPLES:: 

 

sage: latex.extra_macros("\\newcommand{\\foo}{bar}") 

sage: latex.extra_macros() 

'\\newcommand{\\foo}{bar}' 

sage: latex.extra_macros("") 

sage: latex.extra_macros() 

'' 

""" 

if macros is None: 

return _Latex_prefs._option['macros'] 

else: 

_Latex_prefs._option['macros'] = macros 

 

def add_macro(self, macro): 

r"""nodetex 

Append to the string of extra LaTeX macros, for use with 

%latex, %html, and %mathjax. 

 

INPUT: 

 

- ``macro`` -- string 

 

EXAMPLES:: 

 

sage: latex.extra_macros() 

'' 

sage: latex.add_macro("\\newcommand{\\foo}{bar}") 

sage: latex.extra_macros() 

'\\newcommand{\\foo}{bar}' 

sage: latex.extra_macros("") # restore to default 

""" 

current = latex.extra_macros() 

if current.find(macro) == -1: 

_Latex_prefs._option['macros'] += macro 

 

def extra_preamble(self, s=None): 

r"""nodetex 

String containing extra preamble to be used with %latex. 

Anything in this string won't be processed by %mathjax. 

 

INPUT: 

 

- ``s`` -- string or ``None`` 

 

If ``s`` is ``None``, return the current preamble. Otherwise, set 

it to ``s``. If you want to *append* to the current extra 

preamble instead of replacing it, use 

:meth:`latex.add_to_preamble <Latex.add_to_preamble>`. 

 

You will almost certainly need to use this when using the 

XeLaTeX engine; see below or the documentation for 

:func:`engine` for a suggested preamble. 

 

EXAMPLES:: 

 

sage: latex.extra_preamble("\\DeclareMathOperator{\\Ext}{Ext}") 

sage: latex.extra_preamble() 

'\\DeclareMathOperator{\\Ext}{Ext}' 

sage: latex.extra_preamble("\\"+r"usepackage{fontspec,xunicode,xltxtra}\setmainfont[Mapping=tex-text]{UnBatang}\setmonofont[Mapping=tex-text]{UnDotum}") 

sage: latex.extra_preamble() 

'\\usepackage{fontspec,xunicode,xltxtra}\\setmainfont[Mapping=tex-text]{UnBatang}\\setmonofont[Mapping=tex-text]{UnDotum}' 

sage: latex.extra_preamble("") 

sage: latex.extra_preamble() 

'' 

""" 

if s is None: 

return _Latex_prefs._option['preamble'] 

else: 

_Latex_prefs._option['preamble'] = s 

 

def add_to_preamble(self, s): 

r"""nodetex 

Append to the string ``s`` of extra LaTeX macros, for use with 

%latex. Anything in this string won't be processed by 

%mathjax. 

 

EXAMPLES:: 

 

sage: latex.extra_preamble() 

'' 

sage: latex.add_to_preamble("\\DeclareMathOperator{\\Ext}{Ext}") 

 

At this point, a notebook cell containing 

 

:: 

 

%latex 

$\Ext_A^*(\GF{2}, \GF{2}) \Rightarrow \pi_*^s*(S^0)$ 

 

will be typeset correctly. 

 

:: 

 

sage: latex.add_to_preamble("\\usepackage{xypic}") 

sage: latex.extra_preamble() 

'\\DeclareMathOperator{\\Ext}{Ext}\\usepackage{xypic}' 

 

Now one can put various xypic diagrams into a %latex cell, such as 

 

:: 

 

%latex 

\[ \xymatrix{ \circ \ar `r[d]^{a} `[rr]^{b} `/4pt[rr]^{c} `[rrr]^{d} 

`_dl[drrr]^{e} [drrr]^{f} & \circ & \circ & \circ \\ \circ & \circ & 

\circ & \circ } \] 

 

Reset the preamble to its default, the empty string:: 

 

sage: latex.extra_preamble('') 

sage: latex.extra_preamble() 

'' 

""" 

current = latex.extra_preamble() 

if current.find(s) == -1: 

_Latex_prefs._option['preamble'] += s 

 

def add_package_to_preamble_if_available(self, package_name): 

r""" 

Adds a ``\usepackage{package_name}`` instruction to the latex 

preamble if not yet present there, and if ``package_name.sty`` 

is available in the LaTeX installation. 

 

INPUT: 

 

- ``package_name`` -- a string 

 

.. SEEALSO:: 

 

- :meth:`add_to_preamble` 

- :meth:`has_file`. 

 

TESTS:: 

 

sage: latex.add_package_to_preamble_if_available("xypic") 

sage: latex.add_package_to_preamble_if_available("nonexistent_package") 

sage: latex.extra_preamble() # optional - latex 

'\\usepackage{xypic}\n' 

sage: latex.extra_preamble('') 

""" 

assert isinstance(package_name, str) 

if self.has_file(package_name+".sty"): 

self.add_to_preamble("\\usepackage{%s}\n"%package_name) 

 

def mathjax_avoid_list(self, L=None): 

r"""nodetex 

List of strings which signal that MathJax should not 

be used when 'view'ing. 

 

INPUT: 

 

- ``L`` -- A list or ``None`` 

 

If ``L`` is ``None``, then return the current list. 

Otherwise, set it to ``L``. If you want to *append* to the 

current list instead of replacing it, use 

:meth:`latex.add_to_mathjax_avoid_list <Latex.add_to_mathjax_avoid_list>`. 

 

EXAMPLES:: 

 

sage: latex.mathjax_avoid_list(["\\mathsf", "pspicture"]) 

sage: latex.mathjax_avoid_list() # display current setting 

['\\mathsf', 'pspicture'] 

sage: latex.mathjax_avoid_list([]) # reset to default 

sage: latex.mathjax_avoid_list() 

[] 

""" 

if L is None: 

return _Latex_prefs._option['mathjax_avoid'] 

else: 

_Latex_prefs._option['mathjax_avoid'] = L 

 

def add_to_mathjax_avoid_list(self, s): 

r"""nodetex 

Add to the list of strings which signal that MathJax should not 

be used when 'view'ing. 

 

INPUT: 

 

- ``s`` -- string; add ``s`` to the list of 'MathJax avoid' strings 

 

If you want to replace the current list instead of adding to 

it, use :meth:`latex.mathjax_avoid_list <Latex.mathjax_avoid_list>`. 

 

EXAMPLES:: 

 

sage: latex.add_to_mathjax_avoid_list("\\mathsf") 

sage: latex.mathjax_avoid_list() # display current setting 

['\\mathsf'] 

sage: latex.add_to_mathjax_avoid_list("tkz-graph") 

sage: latex.mathjax_avoid_list() # display current setting 

['\\mathsf', 'tkz-graph'] 

sage: latex.mathjax_avoid_list([]) # reset to default 

sage: latex.mathjax_avoid_list() 

[] 

""" 

current = latex.mathjax_avoid_list() 

if s not in current: 

_Latex_prefs._option['mathjax_avoid'].append(s) 

 

def engine(self, e = None): 

r""" 

Set Sage to use ``e`` as latex engine when typesetting with 

:func:`view`, in ``%latex`` cells, etc. 

 

INPUT: 

 

- ``e`` -- 'latex', 'pdflatex', 'xelatex' or ``None`` 

 

If ``e`` is ``None``, return the current engine. 

 

If using the XeLaTeX engine, it will almost always be necessary 

to set the proper preamble with :func:`extra_preamble` or 

:func:`add_to_preamble`. For example:: 

 

latex.extra_preamble(r'''\usepackage{fontspec,xunicode,xltxtra} 

\setmainfont[Mapping=tex-text]{some font here} 

\setmonofont[Mapping=tex-text]{another font here}''') 

 

EXAMPLES:: 

 

sage: latex.engine() 

'pdflatex' 

sage: latex.engine("latex") 

sage: latex.engine() 

'latex' 

sage: latex.engine("xelatex") 

sage: latex.engine() 

'xelatex' 

""" 

if e is None: 

return _Latex_prefs._option["engine"] 

 

if e == "latex": 

_Latex_prefs._option["engine"] = "latex" 

_Latex_prefs._option["engine_name"] = "LaTeX" 

elif e == "pdflatex": 

_Latex_prefs._option["engine"] = "pdflatex" 

_Latex_prefs._option["engine_name"] = "PDFLaTeX" 

elif e == "xelatex": 

_Latex_prefs._option["engine"] = e 

_Latex_prefs._option["engine_name"] = "XeLaTeX" 

else: 

raise ValueError("%s is not a supported LaTeX engine. Use latex, pdflatex, or xelatex" % e) 

 

# Note: latex used to be a separate function, which by default was 

# only loaded in command-line mode: in the notebook, all_notebook.py 

# defined (and still defines) latex by 'latex = Latex(density=130)'. 

# Meanwhile, the __call__ method for Latex used to call the latex 

# function. This has been changed around so that the contents of the 

# old latex function are now in Latex.__call__; thus the following 

# assignment. 

 

latex = Latex() 

# Ensure that latex appear in the sphinx doc as a function 

# so that the link :func:`latex` is correctly set up. 

latex.__doc__ = Latex.__call__.__doc__ 

######################################### 

 

def _latex_file_(objects, title='SAGE', debug=False, \ 

sep='', tiny=False, math_left='\\[', 

math_right='\\]', 

extra_preamble=''): 

r"""nodetex 

Produce a string to be used as a LaTeX file, containing a 

representation of each object in objects. 

 

INPUT: 

 

- ``objects`` -- list (or object) 

 

- ``title`` -- string (default: 'Sage'): title for the document 

 

- ``math_left`` -- string (default: '\\['), left delimiter for math mode 

 

- ``math_right`` -- string (default: '\\]'), right delimiter for math mode 

 

- ``debug`` -- bool (default: False): print verbose output 

 

- ``sep`` -- string (default: ''): separator between math objects 

 

- ``tiny`` -- bool (default: False): use 'tiny' font. 

 

- ``extra_preamble`` -- string (default: ''): extra LaTeX commands, 

inserted before "\\begin{document}" 

 

This creates a string intended to be a LaTeX file containing the 

LaTeX representations of objects. It contains the following: 

 

- a header (with documentclass and usepackage commands) 

 

- ``extra_preamble`` 

 

- the title (centered) 

 

- a size specification if ``tiny`` is ``True`` 

 

- LaTeX representation of the first element of ``objects``, 

surrounded by ``math_left`` and ``math_right`` 

 

Then if ``objects`` contains more than one element, for each 

remaining element: 

 

- the string ``sep``: you can use this, for example, to add 

vertical space between objects with ``sep='\\vspace{15mm}'``, 

or to add a horizontal line between objects with 

``sep='\\hrule'``, or to insert a page break between objects 

with ``sep='\\newpage'``. 

 

- the LaTeX representation of the element 

 

The string ends with '\\end{document}'. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import _latex_file_ 

sage: _latex_file_(3, title="The number three") 

'\\documentclass{article}...\\begin{document}\n\\begin{center}{\\Large\\bf The number three}\\end{center}\n\\vspace{40mm}\\[3\\]\n\\end{document}' 

sage: _latex_file_([7, 8, 9], title="Why was six afraid of seven?", sep='\\vfill\\hrule\\vfill') 

'\\documentclass{article}...\\begin{document}\n\\begin{center}{\\Large\\bf Why was six afraid of seven?}\\end{center}\n\\vspace{40mm}\\[7\\]\n\n\\vfill\\hrule\\vfill\n\n\\[8\\]\n\n\\vfill\\hrule\\vfill\n\n\\[9\\]\n\\end{document}' 

 

TESTS: 

 

This makes sure that latex is called only once on an object:: 

 

sage: class blah(): 

....: def _latex_(x): 

....: print("coucou") 

....: return "x" 

sage: latex(blah()) 

coucou 

x 

sage: s = sage.misc.latex._latex_file_(blah()) 

coucou 

""" 

process = True 

if has_latex_attr(objects): 

objects = [objects] 

 

if not isinstance(objects, list): 

objects = [objects] 

 

if tiny: 

size='\\tiny\n' 

else: 

size='' 

 

formatted_title = "\n\\begin{center}{\\Large\\bf %s}\\end{center}\n"%str(title) if title else "" 

s = '%s\n\\begin{document}%s%s'%(extra_preamble, formatted_title, size) 

 

if title: 

s += '\\vspace{40mm}' 

if process: 

for i in range(len(objects)): 

x = objects[i] 

L = latex(x) 

if '\\begin{pgfpicture}' in L: 

# Resize the pgf figure to the text width if larger. 

s += r'\begingroup\makeatletter\@ifundefined{pgffigure}{\newsavebox{\pgffigure}}{}\makeatother\endgroup' 

s += r'\begin{lrbox}{\pgffigure}' + '\n' 

s += '%s'%L 

s += r'\end{lrbox}' 

s += r'\resizebox{\ifdim\width>\textwidth\textwidth\else\width\fi}{!}{\usebox{\pgffigure}}' + '\n' 

elif not '\\begin{verbatim}' in L: 

s += '%s%s%s'%(math_left, L, math_right) 

else: 

s += '%s'%L 

if i < len(objects)-1: 

s += '\n\n%s\n\n'%sep 

else: 

s += "\n\n".join([str(x) for x in objects]) 

 

# latex_extra_preamble() is called here and not before because some objects 

# may require additional packages to be displayed in LaTeX. Hence, the call 

# to latex(x) in the previous loop may change the result of 

# latex_extra_preamble() 

MACROS = latex_extra_preamble() 

s = LATEX_HEADER + '\n' + MACROS + s + '\n\\end{document}' 

 

if debug: 

print(s) 

 

return s 

 

class MathJaxExpr: 

""" 

An arbitrary MathJax expression that can be nicely concatenated. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJaxExpr 

sage: MathJaxExpr("a^{2}") + MathJaxExpr("x^{-1}") 

a^{2}x^{-1} 

""" 

def __init__(self, y): 

""" 

Initialize a MathJax expression. 

 

INPUT: 

 

- ``y`` - a string 

 

Note that no error checking is done on the type of ``y``. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJaxExpr 

sage: jax = MathJaxExpr(3); jax # indirect doctest 

3 

sage: TestSuite(jax).run(skip ="_test_pickling") 

""" 

self.__y = y 

 

def __repr__(self): 

""" 

Print representation. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJaxExpr 

sage: jax = MathJaxExpr('3') 

sage: jax.__repr__() 

'3' 

""" 

return str(self.__y) 

 

def __add__(self, y): 

""" 

'Add' MathJaxExpr ``self`` to ``y``. This concatenates them 

(assuming that they're strings). 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJaxExpr 

sage: j3 = MathJaxExpr('3') 

sage: jx = MathJaxExpr('x') 

sage: j3 + jx 

3x 

""" 

return MathJaxExpr(self.__y + y) 

 

def __radd__(self, y): 

""" 

'Add' MathJaxExpr ``y`` to ``self``. This concatenates them 

(assuming that they're strings). 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJaxExpr 

sage: j3 = MathJaxExpr('3') 

sage: jx = MathJaxExpr('x') 

sage: j3.__radd__(jx) 

x3 

""" 

return MathJaxExpr(y + self.__y) 

 

class MathJax: 

r""" 

Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJax 

sage: MathJax()(3) 

<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html> 

sage: MathJax()(ZZ) 

<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html> 

""" 

 

def __call__(self, x, combine_all=False): 

r""" 

Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`. 

 

INPUT: 

 

- ``x`` - a Sage object 

 

- ``combine_all`` - boolean (Default: ``False``): If ``combine_all`` is 

``True`` and the input is a tuple, then it does not return a tuple 

and instead returns a string with all the elements separated by 

a single space. 

 

OUTPUT: 

 

A :calss:`MathJaxExpr` 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJax 

sage: MathJax()(3) 

<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html> 

sage: str(MathJax().eval(ZZ['x'], mode='display')) == str(MathJax()(ZZ['x'])) 

True 

""" 

return self.eval(x, combine_all=combine_all) 

 

def eval(self, x, globals=None, locals=None, mode='display', 

combine_all=False): 

r""" 

Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`. 

 

INPUT: 

 

- ``x`` - a Sage object 

 

- ``globals`` - a globals dictionary 

 

- ``locals`` - extra local variables used when 

evaluating Sage code in ``x``. 

 

- ``mode`` - string (optional, default ``'display'``): 

``'display'`` for displaymath, ``'inline'`` for inline 

math, or ``'plain'`` for just the LaTeX code without the 

surrounding html and script tags. 

 

- ``combine_all`` - boolean (Default: ``False``): If ``combine_all`` is 

``True`` and the input is a tuple, then it does not return a tuple 

and instead returns a string with all the elements separated by 

a single space. 

 

OUTPUT: 

 

A :class:`MathJaxExpr` 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import MathJax 

sage: MathJax().eval(3, mode='display') 

<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html> 

sage: MathJax().eval(3, mode='inline') 

<html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html> 

sage: MathJax().eval(type(3), mode='inline') 

<html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\verb|<type|\phantom{\verb!x!}\verb|'sage.rings.integer.Integer'>|</script></html> 

""" 

# Get a regular LaTeX representation of x 

x = latex(x, combine_all=combine_all) 

 

# The following block, hopefully, can be removed in some future MathJax. 

prefix = r"\text{\texttt{" 

parts = x.split(prefix) 

for i, part in enumerate(parts): 

if i == 0: 

continue # Nothing to do with the head part 

n = 1 

for closing, c in enumerate(part): 

if c == "{" and part[closing - 1] != "\\": 

n += 1 

if c == "}" and part[closing - 1] != "\\": 

n -= 1 

if n == -1: 

break 

# part should end in "}}", so omit the last two characters 

# from y 

y = part[:closing-1] 

for delimiter in """|"'`#%&,.:;?!@_~^+-/\=<>()[]{}0123456789E""": 

if delimiter not in y: 

break 

if delimiter == "E": 

# y is too complicated 

delimiter = "|" 

y = "(complicated string)" 

wrapper = r"\verb" + delimiter + "%s" + delimiter 

spacer = r"\phantom{\verb!%s!}" 

y = y.replace("{ }", " ").replace("{-}", "-") 

for c in r"#$%&\^_{}~": 

char_wrapper = r"{\char`\%s}" % c 

y = y.replace(char_wrapper, c) 

subparts = [] 

nspaces = 0 

for subpart in y.split(" "): 

if subpart == "": 

nspaces += 1 

continue 

if nspaces > 0: 

subparts.append(spacer % ("x" * nspaces)) 

nspaces = 1 

subparts.append(wrapper % subpart) 

# There is a bug with omitting empty lines in arrays 

if not y: 

subparts.append(spacer % "x") 

subparts.append(part[closing + 1:]) 

parts[i] = "".join(subparts) 

from sage.misc.latex_macros import sage_configurable_latex_macros 

latex_string = ''.join( 

sage_configurable_latex_macros + 

[_Latex_prefs._option['macros']] + 

parts 

) 

if mode == 'display': 

html = '<html><script type="math/tex; mode=display">{0}</script></html>' 

elif mode == 'inline': 

html = '<html><script type="math/tex">{0}</script></html>' 

elif mode == 'plain': 

return latex_string 

else: 

raise ValueError("mode must be either 'display', 'inline', or 'plain'") 

return MathJaxExpr(html.format(latex_string)) 

 

def view(objects, title='Sage', debug=False, sep='', tiny=False, 

pdflatex=None, engine=None, viewer=None, tightpage=True, margin=None, 

mode='inline', combine_all=False, **kwds): 

r"""nodetex 

Compute a latex representation of each object in objects, compile, 

and display typeset. If used from the command line, this requires 

that latex be installed. 

 

INPUT: 

 

- ``objects`` -- list (or object) 

 

- ``title`` -- string (default: ``'Sage'``): title for the 

document 

 

- ``debug`` -- bool (default: ``False``): print verbose 

output 

 

- ``sep`` -- string (default: ''): separator between 

math objects 

 

- ``tiny`` -- bool (default: ``False``): use tiny font. 

 

- ``pdflatex`` -- bool (default: ``False``): use pdflatex. This is 

deprecated. Use ``'engine'`` option instead. 

 

- ``engine`` -- string or ``None`` (default: ``None``). Can take the 

following values: 

 

- ``None`` -- the value defined in the LaTeX global preferences 

``latex.engine()`` is used. 

 

- ``'pdflatex'`` -- compilation does tex -> pdf 

 

- ``'xelatex'`` -- compilation does tex -> pdf 

 

- ``'latex'`` -- compilation first tries tex -> dvi -> png and if an 

error occurs then tries dvi -> ps -> pdf. This is slower than 

``'pdflatex'`` and known to be broken when overfull hbox are detected. 

 

- ``viewer`` -- string or ``None`` (default: ``None``): specify a viewer 

to use; currently the only options are ``None`` and ``'pdf'``. 

 

- ``tightpage`` -- bool (default: ``True``): use the LaTeX package 

'preview' with the 'tightpage' option. 

 

- ``margin`` -- float or ``None`` (default: ``None``): adds a margin 

of ``margin`` mm; has no affect if the option ``tightpage`` is 

``False``. 

 

- ``mode`` -- string (default: ``'inline'``): ``'display'`` for 

displaymath or ``'inline'`` for inline math 

 

- ``combine_all`` -- bool (default: ``False``): If ``combine_all`` is 

``True`` and the input is a tuple, then it does not return a tuple and 

instead returns a string with all the elements separated by a single 

space. 

 

OUTPUT: 

 

Display typeset objects. 

 

This function behaves differently depending on whether in notebook 

mode or not. 

 

If not in notebook mode, the output is displayed in a separate 

viewer displaying a dvi (or pdf) file, with the following: the 

title string is printed, centered, at the top. Beneath that, each 

object in ``objects`` is typeset on its own line, with the string 

``sep`` inserted between these lines. 

 

The value of ``sep`` is inserted between each element of the list 

``objects``; you can, for example, add vertical space between 

objects with ``sep='\\vspace{15mm}'``, while ``sep='\\hrule'`` 

adds a horizontal line between objects, and ``sep='\\newpage'`` 

inserts a page break between objects. 

 

If ``pdflatex`` is ``True``, then the latex engine is set to 

pdflatex. 

 

If the ``engine`` is either ``pdflatex`` or ``xelatex``, it produces 

a pdf file. Otherwise, it produces a dvi file, and if the program dvipng is 

installed, it checks the dvi file by trying to convert it to a png 

file. If this conversion fails, the dvi file probably contains 

some postscript special commands or it has other issues which 

might make displaying it a problem; in this case, the file is 

converted to a pdf file, which is then displayed. 

 

Setting ``viewer`` to ``'pdf'`` forces the use of a separate 

viewer, even in notebook mode. This also sets the latex engine to be 

``pdflatex`` if the current engine is latex. 

 

Setting the option ``tightpage`` to ``True`` (this is the default setting) 

tells LaTeX to use the package 'preview' with the 'tightpage' option. 

Then, each object is typeset in its own page, and that page is cropped to 

exactly the size of the object. This is typically useful for very 

large pictures (like graphs) generated with tikz. This only works 

when using a separate viewer. Note that the object are currently 

typeset in plain math mode rather than displaymath, because the 

latter imposes a limit on the width of the picture. Technically, 

``tightpage`` adds :: 

 

\\usepackage[tightpage,active]{preview} 

\\PreviewEnvironment{page} 

 

to the LaTeX preamble, and replaces the ``\\[`` and ``\\]`` around 

each object by ``\\begin{page}$`` and ``$\\end{page}``. 

Setting ``tightpage`` to ``False`` turns off this behavior and provides 

the latex output as a full page. If ``tightpage`` is set to ``True``, 

the ``Title`` is ignored. 

 

If in notebook mode with ``viewer`` equal to ``None``, this 

usually uses MathJax -- see the next paragraph for the exception -- 

to display the output in the notebook. Only the first argument, 

``objects``, is relevant; the others are ignored. If ``objects`` 

is a list, each object is printed on its own line. 

 

In the notebook, this *does* *not* use MathJax if the LaTeX code 

for ``objects`` contains a string in 

:meth:`latex.mathjax_avoid_list() <Latex.mathjax_avoid_list>`. In 

this case, it creates and displays a png file. 

 

EXAMPLES:: 

 

sage: sage.misc.latex.EMBEDDED_MODE = True 

sage: view(3) 

<html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html> 

sage: view(3, mode='display') 

<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html> 

sage: view((x,2), combine_all=True) # trac 11775 

<html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}x 2</script></html> 

sage: sage.misc.latex.EMBEDDED_MODE = False 

 

TESTS:: 

 

sage: from sage.misc.latex import _run_latex_, _latex_file_ 

sage: g = sage.misc.latex.latex_examples.graph() 

sage: latex.add_to_preamble(r"\usepackage{tkz-graph}") 

sage: file = os.path.join(SAGE_TMP, "temp.tex") 

sage: O = open(file, 'w'); _ = O.write(_latex_file_(g)); O.close() 

sage: _run_latex_(file, engine="pdflatex") # optional - latex 

'pdf' 

 

sage: view(4, margin=5, debug=True) # not tested 

\documentclass{article} 

... 

\usepackage[tightpage,active]{preview} 

\PreviewEnvironment{page} 

\setlength\PreviewBorder{5.000000mm} 

\begin{document}\begin{page}$4$\end{page} 

\end{document} 

... 

 

sage: view(4, debug=True) # not tested 

\documentclass{article} 

... 

\usepackage[tightpage,active]{preview} 

\PreviewEnvironment{page} 

\begin{document}\begin{page}$4$\end{page} 

\end{document} 

... 

 

 

sage: latex.extra_preamble('') # reset the preamble 

 

sage: view(4, engine="garbage") 

Traceback (most recent call last): 

... 

ValueError: Unsupported LaTeX engine. 

sage: sage.misc.latex.EMBEDDED_MODE = True 

sage: view(4, engine="garbage", viewer="pdf") 

Traceback (most recent call last): 

... 

ValueError: Unsupported LaTeX engine. 

 

""" 

 

if tightpage: 

if margin is None: 

margin_str = "" 

else: 

margin_str = '\n\\setlength\\PreviewBorder{%fmm}' % margin 

latex_options = {'extra_preamble': 

'\\usepackage[tightpage,active]{preview}\n' + 

'\\PreviewEnvironment{page}%s' % margin_str, 

'math_left': '\\begin{page}$', 

'math_right': '$\\end{page}'} 

title = None 

else: 

latex_options = {} 

 

s = _latex_file_(objects, title=title, sep=sep, tiny=tiny, debug=debug, **latex_options) 

if engine is None: 

engine = _Latex_prefs._option["engine"] 

if pdflatex or (viewer == "pdf" and engine == "latex"): 

engine = "pdflatex" 

# notebook 

if EMBEDDED_MODE and viewer is None: 

MathJax_okay = True 

for t in latex.mathjax_avoid_list(): 

if s.find(t) != -1: 

MathJax_okay = False 

if not MathJax_okay: 

break 

if MathJax_okay: # put comma at end of line below? 

print(MathJax().eval(objects, mode=mode, combine_all=combine_all)) 

else: 

base_dir = os.path.abspath("") 

from sage.misc.temporary_file import graphics_filename 

png_file = graphics_filename() 

png_link = "cell://" + png_file 

png(objects, os.path.join(base_dir, png_file), 

debug=debug, engine=engine) 

print('<html><img src="{}"></html>'.format(png_link)) # put comma at end of line? 

return 

# command line or notebook with viewer 

tmp = tmp_dir('sage_viewer') 

tex_file = os.path.join(tmp, "sage.tex") 

open(tex_file,'w').write(s) 

suffix = _run_latex_(tex_file, debug=debug, engine=engine, png=False) 

if suffix == "pdf": 

from sage.misc.viewer import pdf_viewer 

viewer = pdf_viewer() 

elif suffix == "dvi": 

from sage.misc.viewer import dvi_viewer 

viewer = dvi_viewer() 

else: 

print("Latex error") 

return 

output_file = os.path.join(tmp, "sage." + suffix) 

# this should get changed if we switch the stuff in misc.viewer to 

# producing lists 

if not viewer.startswith('sage-native-execute '): 

viewer = 'sage-native-execute ' + viewer 

if debug: 

print('viewer: "{}"'.format(viewer)) 

subprocess.call('%s %s' % (viewer, output_file), shell=True, 

stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

return 

 

def png(x, filename, density=150, debug=False, 

do_in_background=False, tiny=False, pdflatex=True, engine='pdflatex'): 

""" 

Create a png image representation of ``x`` and save to the given 

filename. 

 

INPUT: 

 

- ``x`` -- object to be displayed 

 

- ``filename`` -- file in which to save the image 

 

- ``density`` -- integer (default: 150) 

 

- ``debug`` -- bool (default: ``False``): print verbose 

output 

 

- ``do_in_background`` -- bool (default: ``False``): Unused, 

kept for backwards compatibility 

 

- ``tiny`` -- bool (default: ``False``): use 'tiny' font 

 

- ``pdflatex`` -- bool (default: ``True``): use pdflatex. This option is 

deprecated. Use ``engine`` option instead. See below. 

 

- ``engine`` -- (default: ``'pdflatex'``) ``'latex'``, ``'pdflatex'``, 

or ``'xelatex'`` 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import png 

sage: png(ZZ[x], os.path.join(SAGE_TMP, "zz.png")) # random - error if no latex 

""" 

if not pdflatex: 

engine = "latex" 

import sage.plot.all 

if sage.plot.graphics.is_Graphics(x): 

x.save(filename) 

return 

# if not graphics: create a string of latex code to write in a file 

s = _latex_file_([x], math_left='$\\displaystyle', math_right='$', title='', 

debug=debug, tiny=tiny, 

extra_preamble='\\textheight=2\\textheight') 

# path name for permanent png output 

abs_path_to_png = os.path.abspath(filename) 

# temporary directory to store stuff 

tmp = tmp_dir('sage_viewer') 

tex_file = os.path.join(tmp, "sage.tex") 

png_file = os.path.join(tmp, "sage.png") 

# write latex string to file 

open(tex_file,'w').write(s) 

# run latex on the file, producing png output to png_file 

e = _run_latex_(tex_file, density=density, debug=debug, 

png=True, engine=engine) 

if e.find("Error") == -1: 

# if no errors, copy png_file to the appropriate place 

shutil.copy(png_file, abs_path_to_png) 

else: 

print("Latex error") 

if debug: 

return s 

return 

 

def coeff_repr(c): 

r""" 

LaTeX string representing coefficients in a linear combination. 

 

INPUT: 

 

- ``c`` -- a coefficient (i.e., an element of a ring) 

 

OUTPUT: 

 

A string 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import coeff_repr 

sage: coeff_repr(QQ(1/2)) 

'\\frac{1}{2}' 

sage: coeff_repr(-x^2) 

'\\left(-x^{2}\\right)' 

""" 

try: 

return c._latex_coeff_repr() 

except AttributeError: 

pass 

if isinstance(c, integer_types + (float,)): 

return str(c) 

s = latex(c) 

if s.find("+") != -1 or s.find("-") != -1: 

return "(%s)" % s 

return s 

 

def repr_lincomb(symbols, coeffs): 

r""" 

Compute a latex representation of a linear combination of some 

formal symbols. 

 

INPUT: 

 

- ``symbols`` -- list of symbols 

 

- ``coeffs`` -- list of coefficients of the symbols 

 

OUTPUT: 

 

A string 

 

EXAMPLES:: 

 

sage: t = PolynomialRing(QQ, 't').0 

sage: from sage.misc.latex import repr_lincomb 

sage: repr_lincomb(['a', 's', ''], [-t, t - 2, t^12 + 2]) 

'-t\\text{\\texttt{a}} + \\left(t - 2\\right)\\text{\\texttt{s}} + \\left(t^{12} + 2\\right)' 

sage: repr_lincomb(['a', 'b'], [1,1]) 

'\\text{\\texttt{a}} + \\text{\\texttt{b}}' 

 

Verify that a certain corner case works (see :trac:`5707` and 

:trac:`5766`):: 

 

sage: repr_lincomb([1,5,-3],[2,8/9,7]) 

'2\\cdot 1 + \\frac{8}{9}\\cdot 5 + 7\\cdot -3' 

 

Verify that :trac:`17299` (latex representation of modular symbols) 

is fixed:: 

 

sage: x = EllipticCurve('64a1').modular_symbol_space(sign=1).basis()[0] 

sage: from sage.misc.latex import repr_lincomb 

sage: latex(x.modular_symbol_rep()) 

\left\{\frac{-1}{3}, \frac{-1}{4}\right\} - \left\{\frac{1}{5}, \frac{1}{4}\right\} 

 

Verify that it works when the symbols are numbers:: 

 

sage: x = FormalSum([(1,2),(3,4)]) 

sage: latex(x) 

2 + 3\cdot 4 

 

Verify that it works when ``bv in CC`` raises an error:: 

 

sage: x = FormalSum([(1,'x'),(2,'y')]) 

sage: latex(x) 

\text{\texttt{x}} + 2\text{\texttt{y}} 

""" 

s = "" 

first = True 

i = 0 

 

from sage.rings.all import CC 

 

for c in coeffs: 

bv = symbols[i] 

b = latex(bv) 

if c != 0: 

if c == 1: 

if first: 

s += b 

else: 

s += " + %s" % b 

else: 

coeff = coeff_repr(c) 

if coeff == "-1": 

coeff = "-" 

if first: 

coeff = str(coeff) 

else: 

coeff = " + %s" % coeff 

# this is a hack: i want to say that if the symbol 

# happens to be a number, then we should put a 

# multiplication sign in 

try: 

if bv in CC: 

s += "%s\cdot %s" % (coeff, b) 

else: 

s += "%s%s" % (coeff, b) 

except Exception: 

s += "%s%s" % (coeff, b) 

first = False 

i += 1 

if first: 

s = "0" 

s = s.replace("+ -","- ") 

return s 

 

 

def pretty_print_default(enable=True): 

r""" 

Enable or disable default pretty printing. Pretty printing means 

rendering things so that MathJax or some other latex-aware front end 

can render real math. 

 

This function is pretty useless without the notebook, it shoudn't 

be in the global namespace. 

 

INPUT: 

 

- ``enable`` -- bool (optional, default ``True``). If ``True``, turn on 

pretty printing; if ``False``, turn it off. 

 

EXAMPLES:: 

 

sage: pretty_print_default(True) 

sage: 'foo' 

\newcommand{\Bold}[1]{\mathbf{#1}}\verb|foo| 

sage: pretty_print_default(False) 

sage: 'foo' 

'foo' 

""" 

from sage.repl.rich_output import get_display_manager 

dm = get_display_manager() 

dm.preferences.text = 'latex' if enable else None 

 

 

common_varnames = ['alpha', 

'beta', 

'gamma', 

'Gamma', 

'delta', 

'Delta', 

'epsilon', 

'zeta', 

'eta', 

'theta', 

'Theta', 

'iota', 

'kappa', 

'lambda', 

'Lambda', 

'mu', 

'nu', 

'xi', 

'Xi', 

'pi', 

'Pi', 

'rho', 

'sigma', 

'Sigma', 

'tau', 

'upsilon', 

'phi', 

'Phi', 

'varphi', 

'chi', 

'psi', 

'Psi', 

'omega', 

'Omega', 

'ast', 

'bullet', 

'circ', 

'times', 

'star'] 

 

def latex_varify(a, is_fname=False): 

r""" 

Convert a string ``a`` to a LaTeX string: if it's an element of 

``common_varnames``, then prepend a backslash. If ``a`` consists 

of a single letter, then return it. Otherwise, return 

either "{\\rm a}" or "\\mbox{a}" if "is_fname" flag is ``True`` 

or ``False``. 

 

INPUT: 

 

- ``a`` -- string 

 

OUTPUT: 

 

A string 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_varify 

sage: latex_varify('w') 

'w' 

sage: latex_varify('aleph') 

'\\mathit{aleph}' 

sage: latex_varify('aleph', is_fname=True) 

'{\\rm aleph}' 

sage: latex_varify('alpha') 

'\\alpha' 

sage: latex_varify('ast') 

'\\ast' 

 

TESTS: 

 

sage: abc = var('abc') 

sage: latex((abc/(abc+1)+42)/(abc-1)) # trac #15870 

\frac{\frac{\mathit{abc}}{\mathit{abc} + 1} + 42}{\mathit{abc} - 1} 

""" 

if a in common_varnames: 

return "\\" + a 

elif len(a) == 0: 

return '' 

elif len(a) == 1: 

return a 

elif is_fname is True: 

return '{\\rm %s}'%a 

else: 

return '\\mathit{%s}'%a 

 

def latex_variable_name(x, is_fname=False): 

r""" 

Return latex version of a variable name. 

 

Here are some guiding principles for usage of this function: 

 

1. If the variable is a single letter, that is the latex version. 

 

2. If the variable name is suffixed by a number, we put the number 

in the subscript. 

 

3. If the variable name contains an '_' we start the subscript at 

the underscore. Note that #3 trumps rule #2. 

 

4. If a component of the variable is a Greek letter, escape it 

properly. 

 

5. Recurse nicely with subscripts. 

 

Refer to the examples section for how these rules might play out in 

practice. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_variable_name 

sage: latex_variable_name('a') 

'a' 

sage: latex_variable_name('abc') 

'\\mathit{abc}' 

sage: latex_variable_name('sigma') 

'\\sigma' 

sage: latex_variable_name('sigma_k') 

'\\sigma_{k}' 

sage: latex_variable_name('sigma389') 

'\\sigma_{389}' 

sage: latex_variable_name('beta_00') 

'\\beta_{00}' 

sage: latex_variable_name('Omega84') 

'\\Omega_{84}' 

sage: latex_variable_name('sigma_alpha') 

'\\sigma_{\\alpha}' 

sage: latex_variable_name('nothing1') 

'\\mathit{nothing}_{1}' 

sage: latex_variable_name('nothing1', is_fname=True) 

'{\\rm nothing}_{1}' 

sage: latex_variable_name('nothing_abc') 

'\\mathit{nothing}_{\\mathit{abc}}' 

sage: latex_variable_name('nothing_abc', is_fname=True) 

'{\\rm nothing}_{{\\rm abc}}' 

sage: latex_variable_name('alpha_beta_gamma12') 

'\\alpha_{\\beta_{\\gamma_{12}}}' 

sage: latex_variable_name('x_ast') 

'x_{\\ast}' 

 

TESTS:: 

 

sage: latex_variable_name('_C') # trac #16007 

'C' 

sage: latex_variable_name('_K1') 

'K_{1}' 

""" 

underscore = x.find("_") 

if underscore == -1: 

import re 

# * The "\d|[.,]" means "decimal digit" or period or comma 

# * The "+" means "1 or more" 

# * The "$" means "at the end of the line" 

m = re.search('(\d|[.,])+$',x) 

if m is None: 

prefix = x 

suffix = None 

else: 

prefix = x[:m.start()] 

suffix = x[m.start():] 

else: 

prefix = x[:underscore] 

suffix = x[underscore+1:] 

if prefix == '': 

from sage.calculus.calculus import symtable 

for sym in symtable.values(): 

if sym[0] == '_' and sym[1:] == suffix: 

return latex_variable_name(suffix) 

if suffix and len(suffix) > 0: 

# handle the suffix specially because it very well might be numeric 

# I use strip to avoid using regex's -- It makes it a bit faster (and the code is more comprehensible to non-regex'ed people) 

if suffix.strip("1234567890")!="": 

suffix = latex_variable_name(suffix, is_fname) # recurse to deal with recursive subscripts 

return '%s_{%s}'%(latex_varify(prefix, is_fname), suffix) 

else: 

return latex_varify(prefix, is_fname) 

 

class LatexExamples(): 

r""" 

A catalogue of Sage objects with complicated ``_latex_`` methods. 

Use these for testing :func:`latex`, :func:`view`, the Typeset 

button in the notebook, etc. 

 

The classes here only have ``__init__``, ``_repr_``, and ``_latex_`` 

methods. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: K = latex_examples.knot() 

sage: K 

LaTeX example for testing display of a knot produced by xypic... 

sage: latex(K) 

\vtop{\vbox{\xygraph{!{0;/r1.5pc/:} 

[u] !{\vloop<(-.005)\khole||\vcrossneg \vunder- } 

[] !{\ar @{-}@'{p-(1,0)@+}+(-1,1)} 

[ul] !{\vcap[3]>\khole} 

[rrr] !{\ar @{-}@'{p-(0,1)@+}-(1,1)} 

}}} 

""" 

class graph(SageObject): 

""" 

LaTeX example for testing display of graphs. See its string 

representation for details. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: G = latex_examples.graph() 

sage: G 

LaTeX example for testing display of graphs... 

""" 

 

def __init__(self): 

""" 

See the string representation for complete documentation. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: type(latex_examples.graph()) 

<class 'sage.misc.latex.graph'> 

""" 

pass 

 

def _repr_(self): 

""" 

String representation 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: G = latex_examples.graph() 

sage: len(G._repr_()) > 300 

True 

""" 

return r"""LaTeX example for testing display of graphs. 

 

To use, first try calling 'view' on this object -- it won't work. 

Now, make sure that you have the most recent version of the TeX 

package pgf installed, along with the LaTeX package tkz-graph. Run 

'latex.add_to_preamble("\\usepackage{tkz-graph}")', and try viewing it 

again. From the command line, this should pop open a nice window with 

a picture of a graph. In the notebook, it still won't work. Finally, 

run 'latex.add_to_mathjax_avoid_list("tikzpicture")' and try again 

from the notebook -- you should get a nice picture. 

 

(LaTeX code taken from http://altermundus.com/pages/tkz/) 

""" 

 

def _latex_(self): 

""" 

LaTeX representation 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.graph()._latex_()) > 500 

True 

sage: len(latex_examples.graph()._latex_()) > 600 

False 

""" 

return r"""\begin{tikzpicture}[node distance = 4 cm] 

\GraphInit[vstyle=Shade] 

\tikzset{LabelStyle/.style = {draw, 

fill = yellow, 

text = red}} 

\Vertex{A} 

\EA(A){B} 

\EA(B){C} 

\tikzset{node distance = 8 cm} 

\NO(B){D} 

\Edge[label=1](B)(D) 

\tikzset{EdgeStyle/.append style = {bend left}} 

\Edge[label=4](A)(B) 

\Edge[label=5](B)(A) 

\Edge[label=6](B)(C) 

\Edge[label=7](C)(B) 

\Edge[label=2](A)(D) 

\Edge[label=3](D)(C) 

\end{tikzpicture}""" 

 

class pstricks(SageObject): 

""" 

LaTeX example for testing display of pstricks output. See its 

string representation for details. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: PS = latex_examples.pstricks() 

sage: PS 

LaTeX example for testing display of pstricks... 

""" 

def __init__(self): 

""" 

See the string representation for complete documentation. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: type(latex_examples.pstricks()) 

<class 'sage.misc.latex.pstricks'> 

""" 

pass 

 

def _repr_(self): 

""" 

String representation 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.pstricks()._repr_()) > 300 

True 

""" 

return """LaTeX example for testing display of pstricks output. 

 

To use, first try calling 'view' on this object -- it won't work. Now, 

make sure that you have the most recent version of the TeX package 

pstricks installed. Run 'latex.add_to_preamble("\\usepackage{pstricks}")' 

and try viewing it again. Call 'view' with the option `engine='latex'` 

-- the default behavior is to use pdflatex, which doesn't work with 

pstricks. From the command line, this should pop open a nice window 

with a picture of forces acting on a mass on a pendulum. In the 

notebook, it still won't work, so run 

'latex.add_to_mathjax_avoid_list("pspicture")' and try again -- you 

should get a nice picture.""" 

 

def _latex_(self): 

""" 

LaTeX representation 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.pstricks()._latex_()) > 250 

True 

""" 

return r"""\begin{pspicture}(0,-4)(14,0) 

\psline{-}(0,0)(0,-4) 

\psline[linewidth=2pt]{-}(0,0)(1,-3) 

\qdisk(1,-3){3pt} 

\psarc{-}(0,0){0.6}{270}{292} 

\psline{->}(1,-3.3)(1,-4) 

\psline{->}(1.1,-2.7)(0.85,-1.95) 

\psline{-}(5,0)(5,-4) 

\psline[linewidth=2pt]{-}(5,0)(6,-3) 

\qdisk(6,-3){3pt} 

\psarc{-}(5,0){0.6}{270}{292} 

\psarc{-}(5,0){3.2}{270}{290} 

\end{pspicture}""" 

 

class knot(SageObject): 

""" 

LaTeX example for testing display of knots. See its string 

representation for details. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: K = latex_examples.knot() 

sage: K 

LaTeX example for testing display of a knot... 

""" 

def __init__(self): 

""" 

See the string representation for complete documentation. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: type(latex_examples.knot()) 

<class 'sage.misc.latex.knot'> 

""" 

pass 

 

def _repr_(self): 

""" 

String representation 

 

EXAMPLES: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.knot()._repr_()) > 300 

True 

""" 

return r"""LaTeX example for testing display of a knot produced by xypic. 

 

To use, try to view this object -- it won't work. Now try 

'latex.add_to_preamble("\\usepackage[graph,knot,poly,curve]{xypic}")', 

and try viewing again -- it should work in the command line but not 

from the notebook. In the notebook, run 

'latex.add_to_mathjax_avoid_list("xygraph")' and try again -- you 

should get a nice picture. 

 

(LaTeX code taken from the xypic manual) 

""" 

 

def _latex_(self): 

""" 

LaTeX representation 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.knot()._latex_()) > 180 

True 

""" 

return r"""\vtop{\vbox{\xygraph{!{0;/r1.5pc/:} 

[u] !{\vloop<(-.005)\khole||\vcrossneg \vunder- } 

[] !{\ar @{-}@'{p-(1,0)@+}+(-1,1)} 

[ul] !{\vcap[3]>\khole} 

[rrr] !{\ar @{-}@'{p-(0,1)@+}-(1,1)} 

}}}""" 

 

class diagram(SageObject): 

""" 

LaTeX example for testing display of commutative diagrams. 

See its string representation for details. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: CD = latex_examples.diagram() 

sage: CD 

LaTeX example for testing display of a commutative diagram... 

""" 

def __init__(self): 

""" 

See the string representation for complete documentation. 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: type(latex_examples.diagram()) 

<class 'sage.misc.latex.diagram'> 

""" 

pass 

 

def _repr_(self): 

""" 

String representation 

 

EXAMPLES: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.diagram()._repr_()) > 300 

True 

""" 

return r"""LaTeX example for testing display of a commutative diagram produced 

by xypic. 

 

To use, try to view this object -- it won't work. Now try 

'latex.add_to_preamble("\\usepackage[matrix,arrow,curve,cmtip]{xy}")', 

and try viewing again -- it should work in the command line but not 

from the notebook. In the notebook, run 

'latex.add_to_mathjax_avoid_list("xymatrix")' and try again -- you 

should get a picture (a part of the diagram arising from a filtered 

chain complex).""" 

 

def _latex_(self): 

""" 

LaTeX representation 

 

EXAMPLES:: 

 

sage: from sage.misc.latex import latex_examples 

sage: len(latex_examples.diagram()._latex_()) > 1000 

True 

""" 

return r"""\xymatrix{ 

& {} \ar[d] & & \ar[d] & & \ar[d] \\ 

\ldots \ar[r] & H_{p+q}(K^{p-2}) \ar[r] \ar[d] & 

H_{p+q}(K^{p-2}/K^{p-3}) \ar[r] & H_{p+q-1}(K^{p-3}) \ar[r] \ar[d] & 

H_{p+q-1}(K^{p-3}/K^{p-4}) \ar[r] & H_{p+q-2}(K^{p-4}) \ar[r] \ar[d] & 

\ldots \\ 

\ldots \ar[r]^{k \quad \quad } & H_{p+q}(K^{p-1}) \ar[r] \ar[d]^{i} & 

H_{p+q}(K^{p-1}/K^{p-2}) \ar[r] & H_{p+q-1}(K^{p-2}) \ar[r] \ar[d] & 

H_{p+q-1}(K^{p-2}/K^{p-3}) \ar[r] & H_{p+q-2}(K^{p-3}) \ar[r] \ar[d] & 

\ldots \\ 

\ldots \ar[r] & H_{p+q}(K^{p}) \ar[r]^{j} \ar[d] & 

H_{p+q}(K^{p}/K^{p-1}) \ar[r]^{k} & H_{p+q-1}(K^{p-1}) \ar[r] \ar[d]^{i} & 

H_{p+q-1}(K^{p-1}/K^{p-2}) \ar[r] & H_{p+q-2}(K^{p-2}) \ar[r] \ar[d] & 

\ldots \\ 

\ldots \ar[r] & H_{p+q}(K^{p+1}) \ar[r] \ar[d] & 

H_{p+q}(K^{p+1}/K^{p}) \ar[r] & H_{p+q-1}(K^{p}) \ar[r]^{j} \ar[d] & 

H_{p+q-1}(K^{p}/K^{p-1}) \ar[r]^{k} & H_{p+q-2}(K^{p-1}) \ar[r] \ar[d]^{i} & 

\ldots \\ 

& {} & {} & {} & {} & {} \\ 

{} \\ 

\save "3,1"+DL \PATH ~={**@{-}} 

'+<0pc,-1pc> '+<4pc,0pc> '+<0pc,-4pc> '+<16pc,0pc> 

'+<0pc,-3pc> '+<19pc,0pc> 

'+<0pc,-1pc> 

\restore 

\save "3,1"+DL \PATH ~={**@{-}} 

'+<0pc,2pc> '+<9pc,0pc> '+<0pc,-3pc> '+<18pc,0pc> 

'+<0pc,-4pc> '+<18pc,0pc> 

'+<0pc,-4pc> 

\restore 

}""" 

 

latex_examples = LatexExamples()