首页 > C/C++, Elisp, 自动补全, 配置, 高级 > Emacs 自动填充头文件

Emacs 自动填充头文件

作者: 杨英超

目标

  1. 写 C/C++ 代码时候,可以根据自动补全头文件。注意,是补全,也就是说至少我们需要输入几个字符让它帮忙补全。
  2. 如果头文件存放在搜索路径的子目录中,可以自动列出子目录中的文件,并将这些文件添加到用于补齐的候选名单中。
  3. 补齐完成之后,可以自动判断到底应该使用 #include 还是 #include “FILE” 。

方案

emacser.org 上有一篇文章,其中提到了这个解决方法,主要是利用了 abbrev-mode 和 skeleton-mode 来实现,通过这个方法,我们输入 inc, 然后按空格, 会提示输入文件名称。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
;; 安装 abbrev
(mapc
 (lambda (mode)
   (define-abbrev-table mode '(
                               ("inc" "" skeleton-include 1)
                               )))
 '(c-mode-abbrev-table c++-mode-abbrev-table))
 
;; 输入 inc , 可以自动提示输入文件名称,可以自动补全.
(define-skeleton skeleton-include
  "generate include<>" ""
  > "#include <"
  (completing-read "Include File:"
                   (mapcar #'(lambda (f) (list f ))
                           (apply 'append
                                  (mapcar
                                   #'(lambda (dir)
                                       (directory-files dir))
                                   (list "/usr/include"
                                         "/usr/local/include"
                                         "/usr/include/g++-3")))))
  ">")

该方法有若干局限性:

  • 头文件的搜索路径是写死的,如果某个目录不存在,上面的代码会报错,不能补全。
  • 无法补全搜索路径的子目录下的文件 ( 即前面的 AIM 2)。
  • 没有判断在 #include 一个文件的时候,是应该使用符号 <> 还是符号 “” (即前面的 AIM 3)

解决方法并不复杂,对应如下:

  • 通过某种方法来从系统中自动获取 include 的搜索路径。比如 CEDET 提供的: semantic-gcc-get-include-paths 函数。
  • 重定义 minibuffer-mode 下的按键 “/”。将其绑定到一个用于搜索和展开某个目录,并更新 minibuffer-completion-table 的函数(minibuffer-completion-table 是 minibuffer-mode 中补全的候选 list)。
  • 在 skeleton-include 中不使用 <> 或者 “。我们可以使用一个特殊的标记,然后在 skeleton-include 的结尾,根据头文件的路径判断到底应该使用什么符号。

整理以后的代码实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
;; 输入 inc , 可以自动提示输入文件名称,可以自动补全.
;; Provided by yangyingchao@gmail.com
(mapc
 (lambda (mode)
   (define-abbrev-table mode '(
                               ("inc" "" skeleton-include 1)
                               )))
 '(c-mode-abbrev-table c++-mode-abbrev-table))
 
(defconst yc/inc-dir-list
  (append (semantic-gcc-get-include-paths "c++") '("./")) "nil")
(defvar inc-minibuffer-compl-list nil "nil")
 
(defun yc/update-minibuffer-complete-table ( )
  "Complete minibuffer"
  (interactive)
  (let ((prompt (minibuffer-prompt))
        (comp-part (minibuffer-contents-no-properties)))
    (when (and (string= "Include File:" prompt)
               (> (length comp-part) 0))
      (setq minibuffer-completion-table
            (append minibuffer-completion-table
                    (let ((inc-files nil)
                          (dirname nil)
                          (tmp-name nil))
                      (mapc
                       (lambda (d)
                         (setq dirname (format "%s/%s" d comp-part))
                         (when (file-exists-p dirname)
                           (mapc
                            (lambda (x)
                              (when (not (or (string= "." x)
                                             (string= ".." x)))
                                (setq tmp-name (format "%s/%s" comp-part x))
                                (add-to-list 'inc-files tmp-name)))
                            (directory-files dirname))))
                       yc/inc-dir-list)
                      inc-files)))))
  (insert "/"))
 
(let ((map minibuffer-local-completion-map))
  (define-key map "/" 'yc/update-minibuffer-complete-table))
 
(defun yc/update-inc-marks ( )
  "description"
    (let ((statement (buffer-substring-no-properties
                      (point-at-bol) (point-at-eol)))
          (inc-file nil)
          (to-begin nil)
          (to-end nil)
          (yc/re-include
           (rx "#include" (+ ascii) "|XXX|" (group (+ ascii)) "|XXX|")))
      (when (string-match yc/re-include statement)
        (setq inc-file (match-string 1 statement))
        (if (file-exists-p (format "./%s" inc-file))
            (setq to-begin "\"" to-end "\"")
          (setq to-begin "<" to-end ">")
          )
        (move-beginning-of-line 1)
        (kill-line)
        (insert (format "#include %s%s%s" to-begin inc-file to-end))
        (move-end-of-line 1))))
 
(define-skeleton skeleton-include
  "generate include<>" ""
  > "#include |XXX|"
  (completing-read
   "Include File:"
   (mapcar
    (lambda (f) (list f ))
    (apply
     'append
     (mapcar
      (lambda (dir)
        (directory-files
         dir nil
         "\\(\\.h\\)?"))
      yc/inc-dir-list))))
  "|XXX|"
  (yc/update-inc-marks))

使用和效果

使用方法很简单:

  1. 将上述的代码添加到 Emacs 的配置文件后,打开一个 C/C++ 程序,
  2. 输入 inc 然后按下空格,然后在 minibuffer 中输入部分头文件的名字,并通过 TAB 来补全。
  3. 如果头文件位于子目录中,则输入目录名后输入 “/” 。这样子目录中的内容也会添加到补齐的候选名单中,然后就又可以继续他过 TAB 补全了。
  4. 确认 minibuffer 中填写的内容无误后,回车, skeleton-include 将自动更新标记符号。

截图:

下面是几张截图:

Include 系统文件

Include 自定义文件

全部完成后截图


分享家:Addthis中国
GD Star Rating
loading...
Emacs 自动填充头文件, 7.3 out of 10 based on 30 ratings 标签:C/C++, Elisp, Emacs, 配置, 高级

相关日志

  1. 匿名
    2012年8月22日10:18 | #1

    楼主 我想问一下 如何在emacs中预定义一些代码 比如像一些基本的头文件填充如 , 还有像#define …之类的 怎么让emacs在新建一个c/c++文件时自动填写上

    [回复]

  2. 菜鸟
    2013年12月27日19:38 | #2

    提示木有semantic-gcc-get-include-paths,中么办?

    [回复]

  3. 临时哥
    2015年6月14日12:08 | #3

    请问使用emacs新建文件,比如一个html文件的时候,让它填充一些模板文本,而不是打开一个空白的文件应该怎么实现呢?比如填入如下内容:

    Insert title here

    [回复]

  4. 2016年4月6日19:11 | #4

    Georgia, Nebraska and Arizona State are his three “big offers,” Blanchard said. louis vuitton outlet online Antonio Thomas, Haas Hall, 1:42. j coach factory outlet
    Veteran winger Justin Williams controlled the puck behind the net and sailed it to Kuznetsov on the edge of the crease. louis vuitton outlet online Team 12 2-5 30.
    Black Friday was surprisingly mellow in Portland, elsewhere louis vuitton outlet Of course, the reckless daredevils who took no sides would come through in bands and rob both. g http://www.raybansunglassesebay.us.com
    That proposal is still pending approval by the federal court overseeing the district’s desegregation case, and the plaintiffs in the case have argued against it, saying it would primarily cater to Anglo children and that it would do nothing to diversify the district. coach outlet online But no one has a timeline for even that.
    k Last year, a being open on Thanksgiving Day staged a protest outside of Briarwood Mall in the weeks leading up to the holiday.. coach handbags The FTC is taking “an incredibly narrow” definition of Staples’ officesupply business in its challenge to Staples’ acquisition of Office Depot, Sargent said. http://www.coachhandbags.net.co
    That’s defined as an arena in which you play more than three times in a season. michael kors outlet 3 earthquake rolling through The Farm. http://www.coachoutletstoreonline.me
    Linda M. Tripp and Linda M. Maynard to Earl H. Tripp and Linda M. Tripp, 26 Pepin Ave., $100. ray ban outlet A report last year by the committee’s Democratic staff found that airline fees, especially for things such as ticket cancellations or changes, are often hidden from consumers while shopping fares online or are disclosed in lengthy paragraphs of tiny typeface that’s difficult to read. q michael kors outlet
    The institutions have brought this on themselves. michael kors outlet online Martin has had two outstanding seasons with the Bucs and two injury-filled years.
    and 1 p. coach outlet online Denny Hamlin also is in a backup car after hitting the wall coming out of the same turn in Thursday’s open practice.
    They also stand accused of providing el-Hussein with access to a computer and giving him ammunition that he used during the attack. coach factory outlet store They start calculating which bill they won’t pay, what they won’t eat for dinner.
    Golden State followed a lay-up with 1:13 remaining in the second-quarter by finishing the half on a 9-0 run to open up a 52-41 advantage. louis vuitton outlet The Arkansas Chamber of Commerce will attempt to draw more workers into technical fields by promoting job training programs with the help of the governor and a shiny red Freightliner truck, the chamber said Tuesday.
    j I don’t think our business plan is totally focused on increasing skier visits. coach outlet The appellate judges, citing that lack of evidence, ruled on Oct.
    Well, we ACTUALLY know that polio was going away BEFORE the vaccine was even made. ray ban sunglasses outlet Why don t you like this ad ?It s offensive to meI keep seeing thisIt s not relevant to meSomething elseDoneTrendingIt sounds like there s a big reason why Brock Osweiler spurned the Broncos for the Texans, and it s not just moneyBusiness InsiderTrendingN. r louis vuitton bags
    “I know we are all up to the task. coach outlet Of course, the single best habit one can incorporate into their diet is a steady dose of crunchy fruits and vegetables.
    k Theodore E. Djaferis, trustee, Mary M. Djaferis, trustee, and Djaferis Family Revocable Trust, to Leonard S. Bobrow, 4 Sutton Court, $172,000. michael kors bags To remain competitive with blended cements, portland cement producers are replacing progressively larger portions of clinker with supplementary cementitous materials, which results in a “greener” and lower cost product. e
    expand max-height: 800px;video id video-ad-asset” class video-responsive video-js vjs-default-skin”video p class bwalignc”p class bwalignc”ContactsWayfairMedia Relations Contact:Jane Carpenter,617-502-7595PR@wayfair. coach outlet online Blocks: Evans 2, Frepanier 2. cheap oakleys
    Jester tore her anterior cruciate ligament and shattered a kneecap. She can’t stand too long without her leg buckling. Her injuries have made running, ballet and tap dancing virtually impossible — all things she used to do. http://www.louisvuittonhandbags.us.org Don’t badmouth the ex or say, “I told you so. u http://www.michaelkorshandbagsbuy.us.com
    Dozens of trailers were toppled around by a deadly tornado louis vuitton bags Everything is going to be different, Len said.
    The 11-year-old, who was shot near Everett on Sunday, was taken to Harborview Medical Center in Seattle. Hospital spokeswoman Susan Gregg said Monday he’s in serious condition and expected to live. http://www.coachhandbags.com.co MOHAYMEN Kiaran McLaughlin Junior Alvarado Florida Derby April 2, Gulfstream 41 y coach outlet online
    “We share the challenges in our career paths and how we did not let the conventional thinking that strength and success is based on gender cloud our vision. michael kors handbags Rain stopped the race about 45 minutes after it began for a delay of more than six hours.

    [回复]

  5. 2016年4月7日03:47 | #5

    About this roundup: coach outlet online “I’ve never based my campaign on one single state, but I can tell you this: we will win the state of Florida,” Rubio said. v http://www.michaelkorshandbagsbuy.us.com
    That type of turnaround made the Islanders cautious heading into their second showing in Lancaster, said Donatelli, who played his fourth game for Harrisburg Monday ray ban sunglasses For now, anyway.
    My game story from Autzen, where the Beavers’ comeback ended a forgettable season . coach handbags At 7:30 p. x louis vuitton outlet
    ” Reporter Yoohyun Jung contributed to this story. michael kors handbags It s premature to provide numbers at this point, but even one company being fooled by these criminals is too many, the IRS said in a statement.
    f If passed, the annexed districts normally remain separate for purposes of liquidating voted debt, such as capital bond projects, until the debt is paid off or voters choose to combine the debts of the districts. michael kors outlet JONESBORO — Arkansas State’s 2016 football schedule has been released and includes six home games and three games scheduled for broadcast. http://www.michaelkorshandbagsoutletbuy.us.com
    Maureen Bunyan: One of the negative ways in which Washington is portrayed is that there is an elite community here that supports the arts. cheap air jordans The second seat was a toss up on election night between Wojtovich and Michelle Anderson. http://www.coachhandbags.me
    “I don’t know, but I know we made him think.” http://www.coachfactorysoutlet.com He has the most beautiful orange eyes to match the orange in his coat. t http://www.louisvuittonhandbagsbuy.co.uk
    “I have at least two stores that have been selling it already for 30 days,” Santiago Negre, who owns 20 McDonald’s restaurants in the Birmingham metro area, told AL. coach outlet online The band officially split the following year.
    He travelled the world pointing out that his homeland lies barely two metres (6. cheap ray ban sunglasses A tree on the tracks caused a commuter to derail in stormsoaked Northern California, plunging its lead car into a rainswollen creek and sending passengers scrambling in the dark to get out of the partially submerged car.
    It stars a disoriented Mary Elizabeth Winstead trapped (or is she being protected?) in John Goodman’s bomb shelter. michael kors outlet store Coulson said the drugs and weapons are far less important than who they arrested.
    Zgragen’s mother and said anything about the issue, you should be ashamed of yourself, but I’m sure you are not, because it takes a sense of right and wrong to be ashamed. coach outlet store online HR Nomura.
    o icgpa. ray ban sunglasses outlet The mournful procession reach the exact spot where the “Migras” killed Jose Antonio and repeated their shouts for justice, mixed with prayers and religious songs.
    Mr Jenkins was a two-time British advanced aerobatics champion. michael kors handbags He was the doorman at the comedy club where I lived across the street. q michael kors outlet online
    But never forget: your mom also owns a crown. coach outlet online jpg”> See more camera sample images here
    n “I know I can get a little bit too emotional and excited when I’m on the court,” he continued. “I get to moving too fast and all that kind of stuff. I just have to calm down. A lot of that for me is dealing with personal pressure. coach outlet online Wage growth is often tepid when the jobs report survey week doesn’t include the 15th of the month, Shepherdson noted. c
    The NominatingGovernance Committee of the TeamHealth Board of Directors will review and consider JANA s nominations and will make a recommendation it believes is in the best interest of all TeamHealth shareholders ray ban sunglasses The senior shooting guard woke up with back spasms and was unable to suit up. cheap jordan shoes
    The Blazers shot 8-for-24 in the fourth quarter, including 0-for-5 shooting from Lillard, who carried the Blazers offense in the first three quarters. coach outlet He spoke on condition of anonymity because he wasn’t authorized to comment publicly. y louis vuitton bags
    UPPER MARLBORO, Md. cheap jordan shoes “We are not planning to go anywhere, as long as we are able and as long as there’s a need for some kind of accountability,” she said.
    25 players matched 4 White Balls, with the Gold Mega Ball, winning $5,000. And three players matched 4 White Balls with Megaplier, winning $20,000. coach outlet online He also helps around the house and with my daughter. z ray ban sunglasses outlet
    national team, has 160 appearances with the Timbers. louis vuitton handbags “Miller has called Pitts a “great kid,” and Pitts is also known to be a good student.

    [回复]

  6. 2016年4月7日19:38 | #6

    Berjac of Oregon attracted hundreds of investors through a bread-and-butter business model. coach outlet Oh, shoot, I’ve got to give that back. d coach outlet online
    In this new era of payment and delivery, Citra empowers clients with proven technology, population health, analytics and care management services to strategically expand market opportunity, diversify revenue streams and reduce the cost of care. http://www.louisvuittonhandbagsbuy.us.com “What we tell tenants is, negotiate it,” she said.
    Groban returned to the Oakdale stage for an emotional encore of Harold Arlen and E.Y. Harburg’s Academy Award winning “Over the Rainbow” from “The Wizard of Oz” – a non-Broadway tune, but no one was heard complaining. http://www.coachoutletstores.net.co They get their hands dirty and see animals they’ve never seen before. u http://www.michaelkorshandbagsbuy.us.com
    He said the downtown area would not be overlooked as his plan calls for creating a smaller downtown business district that would be patrolled primarily by officers on foot and on bicycles. michael kors handbags Tickets — including discounted ones for designated drivers — are available online through midnight and at five locations in Tempe and Mesa (Find them online at .
    h “Priorities-wise, Barry is here for athletics and sports teams, and not black students,” said sophomore Carlton Bone, a white student from Florida. coach outlet online Does it have a name? oakley glasses
    While the prom gown is normally the scene-stealer of theat Steelton-Highspire High’s 2015 prom tuxes gave them a run for their money http://www.coachoutletsonlines.us.org Generally, “linear disruptions” such as power lines can be the most difficult to mitigate because their impacts are spread over hundreds of miles, she testified. http://www.coachstoresonline.com
    “A lot of these guys are old farmers,” he said. “They’re not big Black Eyed Peas fans, or Las Vegas or Transformers fans. They don’t really care. They treat us like we’re regular people.” michael kors outlet online The Hall of Famer had just been named head coach at Texas Tech, was looking for a quick rebuild and a coach who knew how to get juniorcollege players annually. o michael kors bags
    “This is great news for Brunswick Arts and will further strengthen our offer in the U. michael kors outlet online Isaac Figueroa, with Picor, represented the tenant, and Aubrey Finkelstein, with Vast Real Estate Solutions, represented the owner.
    Back at WERC, this knowledge has been passed on to other volunteers, continuing to this day. http://www.coachoutlet.cc You’ve got to validate your last success, or you’ve got to overcome your last adversity.
    My home town, Beder, is situated on the outskirts of Aarhus and is definitely not a melting pot of nationalities by any means, but there is only one Dane in the group while the others are from more exotic places – so I get to stay in touch with an international environment even when on maternity leave. http://www.cheapchinajerseysnfl.us.org Volunteers read stories and sing songs with the children, then the children complete an arts and craft project.
    We then have to board our Bostons at a shelter and this gets very expensive,” according to a release from the Arizona Boston Terriers Rescue. cheap louis vuitton bags Topranked Djokovic won the first point for Serbia by defeating Aleksandr Nedovyesov 61, 62, 63 before Mikhail Kukushkin beat Viktor Troicki 75, 62, 64 as Kazakhstan tied the 2010 champion 11.
    d The method allows for the noodles to cook evenly and maintain the proper texture. coach factory outlet Detectives ask that anyone with information about these robberies call 837-7835 or 88-CRIME.
    This coming March that bond approval will be 12 years old and while enormous effort and funding went into what was the former Priority 2 project on the facilities list, almost nothing went into the Priority 1 project, the San Benito Education Center. http://www.michaelkors.us.org Jared M. m michael kors outlet
    In coining the term NPAID (Non-Pharmaceutical Anti-Inflammatory Device), the company is calling attention to this class of treatment as an emerging part of the standard of care in treating pain and inflammation in animals. louis vuitton handbags I ran something like 22 minutes, and it was ridiculous.
    c Max Domi, the son of former Red Wings fan favorite Tie Domi, leads Arizona with 20 points (eight goals, 12 assists) and makes his first visit to Detroit on Thursday. Domi was drafted 12th overall in 2013. cheap michael kors bags The poor old Fourth Amendment sure takes a beating! Actually, there is not much left of the right to be free of unreasonable search and seizure. k
    Meanwhile, whisk the remaining 1?2 cup milk and cornstarch in a small bowl. coach factory outlet They prioritized drawing clearer boundaries for Catholic behavior and belief in the face of legalized abortion, advances in gay rights and the exodus of many Westerners from organized religion. http://www.coachhandbags.me
    Co-defensive coordinator Mike Tressel, who previously coordinated special teams, said the Spartans are setting lofty special teams goals for the 2016 season. http://www.michaelkorsbag.us.org The groups make videos about their ideas. v cheap michael kors bags
    Add the red pepper and cook, stirring, until it is almost tender, about 3 minutes. http://www.michaelkorshandbags.us.org Team 18 7-10 47.
    A total of 20 individuals placed at the state finals, including five state champions. So, who is the Jackson-area s MVP for the 2015-16 season? We re asking readers to pick a winner. coach outlet store Lewis was charged with aggravated robbery; fleeing; commercial burglary; two counts of theft of property; tampering with physical evidence; possession of a firearm by certain persons; failure to stop after an accident and driving with a suspended or revoked license. a michael kors handbags
    Steve Jobs paints an intimate portrait of the brilliant man at the epicenter of the digital revolution, backstage in the final minutes before three iconic product launches. http://www.michaelkorsbags.me Robles 8-5.

    [回复]

评论分页
1 2 41916
  1. 本文目前尚无任何 trackbacks 和 pingbacks.
:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: