(Amber Ferguson,Jorge Ribas,Dalton Bennett/The Washington Post)

Lt. Gov. Ralph Northam won the Democratic nomination for governor of Virginia Tuesday by an unexpectedly wide margin, and Republican Ed Gillespie held off a surprising challenge from Donald Trump acolyte Corey A. Stewart for that party’s nomination.

With more than 99 percent of precincts reporting, Gillespie edged past Stewart by just over a percentage point — fewer than 4,500 votes. State Sen. Frank W. Wagner was a distant third.

The nation was watching Virginia as a political laboratory for how the political parties handle the deep divisions that followed last year’s election of President Trump. The establishment forces seemed to win out, as Virginia voters resisted efforts to pull further to the right or left.

Perriello channeled the energy — and endorsement — of progressive leader Sen. Bernie Sanders (I-Vt.) as he tried to shake up the Democratic Party, but fell short in his bid to bring in enough new voters from among the young and working class to overcome Northam’s command of the Democratic machine, including the endorsement of nearly every Democratic elected leader in state or federal office.

 Celebrating at a restaurant in Arlington, Northam led a giddy crowd in a call-and-response chant, ending with a call to take back the Democratic majority in the GOP-controlled House of Delegates. He said he had spoken with Perriello and “we agreed that we’re going to bring all Democrats under the tent starting tonight. This is too important an election. This is the bellwether of the country.”

He had planned to start campaigning right away with the newly minted Democratic ticket, including lieutenant governor candidate Justin Fairfax, who beat two opponents, and Attorney General Mark R. Herring, who was unopposed for the nomination.

But Northam and Perriello, who were scheduled to appear together Wednesday with the ticket as well as Gov. Terry McAuliffe and Democratic National Committee chair Tom Perez, cancelled their unity rally after a gunman shot and wounded House Republican Whip Steve Scalise (R-La) and several others during a practice for a GOP congressional baseball team earlier in the morning in Alexandria.

The Republican ticket of Gillespie, lieutenant governor candidate Jill Holtzman Vogel, a state senator from Fauquier County who beat two opponents and attorney general nominee John Adams, who had no primary opponent, turned its first campaign stop Wednesday into a prayer event in honor of the shooting victims. The Republicans cancelled the rest of their planned campaign stops for the day.

But there was less unity among Republicans, with Stewart refusing to concede and saying he wouldn’t support Gillespie, a man he derided throughout the campaign as “Establishment Ed.”

“There is one word you will never hear from me, and that’s ‘unity,’ ” Stewart told supporters at a restaurant in Woodbridge. “We’ve been backing down too long. We’ve been backing down too long in defense of our culture, and our heritage and our country.”

Stewart huddled with his campaign staffers, who said they wanted to wait until all absentee ballots were counted and were weighing a request for a recount.

Stewart’s strength on the Republican ballot was the biggest surprise of the evening. He had been running as more Trump than Trump, making provocative statements and campaigning on the issue of preserving Confederate monuments. Polls had shown him with a fraction of Gillespie’s support, but a low turnout among Republican voters gave Stewart’s committed base an outsize influence, and Wagner drew significant votes in Hampton Roads that might otherwise have gone to Gillespie.

Republican candidate for governor Ed Gillespie, right, talks with Republican lieutenant governor candidate Glenn Davis, left, at a polling place Tuesday in Richmond. (Steve Helber/AP)

Overall, Democrats turned out in far greater numbers than Republicans. About 540,000 voters cast ballots in the Democratic gubernatorial primary, while just over 360,000 voters cast ballots on the Republican side, with nearly all precincts reporting.

Both showings outstripped the Democratic primary for governor in 2009, when about 320,000 voters cast ballots.

Gillespie’s support in Fairfax County cushioned his slight edge as final returns came trickling in. Stewart scored big wins in Washington’s exurbs — Loudoun, Fauquier and his home base of Prince William County — as well as in the rural central and southwest regions of the state.

Stewart’s showing rattled Republicans at Gillespie’s party at a Hilton Hotel ballroom in the Richmond suburbs, where supporters who had expected a blowout were concerned to see Stewart running a close second.

Gillespie had remained upstairs at the Hilton most of the evening, but finally took the stage at 10:46 p.m. to chants of “Ed! Ed! Ed!”

“Sorry to keep you waiting,” he said with a small laugh.

He spun the squeaker as sign of fiscal prudence. “I always tell our donors, obviously we did not waste a penny — any more than we needed to win this nomination.”

In his remarks, Gillespie reached out to Republicans who had supported Stewart and Wagner. “We want you to know that we not only will listen to you, we will fight for you through November,” he said.

He did not invoke Trump, who has cast a shadow over the governor’s race all year. The president’s approval rating in Virginia is even lower than it is nationwide: Just 36 percent of Virginians were satisfied with his performance in a poll conducted last month by The Washington Post and the Schar School at George Mason University.

That creates a challenge for Republican candidates this fall, because the party’s base still supports the president, said Mark Rozell, dean of the Schar School. Virginia’s race, he said, will show “whether a prominent Republican in a major campaign is able to separate himself in the public’s mind from the unpopular policies and actions of the Trump administration, while at the same time not losing much of the Republican support a candidate is going to need to win a general election.”

Gillespie’s narrow win, coming from a small and apparently unenthusiastic electorate, suggests that he faces a major challenge as he tries to both woo Stewart voters and attract moderates and independents while he fights a highly motivated Democratic opposition.

A former consultant to President George W. Bush and former chairman of the Republican National Committee, Gillespie played it down the middle during the primary campaign as Stewart kept trying to provoke him. He has been a lukewarm supporter of Trump, but cast himself as a true conservative who will cut taxes and promote business.

But Gillespie, apparently trying to conserve resources and cement his front-runner status, had avoided appearances with his campaign rivals in recent weeks, preferring smaller, more controlled settings. He never seemed to inspire as much passion as Stewart, for good or ill.

Steve Chapman cast a ballot for Stewart at Mullen Elementary School in Manassas. He said that Stewart may have gone a too far with his embrace of Confederate heritage, but figured it was just a campaign shtick.

“Corey, he likes attention so I think he takes controversial stances and I don’t know if he believes it,” said Chapman, who is 39 and self-employed. “That’s what’s he does. It’s a way to get earned media attention.”

But that behavior, combined with the constant flow of controversy from the Trump administration in Washington, also energized Democrats.

Many voters said they were inspired to come out because of events in Washington. Alexandria resident Curt Arledge, 32, had never voted in a gubernatorial primary but decided this year that it was too important for him to miss.

Clothed in a T-shirt that displayed Smokey Bear wearing a “resist” hat, the Democrat voted for Northam because he thought he could win in November.

“I can’t recall any of the issues, I hate to admit,” Arledge said. “I want to nominate Democrats who can get elected.”

Outside groups have poured money and attention into Virginia, and a vast army of new candidates have flooded the Democratic side of House races — including a record number of female candidates.

Perriello drew national attention with his eloquent plea for a new kind of Democratic politics — more aggressive, more about persuading others to change than about accommodating the realities of a Virginia legislature controlled by Republicans. He attracted outside money and endorsements from national political figures.

And more than any other candidate, Perriello made the governor’s race explicitly about standing up to Trump.

In Arlington, Matt Canella, 29, and Mariah Finkel, 30, were inspired to vote for Perriello in large part because they felt he had more aggressively attacked the president.

Finkel’s vote, she said, was “mostly based off what I see on commercials.”

But Northam responded in kind, calling Trump a “narcissistic maniac” and pledging to resist his policies. He and Perriello never really disagreed about many issues, with one notable exception: Perriello opposed a pair of natural-gas pipelines being built in rural parts of the state. Northam refused to condemn them.

That issue will continue to rise up during the general election; anti-pipeline protesters briefly interrupted Northam’s victory rally.

Perriello wasted no time conceding, making his statement to supporters about 90 minutes after polls closed. To screams of “Go, Tom, Go!”Perriello addressed his supporters gathered at the State Theatre in Falls Church and urged unity against “very scary Republicans . . . We don’t even know how scary that individual might be yet,” referring to the down-to-the-wire fight between Stewart and Gillespie.

He credited his own campaign with a “great victory” for forcing issues of economic inequality into the political conversation. “Together we helped elevate mainstream ideas that should have been there all along,” he said, citing his support for a $15 minimum wage as an example. “I think it’s movements that change the world, and politicians who work as allies to that movement.”

But first, Perriello praised Northam for winning a “great victory, and offered him my full and unequivocal support.”

Long before Tuesday’s voting took place, both Perriello and Northam had agreed to appear at a Democratic unity rally on Wednesday in Northern Virginia, along with Gov. Terry McAuliffe and Democratic National Party Chairman Tom Perez. Sen. Elizabeth Warren (Mass.), who had endorsed Perriello, tweeted a congratulatory message to Northam on Tuesday night.

In the House of Delegates, all 100 seats were on the ballot. Democrats caught up in anti-Trump fervor say they want to pick up enough seats to take over the majority, but that will be a tough task. Republicans have a 66 to 34 advantage.

Antonio Olivo, Jenna Portnoy, John Woodrow Cox, Fenit Nirappil, Laura Vozzella, Patricia Sullivan, Alejandra Matos, Reis Thebault, Sarah Robertson and Catherine York contributed to this report.

[Just tuning in to Virginia governor’s race? We’ll help you do your homework]