Touchdevelop Programming On The Go R Nigel Horspool Nikolai Tillmann
Touchdevelop Programming On The Go R Nigel Horspool Nikolai Tillmann
Touchdevelop Programming On The Go R Nigel Horspool Nikolai Tillmann
Touchdevelop Programming On The Go R Nigel Horspool Nikolai Tillmann
1. Touchdevelop Programming On The Go R Nigel
Horspool Nikolai Tillmann download
https://ebookbell.com/product/touchdevelop-programming-on-the-go-
r-nigel-horspool-nikolai-tillmann-42918978
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Touchdevelop Programming On The Go R Nigel Horspool Nikolai Tillmann
https://ebookbell.com/product/touchdevelop-programming-on-the-go-r-
nigel-horspool-nikolai-tillmann-42918978
7. use or reuse of this Apress source code must contain this License. This
Apress code is made available at Apress.com/9781430261360 as is and
Apress makes no claims to, representations or warrantees as to the function,
usability, accuracy or usefulness of this code.
ISBN-13 (pbk): 978-1-4302-6136-0 ISBN-13 (electronic):
978-1-4302-6137-7
Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked name,
logo, or image we use the names, logos, and images only in an editorial
fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and
similar terms, even if they are not identified as such, is not to be taken as an
expression of opinion as to whether or not they are subject to proprietary
rights.
President and Publisher: Paul Manning
Editor: Jeffrey Pepper
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media
New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-
SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or
visit www.springeronline.com. For information on translations, please e-mail
rights@apress.com, or visit www.apress.com.
8. Contents
Preface
Who this book is for
Background to the book
Other learning materials
Acknowledgments
Important websites
The TouchDevelop Team
List of figures
List of tables
Chapter 1 Introduction to TouchDevelop
1.1 Computers want to be programmed
1.2 What is TouchDevelop?
1.3 The TouchDevelop ecosystem
1.4 History and Future
1.5 Platforms
1.6 The scripting language
Chapter 2 The Scripting Language
9. 2.1 Introduction – the language flavor
2.2 Datatypes and variables
2.3 Expressions
2.4 Statements
2.5 Actions
2.6 Events
2.7 Pages
2.8 Creating library scripts
Chapter 3 The Wall – using the screen
3.1 Output – the writing on the wall
3.2 Input of values from the touchscreen
3.3 Updating the wall’s content
3.4 Events on the touchscreen
3.5 Pushing and popping pages
3.6 Titles and subtitles
3.7 Wall buttons
3.8 On-demand creation of output
Chapter 4 The Web
4.1 URLs and webpages
4.2 Downloading and uploading files
4.3 Downloading structured data
4.4 REST guidelines and web requests
Chapter 5 Audio
5.1 Music
10. 5.2 Sounds
5.3 Microphone
Chapter 6 Camera, Graphics and Video
6.1 Camera
6.2 Working with pictures
6.3 Static graphics drawing and display
6.4 Playing videos from the internet
Chapter 7 Sensors
7.1 The sensors
7.2 Sensor-driven events
7.3 Accelerometer
7.4 Compass
7.5 Gyroscope
7.6 Motion
Chapter 8 Interactions
8.1 Social messages
8.2 Locations, places, maps
8.3 Emails
8.4 Phone Calls
8.5 2D barcodes
8.6 SMS messages (WP8 only)
8.7 Calendar and appointments (WP8 only)
8.8 Contacts (WP8 and Android only)
Chapter 9 Game Board
11. 9.1 Introduction
9.2 The Board datatype
9.3 The Sprite datatype
9.4 The Sprite Collection datatype
9.5 Touching and board events
9.6 Debugging games
Chapter 10 UI with Boxes and Pages
10.1 Page Overview
10.2 Box Overview
10.3 Examples of Boxes and Pages
10.4 Working with Pages
10.5 Live Editing of the User Interface
10.6 API Support for Boxes and Pages
Chapter 11 Authenticating Web Services
11.1 Registering your app
11.2 Authenticating
11.3 Libraries
11.4 Advanced topics
Appendix A Editing TouchDevelop Scripts
A.1 The starting point
A.2 The editing steps
A.3 Additional steps
A.4 More advanced editing features
Appendix B TouchDevelop Services
12. B.1 bazaar
B.2 box
B.3 collections
B.4 colors
B.5 contract
B.6 invalid
B.7 languages
B.8 locations
B.9 maps
B.10 math
B.11 media
B.12 phone
B.13 player
B.14 senses
B.15 social
B.16 tags
B.17 tile
B.18 time
B.19 wall
B.20 web
Appendix C TouchDevelop Datatypes
C.1 Appointment
C.2 Appointment Collection
C.3 Board
C.4 Boolean
13. C.5 Camera
C.6 Color
C.7 Contact
C.8 Contact Collection
C.9 DateTime
C.10 Form Builder
C.11 Json Builder
C.12 Json Object
C.13 Link
C.14 Link Collection
C.15 Location
C.16 Location Collection
C.17 Map
C.18 Matrix
C.19 Message
C.20 Message Collection
C.21 Motion
C.22 Number
C.23 Number Collection
C.24 Number Map
C.25 OAuth Response
C.26 Page
C.27 Page Button
C.28 Page Collection
C.29 Picture
C.30 Picture Album
14. C.31 Picture Albums
C.32 Pictures
C.33 Place
C.34 Place Collection
C.35 Playlist
C.36 Playlists
C.37 Song
C.38 Songs
C.39 Song Album
C.40 Song Albums
C.41 Songs
C.42 Sound
C.43 Sprite
C.44 Sprite Set
C.45 String
C.46 String Collection
C.47 String Map
C.48 TextBox
C.49 Vector3
C.50 Web Request
C.51 Web Response
C.52 Xml Object
Appendix D Platform Capabilities
D.1 Supported Browsers
D.2 General Features
15. D.3 Supported Sensors and Devices
D.4 Support for Services/Resources
D.5 Support for Created Apps
Appendix E TouchDevelop Editor on a Windows Phone
E.1 The sample program
E.2 The back button, undo and mistakes
E.3 The editing example
E.4 Additional steps
E.5 Refactoring code into a new action
Index
16. Preface
The sales figures for smartphones continue to rise exponentially.
Tablet computers are showing a similarly phenomenal adoption rate
and are replacing laptop computers in many areas of life. We can
imagine a time when nearly everyone is carrying around a powerful
computer in the form of a smartphone or a tablet. The term mobile
device is used to cover such devices. Typically, an app (an
application program) for a smartphone or tablet has to be developed
in a PC and transferred to the mobile device later. But does it have to
be that way? The TouchDevelop project at Microsoft Research has
proved that the answer is No. TouchDevelop is a programming
environment that runs on all mobile devices. It allows a script to be
developed on a mobile device, or on a PC, and to be run on any
mobile device or a PC. After releasing the app in 2011 when it was
available only for the Windows Phone, the overwhelming response
was a big surprised us: more than 200,000 users downloaded the
app and they published more than 10,000 scripts written entirely on
phones. Since then, TouchDevelop has been made available in a
form that runs on PC, Mac and Linux platforms, and on iPad, iPhone,
iPod Touch and Android devices. TouchDevelop is truly a portable
development environment for creating portable apps.
17. Who this book is for
Mobile devices represent the latest in technology. Furthermore,
many students actually own their own smartphone. High school
teachers and college or university instructors love the idea of using
the latest technology to engage their students. While they may be
experts in the field of teaching programming, many teachers
appreciate guidance on how to navigate a complex app like
TouchDevelop: its visual program editor is designed for touchscreens
and uses different editing paradigms from a traditional keyboard-
based text processor. Another opportunity and challenge is how to
make use of some of the sensors that a modern mobile device has
to offer.
This book has much to offer to both both teachers and self-starting
students who are learning how to program on their own. For
teachers, it walks in detail through all of the screens of the app, and
it points out similarities and differences of the TouchDevelop
language compared to other programming languages that the
teacher might already be familiar with. For students and enthusiasts,
the book can serve as a handy reference which they keep next to the
device they are using – it is particularly useful when that device has
a small screen. The book systematically addresses all programming
language constructs, starting from the very basic constructs such as
variables and loops. The book also explores many of the phone
sensors and data sources which make creating apps for mobile
devices so rewarding.
If you are new to programming with TouchDevelop, or if you have not
yet worked on touchscreen devices, we suggest that you read the
book starting from Chapter 1. If you are already familiar with the
basic paradigm of the TouchDevelop programming environment,
then feel free to jump ahead to the later chapters that address
particular topic areas.
This book is written from the perspective of a person developing their
code using a browser. All screenshots and navigation instructions
refer to the TouchDevelop Web App running in a browser and is
18. applicable to all platforms except the Windows Phone. Only
Appendix E, which covers the editor on the Windows Phone, uses
screenshots and instructions specific to the Windows Phone.
This book is available online as well as being publish in print form by
APress. Please email touchdevelop@microsoft.com to give
feedback.
Background to the book
This edition of the book is the result of the year-long evolution of
earlier book versions, incorporating feedback from tutorials and
lectures given by the authors. The first version of the book was
produced as limited edition of 75 copies for the ACM SIGCSE
Conference in Raleigh, NC, March, 2012. That book was based on
the recently released Version 2.6 of TouchDevelop. An updated copy
of the book with 1000 copies, based on Version 2.10, was printed in
January 2013. This book was made available via a Creative
Commons Licence and put on the Amazon Bookstore as well as the
TouchDevelop website. Much of the contents of the second book
were also applicable to the Web App version of TouchDevelop,
though all the screenshots were still of a phone. This third version
has been retargeted at the Web App version of TouchDevelop.
Other learning materials
On the TouchDevelop website, you can also find extensive videos,
tutorials and slides to help you learn and teach TouchDevelop. Just
tap (or click) on the large tile labeled “Docs” under the “Chat and
Learn” heading once you have logged in to the TouchDevelop
website to find these learning resources.
Comments are very welcome. To contact the TouchDevelop team or
the authors, you can
Send email to touchdevelop@microsoft.com
Post on https://facebook.com/touchdevelop
Post on the forum in the app
19. Acknowledgments
As the TouchDevelop community grows, we are finding that we are
learning from everyone who engages in the project – students at
Hackathons, academics who write papers, and most of all
developers of the amazing apps in the bazaar. Thanks to all of you.
Important websites
https://www.touchdevelop.com
https://www.facebook.com/TouchDevelop
http://research.microsoft.com/touchdevelop
The TouchDevelop Team
Thomas (Tom) Ball is a principal researcher and research
manager at Microsoft Research, Redmond, widely known for his
work in program profiling, software model checking, program testing,
and empirical software engineering. Ball is a 2011 ACM Fellow for
"contributions to software analysis and defect detection." Since
becoming a manager at Microsoft, he has nurtured and grown
research areas such as automated theorem proving, program testing
and verification, and empirical software engineering. He holds a B.A.
in Computer Science from Cornell University and a M.S. and Ph.D.
from the University of Wisconsin-Madison.
20. Judith Bishop is Director of Computer Science at
Microsoft Research, based in Redmond, USA. Her role is to create
strong links between Microsoft’s research groups and universities
globally, through encouraging projects, supporting conferences and
engaging directly in research. Her expertise is in programming
languages and distributed systems, with a strong practical bias and
an interest in compilers and design patterns. She is the author or
editor of 17 books on programming languages. She has a PhD from
the University of Southampton, UK in Computer Science.
Sebastian Burckhardt is a Researcher at Microsoft
Research. He was born and raised in Basel, Switzerland. His
research interests revolve around the general problem of
programming concurrent, parallel, and distributed systems
conveniently, efficiently, and correctly. More specific interests include
consistency models, concurrency testing, self-adjusting computation,
and the concurrent revisions programming model. After a few years
of industry experience at IBM, he earned his PhD in Computer
Science at the University of Pennsylvania.
Juan Chen is a Researcher in the RiSE group at
Microsoft Research Redmond. Her main research areas include
21. compilers, programming verification, and type systems. She has
worked on certifying compilers for object-oriented languages, and
design and implementation of a functional programming language for
specifying and verifying program properties. She has a PhD in
Computer Science from Princeton University.
Jonathan ‘Peli’ de Halleux is a Software Engineer in the
Research in Software Engineering group at Microsoft Research. Peli
also volunteers at the local high school to teach mobile computer
science. From 2004 to 2006, he worked in the Common Language
Runtime (CLR) as a Software Design Engineer in Test in charge of
the Just In Time compiler. He has a PhD in Applied Mathematics
from the Catholic University of Louvain, Belgium.
Manuel Fähndrich is a Senior Researcher in the RiSE
group at Microsoft Research in Redmond. He works on programming
language design, static type systems, program analysis and
verification, as well as runtime techniques and optimizations. His
past and current project involvements include the Singularity OS and
Sing# language, CodeContracts for .NET, and TouchDevelop. He
has a PhD from the University of California, Berkeley.
22. Nigel Horspool is a professor of computer science at the
University of Victoria. His main focus for research and teaching has
been programming languages and compilers, though his main claim
to fame is a string searching algorithm. He is the author or co-author
of three books, which cover the C language, Unix and the C#
language. He is currently the co-editor of the journal ‘Software:
Practice and Experience’. He has a PhD from the University of
Toronto, Canada in Computer Science.
Michał Moskal is a Researcher in Redmond. He is in the
RiSE group working on software verification, automated theorem
proving, and programming languages. He works on a formal verifier
for concurrent C programs called VCC, while also taking on other
projects including Boogie intermediate verification language, SPUR
tracing JIT, and DKAL authorization engine. He has a PhD from the
University of Wrocław, Poland.
Arjmand Samuel works with the academic community to
foster research and collaborations in the devices and services
research areas. He leads the mobile and cloud computing research
and outreach for Microsoft Research (Project Hawaii and
TouchDevelop). His recent research interests are in software
architectures and programming paradigms for devices of all shapes
23. and forms (TouchDevelop and HomeOS). He has published in a
variety of publications on topics of security, privacy, location aware
access control, and innovative use of mobile technology. Samuel has
a Ph.D. in Information Security from Purdue University.
Nikolai Tillmann is a Principal Research Software
Design Engineer, Microsoft Research. His main areas of research
are program authoring on mobile devices, program analysis, testing,
optimization, and verification. He started the TouchDevelop project,
which enables end-users to write programs for mobile devices on
mobile devices. He also leads the Pex project, in which he develops
together with Peli de Halleux a framework for runtime verification and
automatic test case generation for .NET applications based on
parameterized unit testing and dynamic symbolic execution. Nikolai
has a Dipl. Inf. in Computer Science from TU Berlin, Germany.
24. List of figures
Figure 1-1: The TouchDevelop ecosystem
Figure 1-2: Viewing metadata of a script
Figure 1-3: Editing a script
Figure 2-1: The ‘new songs’ script (/okzc)
Figure 3-1: Simple output, normal and reversed order
Figure 3-2: Displaying a string using a TextBox
Figure 3-3: Displaying composite values
Figure 3-4: Prompting for input
Figure 3-5: An updatable textbox (/censaair)
Figure 3-6: Updating text using a board (/wkoxnasz)
Figure 3-7: Using tap wall events
Figure 3-8: Using sprite events (/akmcnpux)
Figure 3-9: Title and subtitle example
Figure 3-10: The ‘Question Mark’ page button
Figure 4-1: Posting a Webpage Link to the wall
Figure 4-2: Posting a link to an image on the wall
Figure 4-3: Downloading a text file
Figure 4-4: Picture download
Figure 4-5: Snapshot of a weather webpage
Figure 4-6: Weather data in JSON format
25. Figure 4-7: Accessing Twitter with a library
Figure 4-8: Weather data in JSON format
Figure 5-1: The ‘new songs’ script (WP8 and Android only)
Figure 6-1: A simplified camcorder script (/xbhl)
Figure 6-2: Computing brightness
Figure 6-3: Blending two pictures
Figure 6-4: Using the draw ellipse method
Figure 7-1: A simple pedometer program (/jbpv)
Figure 7-2: Accelerometer orientation
Figure 7-3: Accelerometer colors simplified (script /tbcb)
Figure 7-4: Magnetic compass script (script /drvu)
Figure 7-5: Methods of the Motion type
Figure 7-6: Yaw, pitch and roll
Figure 8-1: Examples of 2D barcodes
Figure 8-2: Sending an SMS message
Figure 9-1: Example script: a moving ball (/nyuc)
Figure 10-1: Page Example 1 (/bvhugenw)
Figure 10-2: (a) Result from Page Example 1
Figure 10-3: Page Example 2 (/hnimxaiw)
Figure 10-4: Result of Running Page Example 2
Figure 10-5: Page Example 3 (/wrsonnwh)
Figure 10-6: Translation produced by Page Example 3
Figure 10-7: Icons for User Interface Editing
Figure 11-1: Post a message to Facebook with OAuth
Figure 11-2: Using Facebook Library
Figure A-1: The rotor program /gtbd
26. Figure A-2: The first few script templates
Figure A-3: The editor webpage
Figure A-4: The left keypad
Figure A-5: The right keypad
Figure A-6: Add above and add below buttons
Figure A-7: The running script
Figure A-8: Selecting the first line
Figure A-9: Marking the first line to extract
Figure A-10: Marking the last line to extract
Figure A-11: Naming the extracted code
Figure E-1: The rotor program /cqxk
Figure E-2: Getting started screenshots
Figure E-3: Editing the first line
Figure E-4: Running the script
27. List of tables
Table 2-1: Special symbols used in scripts
Table 2-2: The Value types
Table 2-3: Reference types provided by the API
Table 2-4: Regular collection types
Table 2-5: Special collection types
Table 2-6: Operators
Table 2-7: Events
Table 2-8: Gameboard events
Table 3-1: Display of media values
Table 3-2: Display of social values
Table 3-3: Display of web values
Table 3-4: Prompting for input
Table 3-5: Tap wall events
Table 3-6: Methods of the Page Table datatype
Table 4-1: Converting URLs
Table 4-2: Creating web links
Table 4-3: Uploading/downloading to websites
Table 4-4: Methods of Web Request datatype
Table 4-5: Methods of Web Response datatype
Table 5-1: Supported music formats
28. Table 5-2: Accessing media resources (WP8 and Android only)
Table 5-3: Using songs and song albums (WP8 and Android only)
Table 5-4: Methods of player resource for songs
Table 5-5: Methods of Sound datatype
Table 6-1: Methods for using the camera(s)
Table 6-2: Methods of the Camera datatype
Table 6-3: Methods of Picture Album and Pictures datatypes (WP8
and Android)
Table 6-4: General Picture methods
Table 6-5: Colorizing/intensity picture effects
Table 6-6: Drawing methods of the Picture datatype
Table 7-1: Sensing methods of the senses service
Table 7-2: Sensor events
Table 8-1: Messaging methods of the social service
Table 8-2: Extra methods of the Message Collection datatype
Table 8-3: Methods of the locations service
Table 8-4: Methods of the maps service
Table 8-5: Methods of the Map datatype
Table 8-6: Methods for handling phone calls
Table 8-7: Barcode generation methods
Table 8-8: Methods of the Appointment datatype
Table 8-9: Methods for accessing and creating contacts
Table 9-1: Methods to create a board
Table 9-2: Methods of Board datatype: appearance
Table 9-3: Methods of Board datatype: creating/accessing sprites
Table 9-4: Methods of Board datatype: obstacles/boundaries
29. Table 9-5: Methods of Board datatype: forces/animation
Table 9-6: Methods of Sprite datatype: visual attributes
Table 9-7: Methods of Sprite datatype: position/velocity
Table 9-8: Methods of Sprite datatype: mass, friction, elasticity
Table 9-9: Methods of Sprite datatype: additional features
Table 9-10: Additional or modified Sprite Set methods
Table 9-11: Touch methods of the Board datatype
Table 10-1: General Methods of box Service
Table 10-2: Text Handling Methods of box Service
Table 10-3: Layout Methods of box Service
Table 11-1: General methods related to OAuth 2.0
30. Chapter 1
Introduction to TouchDevelop
TouchDevelop is a complete app creation ecosystem designed for
touch, cloud connected, mobile devices. This chapter provides a
brief introduction to the world of TouchDevelop scripting and the
devices that support it.
1.1 Computers want to be programmed
1.2 What is TouchDevelop?
1.3 The TouchDevelop ecosystem
1.4 History and Future
1.5 Platforms
1.6 The scripting language
1.1 Computers want to be
programmed
Computers are everywhere, and they take on many different forms:
TVs, smart phones, fridges with apps, etc. Despite this abundance of
form and function, until recently, most people thought of desktop PCs
and then laptops when they were asked about computers. This
perception is shifting, as smartphones and tablets are quickly
becoming the main computers for an increasing number of people.
As a matter of fact, smartphone sales have surpassed PC sales
even faster than some analysts anticipated.
New smartphone and tablet models are getting more powerful and
becoming suitable for many tasks that used to require PCs. Mobile
devices have become well established tools for reading and
composing emails, browsing the web, and playing games. These
devices are even being used to annotate documents. And yet, the
one task that can be seen as the defining moment of any computing
31. platform is not yet widely performed on smartphones and tablets:
writing code, or even creating entire applications.
The previous generation of people who grew up with full featured
PCs always had the option to program them. While most people
chose not to do that, they at least had the option. Decades of
programming language and development environment research
produced powerful tools suitable for PCs. It is through exploring this
opportunity that many young people became interested in computer
science.
Unfortunately, in the new world of apps and app marketplaces with a
focus on existing curated content, it seems that the creative outlet of
programming that encouraged aspiring programmers in the past is
no longer easily accessible. The ability to program on the very
device one owns and uses all the time is not a prominent option
anymore.
Granted, smartphones and tablets pose new challenges for
programming tasks. These devices have no physical keyboard, the
screen tends to be rather small, and data tends to not be stored
locally but is dynamically fetched from the cloud. A group at
Microsoft Research asked the question: “Is it possible to create
interesting apps directly on a smartphone, without using a separate
PC or a keyboard?” It is in the attempt to answer this question that
TouchDevelop was born.
The TouchDevelop team took on the challenge of rethinking
computer programming from the ground up, trying to understand
how a modern mobile touch-screen device should be programmed in
its own right. TouchDevelop was created with a goal to ignore the
legacy of programming languages optimized for linear text input via a
keyboard, often having a verbosity that assumes big screens.
We believe that as more people adopt mobile devices as their
primary, or possibly only, computing devices, it will become more
important to not just enable users to consume content but to also
empower them to produce content. We particularly believe in
empowering users to produce new applications.
32. 1.2 What is TouchDevelop?
TouchDevelop is a novel application development environment that
allows anyone to script their mobile devices anywhere. It does not
need a separate PC and can be used by students, hobbyists, power
users, and developers. Through TouchDevelop, users can create
scripts (i.e., apps written using TouchDevelop) to access data,
media, and sensors on a smart phone, tablet or PC. The scripts can
also interact with the cloud services for storage, computing, and
social networks. TouchDevelop applications can serve many
purposes and are typically written for fun, for personalizing the
phone, and for creating productivity tools.
TouchDevelop brings the excitement of the first programmable
personal computers to the now ubiquitous mobile devices. Scripts
developed using TouchDevelop allow users to show and manipulate
music and pictures stored on their own mobile devices, to use the
device’s sensors, and to interact with friends in their social networks.
TouchDevelop can be used to develop games such as “missile
defense”, which is a full featured game where cities must be
defended against incoming missiles
(https://www.touchdevelop.com/zvpj). The script for this sample
game can be downloaded to the TouchDevelop application installed
on a Windows Phone or directly from the TouchDevelop web
application. The user has full access to the script and can modify the
game in any way imaginable. If someone has made improvements to
the game, the improved game can be shared with others. It is as
simple as tapping a button to upload the changed script back to the
website. The script will be assigned a different identification tag
(replacing the /zvpj letters at the end of the URL). If the author of
missile defense publishes an update, TouchDevelop will
automatically redirect the user to the latest version of that game.
An example of a TouchDevelop script being used for productivity is
the “my online meetings” script, which finds active online meetings. If
there is one, it can be joined through the Microsoft Lync application
installed on the phone (https://www.touchdevelop.com/mpuj).
33. The TouchDevelop website provides a variety of scripts that can be
used for learning or as examples. Sample scripts meant to illustrate
how to use the built-in APIs can be found at the URL
https://www.touchdevelop.com/pboj. Scripts written by other users
can be found by going to the TouchDevelop URL
https://www.touchdevelop.com/search and entering a term like
‘game’ into the search box. Alternatively one can explore the on-line
API manual at https://www.touchdevelop.com/doc/api.
1.3 The TouchDevelop ecosystem
A script developed using the TouchDevelop editor can be shared
with other users by using the TouchDevelop cloud infrastructure at
https://www.touchdevelop.com.
Figure 1-1 gives a high level architectural overview of the
TouchDevelop ecosystem: regardless of whether a phone or browser
client is used, all information such as scripts is retrieved and stored
in the touchdevelop.com cloud service.
Figure 1-1: The TouchDevelop ecosystem
34. TouchDevelop scripts are developed by users on their devices and
executed within the TouchDevelop run time environment. These
scripts can be shared with other users. The TouchDevelop cloud
infrastructure supports this sharing amongst a community of
TouchDevelop users. These scripts can also be searched, viewed,
and installed into a user’s account using the TouchDevelop website.
The cloud infrastructure enables sharing, and, acts as a repository of
all scripts developed and published by users.
The TouchDevelop website allocates a unique deep link for each
script on http://touchdevelop.com; where each script is identified by a
seemingly random letter sequence. For example,
https://www.touchdevelop.com/zpco refers to a particular version of
the TouchInvaders game, as in Figure 1-2. It can be used to open
the script directly. This link can be shared with other people or on
social networks.
35. Figure 1-2: Viewing metadata of a script
If a user likes this script, he or she can show their appreciation of a
script or a comment by giving it a positive review in the form of a
“heart”.
On any client, a phone or a web browser, the user can edit a script
as shown in Figure 1-3.
Figure 1-3: Editing a script
36. 1.4 History and Future
After releasing TouchDevelop in April of 2011, first exclusively
available for Windows Phone, the overwhelming response surprised
us. Since then, more than 300,000 people downloaded the app. At
first, TouchDevelop was limited to creating scripts on the device
where it was installed – there was no way to share scripts with other
people.
In August 2011, the update to v2.0 of TouchDevelop brought sharing
of scripts via the touchdevelop.com cloud service. The update also
enabled many more social features such as reviewing scripts, writing
comments, taking screenshots, etc. Since then, more than 90,000
people registered online and shared more than 25,000 scripts, most
of them written entirely on phones. Many features were added over
37. time, making TouchDevelop an increasingly powerful development
environment and language. The features include support for libraries
for code reuse and custom structured data types.
In order to share scripts not only within the TouchDevelop
environment, but also with other people who might not be aware of
TouchDevelop, we added the ability to export scripts as apps that
can be submitted to the Windows Phone Store. This capability has
existed since March of 2012.
In October 2012, TouchDevelop took a giant step forward. Thanks to
a complete re-implementation, TouchDevelop could now run not just
on Windows Phones, but on virtually any modern device in a
browser as a Web App. The supported platforms include PC, Mac,
iPhone, iPad, iPod Touch, and Android. The new TouchDevelop
implementation harnesses the power of HTML5 and JavaScript,
while still using the same programming language as before. The
code editor dynamically adjusts to the screen size to accommodate
small screens on smartphones, medium-sized screens on tablets,
and large screens on PCs. The user interface of the Web App has
again been optimized for touchscreens, but a keyboard and a mouse
can also be used if desired and available. At the same time, we also
added the ability to export scripts as apps that can be submitted to
the Windows Store (which is a separate concern from the Windows
Phone Store).
In the near future, the update v3.0 of the TouchDevelop app for
Windows Phone will bring the same editing and execution engine
that currently powers the TouchDevelop Web App to Windows
Phone 8 devices.
A significant upcoming addition to the TouchDevelop programming
language will be the concept of “cloud state.” By just tagging a
variable as “cloud”, similar to how one marks a variable as “static” in
C#, an app is turned into a distributed app with shared state. All
changes to that variable will get automatically synchronized between
different devices and users.
1.5 Platforms
38. There are a number of optional sensors for Windows Phones. “Near
field communication” (NFC), front camera, rear camera,
magnetometer and gyroscope may or may not be present in any
given device model. Similarly, some browsers choose to expose
certain sensors while others don’t. Safari on iOS exposes the
accelerometer; Chrome on Android only partially, and Internet
Explorer 10 not at all. This variety is most likely an artifact of the
continuously evolving HTML5 standard; so, hopefully, more and
more sensors will be supported by all browsers as time goes by.
Depending on these constraints, and depending on whether you are
running the native TouchDevelop app on Windows Phone or the
Web App in the browser, different feature sets are available to you
when you write your scripts. See
https://www.touchdevelop.com/platforms for a complete and up-to-
date overview of the different platform capabilities.
1.5.1 Installing TouchDevelop on a Windows
phone
If TouchDevelop is to be used for the first time on a Windows Phone,
it will need to be installed. To install the app, follow these steps:
1. Tap the Store tile on the Windows phone.
2. Press the search icon at the bottom of the screen, and type
the text ‘touchdevelop’ into the Store Search text box. Before
you finish typing all the letters, the TouchDevelop app should
appear as a choice on the screen.
3. Tap that choice to select it.
4. Tap Install.
If your device is running a Windows Phone 7 or 7.5 or 7.8 operating
system, then you will get TouchDevelop v2.0, which uses a slightly
different user interface that does not match the screenshots in this
book, and its language is a subset what is discussed in this book.
If your device is running Windows Phone 8, then you will get
TouchDevelop v3.0, which resembles the Web App at
39. https://www.touchdevelop.com/app, but it exposes many more
sensors and data providers available on the phone.
1.5.2 Running TouchDevelop on other platforms
On all other platforms, TouchDevelop does not come as an app in a
marketplace, but instead as a Web App. You can run it from your
web browser:
1. Go to https://www.touchdevelop.com/
2. Log in. You will be taken to the Web App.
1.6 The scripting language
TouchDevelop is a language for writing mobile apps. The
TouchDevelop Windows Phone application and the web app also
provide a runtime environment for executing TouchDevelop scripts.
The TouchDevelop language is a typed, structured programming
language built around the idea of only using touch to author code. It
has built-in primitives that make it easy to access the rich sensor
data available on a mobile device. The TouchDevelop language
mixes imperative, object-oriented, and functional features. The
imperative parts are the most visible: users can update local
variables, and the states of global objects. Object-orientation is
dictated by auto completion requirements – properties of objects are
an easily accessible and intuitive concept. However, for the sake of
simplicity, the language does not provide the ability to define new
types which are subtypes of other types.
A TouchDevelop script consists of a number of actions (functions or
procedures), events (actions to be performed when an external
event occurs), definitions of tables and record types, global state
(global variables and read-only data) and library references
(references to other scripts). The language is covered in some depth
in Chapter 2.
The TouchDevelop script editor is part of the TouchDevelop
application. It is designed for efficient entry of scripts using only the
40. touchscreen. TouchDevelop scripts execute within the TouchDevelop
application. The mode of execution is entirely reactive - actions are
run in response to events. Events can be raised by user input (e.g.,
interacting with a UI element, changing the orientation of the phone,
or shaking it), events from the phone (e.g., change of active song in
the song player) or passage of time. TouchDevelop uses cooperative
multi-threading. Actions and events are executed in a single-
threaded manner.
41. Chapter 2
The Scripting Language
A TouchDevelop script appears to the user as statements in a
language which is not unlike many other programming languages.
This chapter covers the syntax and semantics of that language. The
language is augmented by a powerful and rich API (Application
Programming Interface), an API which significantly extends the
programming capabilities of the TouchDevelop language. The API is
covered in the chapters which follow this one.
2.1 Introduction – the language flavor
2.2 Datatypes and variables
2.3 Expressions
2.4 Statements
2.5 Actions
2.6 Events
2.7 Creating library scripts
2.1 Introduction – the language
flavor
These introductory paragraphs are written for people who know
some of the terminology used to describe programming language
semantics, and will allow such readers to fast forward over large
chunks of this chapter.
The scripting language is statement oriented. Statements are
executed in a sequential manner. Control flow constructs include if-
statements, for and while loops, and functions (which are called
actions in this language).
42. The statements manipulate values. All intermediate values and
variables are statically type checked. Only parameters of actions
have explicit type declarations. The datatypes of all other values and
variables are inferred through analysis of the code.
The language is strongly typed, in that (with one exception), every
operation requires operands of particular datatypes and there is no
automatic coercion to the type required by an operation. The
datatypes belong to one of two categories: value types and
reference types. Value types may have storage on the stack used for
local variables, and their storage is automatically deallocated on exit
from an action (i.e. from a function). Reference types have their
storage allocated on the heap.
The heap is garbage collected. In addition to parameters and local
variables, a script can define globally visible variables in its data
section or read-only variables in its art section. Their storage is
persistent across script executions.
Although the language syntax shows similarities to object-oriented
languages, the language does not support the object-oriented
paradigm. For example, there is no equivalent of class inheritance or
method overloading.
To conserve real estate on smaller screens, several symbols are
used instead of keywords. These symbols are all available as
characters in the Segoe UI Symbol font (a font which is distributed
with the Windows 7 and 8 operating systems). The symbols are
summarized in Table 2-1.
Table 2-1: Special symbols used in scripts
Symbol
Unicode
Value
Description
U+2192
Select a method or field belonging to the value
provided on the left
43. Symbol
Unicode
Value
Description
U+25B7
Call the action named on the right and defined in
the current script
U+25F3
Access a global persistent variable defined in the
data section of the script
U+267B
Call a function defined in another script, which
has been published as a library
U+2339
Access a datatype or item declared in the record
section of the script
U+273F Access a value in the art section of the script
2.1.1 A sample program (/okzc)
This sample program is shown in Figure 2-1. It uses several features
provided by the API. They will be explained only briefly. More
complete explanations are provided in later chapters. Note that this
script runs only on a Windows Phone.
Figure 2-1: The ‘new songs’ script (/okzc)
44. The script comprises two actions and two events. The action named
main is the entry point for the script. The action named display song is
called by main. It has one input parameter named song (with type Song)
and has one result parameter named result (with type Number).
The main action defines and initializes a local variable named found.
No datatype is provided in that definition; it is inferred from the value
45. used for initialization which has type Number. The local variable named
songs is, by using the API, initialized with a collection of all songs held
on the phone.
A for-each loop steps through every value in the collection,
assigning the next variable to a new local variable named song. The
first statement inside the loop calls an action using the notation
display song(song). It passes a reference to the local variable song and
receives a number back as the result, adding that to the found
variable.
The second statement inside the loop takes a string constant and
concatenates the value of the global data item named played. The
preceding symbol indicates that the variable has global scope and
is persistent. The string concatenation operator is || and is the only
operator in TouchDevelop which is overloaded – meaning that it
accepts operands with any datatypes and those operand values are
converted to strings.
The resulting string value constructed by the concatenation appears
to the left of the arrow operator →. It indicates that the value is to be
transmitted to the method shown on the right, whose name is post to
wall. Almost every datatype has a post to wall method; it causes a
representation of the value to be displayed on the screen.
The sample script contains two events. An event is an action which
is executed whenever the specified event occurs. The shake event is
caused by physically shaking the phone. When shaking is detected
by the phone’s sensors, the code provided for the shake event is
executed. Events do not interrupt each other; they are executed in
first-come first-served order.
If a script contains one or more events, the main program does not
terminate. It waits for events to occur. In this case, the script
terminates only if halted by the user (e.g. tapping the phone’s back
button) or if it executes a call to a method in the API for that purpose
(time→stop).
2.2 Datatypes and variables
46. Each type (except the special type Nothing) belongs to one of two
categories: Value Types or Reference Types. If a variable has a
value type, then storage for an instance of that type is held inside the
variable itself. For example, a variable with type Number is allocated
storage which is used to hold number values. However, if a variable
has a reference type, then storage for its value is allocated on the
heap and the variable holds a reference to that heap storage.
2.2.1 The Invalid value
Every datatype (except the special type Nothing) has a special value
Invalid in addition to all its normal values. This special value is
normally used to indicate that a global data variable has not been
initialized or that a method in the API was unable to return a value.
TouchDevelop provides a method for testing a value of any datatype
(except Nothing) to test whether it is the Invalid value. There are also
API methods for obtaining the Invalid value for any desired type.
If a data structure (such as a tree or linked list) is constructed using
Object types declared in the Records section of a script, the Invalid
value would usually be used to play the role of a null reference
value.
Some code to demonstrate the use of Invalid values appears below.
var numUsers := 0
…
if connection failure detected then
numUsers := invalid → number
else
…
if numUsers → is invalid then
“Script is terminating” → post to wall
else
2.2.2 The Nothing type
A method or an operation which does not return a usable result, but
which otherwise succeeded, actually returns a value of type Nothing.
For example, the post to wall method which is provided for every
datatype returns a result of type Nothing. In some languages, such as
F#, the Unit type is the equivalent of the Nothing type in
TouchDevelop. There is a single value with type Nothing. No
47. operations at all are provided for this type; it is similar to the void
type in languages like C/C++ and Java.
Value types
The basic types or elementary types provided in the TouchDevelop
scripting language are Number, Boolean, and String. These are all Value
Types. There are also several composite types which are value
types. All the value types are listed in Table 2-2. Here are some
further details about the Number and String types.
Table 2-2: The Value types
Value
Type
Description
Covered
in
Chapter
Number
An integer or floating-point number 2
Boolean
The type whose constants are true and false 2
String
A sequence of zero or more Unicode characters 2
Color
Used for colors displayed on the screen. Values
are compatible with 4 byte ARGB (alpha, red,
green, blue) color representations. Many standard
colors are provided as constants of the Color
datatype.
6
DateTime
Holds any date from 0001 CE (Common Era) to
9999 CE, combined with a time of day. The time of
day is recorded with 100 nanosecond accuracy.
8
Location
Holds a combination of latitude, longitude and
altitude values plus a course direction and a speed
in two-dimensional space.
8
48. Value
Type
Description
Covered
in
Chapter
Motion
A combination of sensor readings which describe
motion of the phone in 3D space plus a time-stamp
which specifies when the readings were taken. The
motion information includes speed, acceleration
and angular velocity.
7
Vector3
A triple of three numbers used to hold a velocity or
acceleration in the three spatial dimensions or an
angular velocity about the three axes in 3D space.
7
Number
The Number type combines the integer and floating-point types found
in other languages. Values are held in double-precision floating point
format, consistent with the IEEE 754 standard. This implies that the
special values plus infinity, minus infinity and NaN (not-a-number)
can be computed as the result of a calculation.
When a Number value is used in a context where an integer is needed,
such as when selecting the k-th value in a collection, the value is
rounded to the closest integer. A value exactly half-way between is
rounded up; for example, 1.5 is rounded up to 2 while 1.49 is
rounded down to 1.
String
A string may contain zero or more Unicode characters. When a
string constant is shown as part of a TouchDevelop script, double-
quote characters are used to enclose the string and a backslash
character is used to escape a double-quote character or a special
character which appears inside the string. However, when using the
editor to enter a string constant, no backslash characters should be
entered (unless a backslash character itself is wanted inside the
string constant).
It should be noted that TouchDevelop does not provide the char type
for working with single characters. Instead a string of length one
49. should be used.
2.2.3 Reference types
Storage for an instance of a reference type is allocated in a different
place from a variable declared with that type. A local variable with a
reference type is implemented as a pointer (a reference) to the
actual value which is stored elsewhere.
In TouchDevelop, two kinds of reference types are provided. If the
value represents an entity which exists outside TouchDevelop, such
as a song on a Windows phone, then storage is allocated outside the
TouchDevelop application. Otherwise the storage is allocated within
an area of memory controlled by TouchDevelop which is called the
heap. When there are no more references to a value on the heap,
the storage used by that value is automatically reclaimed. It is
garbage collected. The language facilities and the operations which
can be performed on reference types in a TouchDevelop script
depend on whether the values are external to the script or are
internal.
When one variable with a reference type is assigned to another
variable, both variables will become references to the same
instance. A simple example to illustrate this sharing of one instance
between two variables is provided by the following code.
// Set x to refer to a value of type Contact
var x := social → choose contacts
var y := x
x → set title(“His Excellency”)
y → title → post to wall
In this example, the title displayed on the screen by the last
statement will always be ‘His Excellency’ because x and y are both
references to the same instance on the heap, in which the title field
of an instance of the Contact type has been set to that string.
Reference types provided by the API
Excluding the collection types (which are covered in the next
subsection of this chapter below), Table 2-3 lists the reference types
implemented by the API and available to TouchDevelop scripts. The
50. table explicitly indicates whether storage for an instance of each type
is allocated on the heap or is external to the TouchDevelop script.
Table 2-3: Reference types provided by the API
51. Collection types
The API also provides homogeneous collections. A collection
contains zero or more elements whose type is one of the value types
or one of the reference types listed in Table 2-2. Collections are
provided for many of the possible element types. When a collection
type has not been provided, an equivalent list type can be defined
instead using an Object declaration (see Objects and Decorators,
below).
Some collections correspond to resources provided on a Windows
Phone (and therefore may not be supported on other platforms),
such as a collection of stored songs, and such collections are
immutable. Other collections are mutable, meaning that new
elements can be inserted into the collection and/or elements may be
deleted.
The collection types provided by the API are listed in Table 2-4 and
Table 2-5. Three of the collection types have been tagged as special
and are listed separately in Table 2-5. These three collection types
have some special properties not possessed by the other collection
types and need some additional explanation.
52. Table 2-4: Regular collection types
Table 2-5: Special collection types
2.2.4 Tables and indexes
54. were placed, side by side, that fifty could go up abreast. The blue
Voltigeur flag, now full of holes, was planted on the parapet. A tide
of brave Americans overflowed the fort. Resistance was vain. A little
before half-past nine Bravo gave up his diamond-hilted sword, and
the tricolor, that had been waving placidly amidst the uproar, came
down with a jerk.[17]
Fire was opened then upon the Mexicans at the gateway below, and
fearless Captain Roberts of Casey’s storming party, at the head of all
the troops on the causeway and supported by General Smith’s
brigade, carried the gateway batteries. Many from Quitman’s and
Smith’s commands rushed to the summit, dealing with flying
enemies as they went. Scott himself came up—the hero of Chippewa
and Lundy’s Lane. The men pressed round him. He told them how
glad he was, and how proud of them; and how proud their country,
their wives, their sisters and their sweethearts would be; and it
seemed as if such cheering had never been heard, anywhere in the
world, before.[17]
Exultant but weary, the soldiers now looked about them as they took
breath. From this eyrie the whole wonderful Valley of Mexico could
be surveyed. All round the west the great wall of rugged mountains
closed it in, and two vast, snowy peaks guarded its portal on the
east. As if reluctantly the mountains gradually subsided into verdant
hills and a wide plain, enamelled in a thousand soft hues. The broad,
smooth lakes gleamed like molten silver. The gold of ripening grain,
penciled lines of pale-green maguey, cottages radiant in the sun like
the sails of distant ships, country-houses and villas half hiding in
foliage, and many straight, converging avenues, lined with trees,
delighted the eye. In the midst, clear-cut as a medallion, lay the city
of Mexico, the capital, its roofs and towers black with people; and
there, just yonder, stood the Halls of the Montezumas, the Jerusalem
of these ardent young crusaders. Unfortunately breastworks,
redoubts, cannon and a Mexican army were still to be reckoned with.
Santa Anna had probably lost not more than 1800 killed, wounded
and missing this day, and apparently Scott’s loss had been about one
fourth as great.[18]
55. QUITMAN’S
OPERATIONS
The Citadel in 1840.
But the Americans quickly prepared to
advance—first of all, Quitman. Naturally a
certain discretion had been given to the
commanding generals, and he intended to
make the most of it. Looking from the hill along the Belén causeway,
he saw a wide avenue divided through the middle by a stone
aqueduct some eight feet wide and fifteen feet high, resting on
heavy arches and pillars of masonry. Owing to fine weather the road
was unusually firm. A small number of troops, fleeing in the utmost
confusion, could be seen upon it, but at only one point fortifications.
Borrowing all of Pillow’s troops except the Fifteenth Infantry, which
remained to hold Chapultepec and guard the prisoners, he quietly
gave orders that his men should assemble near the main gateway.
At once the inspiring words began to circulate, “Quitman’s division to
the city!” and as soon as possible the Rifles, in their crimson sashes,
were leading the march forward. About a mile on, a two-gun battery,
with a field redan at its right on the marsh, blocked the way. For an
hour or so Drum used a small gun upon it. Then the Rifles, after
creeping along the aqueduct from arch to arch, took it by assault,
and the march continued toward the fortifications at the garita.[19]
As at the other garitas, no gates existed here,
but a ditch and a parapet blocked one half of
the causeway and a zigzag redoubt the other.
Just at the north was the stone house intended
for guards and customs officials, beyond which
lay the wide Paseo (Promenade). South, on the
Piedad road, were artillery and infantry that
could fire through the arches. Inside the garita,
buildings extending toward the east offered
shelter, and in open ground a little more
toward the north and about 300 yards distant,
the extensive edifice called the citadel,
protected with a wall and a wet ditch, constituted a serious obstacle.
[19]
56. Santa Anna, after acting like a madman when Chapultepec fell, came
to this garita. General Terrés, a brave old Spaniard, commanded
here with about 180 infantry and some artillerymen. Santa Anna
gave him three guns of medium power, and stationed General
Ramírez in the Paseo, Brevet General Argüelles on the opposite side,
and General Perdigón Garay and Colonel Barrios in the rear with
substantial reserves.[19]
On approaching this formidable position, Quitman encountered a
withering storm of bullets, grape and solid shot from both sides and
the front, and suffered rather severely. But Drum and Benjamin, iron
men, bringing up as soon as possible a long 18-pounder and a 24-
pound howitzer on the opposite sides of the aqueduct, dampened
the ardor of the Mexicans not a little, and splinters from the masonry
did havoc among the sheltered artillerymen at the garita. Some
troops already beaten at Chapultepec and at the intermediate
battery soon became demoralized. At about one o’clock rumors crept
in that Americans from the southern front were turning the position.
Ramírez, Garay, Argüelles and Barrios retired without the formality of
saying good-by; and Terrés, whose cannon ammunition had failed,
withdrew prudently to the citadel with two of the guns and about
seventy panicky men, the remnant of his garrison. The Rifles now
dashed over the parapet; and at exactly twenty minutes past one a
tall, slender man with short, bristling, grayish hair stood on it,
smoking a cigar and waving a red handkerchief tied to a rifle. It was
Quitman, self-possessed but exultant; and in a few moments the
Palmetto colors and the green banner of the Rifles, with its blazing
gold eagle, were flying at the portal of the city.[19]
The advance then continued for some little distance, and, as the
ammunition of our two heavy guns had been exhausted, the
captured Mexican 8-pounder was made to do good service. But
Santa Anna, who had thought the position safe and gone on to San
Cosme, soon arrived with ordnance and troops. The citadel was
reinforced, and infantry and cannon were placed at other points.
Quitman’s last artillery cartridges were used, and under the enemy’s
fire no more could be brought up. Solid shot cut down both Drum
57. THE SAN COSME
APPROACH
and Benjamin. Our infantry had to retire to the vicinity of the garita.
Attempts were then made to strengthen the position; but they did
not accomplish very much. Ammunition gave out entirely, and firing
ceased. The enemy grew bolder. Again and again they charged, and
though repulsed they did not appear to be discouraged. By this time
every member of Quitman’s staff, Beauregard, his engineer officer,
and all his artillery officers had been killed or wounded, and he
longed anxiously for night.[19]
Meanwhile, events had occurred on Scott’s other wing. Trousdale’s
command, supplemented with Jackson’s guns, pushed along the
road and aqueduct on the north side of the rectangle, and the latter
distinguished himself by fearlessly attacking a one-gun redoubt,
which, supported by infantry and by fire from the summit of the hill,
barred the way. To check Mexican reinforcements and threaten the
enemy—particularly the troops in Quitman’s front—Scott now had
Worth, Garland’s brigade, C. F. Smith’s battalion, Duncan’s battery,
the rest of Magruder’s battery and Sumner’s dragoons pursue the
same route. The one-gun redoubt was flanked and occupied; and
Worth’s forces arrived at the northeast corner of the rectangle in
time to annoy the retreat of Rangel and other departing Mexicans.
[20]
Here began the broad, straight Verónica
causeway—closely similar to that of Belén—
which extended almost north for nearly two
miles (3530 yards) to the English cemetery,
and there joined the San Cosme highway at approximately a right
angle. Understanding the difficulties of the Belén approach, Scott
intended to make only a feint in that quarter, and let his left wing
break into the city. He therefore sent the brigades of Clarke and
Cadwalader and also Huger with siege guns to Worth. To organize
the attacking column, replenish the ammunition, make other needed
preparations, and sweep away the resistance encountered at several
minor fortifications, especially near the cemetery, required time; but
at about four o’clock Worth found himself on the straight highway
about half a mile from the San Cosme garita.[20]
58. This entrance to the city had been included in the general scheme of
defence, but on account of its remoteness from pressing danger few
workmen had been employed here; and when Chapultepec fell, it lay
entirely open except for a small parapet without a ditch extending
partly across the highway some 250 yards to the west. General
Peña, however, coming this way from Chapultepec, stopped at the
parapet, and Rangel placed at the garita such troops as he could
assemble. Santa Anna, who displayed on this occasion reckless valor
and an almost fiendish activity, sent three available cannon and
brought additional troops. The roofs of buildings in the vicinity were
occupied. A redoubt with embrasures was hastily erected at the
garita, the near arches of the aqueduct were stopped up with sand-
bags, and some guns in the Paseo were prepared to coöperate.[20]
On attempting to advance, therefore, Worth found the highway
swept with bullets, canister, grape and shells. Garland, however, was
ordered to creep forward under the protection of the arches, and
endeavor to reach the south flank of the garita, and Clarke to
burrow through the continuous line of buildings on the other side,
and strike the northern flank. Lieutenant U. S. Grant, who was
reported as acquitting himself at this time “most nobly,” waded some
ditches with a party of men and a mountain howitzer, and planted
the gun on the roof of a church at the right; and Lieutenant Raphael
Semmes of the navy performed a similar exploit on the left. Artillery
fire compelled Peña, who—reinforced by Santa Anna with two
companies of the Eleventh Infantry—was fighting gallantly, to leave
the parapet; and Hunt, of Duncan’s battery, though he lost more
than half his men in dashing 150 yards at full speed, landed a gun at
that point, where he could load in safety and then fire from the one
embrasure.[20]
By five o’clock these preparations were complete. On the other hand
Rangel had been severely wounded, and his principal gun, a 24-
pound howitzer, had become unserviceable. Suddenly, to his utter
astonishment, Americans appeared on the top of a three-story house
that commanded the interior of his redoubt, and with a single volley
disposed of almost every gunner and artillery mule. Then some of
59. them hurried down to the front door of the house, burst it open, and
rushed into the redoubt, where they met Americans just arrived by a
flanking movement from the other side of the highway. In a panic
the Mexicans fled, literally sweeping away Santa Anna and a body of
troops, who had come at all speed from Belén to support the
position. Many of them scattered, but with no little difficulty others
were conducted to the citadel. By six o’clock Worth entered Mexico.
Near the garita his forces were safely housed, and by way of “good-
night” and good advice, Huger dropped a few shells in the vicinity of
the palace.[20]
The end, however, was not yet in view. Santa Anna had some 5000
infantry and fifteen cannon at the citadel, with probably about 7000
more troops not far away, and the Americans, besides having lost
many in the day’s fighting, were now fearfully divided. Not only
Worth but Quitman, who planted three heavy guns in battery during
the night, intended to advance in the morning, and apparently a day
of carnage was to ensue.[20]
But Santa Anna probably began to feel the reaction that always
followed his great efforts. Funds and provisions were scanty. The
army was demoralized, and the mass of the people felt
disheartened. Within the town there were no fortifications, and it
looked as if another battle under these conditions might scatter the
troops, and involve the loss of nearly all the war material. Besides,
leading persons in the city had always been strenuously anxious to
prevent bombardment and assault; and the President was urged
now, as four months previously, to spare it. Early in the evening,
therefore, he briefly discussed the situation with Olaguíbel, the
minister of war and three generals. The Governor was for acting
deliberately; but Santa Anna, declaring that honor had been satisfied
and the city could not be defended successfully, ordered immediate
evacuation; and by one o’clock the troops retired in a somewhat
orderly fashion to Guadalupe Hidalgo. About three hours later a
commission of the city council (ayuntamiento) offered terms of
capitulation at the American headquarters in Tacubaya. These were
60. THE AMERICANS
CAPTURE MEXICO
of course rejected, for the town lay at our mercy; but Scott gave
informally the usual assurances of good treatment.[21]
So when the first thin streak of dawn
glimmered forth behind the gray volcanoes,
and our cannon at Belén garita were on the
point of opening fire, a white flag and an
invitation to enter the capital reached Quitman. First making sure
there was no deception, he advanced; and after stopping about half
an hour at the citadel he moved forward under a splendid sun to the
grand plaza, which fronted the palace and the cathedral, with
Smith’s brigade, the Marines, the New York volunteers and Steptoe’s
battery. As a triumphal procession the command looked rather
strange. Quitman and Smith marched at its head on foot—the
former with only one shoe; and behind them came troops decorated
with mud, the red stains of battle and rough bandages, carrying
arms at quite haphazard angles. Not less astonishing looked the city,
for sidewalks, windows, balconies and housetops were crowded with
people. Except for the silence, the countless white handkerchiefs and
the foreign flags, it might have been thought a holiday. Before the
palace, which filled the east side of the plaza, the troops formed in
line of battle. Officers took their places at the front, and when
Captain Roberts hoisted a battle-scarred American flag on the staff
of the palace at seven o’clock, arms were presented and the officers
saluted.[22]
Soon loud cheering was heard. A few squares away the commander-
in-chief, escorted by cavalry with drawn swords, had reached
Worth’s command, which had stopped at six o’clock by orders
opposite the high ash trees of the Alameda. A clatter of galloping
hoofs followed; and in another moment, amidst the involuntary
applause of the Mexicans, General Scott, dressed in full uniform and
mounted on a tall, heavy bay charger, dashed with his staff and
Harney’s dragoons into the grand plaza—his noble figure, gold
epaulets and snowy plumes, resplendent under the brilliant sun, fitly
typifying the invisible glory of his unkempt and limping army.
Uncovering, he rode slowly along the line of battle to the music of
61. our national airs; the troops, presenting arms again, cheered and
hurrahed till it seemed as if the earthquake-proof cathedral must be
shaking, and the cavalry escort waved high their flashing blades.[22]
In stentorian tones the commander-in-chief appointed Quitman
governor of the city; and then, dismounting in the courtyard, he
clanked up the broad stairway of the palace, to indite
congratulations on the “many glorious victories” of his army.
Presently cross-belted American Marines were calmly patrolling the
Halls of the Montezumas as if they owned them, while the rest of
the troops gazed with profound exultation at the long pinkish façade
and the endless balconies of the upper story, and the people gazed
silently at the troops. “They are all and each of them heroes,”
commented a foreigner present, and others in the world thought the
same.
62. “Light up your homes, O fathers,
For those young hero bands,
Whose march is still through vanquished towns
And over conquered lands,
Whose valor, wild, impetuous
In all its fiery glow,
Pours onward like a lava-tide,
And sweeps away the foe!”[22]
63. XXIX
FINAL MILITARY OPERATIONS
January, 1847–April, 1848
At the north, after the Buena Vista campaign and the embarrassments growing out
of it came to an end, Taylor probably wished, in what an officer calledto advance as
far as San Luis Potosí, and retained troops urgently needed by Scott; but by the
middle of June, 1847, he doubtless realized that effective operations on so long a
line, especially through hostile and much of the way through barren territory, were
impracticable, and advised that Scott’s column alone should act on the offensive. A
month later orders of a corresponding tenor were issued at Washington, and then
some 3000 surplus troops of the northern army proceeded toward the capital,
though too late, of course, to assist in the decisive struggle.[1]
Valencia, during his brief stay at San Luis Potosí in the early summer of 1847, not
only requested permission to move against Saltillo, but planned that General
Filisola, aided by a brigade under Avalos, then lying at Matehuala, by Reyes, the
comandante general of Zacatecas, and by Urrea—who still commanded theand
could easily pass across the Sierra Madre from Tula—should threaten, if not attack,
Saltillo and Monterey, and at least keep the Americans on the defensive. Some
disquieting movements of these troops resulted; but Valencia was soon called to
Mexico, and various difficulties, chiefly a lack of means resulting from the American
occupation, proved fatal to this ambitious enterprise, besides hindering the Mexican
preparations to receive Taylor at San Luis Potosí.[1]
During the winter of 1846–47 and to some extent later, the garrison of Tampico was
menaced by plans for an uprising, to be assisted by outside forces, and sometimes
it was feared that a move to capture the city would be launched from Tula in the
hope of embarrassing Scott’s communications; but the Americans, though not
strong in numbers there, were vigilant and well protected by fortifications. Besides,
the authorities of Tamaulipas, now living on fairly good terms with the invaders,
had little wish to take part in active hostilities. They quarrelled bitterly with Urrea,
who naturally attempted to draw supplies and money from the region, and in
November, 1847, with a view to bringing about harmony, that officer was removed.
Scott’s victories and especially the fall of Mexico had no little effect in this quarter;
the prospect of serious operations entirely disappeared; and early in November,
1847, General Taylor, who had reached the conclusion some time before that his
country wanted him for President, and had laid aside his old brown coat in favor of
checked shirt sleeves, set out for home on a leave of absence, which actually
64. FIGHTING IN THE CAPITAL
continued until the close of the war. Wool took his place; but nothing occurred in
this region except guerilla affairs, of which a due account will be given presently.[1]
In the northwest, meantime, Price, who commanded in New Mexico and was
disturbed by rumors of danger from the south, decided on his own responsibility,
ignoring instructions to do otherwise, that he must assume the aggressive. Early in
March, 1848, the city of Chihuahua was therefore reoccupied; and on the sixteenth
of that month, after a little brisk fighting, the town of Rosales, about sixty miles to
the southeast, which Angel Trias held with some 800 men, chiefly National Guards,
was captured by assault with a trifling loss. But this campaign had no general effect
on the war—indeed, the treaty of peace had already been signed—and Price was
ordered by Marcy to retire.[1]
In Scott’s department the final military operations
began very promptly. Immediately after the Americans
took possession of the grand plaza at Mexico on the
morning of September 14, a multitude of blanketed léperos crowded closely upon
them. Already these miscreants had tasted the disorder they loved, for the palace
had been left unguarded, and they had sacked it; and now they showed signs of
turbulence. The plaza was cleared, however, and no further trouble seemed likely.
But when our troops began to march away to their quarters, a shot was heard. A
bullet probably intended for Worth struck Garland, and almost instantly firing from
street corners, windows and the tops of houses became general, though not
systematic. Thousands of convicts from the jail supported the populace, and in one
way or another not a few of the better class coöperated. By Tornel’s order paving
stones had been taken to many of the azoteas with a view to resisting the invader
step by step, and these, like every other sort of weapon, were now used.[2]
Though surprised, the Americans promptly accepted the challenge. Skirmishers
drove back the mobs. Grape and canister swept the streets. As a rule, every house
from which a shot flew became a target for our heavy cannon, which seemed to
shake the very foundations of the city, and when breached was immediately
sacked; and sharpshooters worked effectively on towers and roofs. Scott
threatened even sterner measures; and the city authorities not only put up notices,
embodying his threats and imploring the people to desist from a vain and
imprudent contest, but interceded personally with them in the streets. By about
noon the Americans held all the points of vantage, and as evening approached, the
firing died away. A fearful night ensued. It was dark and cold. No lights relieved the
gloom. Wild mobs ran shouting through the streets, and the hoof-beats of American
patrols resounded from square to square.[2]
Santa Anna, finding it impossible on the morning of the fourteenth to subsist his
army at Guadalupe, had ordered the infantry and heavy guns to Querétaro under
General Herrera, and proceeded with four small pieces and the cavalry to San
Cristóbal, a point about fourteen miles northeast of the capital. After seeing the
65. people of Mexico view with indifference his efforts of the previous day, he expected
nothing of them; but on learning of the outbreak he marched back to Guadalupe,
and at a late hour sent into Mexico a small force of cavalry and infantry to
investigate and assist. This met Duncan’s battery and retreated; but Santa Anna,
assured that on the next day there would be a rising en masse, erected a
breastwork at the Peralvillo garita on the north side of the town, and waited.[2]
As soon as day broke, gloomy and wet, the shooting was in fact resumed, at least
in the northern quarters. But he soon perceived that no general movement was
taking place, and again marched away. This disheartened the people still more; the
efforts of the authorities influenced them greatly; and by the end of the afternoon,
realizing that much was to be suffered and nothing gained, they generally
abandoned hope. During the next day or two scattering shots could be heard, but
real fighting was over. Extravagant hopes of destroying the small American army
were still entertained by lightheaded men.wrote one of these, and attempts were
made by military officers to organize a real conspiracy; but lack of courage, means,
confidence and mutual trust—as well as the watchfulness of the Americans—made
success impossible. Scott repeatedly warned his troops to be vigilant and orderly, to
keep together, and to refrain from drinking. As the danger grew less menacing,
however, they became less careful, and for probably a month assassinations were
frequent. From first to last several hundred Americans perished in the hostilities,
and no doubt far more of the enemy. But by the middle of October the city was
tranquil.[2]
The concluding field operations in Scott’s department resembled for the most part
the fighting just described, for they had to do chiefly with guerillas. That style of
warfare suited the national character. It had figured prominently in the Spanish
struggle against Napoleon and in the Mexican war of independence; and when the
public began to see clearly that battles could not stop the Americans, it was
invoked—even though by universal military practice in Europe those who robbed
and fought at will, while pretending to be inoffensive, were considered brigands
and assassins—as the one hope.[3]
Thoughtful persons like J. F. Ramírez and General Mora pointed out serious
dangers: the impossibility of discipline, the relaxation of morale, the destruction of
all standards, and the certainty that a spirit of violence and rapine would grow by
what it fed upon; and they recognized the improbability that such methods could
prevail against the strength, equipment, compactness and skill of the Americans.
But the obvious advantages of the guerilla system, which it required far less
intelligence to perceive and appreciate, counted powerfully on the other side. How
much the Spanish themselves had suffered from their irregulars during the
hostilities against Napoleon was not understood, and patriotic pride in the war of
independence had tended to draw a veil over its horrors.[3]
66. THE GUERILLAS OF THE
NORTHEAST
The dagger, said the official newspaper, was the favorite weapon of the people.
Unarmed men could burn wagons and intercept communications, it was pointed
out. Even women and children could help. A thorough knowledge of the country, its
mountains and its by-paths, would evidently constitute an enormous advantage.
Light corps of the abstemious rancheros, embarrassed with no baggage, could
travel quickly day and night, concentrate in large numbers against an American
detachment, strike, vanish, and then, when least expected, reappear, making the
most of all neglects, all mistakes, nullifying superior strength by avoiding it, and
nullifying discipline by fighting in a style that had no need of discipline. Situated
even more favorably than Spain for such warfare, the Mexicans were to outdo her
example.[3]
This is what will save us, proclaimed in effect the legislature of México
state.exclaimed the congress of Vera Cruz. Santa Anna endorsed the plan. Salas
organized thewhich were to make” “in every manner imaginable”; and in April,
1847, the government, pinning its faith to the system, set it on foot in earnest.
Scott, thewas to be routed after all.[3]
In the north February, 1847, was the golden month of
the irregulars, for the approach of the Mexican army
under Santa Anna encouraged the rancheros to lay
aside the habits of peace. Canales boasted of 161
Americans killed that month, and Urrea with his combined force of regulars and
guerillas, besides engaging in other operations, captured a train of wagons at Agua
Negra, and horribly slaughtered a large number of guards and teamsters. To
avenge this butchery a party of Rangers, teamsters and other civilians murdered
twenty-four men in a village not far distant. Upon this Canales declared what he
called martial law, announcing that every American, armed and unarmed, and every
Mexican living peaceably would be shot; and many were led by fear or a lust for
plunder to take up arms.[4]
The American trains in particular seemed likely to be easy prey. As they commonly
stretched out for some two miles and were guarded only—for so the character of
the road usually dictated—at the ends, the Mexicans, trained to charge at full speed
through an ordinary thicket, could readily attack them from ambush at about the
middle point, create a stampede, and do a great deal of mischief. Infantry could not
pursue the guerillas with success, and the number of our mounted men was always
comparatively small, for every Mexican ranchero had at least one smart pony. In
September, 1847, a band even attacked Mier. Governor Aguirre of Coahuila exerted
himself particularly to organize forces of this character, and not only alcaldes but
priests aided the cause.[4]
The American leaders, however, pursuing a course that was now conciliatory, now
severe, and in many instances technically unjust, succeeded in coping with a
system that was itself unjust. Taylor levied on the people of Nuevo Léon a tax of
67. GUERILLAS IN VERA CRUZ
STATE
$96,000, the estimated value of the goods destroyed at Agua Negra, but suspended
it indefinitely, when representative authorities proved the substantial innocence of
the population and begged for mercy. Cavalry patrols and detachments pursuing
culprits fairly wore out their horses. Villages, if even suspected of harboring
thewere burned. Contributions were imposed wherever connivance appeared
probable. By April, 1847, Canales was in despair.[5]
Then Wool determined to stamp out the evil, and announced in July that any
guerillas caught by him would be executed. In December, 1847, he issued his
famous Order 11, which not only made the Mexican authorities and their towns
responsible for all damages done, but required them to hunt down theAguirre
attempted to retaliate, but in vain. The Americans had power enough to carry out
threats, whereas he had not; and he admitted his failure. Besides, the mass of the
population were indolent in mind as well as body, and looked upon submission as
preferable to danger. In February, 1848, finding the guilty rancheros were anxious
to give up the business, Wool enabled them to resume peaceful occupations by
declaring an amnesty, and in the following May he stated that the country had
never before been so free from highway robbery.[5]
In the south, Vera Cruz, a state of mountains, gorges,
thickets and forests threaded with blind paths, was
the chief home of the guerilla, and it looked as if
Scott’s line of communication might be virtually
destroyed. Not only many hardy, hot-blooded and unscrupulous natives, but a great
many desperadoes hailing from Cuba were ready to enlist. After the fall of Vera
Cruz, and still more after the battle of Cerro Gordo, a large number of regular
officers, to say nothing of privates, could scarcely find bread, and some men, like
the ex-divinity student, ex-Carlist, Jarauta—whose small, close beard, fierce black
eyes, braided jacket, graceful cloak and gold-laced sombrero gave him a romantic
air—had acquired in Spain a taste for this adventurous, reckless life; but a vastly
greater number were prosaic felons, liberated from prison under a pledge to rob
and murder. Nominally J. C. Rebolledo, a fine looking man of rather humane
instincts, was the chief in this district, but the 800 or so persons belonging to many
small bands, while occasionally acting more or less in concert, were mainly
independent. The decree under which all goods coming from points occupied by the
Americans were lawful booty opened possibilities of large gains, and Rebolledo’s
capture of ten loaded wagons in April, 1847, set the people aflame with cupidity.[6]
Brevet Colonel McIntosh and his inexperienced officers, who left Vera Cruz for the
interior—it will be recalled—about the first of June, 1847, with a well-advertised
convoy including a large amount of specie, dependent on wild mustangs under raw,
half-mutinous drivers largely ignorant of English, received the full benefit of this
ambitious feeling. Near Tolomé and at Paso de Ovejas he lost men, wagons and
pack-mules; and at the national bridge there was a genuine skirmish, in which a
number of Americans were killed or wounded. Out of about 130 wagons twenty-
68. four had to be abandoned in the low country; and a little way above Jalapa, though
strongly reinforced, the troops had to fight again. General Pierce, who left Vera
Cruz about six weeks later than McIntosh, had similar experiences. Early in August
Major Lally set out from the coast with a few more than 1000 soldiers, two 6-
pounders and sixty-four wagons. He lost no merchandise, but his four fights cost
him nearly 100 men killed, wounded and missing; and Captain Wells, who followed
Lally with some 200 recruits and additional ammunition, lost forty and had to
retreat. These and other affairs proved that irregulars, favored by the geography of
the region, were capable of doing substantial harm.[7]
But in Vera Cruz, as in every other quarter where they operated, though perhaps
nowhere else in so marked a degree, the lack of morale, which enabled the guerilla
system to exist, proved the cause of its failure. Poor arms, poor ammunition, poor
marksmanship, and the want of artillery might have been remedied, or at least
might have been offset by the counter-balancing advantages; but this defect was
fatal. The Mexican guerillas were very different from what the guerillas of Spain had
been. They fought like savages without the excuse of savages, for they knew
better. Infuriated by their treacheries and cruelties, the Americans were persistent
and unsparing in severity. Patrols who seemed never to sleep hunted out their nests
in the mountains. On the march, flanking parties would force their way through the
woods five miles or more from the road to catch them between two fires. The torch
was applied with much liberality on suspicion, and sometimes on general principles,
to huts and villages; and in the end a black swath of devastation, leagues in width,
marked the route.[8]
Scott ordered that in every case of outrage the nearest alcalde, if he failed to
deliver up the guilty, should be fined at least $300 for a murder or the value of the
stolen property for a robbery, and that any robber or murderer and any person
belonging to a known party of such miscreants might, when caught, be summarily
tried by three officers, and either flogged or executed. This plan, however, did not
quite satisfy those on the ground—especially the Texas troops. Captain Walker, on
his cream-colored horse, and Colonel Hays, in his blue roundabout, black trousers
and black leather cap, impressed themselves on the Mexican imagination as the
agents of diabolical wrath; and in general it was a tale of merciless atrocities
followed by merciless reprisals.[8]
At the same time this lack of morale deprived the guerillas of Mexican support. By
taking bribes for letting merchandise pass up to the interior and sometimes even
guarding it, they violated the laws on which their existence rested. Mostly they
were brave only where they felt safe. When laden with booty they would scatter to
their homes, no matter how important the business in hand. Rivalries and even
hostilities between parties operating in the same district arose. Cooperation could
seldom be reckoned upon, and hardly any would face the climate far above Jalapa.
Soon learning that it was more wholesome to waylay Mexicans than Americans,
they plundered their fellow-countrymen without ceremony; and they would rob
69. GUERILLAS OF THE CENTRE
even old women or young children of their needful clothing. Sheafs of complaints
against them piled up in the state and national archives. People organized to fight
them, and sometimes appealed to the Americans against the very men who were to
have been their champions.said an American officer.[9]
In the states of Puebla, México and Oaxaca also
guerillas were organized, and in Puebla all these
parties could find an opportunity. General Rea, a pupil
of Morelos and the Mexican revolution, had the discredit of the chief command,
though Bravo, who stood at the summit of the social scale, was mainly responsible
for their iniquities, since during his brief term as comandante general of Puebla he
issued a great number of patents to unfit leaders. What Rea did particularly in this
regard was to combine individuals and small groups, and place them under some
kind of supervision. He loved to answer critics by saying that his guerillas were in
the field because honorable men were not; and that, had not the government
condoned their crimes, they would have served the Americans as counter-guerillas.
After a time his officers adopted a set of rules which aimed to regulate operations,
but even this measure seems to have accomplished little. The guerillas robbed the
people, seized funds belonging to the state, and pillaged even churches. Some
gangs were large enough to attack haciendas. One party called themselves the
“Lancers of the Poisoned Spear.”[10]
Soon after Scott left Puebla for Mexico early in August, 1847, these banditti and
every individual ruffian of that vicinity hurried to the city. Mexicans and even foreign
residents were robbed and outraged, and about the first of September, in the hope
of more booty, the Americans also were attacked. Two thousand soldiers were
needed for a garrison, and Colonel Childs, the civil and military governor, actually
had 2193; but 1800 of these were in hospitals. His effectives consisted of about
fifty cavalry, 100 artillery, 250 of the First Pennsylvania volunteers, and a small spy
company of Mexicans.[11]
Headquarters, Lieutenant Colonel Black of Pennsylvania and the main body of
troops occupied thea large rectangular building on the eastern side of the town,
which had a plaza of its own opening toward a public promenade called the Tivoli.
To this position five howitzers were allotted, and within a hundred and fifty yards of
it all the sick were placed. Half a mile or so from the town on a hill stood Loreto
fort, a stone affair equipped with two 12-pound field guns and a 10-inch mortar,
where Major Gwynn of the Sixth Infantry commanded; and not far distant, on a
higher point of the same hill, was Guadalupe church, now protected with mountain
howitzers, a ditch and an earthen wall, under Captain Morehead of the
Pennsylvania regiment. But the chief element of the defence was the large, robust,
finely-featured Childs, a skilful and veteran officer, cold in manner, clear in
judgment, and inflexible in courage. September 13 thebegan in earnest, and from
that day on there was a continual small-arm attack, particularly at night, upon San
José, which replied with a musket and howitzer fire that kept the assailants at a
70. THEOF PUEBLA
respectful distance. What was more serious than guerilla shooting, all supplies were
now cut off. Such was the state of things at the second city of Mexico when Santa
Anna retired from the first.[11]
Santa Anna’s real intention was probably to seek an
asylum in Guatemala. But many of his friends urged
that he could make himself dictator as the sole hope
of the country, and it was clear that, if he should recover Puebla and cut off Scott,
he would still be able to boast of a triumph. His cavalry, though greatly reduced by
desertion, included some 2000 men backed with four light guns. Alvarez, who was
ordered to Puebla, still had about 600 foot and horse. Rea, Santa Anna understood,
commanded 600 irregulars; 2500 National Guards lay near him with two field
pieces, it was reported; and the Pueblans were described as eager to fight. Six
thousand men and six guns appeared quite enough to dispose ofas Mexicans
described the garrison; and he therefore presented himself at Puebla on September
21. Two days later Alvarez arrived there. But between these two events Childs
appeared at a second-story balcony, as a soldier expressed it, and announced that
Scott had taken the capital. Evidently, therefore, the Mexican President was not
greatly to be feared.[11]
After looking about, Santa Anna concluded that it would not be easy to capture the
American positions by assault, and appealed to the minister of war—wherever that
official might be—for 1000 infantry, a 16-pounder, a 12-pounder, ammunition and
supplies. He now had ten cannon, but all of them were light; owing to desertion his
force included only some 4000 men; and the citizens had no arms, he reported.
Probably, too, the annoyances and outrages inflicted upon them by him and his
troops, and his appointing the guerilla chief military commandant of the city
dampened whatever ardor they had possessed.[12]
On September 23 and 24 unsuccessful attempts were made at Guadalupe, and the
next day Santa Anna summoned Childs, describing his army as 8000 strong, and
graciously announcing thatthe Americans might retirewith the honors of war. Childs
replied as was proper, and then, riding to the posts, gave notice amid cheers that
no surrender need be expected. To add the touch of humor that soldiers love, an
American flag was manufactured out of an old Mexican uniform, and raised aloft;
and the garrison settled down to severe duty, stern discipline, short rations and
incessant watchfulness at all hours. The Mexicans tried to approach San José by
throwing up successive breastworks at night in the streets leading that way, but
shot, shell and rockets from Loreto kept them back. September 30 Santa Anna
learned that no ammunition could be provided for the heavy cannon demanded of
the minister, and resolved apparently to make a bold effort. With two 6-pounders
he fired all day on the weak, plaza face of San José. But Childs, anticipating such a
manoeuvre, had brought a 12-pounder from Loreto the night before; and this,
protected with bags of tobacco, made an assault impracticable.[12]
71. THE FIGHT AT HUAMANTLA
A new factor now entered the military situation. About the middle of September
GeneralLane, one of Taylor’s chief officers at Buena Vista, arrived at Vera Cruz from
the Rio Grande, and on the nineteenth his brigade set out for the interior. Aware of
the situation at Puebla but not aware what was to be encountered on the route, the
General had not made adequate preparations, and on meeting guerillas at the
national bridge he was obliged to send back for ammunition and supplies. By
October 1, however, he managed to leave Jalapa.[13]
It was a hard march that ensued. Torrents of rain deluged the troops. Sometimes
the road lay deep under water. For dinner they had a thin slice of beef, a couple
ofand some coffee; for supper, after darkness fell upon them with tropical
abruptness, the same without the beef; and perhaps mud for a couch. But Lane, a
hearty westerner with a stout frame and unbounded vigor, led on unshrinkingly in
his black hat and old blue overcoat, and the rest followed him eagerly. October 5,
after incorporating additional troops at Perote, he left that place with a force of
about 3300 and seven guns, and marched on across hot plains, where water sold
for five dollars a drink, and men died of sheer fatigue.[13]
Santa Anna, informed by spies that 1000 Americans were approaching, and
anxious, not only to prevent them from joining Childs, but still more to win the
glory of routing them, had set out from Puebla four days earlier with perhaps 3500
men, leaving Rea to continue the fighting. Desertion played havoc with his
command, especially when the strength of Lane’s force was ascertained; but, after
sending back a large part of the faithful in order to keep control of them, he took
possession of El Pinal, where the national highway passed between a precipitous
mountain and a ravine, with about 1000 cavalry and six guns, and made
preparations to ambush Lane’s rear. This done, he moved to Huamantla, a sizable
town eight miles distant, and waited.[13]
Early on October 9 the drums and bugles awoke
Lane’s troops at the hacienda of San Antonio Tamaris,
approximately ten miles from Huamantla and twelve
from El Pinal; and the men, leaping from the damp grass and buckling their muddy
belts, found the white walls of the hacienda, the church towers of neighboring
villages, the dark woods on the hillsides, and the distant, snowy peaks all aglow
under a splendid sun. Never, perhaps, did soldiers feel more like having an
adventure. Santa Anna had just marched from Huamantla to conceal his force at El
Pinal, leaving behind him with no scouts or outposts his six guns, a very small
guard for them and a party of irregulars; but a spy reported to the Americans that
he was at Huamantla, and Lane moved off to attack him. First rode four mounted
companies, and at their head a rather short, slender, spare, slouchy man, with
reddish hair, a small reddish beard, mild blue eyes and a quiet, kindly manner,
whom nobody would have picked out as a fearless, indomitable fighter, the scourge
of the guerillas, but in fact he was Captain Walker; and then marched Lane with
five guns and some 1800 men.[14]
72. When about three miles from their destination, Walker and his 200 cavalry, seeing a
party of Mexican horse approach the town, dashed ahead. Entering Huamantla they
formed in fours, and then with a yell, a flash of sabres and a thunder of hoofs they
swept through to the plaza. The Mexicans had time to get four of the guns away,
but the others were captured, and most of the American troopers, concluding their
work had been finished, scattered to drink, loot or hunt for cannon and
ammunition. But now Santa Anna, who had observed Lane’s movement from a
church tower near El Pinal, appeared with his full command. They were a beautiful
sight—galloping horses, red and green uniforms, brilliant pennons and a billowy sea
of flashing lance points; but they were enemies, and the Americans accepted their
challenge.[14]
“Take it cool, my boys, but run like the devil!” cried Lane. Every nerve was taxed.
Blood gushed from nostrils. The Mexicans, lashing their steeds into foam, reached
the goal first, however, and the American troopers found themselves attacked on all
sides. Walker was shot from a house, and soon expired; but he lived long enough
to give a final order: “Don't surrender boys; the infantry will soon be here.” And so
they were—“with a shout and a bound,” said one of them. The tide was quickly
turned, and giving up the town, as the soldiers loved to call Santa Anna, passed the
night some distance away. So ended the Tale of Huamantla or The Biter Bitten,
which received no little applause at the time.[14]
While these events were taking place, the garrison of Puebla continued to be
hemmed in, starved and harassed. Their casualties numbered in all only fifty-two,
but they felt severely the effect of so long a strain. Though a number of sorties
were made, and their persecutors had to retire from several annoying positions, the
Americans were not strong enough to do more. Their day of deliverance was
approaching, however. October 10 Lane moved forward, dogged and somewhat
annoyed by Santa Anna. Two days later his men saw the spires of Puebla,
dominated by the sombre towers of the cathedral, and set off by white volcanoes
veiled with clouds. And now and again the numberless bells of the city, great and
small, pealed forth harmonious tones of many colors, that seemed to blend and
interweave in rich and varied tapestries of sound, hung out in the mediaeval style
to honor their triumphal approach.[15]
At about one o’clock, announced by the bells of Guadalupe, they entered the
suburbs—not a few of them at a run. One column then advanced by the main
street, while another flanked the town by the left. For two hours there was
considerable firing from houses, though Rea’s guerillas had begun to leave their
posts the night before; but at length Lane extended histo Childs, with a sunny smile
on his rather hard features, and the garrison joyously welcomed their deliverers. In
the main plaza a bugler playedand all sang the chorus:
“The star-spangled banner, Oh, long may it wave
O’er the land of the free and the home of the brave!”[15]
73. POLITICAL CHAOS IN
MEXICO
Now followed the punishment of Rea. Some twenty-five miles from Puebla toward
the southwest lay beautiful Atlixco, a defensible point that not only reconciled the
climates of the temperate and the cold zones of Mexico, and controlled a region
fertile in grains, flocks and herds, but, while fairly remote from the Americans, gave
convenient access to important roads. Here, in the midst of flowers, fruits and
snowy mountains, the government of Puebla had found a refuge, when the
Americans under Worth approached the state capital; and to this asylum Rea now
withdrew. De facto, at least, the guerilla chief was the most important person on
the ground. The authorities did not relish his prominence; they detested his men
and his methods; and on October 18, tired of spending money fruitlessly on the
National Guards for Rea to command, they dissolved the corps. But many of the
irregulars proposed to make the best of what appeared to be a good situation, in
which they could live on plunder, if not paid.[16]
October 18 Lane, who apparently never slept nor expected his followers to sleep,
ordered them to be ready in the morning for an expedition. Many of the soldiers
were barefoot, but they borrowed shoes; and at about nine o’clock, cheered by the
fife and the drum, some 1500 men set out round the base of Popocatepetl under a
hot sun. At about four in the afternoon, after making twenty miles or so, they came
in sight of the enemy, and a running fight began. Blistered feet and parching
tongues were now forgotten. The Mexicans, holding some good position and
protected by chaparral, could make a stand against cavalry, but when the infantry
came up they always fled. Shortly after sunset Lane reached Atlixco, which stood
on the slope of a lofty hill. As it was unsafe to risk a street fight in an unknown
town at night, he ordered the artillery to open. The moon was full. Marks were
easily selected. By their burning fuses the shells could be traced until they fell
amidst the shadows; and then a burst of red fire, the crash of roofs and walls, and
the cries of the people told the rest.[17]
After about an hour of cannonading, the troops advanced into the town—which
surrendered at once—and there slept as best they could. Rea, with two guns and
the disordered remnants of his force, retreated to Izucar de Matamoros, about
thirty miles farther down the valley; but from that point he was routed a month
later. These and other exploits of Lane’s discouraged as well as dispersed the chief
guerilla forces of the plateau, and in February, 1848, Rea asked permission of the
Mexican authorities to leave the country.[17]
Neither in these affairs nor in any other military
operations did Santa Anna figure at this time, and
there was a good reason for his inactivity. Officially he
no longer existed. As General Scott had feared, our
entering the capital had resulted in the destruction of the Mexican government.
September 16 Santa Anna resigned, explaining that it was advisable to preserve the
chief magistracy from the hazards of war, and fix it near the centre of wealth and
population, whereas he proposed to continue the hostilities wherever that should
74. SANTA ANNA ELIMINATED
be possible. The same proclamation or decree assigned the executive power to a
triumvirate: the president of the supreme court, General Herrera and General
Alcorta, and Santa Anna then ceased actually to exercise any civil authority.[18]
But as Congress was not in session to accept his resignation, some doubted
whether it became effective; the presidency of the supreme court was vacant on
account of the incumbent’s death; the appointment of Herrera and Alcorta needed
to be made, or at least confirmed, by the council of government, a body no longer
acting; and it was denied broadly that Santa Anna had the power to issue such a
decree. Peña y Peña, to be sure, was regarded as a member of the court, and, if he
was, he could claim by right of seniority to act as the chief justice; but the legality
of his membership was questioned, and the presidency of that body was really an
elective office. Peña was old, feeble and even timid; his ill-success as Herrera’s
minister of relations doubtless weighed heavily upon him; and he was now living,
almost as a recluse, in the country. Indeed there was really no organic law even, for
the amended constitution of 1824, though formally adopted, had not come into
effect. In short, chaos reigned, and the states were officially “resuming” their
individual sovereignty.[18]
But a number of good and able men, particularly Cuevas and Couto, determined to
ward off ruin, and awakened others. Peña, drawn from his retirement, consented
for patriotic reasons to override all the technical difficulties; and on September 22
he announced formally that, in order to give the nation a head, he would act as the
Executive until an interim President could somehow be chosen. At the small city of
Toluca, capital of the state of México, just outside the Valley, this fiction of a
government pitched its tent; and perhaps it gained some feeling of security from
the vast bastioned, battlemented ridge between it and the Americans, from snowy
Mt. Miguel towering above the city, and from the peacefully shining lagoons of the
intervening meadows. What was more important, Herrera, Olaguíbel and many
others of the best men rallied to the support of Peña, the representatives of neutral
governments recognized him, and the states began to concur. Early in October,
however, he removed to Querétaro, a safer yet central place, and with Luis de la
Rosa as sole minister addressed himself to his task.[19]
The programme that he announced was honorable
and straightforward. My tenure of office will be
extremely brief, he said in effect, for Congress will be
assembled as soon as possible; I will usurp no powers, but will not be turned from
the path of duty by insurrections; the closest economy will be practised, the
necessary taxes laid fairly, and all interests respected; union and harmony will be
the watchwords, and the national rights will be maintained. His most urgent
problem, of course, was to deal with Santa Anna, who not only held the chief
military command, but insisted that he could resume the Presidential authority by
simply withdrawing his resignation; and in this matter the government showed a
decision that earned it no little prestige. All Santa Anna’s protests against political
75. effacement were disregarded, and on October 7 he was instructed both to give up
his troops and to submit, as did other unsuccessful commanders, to a military trial.
[20]
At about the time this order overtook him, the Huamantla affair occurred. From a
military point of view he was now prostrate. He saw it himself, and knew that the
country would see it. Evidently his countless political enemies would make the most
of his complete failure, and he was doubtless aware that his military reports had
offended many officers. His chief executive merits—decision and activity—had led
only to a useless expenditure of life and money, it was now pointed out, and his
ostensible patriotism was attributed to passion and obstinacy. Even his confidence
in himself broke down. Unable to understand why failure had attended all his
efforts, he fell into a sombre depression, and without a struggle he placed his
troops at the orders of General Reyes, who joined him on October 11 with about
1000 men. His part in the war was over; and in the following January, realizing that
nothing could be gained through intrigue or conspiracy and fearing the Americans
would make him a prisoner, he asked for permission to leave the country. Both his
own government and our authorities consented. And after giving a dinner at El
Encero to the American officers of that vicinity, who had treated him with
distinguished consideration, he sailed once more, about the first of April, from what
he regarded as an ungrateful country.[21]
Santa Anna being now eliminated, the government had to face its military
difficulties without his assistance. In general the problem was to make bricks with
neither straw nor clay. Almost every good cannon had been taken by the
Americans, and the muskets had nearly all been captured, thrown away or sold.
Ammunition was almost wholly wanting. The engineering material had been lost or
destroyed. Vast sums of money were needed to provide fortifications as well as
replace all this equipment, and the government could hardly obtain enough, day by
day, to cover its minimum expenses. Even officers had to sell their shoes for bread.
[22]
As for an army, Santa Anna and Alvarez together had some 2000 troops the first
week of October, Reyes had about 1000, about 3000 from Mexico City concentrated
at Querétaro under Herrera, about 1000 from Jalisco were on their way to the same
point, and small detachments existed at various other places. But nearly all of these
men were utterly demoralized. “Almost useless,” they were officially termed; and
the army as a whole felt the crushing weight of general contempt. Herrera, the
commander-in-chief, became so disgusted over the uncontrolled excesses of the
troops that he resigned. Rincón declined on the ground of ill-health to serve. Arista,
when summoned to Querétaro, declared he would not command a soldier until
exonerated for his conduct on the Rio Grande. No officers of high distinction,
indeed, were available except the aged, torpid and infirm Bustamante and “the old
woman,” Filisola, as Bancroft described him.[22]
76. THE AMERICAN POLICY
Attempts were made to lay plans of campaign, but an expert summed up one of
them by saying it appeared excellent—only it was based upon things as they should
have been, not as they were; and all the others had the same defect. Schemes
were devised to reform, reorganize and build up the forces, and quotas amounting
to 16,000 were assigned to the states; but México, which had been expected to
furnish nearly a quarter of these men, promptly answered that she could not, and
other states did not even reply. In fact, the regular forces decreased instead of
multiplying, for sometimes a general could not feed his troops, and frequently,
when soldiers were let out of the barracks on service, they vanished; and the
people, instead of helping to support the Mexican troops, even dreaded to see
them approach, for their coming was liable to draw an American attack, and more
than liable to mean extortion, outrage and robbery. Nowhere on the military horizon
could a glimmer of light be seen.[22]
Over against this pitiful government stood the United
States—wealth against poverty, strength against
weakness; and the antithesis was complete, for while
the Mexicans could only plan, that was the hardest thing for us to do. The idea of
retiring to a defensive line still persisted. Taylor himself adhered to it. But in
addition to the other overwhelming objections to this project, it seemed improbable
that a majority in Congress could agree where to draw the line. Even Calhoun,
though qualified to make a better argument for an untenable proposition than any
other man in the country, was unable to present this policy in such a manner as to
satisfy either the friends or the opponents of the war. Some advised holding, in
addition to the territory thus to be cut off, the chief ports of Mexico; and some
advocated retaining the capital also, and the line to Vera Cruz. Others favored the
occupation of still more cities; and many were for subjugating and holding the
entire country.[23]
To this last plan, however, even had it been practicable to levy all the costs upon
Mexico, there were tremendous objections. It would have involved keeping under
arms 80,000 or possibly 100,000 young men, seriously needed at home for the
most part, in order to be sure of having effectives enough at the front. The troops
in Mexico would have become corrupted both physically and morally; and the
commanders would have acquired the ideas and vices of proconsuls. It seemed to
be almost an insoluble problem. No final decision was made. But the government
determined to occupy the capital, hold the line to Vera Cruz, retain the chief ports,
and extend our holdings according to circumstances.[23]
To Scott, however, the lack of a definitive plan signified little. Not one reinforcement
entered the capital until after the first of November, and even at the end of that
month he was barely able to garrison Mexico and Chapultepec. December 4 his
army included only about 8000 privates, of whom a quarter were sick. During the
next three weeks Generals Patterson, Butler and Cushing, Colonel Hays, Lieutenant
77. Colonel Johnston and Major Lally, each with troops, arrived; and the forces then
numbered about 11,000 effectives and 3000 sick.[24]
Scott therefore announced, with no doubt a strategic purpose as well as a rhetorical
flourish, that our army was “about to spread itself over and to occupy the Republic
of Mexico.” What he really intended was to take possession successively of the
principal mining regions—those of Zacatecas and San Luis Potosí—and the capitals
of such important states as lay within easy reach. Even for the former purpose,
however, two columns of some 5000 effectives each were needed, and the men as
well as clothing for them could not be provided. The only immediate operations,
therefore, aside from the establishment of new posts on the road to Vera Cruz,
were the peaceful occupation of Pachuca, a mining town about fifty miles northeast
of Mexico, Toluca, about thirty-eight miles distant in the opposite direction, and
Cuernavaca, the key to the Acapulco region, a little farther away toward the
southwest.[24]
February 6, 1848, an expedition of more consequence marched, by Scott’s orders,
from Vera Cruz. Most of the guerillas who infested the road to the interior lived and
found a market at or near Córdoba, a city about sixty-five miles to the southwest,
and Orizaba, sixteen or eighteen miles beyond it in the same direction; and
Bankhead was instructed to occupy those towns. Very different from Lane’s rough
trips on the plateau was this march. Near Córdoba flourished such genuine tropical
wonders as the bread tree, the butter tree, the milk tree, and a kind of palm called
“the traveller’s friend,” which covered the wayfarer’s head with a tent, and
quenched his thirst with abundant sap. Going on, one found enormous masses of
vegetation—thick, matted, boundlessly prolific—moulded into astonishing yet
harmonious forms by the bays and promontories of the rapidly mounting foothills;
terraces of luxuriant foliage piled on sheer cliffs, castles on the terraces, and
cathedrals on the castles; verdure, verdure everywhere, dripping, flowing, spurting,
tumbling in every hue and shade of green, with a dark, velvety mist in the gorges
that became clear sapphire when the sun touched it, and here and there a cascade
letting fall its crystal thread from a mossy crag.[25]
Then came the rich Orizaba valley, hemmed in with jungles, and winding off
between sombre, precipitous mountains until lost in the dreamy distance; and
above it the sparkling snows of the vast peak sent down a torrent of gray glacier
water, that leaped into mid-air, and then, gathering itself below, wound on through
splendid, odorous trees full of parrots, canaries and mocking-birds, hurried past
fragrant orange groves and still more fragrant blossoms, poured through the arches
of a noble old bridge, and buried itself in the woods. But the Americans did not
forget their orders. Both cities were occupied without resistance, and both were
garrisoned; and the guerillas now found their proceedings considerably hampered.
[25]
78. THE REMOVAL OF SCOTT
The final military operations of Scott seemed thus
rather tame, as was natural; but Polk executed one
that could be termed startling, if not exactly brilliant.
His principal assistants were Pillow, Worth and Duncan; and in different ways each
had excellent qualifications for the work. Pillow was not “The Lie Incarnate,” as Trist
believed, nor even “a perfect ass,” as many thought; but vanity, ambition, lack of
probity, and a gift for dark and cunning methods characterized him. His instincts
and talents, indeed, were those of the criminal lawyer who minds nothing about his
case except the verdict. When the President’s brother shot a man down in the
street at Nashville, Pillow got him off. With reference to his work in helping bring
about Polk’s nomination at Baltimore he wrote, “The fatal blow was given, but it
was not seen nor known what produced such a result—nor where the blow came
from.” “I feel as boyant as the air,” he said in December, 1846, when great
dissatisfaction with Taylor prevailed at Washington, because I know “that I have
done the work.... I have paid him in full” for his treatment of me. And one could
seldom get a finger on Pillow’s back, when he was not wriggling actively toward
some object of selfish desire.[26]
Without a particle of real military ability or success to his credit, he now stood
second in our army, and hence logically enough saw no reason why he might not,
by some devious path, arrive at the first position and even at the Presidency.
“Modesty,” said Burke, “does not long survive innocence.” To plant such a person,
with urgent recommendations, at open, big-hearted Scott’s right hand, to win his
confidence, to spy upon, criticise and undermine him, and inevitably to scheme for
his place, was indecent; but Polk did it.[26]
Very unlike Pillow was the courtly and fascinating Worth; but his mind was intense,
narrow and self-centred. After the battle of Monterey he exclaimed, “I am satisfied
with myself. The most vindictive foes crouch at my feet, and my friends choke with
joy and delight.” And there is one sin of which even angels are capable, we have
been told. All his military recognition he owed to Scott, but probably the debt
weighed heavily on his proud and restive nature; and, while apparently
reciprocating the genuine affection of his chief, he had inwardly rejected Scott’s
principles and methods nearly thirty years before the Mexican war. Regarding his
friend, fellow New Yorker and brother Democrat, Marcy, an adroit politician, he felt
very differently. “I would not give an ounce” of his wisdom, he wrote in June, 1846,
for all Scott’s glory; Scott “is determined to sink and draw his friends down with
him.”[27]
At Vera Cruz the commander-in-chief, relying on their long intimacy, told Worth
frankly that he believed the administration intended to ruin him, and the
subordinate officer evidently determined not to be drawn down. At the same place
a brother officer suggested to Worth a higher position than was even the highest in
the army. The suggestion appears to have struck root. All military men believed the
next President would be one of them, and what commander had acquired a more
79. THE REMOVAL OF SCOTT
brilliant reputation? The New York Sun recommended him for the place; and the
idea of his candidacy was favorably received by many. This prospect naturally
turned him still more against his old friend, for either Scott or Taylor seemed almost
certain to be the Whig nominee. Through a series of clashes, for which little—if any
—justification can be seen, and in spite of Scott’s efforts to conciliate him, Worth
proceeded then to gain emancipation from his burden of gratitude, and place
himself in open antagonism to his former patron.[28]
Duncan’s motives were different again. He was
intimate with Worth; and Pillow, who offered to marry
the Colonel to a rich and handsome widow, doubtless
promised him the post of inspector general. At any rate he urged Polk to make the
appointment, hinting at other reasons than mere qualifications, and it was made;
and we know that Duncan gave himself much trouble to assist Pillow as a partisan
supporter. The power of such a combination, headed by the President himself, to
gather adherents from the many ambitious officers hardly needs to be pointed out;
and finally there were, of course, jealous and envious men. “Since we cannot attain
to greatness, let us revenge ourselves by railing at it,” said Montaigne for the
benefit of such persons; and many of the officers knew that greatness was beyond
their powers. None of them could monologue as Scott did; none could look in a
cocked hat as he looked; none had won the Mexican war; and, moreover, he was
the sole general-in-chief.[29]
The result was a powerful movement against the prestige and authority properly
belonging to Scott. Pillow’s reports on the battles of Contreras and Chapultepec
tended to represent the General as a nonentity; and Worth not only did somewhat
the same, but referred to the Commander in terms of ridicule and contempt. A
letter, doubtless written directly or indirectly by Pillow over the signature of
“Leonidas,” extolling Pillow shamelessly and belittling Scott, was trickily worked into
the New Orleans Delta of September 10, 1847; and another letter, containing a
passage intended to show that Worth and Duncan had saved Scott from choosing
the wrong approach to the capital, appeared in the United States, then in a
Tampico newspaper and finally at Mexico City. Both letters were grossly improper,
especially since the army lay in the enemy’s country; and Scott found it necessary
to act. As he well said, “The general-in-chief who once submits to an outrage from
a junior, must lay his account to suffer the like from all the vicious under him,” and
“even the great mass of the spirited, intelligent, and well affected, among his
brothers in arms, would soon reduce such commander to utter imbecility, by
holding him in just scorn and contempt” for his recreancy to himself and the
country.[30]
On November 12, therefore, he issued his General Orders 349, which aimed to
stigmatize these offences in such a way as to prevent a recurrence of them.
Duncan then assumed in a plainly defiant manner the paternity of the Tampico
letter, although in fact the offensive passage had not been written by him. His
80. primary object in doing this was evidently to give Worth a handle, and the handle
was promptly seized. One thing led to another; and in the end formal charges were
brought by the commander-in-chief against Pillow, Worth and Duncan, and by the
two generals against him; appeals—insulting to Scott—were made by Pillow and
Worth to the government; and the technical “arrest” of the three officers followed.
[31]
The government then stepped in. Scott had no doubt given it offence during the
campaign, for his letters had plainly enough revealed a conviction that Polk had
broken faith with him, and purposely thrown difficulties and annoyances across his
path; but the circumstances had appeared to warrant his complaints, and Marcy
had at least “got even” by administering liberal censures in reply. The balance in
fact—aside, perhaps, from a mere acerbity of language—was against the
administration. Besides, having served the country well and saved the government
from disaster, Scott was entitled to some indulgence for irritation caused by the
peculiarly trying circumstances that surrounded him. He was a large man, had done
a large work and merited large treatment. But there was nothing large about the
administration. The confines of mediocrity hemmed it in. Pillow and Duncan were
therefore by its orders relieved of arrest; Worth was not only released, but assigned
to duty according to his highest brevet rank; and “in view of the present state of
things in the army,” chiefly or entirely caused by Polk’s agent and Marcy’s friend,
Scott was deposed. He had performed his task, said Robert E. Lee, and now was
“turned out as an old horse to die.” April 22, 1848, amidst the lamentations, cheers
and blessings of the army as a whole—trembling himself with emotion—he took his
leave, and Major General Butler, who was a Democrat and looked well on a horse,
bore sway at headquarters.[32]
81. XXX
THE NAVAL OPERATIONS OF THE WAR
1845–1848
In January, 1846, the United States had available for naval hostilities one ship-of-
the-line, seven frigates and razees, fifteen sloops-of-war, six brigs, one schooner
and three steamers—that is to say, thirty-three war craft. As ships-of-the-line
carried more than seventy guns, frigates about forty-four to fifty, sloops twenty,
brigs ten and other vessels in proportion, this fleet had 1155 cannon. Two of the
vessels, under Commodore James Biddle, were on the coast of Asia; several
occupied the Brazil station; and five cruised in African waters to check the trade in
slaves. The Pacific squadron, commanded by Commodore John D. Sloat, comprised
on July 1, 1846, the frigate Savannah, the sloops Portsmouth, Levant, Warren and
Cyane, the schooner Shark and the storeship Erie, to which the frigate Congress,
the razee Independence and the sloops Dale, Saratoga and Preble were added later
in the year, while the Levant went home; and substantially all the rest of the fleet,
known as the Home Squadron, attended to the West Indies and Gulf service, under
Commodore David Conner.[1]
The appropriation for the year ending with June, 1846, was a little less than ten
millions, but only about six and a half millions were expended. The war bill of May
13 permitted the completion of all vessels then building and the purchase of others;
and by November, 1847, after suffering a number of losses, the navy had in
commission five ships-of-the-line, one razee, four frigates, thirteen sloops, six brigs,
eleven schooners, four bomb-vessels, twelve steamers and six storeships.[1]
The peace establishment created by Congress in 1844 provided for 7500 petty
officers, seamen, landsmen and boys, and in August, 1846, this number was raised
to 10,000 for the period of the war; but owing to the remarkable activity of the
merchant marine and the consequently high wages, men could not easily be
obtained. During the most important year—November, 1846, to November, 1847—
not over 8000 were in the fleet at any one time. The whole number of seamen
employed in the course of the war did not exceed 7000; and hence plans to
strengthen our forces in the Gulf and the Pacific had to be curtailed. The service,
too, did not enjoy unqualified popularity. In the sailor’s decalogue appeared this
commandment:
82. PRIVATEERING
“Six days shalt thou work
And do all thou art able,
On the seventh thou shalt holystone
The deck and scrape the cable”;
and the cannon had to be rubbed with fragrant “sea pitch” from the bottom of the
ocean until they shone like Japanese lacquer. Discipline, therefore, not reinforced by
the enthusiasm and the necessities of war, fell considerably below its reputation,
and the crews were eager to be free when their time expired. The officers, even,
had become lax after thirty years of peace, and in too many instances their
standards of conduct had given way.[2]
In the administration of the navy, also, the effects of a long peace could be seen.
The control of matters had fallen, though not by accident, into the hands of shrewd
officers deeply interested in themselves and their friends. Supernumeraries
abounded. Those who drew the most pay often rendered the least service. The pet
ambition was for a safe, quiet and easy position. Shore billets were too numerous.
No field officer of the Marines had cruised since his promotion, and one of them
had been in the service more than a generation without going to sea. Secretary
Bancroft, eager for distinction, undertook to eliminate the abuses, but only
succeeded in eliminating himself. He had taught Greek, and was ridiculed by the
naval men as undertaking to play the pedagogue over them. Having no dominating
force of character nor even a commanding presence, he could not stand against the
governing clique. The requirements of the war, which might have assisted an abler
administrator to win the day, only increased his difficulties. The Senate refused to
confirm some of his appointees; and early in September, 1846, he became our
minister to England.[3]
J. Y. Mason, who succeeded him, was a fat, easy, agreeable man, quite innocent of
the desire to achieve reforms. Nobody disliked him, but nobody felt obliged to obey
him; and as late as the twentieth of February, 1847, suddenly discovering that Scott
had mentioned certain designs of the army against Vera Cruz, he awoke to the fact
that his department had failed to give the anticipated assistance. Just what could
be expected of the navy under all these prejudicial conditions was, therefore, in
some minds, a little uncertain.[3]
One of the most serious duties imposed upon it was to
guard against privateering, for not only our commerce
but the supplies required by our troops depended
upon free lanes. About the middle of 1845 the government issued orders that any
activity of such a kind on the part of Mexico should be considered the signal for
war; and as a deterrent it was announced by the newspapers, though incorrectly,
that privateersmen were to be regarded as pirates. Crews not predominantly
composed of Mexicans, it was often asserted, could legally be “strung up to the
83. yard-arm,” since we were understood to have treaties that sanctioned this principle
with most countries.[4]
After the war actually began, a great deal of danger was apprehended. Desperate
characters were believed to be waiting at New Orleans, and “piratical gangs” in the
ports of Cuba, where Almonte seemed to be at work. News arrived early in August,
1846, that privateering regulations had been issued by Mexico, and suspicious craft
soon appeared off Key West. In December the Mexican minister of war openly
avowed that great hopes of injuring the United States in this manner were
entertained. Blank certificates and commissions reached Washington; information
regarding efforts to set vessels at work in various quarters arrived there; and finally
the Carmelita of Bangor, Maine, was captured near Gibraltar by a felucca named El
Unico, fitted out at Oran, Algeria, and run by Spanish desperadoes.[4]
Mexico had not in reality, after studying the subject with deep interest, much
expectation of accomplishing any large results by issuing letters of marque, and the
regulations of July, 1846, were intended principally or wholly to annoy this country;
but in September and October she took the matter up rather seriously. A new law
provided that any foreigner entering her naval service might become a Mexican at
once, and blank naturalization papers as well as thousands of privateering
commissions, duly signed but not filled out, were carried by agents to the West
Indies, Great Britain, France and Spain. Almonte did his best at Havana. J. N.
Pareda, appointed Mexican chargé d’affaires at Madrid, appears to have circulated
the documents actively in the Peninsular ports; and another privateer, a Spanish
steamer named La Rosita, put out from Oran.[5]
On the other hand, the representatives of the United States insisted upon our
treaties and the obligations of neutrality. Polk’s annual Message of December, 1846,
denounced the Mexican plan as inviting “all the freebooters upon earth,” who felt
like paying for the privilege, to cruise against American commerce, announced that
our own courts would say whether such papers could protect them from the pirate’s
doom, recommended that Congress provide at once for the trial of Spanish subjects
caught in such business, and suggested American privateers—intended mainly to
recapture vessels taken under Mexican letters. An American force hastened to the
Mediterranean, and our squadrons were expected to seize all the rovers putting
out, as well as intercept all prizes on their way to the enemy’s ports. These
precautions looked rather discouraging to enterprising desperadoes.[6]
In England there was a feeling, as will appear later, that Mexico should be allowed
the utmost license against us, and the Mexican minister at London received many
applications for letters; but Great Britain did not really wish her supplies of cotton
to be endangered, and all the seas to be filled with corsairs preying upon the trade
of the world; and in October, 1845, her minister to Mexico was instructed to
prevent that country, if he could, from issuing letters of marque indiscriminately.
Bankhead protested also, as did the Spanish minister, against important features of
84. THE BLOCKADE
the regulations. Palmerston himself, though he acted in a languid fashion, and gave
notice at Washington that British subjects, found on Mexican privateers, could not
be treated as pirates, announced that his government would faithfully do its duty.[7]
France was prompt and active in responding to our demands. Spain, placed under
stringent obligations by the treaty of October, 1795, promised full compliance with
its requirements, captured El Unico, punished its crew, pursued La Rosita, and
ordered O’Donnell, the captain general of Cuba, to act as her obligations required;
but she accepted Pareda, the colporteur of what was piracy under her agreement,
as consul of Mexico; and the captain general, while he convinced the American
representative of his good-will and in fact would not permit an open violation of the
treaty, suggested to the Mexicans ways—fortunately impracticable—of evading his
own rules. But the risks of privateering under so many embarrassments and the
virtual impossibility of converting a prize into cash, prevented all attempts except
the feeble ones already mentioned. In this field, consequently, our navy, though
incessantly watchful, could acquire no laurels.[7]
Another aspect of the situation concerned it more
seriously. On the day Congress passed the war bill
(May 13, 1846) orders were issued to blockade the
ports of Mexico. Several definite aims prompted this action. Primarily, of course, it
was desired to prevent supplies of all kinds from reaching the enemy, and to
deprive them of the almost indispensable revenues obtained in peace by taxing
imports; but there were also hopes that loss of business would induce Great Britain
and France, which had a profitable trade in that quarter, to urge upon Mexico the
acceptance of our terms. The blockade was therefore to be enforced vigorously. At
the same time neutrals were to be treated with all reasonable indulgence.
Theoretically only their war vessels had the right of entering closed ports, but
practically the intention was to broaden that narrow door considerably. Toward
itself, however, the United States determined to be strictly faithful in observing its
declared principles. Merely those ports where the order could become effective
were in view. The announcement of blockade was to be made as public as it could
be; and in particular the government required that a full warning should be given to
neutral ships.[8]
For the work thus imposed upon him Conner had ample time to prepare. As early
as August, 1845, he was directed to blockade the Gulf ports in case of war; early in
1846 he knew of Mexico’s attitude regarding Slidell; before the end of March his
vessels occupied convenient positions; and promptly on the outbreak of hostilities a
blockade was announced at the chief harbors. By July, with some assistance from
the revenue service, it extended from the Rio Grande to the Goatzacoalcos.[9]
But the difficulty of making it continuously effective proved to be extraordinary.
There were not vessels enough of the proper kind; occasionally a more or less
complete concentration became necessary; and accidents of many sorts occurred.
85. Uncharted shoals and rocks, currents of unknown direction and force, the frequent
haze, and the darkening of the lighthouses made extreme caution imperative. The
suddenness and violence of the storms almost surpassed belief. At Vera Cruz the
Somers was blown over and sunk before Semmes, her able commander, could take
steps to avert the disaster. Even at the anchorages one would suddenly hear on a
calm afternoon the clarion orders of the speaking trumpet; the ship would quiver
and reverberate as the cable of the heaviest anchor ran swiftly out; in a moment
the storm would burst; and for days it might be a question almost hourly of going
ashore. At such times all sailing vessels on patrol duty had to make instantly for the
open sea, and before they could return to their stations a lurking blockade runner
could perhaps enter the port. Owing to such difficulties Alvarado and Frontera, for
instance, could not be watched continuously.[9]
Embarrassments also of a minor yet serious character had to be encountered. Our
vessels, unlike those of England, were designed exclusively for war, and long
confinement impaired the efficiency of the men. The government supplies of
eatables needed to be eked out from New Orleans huckster boats and European
merchant ships. Water could not be obtained readily from a hostile shore. At the
Antigua River, in July, 1846, the boats going up with casks were fired upon, and
such affairs had to be expected. Vessels were despatched long distances
occasionally to obtain fresh provisions, but even then scurvy of a most serious
nature broke out in the summer of 1846, disabling some of the largest and most
efficient ships for several months. The Raritan had more than 200 cases. Nearly all
on the Potomac suffered. The Falmouth had to go as far north as Boston to throw it
off. Swampy shores and kelp rotting under the torrid sun produced myriads of
poisonous as well as otherwise annoying insects. During a brief stay in the river off
Tampico nearly all the officers and men contracted ague, and the yellow fever
scourged a number of the vessels. More than two thirds of those on the Saratoga
had the latter disease. In August, 1847, the Mississippi left her station with some
200 men suffering from it.[10]
Being strangers and enemies, the Americans labored under peculiar disadvantages.
The people gladly assisted blockade runners in every possible way. Spanish captains
in particular, having friends on shore and pilots thoroughly familiar with the coast,
could not be prevented from reaching harbor at night or in thick weather by way of
the shoals. Sometimes it looked, for one or another of these many reasons, as if
our officers were careless or incompetent. Army observers, not well informed
regarding the conditions, felt disposed now and then to pronounce the blockade a
humbug, and naturally some foreigners did so. This opinion had neither truth nor
probability in its favor. But naturally, in view of all the circumstances, it proved more
satisfactory to occupy the ports, and open them to commerce on the basis of a
reasonable contributory tariff.[11]
Besides cruising to watch for privateers and hovering off the chief harbors to
maintain a blockade, our fleet was expected to share in the general offensive. For
86. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com